From 3f4ce36b2c87e6974d93f0d8096a5feca207e9e4 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Thu, 1 Oct 2026 02:29:44 -0500 Subject: [PATCH 01/10] OSC-0B: II.11 executable memory model, seeded 10^6 sweep, receipt writer; OSC-1 design + self-host statement The OSC-0 ADR makes the II.11 model the OSC-0B exit gate and a precondition for starting OSC-1. It did not exist on main; this adds it (C, fixed capacity, u64 generations, 13 named invalid transitions + typed MALFORMED/CAPACITY/PROTOCOL refusals) with a seeded generator whose shadow state labels injected faults. Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Fable 5.1 --- docs/osc/OSC-1-DESIGN.md | 229 ++++++++ docs/osc/OSC-1-SELF-HOST-STATEMENT.md | 41 ++ src/compiler/model/osc_model.c | 415 ++++++++++++++ src/compiler/model/osc_model.h | 213 +++++++ src/compiler/model/osc_model_gen.c | 778 ++++++++++++++++++++++++++ src/compiler/model/osc_model_gen.h | 39 ++ tests/compiler/osc0b_model_receipt.sh | 123 ++++ tests/compiler/test_osc_model.c | 313 +++++++++++ 8 files changed, 2151 insertions(+) create mode 100644 docs/osc/OSC-1-DESIGN.md create mode 100644 docs/osc/OSC-1-SELF-HOST-STATEMENT.md create mode 100644 src/compiler/model/osc_model.c create mode 100644 src/compiler/model/osc_model.h create mode 100644 src/compiler/model/osc_model_gen.c create mode 100644 src/compiler/model/osc_model_gen.h create mode 100755 tests/compiler/osc0b_model_receipt.sh create mode 100644 tests/compiler/test_osc_model.c diff --git a/docs/osc/OSC-1-DESIGN.md b/docs/osc/OSC-1-DESIGN.md new file mode 100644 index 000000000..304ef30a3 --- /dev/null +++ b/docs/osc/OSC-1-DESIGN.md @@ -0,0 +1,229 @@ +# OSC-1: the first compiler slice (design, normative) + +**OSC-1 slice; not a general Omega compiler; no self-hosting.** + +Status: in progress (Lane 22, 2026-10-01). Governing record: +[OMEGA-SYSTEMS-CORE-0000](../adr/OMEGA-SYSTEMS-CORE-0000.md) and the audit +sections it cites ([OMEGA_SYSTEMS_CORE_CODE_AUDIT.md](../../OMEGA_SYSTEMS_CORE_CODE_AUDIT.md) +III.6 pipeline, III.7 OSC-1 definition, III.8 acceptance tests, II.9 determinism, +II.11 executable model). + +## 1. What OSC-1 is + +OSC-0 III.7 defines OSC-1 as "the smallest vertical slice: source -> parser -> +typed value -> unique allocation -> borrow -> bounds check -> deterministic +destruction -> native execution". This slice implements exactly that path, for +a small language that extends V0 (spec/omega-language-v0.md), plus the integer +and control-flow core needed to write programs that exercise it: + +- integer scalars u8 u16 u32 u64 (wrap, V0 compatible) and i8 i16 i32 i64 + (checked: overflow is a deterministic trap, OSC-0 III.3), and bool; +- `let` bindings (immutable by default, `let mut` for reassignment); +- arithmetic, bitwise, shift, comparison, logical operators; +- `if` / `else`, `while ... bound N` and `for i in A .. B` loops whose trip count + has a static bound; +- calls to functions defined earlier in the same unit (no recursion); +- unique allocation `own [T; N]`, moves, shared and mutable borrows `&[T; N]` / + `&mut [T; N]`, indexing with a bounds check, deterministic destruction at + scope end; +- `requires` / `ensures` clauses parsed and recorded as text, **not checked** + (OSC-0 decision 3, III.6). Enforcement is OSC-2 and mandatory before any + production C migrates. + +Pipeline (III.6 steps realised here): lexer/parser -> typed AST (disposable) -> +name/type resolution -> ownership + borrow analysis (lexical lifetimes) -> typed +IR (`src/compiler/osc_ir.h`, canonical encoding + SHA-256 digest) -> realization +to AArch64 through an in-repo encoder whose every emitted word is mirrored in a +decoder. Not in OSC-1: effects/capabilities (III.6 step 6), structs, strings, +generics, generations, arenas, unsafe physical, FFI, Flow IR optimisation. + +## 2. Surface grammar (EBNF) + +``` +unit = { fn_def } EOF ; +fn_def = "fn" NAME "(" [ param { "," param } ] ")" [ "->" type ] + [ "requires" clause ] [ "ensures" clause ] block ; +param = NAME ":" ptype ; (* at most 6 params *) +ptype = type | arr_type ; +arr_type = "own" "[" type ";" INT "]" (* owner, moved into the callee *) + | "&" "[" type ";" INT "]" (* shared borrow *) + | "&" "mut" "[" type ";" INT "]" ; (* mutable borrow *) +type = "u8" | "u16" | "u32" | "u64" | "i8" | "i16" | "i32" | "i64" | "bool" ; +clause = { token } ; (* up to "ensures" / "{" at paren depth 0; recorded text *) +block = "{" { stmt } "}" ; +stmt = "let" [ "mut" ] NAME ":" type "=" expr ";" + | "let" NAME ":" "own" "[" type ";" INT "]" "=" "alloc" "(" expr ")" ";" + | "let" NAME ":" "own" "[" type ";" INT "]" "=" NAME ";" (* move *) + | "let" [ "mut" ] NAME ":" ( "&" | "&" "mut" ) "[" type ";" INT "]" "=" borrow ";" + | NAME "=" ( expr | borrow ) ";" (* mut scalar, or mut borrow binding *) + | NAME "[" expr "]" "=" expr ";" + | "if" expr block [ "else" ( block | if_stmt ) ] + | "while" expr "bound" INT block + | "for" NAME "in" INT ".." INT block (* i: i64, half-open, literal ends *) + | "return" [ expr ] ";" + | call ";" + | block ; +borrow = "&" NAME | "&" "mut" NAME ; +expr = lor ; +lor = land { "||" land } ; (* short-circuit *) +land = cmp { "&&" cmp } ; (* short-circuit *) +cmp = bor [ cmp_op bor ] ; (* non-associative *) +bor = bxor { "|" bxor } ; +bxor = band { "^" band } ; +band = shift { "&" shift } ; +shift = add { ( "<<" | ">>" ) add } ; +add = mul { ( "+" | "-" ) mul } ; +mul = unary { ( "*" | "/" | "%" ) unary } ; +unary = ( "-" | "~" | "!" ) unary | postfix ; +postfix = primary [ "as" type ] ; +primary = INT | "true" | "false" | NAME | NAME "[" expr "]" | call | "(" expr ")" ; +call = NAME "(" [ arg { "," arg } ] ")" ; +arg = expr | borrow ; (* an owner NAME as an `own` arg is a move *) +cmp_op = "==" | "!=" | "<" | "<=" | ">" | ">=" ; +``` + +Literals, comments and identifiers are spelled as in V0 (decimal, `0x`, `0b`; +`//` and `/* */`). Precedence differs from V0 only by the added levels; every V0 +operator keeps its V0 meaning. `free`, `drop`, `delete`, `dealloc` are reserved +and are a syntax error: destruction has no surface syntax, so a forgotten free +is inexpressible (III.8). + +## 3. Static rules (all refusals are typed diagnostics, section 6) + +Types. No implicit conversion: both operands of a binary operator have the +identical type (shift: the amount may be any integer type), comparison operands +have the identical type, `if`/`while` conditions and `&& || !` operands are +`bool`. `as` converts between integer types only (checked at run time). The +array element type is an integer type or bool; N is 1..64. + +Literals. A literal gets its type from the context (let annotation, the other +operand, the parameter / return / element type it is passed to, the `as` +source is refused for literals). A literal with no context is refused +(ambiguous width, as in V0); a literal that does not fit its type is refused +(`overflow-unsafe`). + +Overflow-unsafe, refused at compile time: a constant expression of a signed +type whose value overflows; a literal shift amount >= width; a literal zero +divisor; a negative literal for an unsigned type. + +Names. Every name is defined before use, in an enclosing scope. Shadowing in +an inner scope is refused (keeps diagnostics unambiguous). Functions are called +only after their definition (no recursion, no forward reference). + +Loops. `while` without `bound N` is refused (`unbounded loop`). `for` ends must +be integer literals with A <= B. N and B - A are at most 1_000_000. A `while` +that would start iteration N+1 traps with OSC_TRAP_LOOP_BOUND. + +Return. Every path of a non-void function ends in `return expr;`. A function +returns a scalar only (no `->` arr_type in OSC-1). + +### 3.1 Ownership and borrows (lexical lifetimes) + +Objects: each `alloc(...)` creates one unique allocation owned by the binding. +An owner binding is in one of: `owned`, `moved`. A borrow binding (or a borrow +argument for the duration of a call) holds a borrow of one or more owners. + +- Move: `let b: own[..] = a;` or passing owner `a` to an `own` parameter. After + a move, any use of `a` (read, index, borrow, move) is refused: **use after + move**. A move inside a loop body of an owner declared outside that loop is + refused (use after move on the next iteration). A move on only some paths of + an `if` is refused (`conditional move`): OSC-1 has no drop flags. +- Shared borrow `&a`: allowed while `a` is owned and not mutably borrowed. +- Mutable borrow `&mut a`: `a` must be owned and not borrowed at all; through a + borrow binding `r: &mut`, `&mut r` is a reborrow of the same target. +- While a borrow of `a` is live (borrow binding in scope, or a call argument + during the call): moving `a`, storing into `a[i]` directly, or taking + `&mut a` with any other live borrow is refused: **mutable alias**. A call + `f(&mut a, &a)` or `f(&mut a, &mut a)` is a mutable alias. While a `&mut` + borrow of `a` is live, any direct use of `a` is refused (mutable alias). +- **Borrow outlives owner**: a borrow binding declared in an outer scope is + assigned a borrow of an owner declared in an inner scope (the owner is + destroyed while the borrow is still in scope); also refused: returning or + storing a borrow in any other place (OSC-1 has nowhere else to put one). +- Indexing: `a[i]` reads through an owner or any borrow; `a[i] = v` writes + through an owner (not borrowed) or a `&mut` borrow binding. A shared borrow is + read only. **Statically known out-of-bounds**: an index that is an integer + literal (or a constant expression) outside 0..N-1 is refused at compile time. + Any other index is checked at run time: out of range is a deterministic trap + OSC_TRAP_BOUNDS. +- Destruction: at the end of each scope, every owner declared in it that was + not moved is destroyed (OSC_I_RELEASE) in reverse declaration order, + including on early `return`. An `own` parameter is an owner of the function + scope. There is no other way to free. + +The ownership analysis records, per function, the event sequence it checked +(alloc, borrow_shared, borrow_mut, end_borrow, move, use, release, scope end). +The tests replay these sequences through the II.11 executable model +(`src/compiler/model/`) and require the model's verdict to agree with the +compiler's (accept/accept, or the same named invalid transition). + +## 4. IR + +`src/compiler/osc_ir.h` is the data definition. Notes: + +- vregs 0..nparams-1 are the parameters. Each named local gets one vreg; + temporaries get fresh vregs. Every vreg has one type. +- The front end lowers `&&`/`||` to branches, loops to blocks with an explicit + counter vreg, CMP and CBR on the bound, and `OSC_I_TRAP 4` when exceeded. +- Release instructions are emitted by the front end at every scope exit. +- The IR has a canonical little-endian encoding with no padding + (`osc_ir_encode`); the SHA-256 of that encoding is the unit's identity. + Source spelling, comments and whitespace never reach it. + +## 5. Semantics shared by interpreter and native code + +Values: 64-bit canonical (unsigned zero-extended, signed sign-extended, bool +0/1). Unsigned results are reduced modulo 2^w. Signed results must be +representable or the run traps with OSC_TRAP_OVERFLOW. Division truncates +toward zero; remainder has the sign of the dividend; divisor 0 traps DIV0. +Shift amount must be in 0..w-1 or the run traps SHIFT. Signed `<<` traps +OVERFLOW if the result is not representable. `as` traps CAST if the value is +not representable in the target type. Array elements are 8-byte canonical +cells; allocation initialises every element to the given value; release zeroes +the cells. Allocation takes the lowest free pool slot; pool exhaustion traps +OOM. A trap ends the whole run: no destructors run (no unwinding, OSC-0 +decision 6); the harness resets the pool. + +Observable outcome of a run = (trap code, return value if no trap, the pool +event log). The interpreter and native code must agree on all three. + +## 6. Diagnostics + +Every refusal is an `OscDiag` with: `kind` (enum, below), `line`, `col`, +`object` (the name involved), `origin_line` (where that object / borrow was +created), `other` (the conflicting borrow or name, if any), `transition` (the +attempted transition as text, e.g. "use after move", "borrow_mut while +borrow_shared live"). Kinds: SYNTAX, UNSUPPORTED, CAPACITY, UNDEFINED_NAME, +REDEFINED_NAME, TYPE_MISMATCH, AMBIGUOUS_WIDTH, OVERFLOW_UNSAFE, +UNBOUNDED_LOOP, MISSING_RETURN, USE_AFTER_MOVE, CONDITIONAL_MOVE, +MUTABLE_ALIAS, BORROW_OUTLIVES_OWNER, STATIC_OUT_OF_BOUNDS, IMMUTABLE_ASSIGN, +READ_ONLY_BORROW. Negative tests assert the kind and the fields. + +## 7. Native ABI (AArch64, Linux host) + +- Each function: params in x0..x5, return in x0 (bool 0/1, canonical + extension), hidden runtime pointer `OscRt *` in x7. +- Frame: `stp x29, x30, [sp, #-16]!; mov x29, sp; sub sp, sp, #F` with F = + 8 * nvregs + 8 rounded up to 16. Slot 0 holds x7; vreg v lives at + `[sp, #8 * (v + 1)]`. Every instruction loads its operands from slots into + x9..x15 and stores its result to the destination slot (no register + allocation in OSC-1; deterministic and simple). +- Calls between compiled functions use BL; runtime entry points are reached by + `ldr x16, [x7_slot]`, `ldr x16, [x16, #off]`, `blr x16`. +- Encoder: `src/compiler/osc_a64.c`. Every emitter refuses an out-of-range + field (no silent masking), SP and XZR are distinct operand kinds, and every + emitted word decodes through `osc_a64_decode` back to the same fields. + The existing `src/aarch64_encoder.c` is not changed. + +## 8. Determinism (II.9) + +Compiler output is a pure function of the source bytes: no timestamps, paths, +environment, pointer values or hash-order dependence. Gate: compile every +corpus program twice in separate processes and compare IR digests and machine +code bytes. + +## 9. Self-hosting + +See [OSC-1-SELF-HOST-STATEMENT.md](OSC-1-SELF-HOST-STATEMENT.md). Short form: +the OSC-1 compiler cannot compile any part of itself, and this slice makes no +self-hosting claim. diff --git a/docs/osc/OSC-1-SELF-HOST-STATEMENT.md b/docs/osc/OSC-1-SELF-HOST-STATEMENT.md new file mode 100644 index 000000000..944556261 --- /dev/null +++ b/docs/osc/OSC-1-SELF-HOST-STATEMENT.md @@ -0,0 +1,41 @@ +# OSC-1 self-hosting statement + +**OSC-1 slice; not a general Omega compiler; no self-hosting.** + +Question: can the OSC-1 compiler compile any part of itself? + +**Answer: no.** No part of the OSC-1 compiler's source is written in the OSC-1 +language, and the OSC-1 language cannot express it. Reasons, each a missing +language feature, not a missing test: + +1. **No bytes, strings or text.** The lexer and parser consume source bytes and + produce names and diagnostics. OSC-1 has integer scalars, bool and fixed + arrays of at most 64 integers. It has no `u8` slice over input, no string + type and no way to receive a source file. +2. **No structs, unions or tagged data.** The IR (`osc_ir.h`) is a tree of + structs and enums (`OscUnit`, `OscFunc`, `OscInsn`). OSC-1 has no aggregate + type other than `own [T; N]` with N <= 64, so it cannot hold an IR. +3. **No growable or large storage.** The compiler needs tables of thousands of + entries (4096 instructions per function, 480 vregs). OSC-1 allocations are + fixed-size pool slots of 64 cells, at most 64 live. +4. **No recursion and no forward calls.** The parser is recursive descent. OSC-1 + calls only functions defined earlier in the unit. +5. **No output channel.** The back end writes machine code into a buffer the + host maps executable, and the receipt writer writes files. OSC-1 programs can + only return a scalar; they have no I/O, no capabilities and no effects. +6. **No checked contracts.** `requires`/`ensures` are recorded text in OSC-1 + (OSC-0 decision 3). By OSC-0 rule, no production C migrates into Omega + Systems Core until contract enforcement exists (OSC-2). + +What could be written in OSC-1 today is a re-implementation of a few pure +integer helpers that the compiler uses (for example the width mask or the +"is this value representable in type T" check). That would be new code that +happens to compute the same numbers, not the compiler compiling its own +source, and it is not claimed as self-hosting. + +What this means for the roadmap. Self-hosting is OSC-14 in the OSC-0 migration +order (audit III.7). The determinism gate II.9 defines the evidence it will +need: `compiler_n` built by `compiler_{n-1}` producing byte-identical output +on a fixed corpus. The M6 `OMEGA_SELF_HOST` result is a fixed-output self-copy +check and is never evidence of a compiler (OSC-0 decision 2, ROADMAP ยง3 M6 +correction note). OSC-1 does not change that and does not touch M6. diff --git a/src/compiler/model/osc_model.c b/src/compiler/model/osc_model.c new file mode 100644 index 000000000..259d95119 --- /dev/null +++ b/src/compiler/model/osc_model.c @@ -0,0 +1,415 @@ +/* + * osc_model.c -- II.11 executable reference model (see osc_model.h). + * Every handler validates completely before it mutates, so a rejected event + * leaves the state unchanged. + */ +#include "osc_model.h" + +#include + +enum { O_UNALLOC = 0, O_OWNED, O_MOVED, O_RELEASED }; +enum { B_UNUSED = 0, B_LIVE, B_ENDED }; +enum { R_UNUSED = 0, R_OPEN, R_DESTROYED }; +enum { S_FREE = 0, S_LIVE, S_RETIRED }; +enum { C_UNUSED = 0, C_WRITTEN, C_PUBLISHED, C_OBSERVED, C_RECLAIMED }; +enum { T_UNUSED = 0, T_LIVE, T_CONSUMED }; + +static const char *const k_reject_names[OSC_REJ__COUNT] = { + "accept", + "use-after-move", + "use-after-release", + "double-release", + "stale-generation", + "generation-wrap", + "mutable-alias", + "borrow-outlives-owner", + "arena-escape", + "reclaim-without-quiesced", + "read-before-observe", + "publish-without-release", + "forged-rights", + "live-handle-durable", + "malformed", + "capacity", + "protocol", +}; + +static const char *const k_event_names[OSC_EV__COUNT] = { + "?", "alloc", "move", "borrow_shared", "borrow_mut", "end_borrow", + "use_read", "use_write", "release", "region_open", "region_destroy", + "slot_alloc", "slot_free", "handle_derive", "handle_use", "persist", + "durable_write", "cell_write", "cell_publish", "cell_observe", "cell_read", + "quiesce", "reclaim", +}; + +const char *osc_model_reject_name(OscModelReject r) +{ + if ((unsigned)r >= OSC_REJ__COUNT) return "?"; + return k_reject_names[r]; +} + +const char *osc_model_event_name(uint32_t kind) +{ + if (kind == 0 || kind >= OSC_EV__COUNT) return "?"; + return k_event_names[kind]; +} + +void osc_model_init(OscModel *m, uint64_t gen_base, uint64_t gen_max) +{ + memset(m, 0, sizeof *m); + if (gen_base > gen_max) gen_base = gen_max; + m->gen_base = gen_base; + m->gen_max = gen_max; + for (uint32_t s = 1; s <= OSC_MODEL_MAX_SLOTS; s++) { + m->slot[s].state = S_FREE; + m->slot[s].gen = gen_base; + } +} + +/* Id checks. "ref": the id must already exist. "fresh": it must be unused. */ +#define IDCHK(id, cap) do { if ((id) == 0) return OSC_REJ_MALFORMED; \ + if ((id) > (cap)) return OSC_REJ_CAPACITY; } while (0) + +static OscModelReject obj_ref(const OscModel *m, uint32_t id) +{ + IDCHK(id, OSC_MODEL_MAX_OBJECTS); + return m->obj[id].state == O_UNALLOC ? OSC_REJ_MALFORMED : OSC_REJ_NONE; +} +static OscModelReject obj_fresh(const OscModel *m, uint32_t id) +{ + IDCHK(id, OSC_MODEL_MAX_OBJECTS); + return m->obj[id].state != O_UNALLOC ? OSC_REJ_MALFORMED : OSC_REJ_NONE; +} +static OscModelReject bor_ref(const OscModel *m, uint32_t id) +{ + IDCHK(id, OSC_MODEL_MAX_BORROWS); + return m->bor[id].state == B_UNUSED ? OSC_REJ_MALFORMED : OSC_REJ_NONE; +} +static OscModelReject bor_fresh(const OscModel *m, uint32_t id) +{ + IDCHK(id, OSC_MODEL_MAX_BORROWS); + return m->bor[id].state != B_UNUSED ? OSC_REJ_MALFORMED : OSC_REJ_NONE; +} +static OscModelReject reg_ref(const OscModel *m, uint32_t id) +{ + IDCHK(id, OSC_MODEL_MAX_REGIONS); + return m->region[id] == R_UNUSED ? OSC_REJ_MALFORMED : OSC_REJ_NONE; +} +static OscModelReject reg_fresh(const OscModel *m, uint32_t id) +{ + IDCHK(id, OSC_MODEL_MAX_REGIONS); + return m->region[id] != R_UNUSED ? OSC_REJ_MALFORMED : OSC_REJ_NONE; +} +static OscModelReject slot_ref(uint32_t id) +{ + IDCHK(id, OSC_MODEL_MAX_SLOTS); + return OSC_REJ_NONE; +} +static OscModelReject hnd_ref(const OscModel *m, uint32_t id) +{ + IDCHK(id, OSC_MODEL_MAX_HANDLES); + return m->hnd[id].used ? OSC_REJ_NONE : OSC_REJ_MALFORMED; +} +static OscModelReject hnd_fresh(const OscModel *m, uint32_t id) +{ + IDCHK(id, OSC_MODEL_MAX_HANDLES); + return m->hnd[id].used ? OSC_REJ_MALFORMED : OSC_REJ_NONE; +} +static OscModelReject cell_ref(const OscModel *m, uint32_t id) +{ + IDCHK(id, OSC_MODEL_MAX_CELLS); + return m->cell[id].state == C_UNUSED ? OSC_REJ_MALFORMED : OSC_REJ_NONE; +} +static OscModelReject tok_ref(const OscModel *m, uint32_t id) +{ + IDCHK(id, OSC_MODEL_MAX_TOKENS); + return m->tok[id].state == T_UNUSED ? OSC_REJ_MALFORMED : OSC_REJ_NONE; +} +static OscModelReject tok_fresh(const OscModel *m, uint32_t id) +{ + IDCHK(id, OSC_MODEL_MAX_TOKENS); + return m->tok[id].state != T_UNUSED ? OSC_REJ_MALFORMED : OSC_REJ_NONE; +} +static OscModelReject sem_ref(const OscModel *m, uint32_t id) +{ + IDCHK(id, OSC_MODEL_MAX_SEMIDS); + return m->semid[id] ? OSC_REJ_NONE : OSC_REJ_MALFORMED; +} +static OscModelReject sem_fresh(const OscModel *m, uint32_t id) +{ + IDCHK(id, OSC_MODEL_MAX_SEMIDS); + return m->semid[id] ? OSC_REJ_MALFORMED : OSC_REJ_NONE; +} + +#define TRY(expr) do { OscModelReject r_ = (expr); if (r_ != OSC_REJ_NONE) return r_; } while (0) + +/* The owner itself must still be owned (direct use). */ +static OscModelReject owner_usable(const OscModel *m, uint32_t obj) +{ + if (m->obj[obj].state == O_MOVED) return OSC_REJ_USE_AFTER_MOVE; + if (m->obj[obj].state == O_RELEASED) return OSC_REJ_USE_AFTER_RELEASE; + return OSC_REJ_NONE; +} + +/* Optional `via` borrow: exists and refers to obj. */ +static OscModelReject via_ref(const OscModel *m, uint32_t via, uint32_t obj) +{ + if (via == 0) return OSC_REJ_NONE; + TRY(bor_ref(m, via)); + return m->bor[via].obj == obj ? OSC_REJ_NONE : OSC_REJ_MALFORMED; +} + +static int hnd_stale(const OscModel *m, uint32_t h) +{ + const OscMSlot *s = &m->slot[m->hnd[h].slot]; + return s->state != S_LIVE || s->gen != m->hnd[h].gen; +} + +/* Direct read of an owner (USE_READ via 0, DURABLE_WRITE of an object). */ +static OscModelReject direct_read(const OscModel *m, uint32_t obj) +{ + TRY(owner_usable(m, obj)); + if (m->obj[obj].n_mut) return OSC_REJ_MUTABLE_ALIAS; + return OSC_REJ_NONE; +} + +static OscModelReject step(OscModel *m, const OscModelEvent *e) +{ + switch (e->kind) { + case OSC_EV_ALLOC: + TRY(obj_fresh(m, e->obj)); + if (e->region) { + TRY(reg_ref(m, e->region)); + if (m->region[e->region] == R_DESTROYED) return OSC_REJ_USE_AFTER_RELEASE; + } + m->obj[e->obj].state = O_OWNED; + m->obj[e->obj].region = e->region; + return OSC_REJ_NONE; + + case OSC_EV_MOVE: + TRY(obj_ref(m, e->obj)); + if (e->obj2) TRY(obj_fresh(m, e->obj2)); + TRY(owner_usable(m, e->obj)); + if (m->obj[e->obj].n_shared || m->obj[e->obj].n_mut) return OSC_REJ_MUTABLE_ALIAS; + m->obj[e->obj].state = O_MOVED; + if (e->obj2) { + m->obj[e->obj2].state = O_OWNED; + m->obj[e->obj2].region = m->obj[e->obj].region; + } + return OSC_REJ_NONE; + + case OSC_EV_BORROW_SHARED: + case OSC_EV_BORROW_MUT: { + int mut = e->kind == OSC_EV_BORROW_MUT; + TRY(obj_ref(m, e->obj)); + TRY(bor_fresh(m, e->borrow)); + TRY(via_ref(m, e->via, e->obj)); + if (e->via == 0) { + const OscMObj *o = &m->obj[e->obj]; + TRY(owner_usable(m, e->obj)); + if (o->n_mut) return OSC_REJ_MUTABLE_ALIAS; + if (mut && o->n_shared) return OSC_REJ_MUTABLE_ALIAS; + } else { + const OscMBorrow *p = &m->bor[e->via]; + if (p->state == B_ENDED) return OSC_REJ_USE_AFTER_RELEASE; + if (mut && !p->mut) return OSC_REJ_FORGED_RIGHTS; + if (p->live_kids_mut) return OSC_REJ_MUTABLE_ALIAS; + if (mut && p->live_kids_shared) return OSC_REJ_MUTABLE_ALIAS; + } + OscMBorrow *b = &m->bor[e->borrow]; + b->state = B_LIVE; + b->mut = (uint8_t)mut; + b->obj = e->obj; + b->parent = e->via; + b->live_kids_shared = b->live_kids_mut = 0; + if (e->via) { + if (mut) m->bor[e->via].live_kids_mut++; else m->bor[e->via].live_kids_shared++; + } else { + if (mut) m->obj[e->obj].n_mut++; else m->obj[e->obj].n_shared++; + } + return OSC_REJ_NONE; + } + + case OSC_EV_END_BORROW: { + TRY(bor_ref(m, e->borrow)); + OscMBorrow *b = &m->bor[e->borrow]; + if (b->state == B_ENDED) return OSC_REJ_DOUBLE_RELEASE; + if (b->live_kids_shared || b->live_kids_mut) return OSC_REJ_BORROW_OUTLIVES_OWNER; + b->state = B_ENDED; + if (b->parent) { + if (b->mut) m->bor[b->parent].live_kids_mut--; else m->bor[b->parent].live_kids_shared--; + } else { + if (b->mut) m->obj[b->obj].n_mut--; else m->obj[b->obj].n_shared--; + } + return OSC_REJ_NONE; + } + + case OSC_EV_USE_READ: + case OSC_EV_USE_WRITE: { + int wr = e->kind == OSC_EV_USE_WRITE; + TRY(obj_ref(m, e->obj)); + TRY(via_ref(m, e->via, e->obj)); + if (e->via == 0) { + if (!wr) return direct_read(m, e->obj); + TRY(owner_usable(m, e->obj)); + if (m->obj[e->obj].n_shared || m->obj[e->obj].n_mut) return OSC_REJ_MUTABLE_ALIAS; + return OSC_REJ_NONE; + } + const OscMBorrow *b = &m->bor[e->via]; + if (b->state == B_ENDED) return OSC_REJ_USE_AFTER_RELEASE; + if (!wr) return b->live_kids_mut ? OSC_REJ_MUTABLE_ALIAS : OSC_REJ_NONE; + if (!b->mut) return OSC_REJ_FORGED_RIGHTS; + if (b->live_kids_shared || b->live_kids_mut) return OSC_REJ_MUTABLE_ALIAS; + return OSC_REJ_NONE; + } + + case OSC_EV_RELEASE: { + TRY(obj_ref(m, e->obj)); + OscMObj *o = &m->obj[e->obj]; + if (o->state == O_MOVED) return OSC_REJ_USE_AFTER_MOVE; + if (o->state == O_RELEASED) return OSC_REJ_DOUBLE_RELEASE; + if (o->n_shared || o->n_mut) return OSC_REJ_BORROW_OUTLIVES_OWNER; + o->state = O_RELEASED; + return OSC_REJ_NONE; + } + + case OSC_EV_REGION_OPEN: + TRY(reg_fresh(m, e->region)); + m->region[e->region] = R_OPEN; + return OSC_REJ_NONE; + + case OSC_EV_REGION_DESTROY: + TRY(reg_ref(m, e->region)); + if (m->region[e->region] == R_DESTROYED) return OSC_REJ_DOUBLE_RELEASE; + for (uint32_t b = 1; b <= OSC_MODEL_MAX_BORROWS; b++) + if (m->bor[b].state == B_LIVE && m->obj[m->bor[b].obj].region == e->region) + return OSC_REJ_ARENA_ESCAPE; + for (uint32_t o = 1; o <= OSC_MODEL_MAX_OBJECTS; o++) + if (m->obj[o].state == O_OWNED && m->obj[o].region == e->region) + m->obj[o].state = O_RELEASED; + m->region[e->region] = R_DESTROYED; + return OSC_REJ_NONE; + + case OSC_EV_SLOT_ALLOC: { + TRY(slot_ref(e->slot)); + if (e->handle) TRY(hnd_fresh(m, e->handle)); + OscMSlot *s = &m->slot[e->slot]; + if (s->state == S_RETIRED) return OSC_REJ_GENERATION_WRAP; + if (s->state == S_LIVE) return OSC_REJ_PROTOCOL; + s->state = S_LIVE; + if (e->handle) { + OscMHandle *h = &m->hnd[e->handle]; + h->used = 1; h->slot = e->slot; h->gen = s->gen; h->rights = e->rights; + } + return OSC_REJ_NONE; + } + + case OSC_EV_SLOT_FREE: { + uint32_t sid; uint64_t g; + if (e->handle) { + TRY(hnd_ref(m, e->handle)); + sid = m->hnd[e->handle].slot; g = m->hnd[e->handle].gen; + } else { + TRY(slot_ref(e->slot)); + sid = e->slot; g = e->gen; + } + OscMSlot *s = &m->slot[sid]; + if (s->state != S_LIVE || s->gen != g) return OSC_REJ_STALE_GENERATION; + if (s->gen == m->gen_max) s->state = S_RETIRED; + else { s->state = S_FREE; s->gen++; } + return OSC_REJ_NONE; + } + + case OSC_EV_HANDLE_DERIVE: { + TRY(hnd_fresh(m, e->handle)); + TRY(hnd_ref(m, e->handle2)); + if (hnd_stale(m, e->handle2)) return OSC_REJ_STALE_GENERATION; + const OscMHandle *p = &m->hnd[e->handle2]; + if (e->rights & ~p->rights) return OSC_REJ_FORGED_RIGHTS; + OscMHandle *h = &m->hnd[e->handle]; + h->used = 1; h->slot = p->slot; h->gen = p->gen; h->rights = e->rights; + return OSC_REJ_NONE; + } + + case OSC_EV_HANDLE_USE: + TRY(hnd_ref(m, e->handle)); + if (hnd_stale(m, e->handle)) return OSC_REJ_STALE_GENERATION; + if (e->rights & ~m->hnd[e->handle].rights) return OSC_REJ_FORGED_RIGHTS; + return OSC_REJ_NONE; + + case OSC_EV_PERSIST: + TRY(hnd_ref(m, e->handle)); + TRY(sem_fresh(m, e->semid)); + if (hnd_stale(m, e->handle)) return OSC_REJ_STALE_GENERATION; + m->semid[e->semid] = 1; + return OSC_REJ_NONE; + + case OSC_EV_DURABLE_WRITE: + switch (e->vkind) { + case OSC_VK_OBJECT: TRY(obj_ref(m, e->id)); return direct_read(m, e->id); + case OSC_VK_SEMID: return sem_ref(m, e->id); + case OSC_VK_HANDLE: TRY(hnd_ref(m, e->id)); return OSC_REJ_LIVE_HANDLE_DURABLE; + case OSC_VK_BORROW: TRY(bor_ref(m, e->id)); return OSC_REJ_LIVE_HANDLE_DURABLE; + default: return OSC_REJ_MALFORMED; + } + + case OSC_EV_CELL_WRITE: + IDCHK(e->cell, OSC_MODEL_MAX_CELLS); + if (m->cell[e->cell].state == C_RECLAIMED) return OSC_REJ_USE_AFTER_RELEASE; + m->cell[e->cell].state = C_WRITTEN; + return OSC_REJ_NONE; + + case OSC_EV_CELL_PUBLISH: + TRY(cell_ref(m, e->cell)); + if (m->cell[e->cell].state == C_RECLAIMED) return OSC_REJ_USE_AFTER_RELEASE; + if (e->order != OSC_ORD_RELEASE) return OSC_REJ_PUBLISH_WITHOUT_RELEASE; + if (m->cell[e->cell].state != C_WRITTEN) return OSC_REJ_PROTOCOL; + m->cell[e->cell].state = C_PUBLISHED; + return OSC_REJ_NONE; + + case OSC_EV_CELL_OBSERVE: + TRY(cell_ref(m, e->cell)); + if (m->cell[e->cell].state == C_RECLAIMED) return OSC_REJ_USE_AFTER_RELEASE; + if (e->order != OSC_ORD_ACQUIRE) return OSC_REJ_READ_BEFORE_OBSERVE; + if (m->cell[e->cell].state != C_PUBLISHED) return OSC_REJ_PROTOCOL; + m->cell[e->cell].state = C_OBSERVED; + return OSC_REJ_NONE; + + case OSC_EV_CELL_READ: + TRY(cell_ref(m, e->cell)); + if (m->cell[e->cell].state == C_RECLAIMED) return OSC_REJ_USE_AFTER_RELEASE; + if (m->cell[e->cell].state != C_OBSERVED) return OSC_REJ_READ_BEFORE_OBSERVE; + return OSC_REJ_NONE; + + case OSC_EV_QUIESCE: + TRY(tok_fresh(m, e->token)); + TRY(cell_ref(m, e->cell)); + if (m->cell[e->cell].state == C_RECLAIMED) return OSC_REJ_USE_AFTER_RELEASE; + if (m->cell[e->cell].state != C_OBSERVED) return OSC_REJ_PROTOCOL; + m->tok[e->token].state = T_LIVE; + m->tok[e->token].cell = e->cell; + return OSC_REJ_NONE; + + case OSC_EV_RECLAIM: + TRY(cell_ref(m, e->cell)); + if (e->token) TRY(tok_ref(m, e->token)); + if (m->cell[e->cell].state == C_RECLAIMED) return OSC_REJ_DOUBLE_RELEASE; + if (e->token == 0 || m->tok[e->token].state != T_LIVE || m->tok[e->token].cell != e->cell) + return OSC_REJ_RECLAIM_WITHOUT_QUIESCED; + m->cell[e->cell].state = C_RECLAIMED; + m->tok[e->token].state = T_CONSUMED; + return OSC_REJ_NONE; + + default: + return OSC_REJ_PROTOCOL; + } +} + +OscModelVerdict osc_model_step(OscModel *m, const OscModelEvent *ev, OscModelReject *out_reject) +{ + OscModelReject r = step(m, ev); + if (out_reject) *out_reject = r; + if (r == OSC_REJ_NONE) { m->accepted++; return OSC_MODEL_ACCEPT; } + m->rejected++; + return OSC_MODEL_REJECT; +} diff --git a/src/compiler/model/osc_model.h b/src/compiler/model/osc_model.h new file mode 100644 index 000000000..25deec245 --- /dev/null +++ b/src/compiler/model/osc_model.h @@ -0,0 +1,213 @@ +/* + * osc_model.h -- OSC-0B exit gate: the II.11 executable reference model of the + * Omega Systems Core memory rules (OMEGA_SYSTEMS_CORE_CODE_AUDIT.md II.11). + * + * A deterministic state machine over objects, borrows, regions, pool slots + * with u64 generations, live handles with rights, device cells (publication), + * Quiesced tokens and SemanticIds. It is a reference oracle, not compiler + * code. Fixed capacity, no malloc, no globals, no I/O. + * + * ---------------------------------------------------------------- EVENT API + * Fill an OscModelEvent (zero it first; unused fields stay 0) and call + * osc_model_step(). All ids are small integers 1..CAP; 0 means "none". An id + * is created exactly once (single assignment); re-creating a used id, or + * naming an id never created, is OSC_REJ_MALFORMED; an id > CAP is + * OSC_REJ_CAPACITY. A rejected event leaves the model state unchanged. + * + * The OSC-1 front-end subset (OSC-1-DESIGN 3.1): + * OSC_EV_ALLOC obj, region (0 = unique own, else an open region) + * OSC_EV_MOVE obj -> obj2 (fresh new owner id) or obj2 = 0 (consumed, + * e.g. passed to an own parameter) + * OSC_EV_BORROW_SHARED obj, borrow (fresh), via (0 = borrow the owner + * directly, else reborrow through live borrow `via`) + * OSC_EV_BORROW_MUT obj, borrow (fresh), via (as above; `&mut r` = via r) + * OSC_EV_END_BORROW borrow (borrow binding leaves scope / call returns) + * OSC_EV_USE_READ obj, via (0 = direct use of the owner) + * OSC_EV_USE_WRITE obj, via (0 = direct store into the owner) + * OSC_EV_RELEASE obj (scope-end destruction of an unmoved owner) + * OSC_EV_REGION_OPEN / OSC_EV_REGION_DESTROY region + * Further events (runtime, handles, publication): + * OSC_EV_SLOT_ALLOC slot, handle (fresh, or 0 = mint none), rights + * OSC_EV_SLOT_FREE handle; or handle = 0 with explicit slot + gen + * OSC_EV_HANDLE_DERIVE handle (fresh) from handle2 (parent), rights + * OSC_EV_HANDLE_USE handle, rights (the rights the use needs) + * OSC_EV_PERSIST handle -> semid (fresh SemanticId; resolves live object) + * OSC_EV_DURABLE_WRITE vkind (OSC_VK_*), id: write a value to a durable encoder + * OSC_EV_CELL_WRITE cell (first write creates the cell; starts a round) + * OSC_EV_CELL_PUBLISH cell, order (must be OSC_ORD_RELEASE) + * OSC_EV_CELL_OBSERVE cell, order (must be OSC_ORD_ACQUIRE) + * OSC_EV_CELL_READ cell (consumer reads device data) + * OSC_EV_QUIESCE token (fresh own), cell (must be observed) + * OSC_EV_RECLAIM cell, token (0 = no token); consumes the token + * + * ------------------------------------------------- CLASSIFICATION CHOICES + * Checks run in a fixed order: id range (CAPACITY), id existence/freshness + * (MALFORMED), then the rules below in the order listed per event in + * osc_model.c. Choices where the II.11 list leaves room: + * - Moving, or storing directly into, an owner while any borrow of it is live, + * reading it directly while a &mut is live, a second &mut, & with &mut, a + * &mut reborrow while the parent already has a live child, and using a &mut + * parent while its &mut child is live: MUTABLE_ALIAS (OSC-1-DESIGN 3.1). + * - Releasing an owner while a borrow of it is live, or ending a borrow while + * a reborrow of it is live: BORROW_OUTLIVES_OWNER. + * - Destroying a region while a borrow of an object in it is live: + * ARENA_ESCAPE (the reference outlives its region). + * - Writing through a shared borrow, or taking &mut through a shared borrow: + * FORGED_RIGHTS (a shared borrow carries read rights only; II.12 + * "mutability is authority"). The compiler's READ_ONLY_BORROW maps here. + * - Any use of a MOVED object (including release): USE_AFTER_MOVE. + * - Use of a RELEASED object, of an ended borrow, of a reclaimed cell, or an + * alloc into a destroyed region: USE_AFTER_RELEASE. + * - Second release of an object / end of a borrow / destroy of a region / + * reclaim of a cell: DOUBLE_RELEASE. + * - Any handle (or explicit slot+gen) whose generation is not the slot's live + * generation, including a second SLOT_FREE and use after retirement: + * STALE_GENERATION. Stale is checked before rights. + * - SLOT_ALLOC of a retired slot: GENERATION_WRAP. A slot whose generation + * equals gen_max is retired on free, never wrapped (OSC-0 decision 1). + * - DURABLE_WRITE of a handle or a borrow (any non-durable live reference): + * LIVE_HANDLE_DURABLE, regardless of the reference's liveness. + * - CELL_OBSERVE with a non-acquire order, CELL_READ before an acquire + * observe of the current round: READ_BEFORE_OBSERVE. + * - CELL_PUBLISH with a non-release order: PUBLISH_WITHOUT_RELEASE (checked + * before the cell's state). + * - RECLAIM with no token, a consumed token, or a token for another cell: + * RECLAIM_WITHOUT_QUIESCED. + * - Out-of-protocol transitions outside the II.11 list (publish of an + * unwritten cell, observe of an unpublished cell, QUIESCE of an unobserved + * cell, SLOT_ALLOC of a live slot, unknown event kind): OSC_REJ_PROTOCOL. + */ +#ifndef OSC_MODEL_H +#define OSC_MODEL_H + +#include + +#define OSC_MODEL_MAX_OBJECTS 64 +#define OSC_MODEL_MAX_BORROWS 64 +#define OSC_MODEL_MAX_REGIONS 16 +#define OSC_MODEL_MAX_SLOTS 16 +#define OSC_MODEL_MAX_HANDLES 64 +#define OSC_MODEL_MAX_CELLS 16 +#define OSC_MODEL_MAX_TOKENS 32 +#define OSC_MODEL_MAX_SEMIDS 32 + +typedef enum { + OSC_EV_ALLOC = 1, + OSC_EV_MOVE, + OSC_EV_BORROW_SHARED, + OSC_EV_BORROW_MUT, + OSC_EV_END_BORROW, + OSC_EV_USE_READ, + OSC_EV_USE_WRITE, + OSC_EV_RELEASE, + OSC_EV_REGION_OPEN, + OSC_EV_REGION_DESTROY, + OSC_EV_SLOT_ALLOC, + OSC_EV_SLOT_FREE, + OSC_EV_HANDLE_DERIVE, + OSC_EV_HANDLE_USE, + OSC_EV_PERSIST, + OSC_EV_DURABLE_WRITE, + OSC_EV_CELL_WRITE, + OSC_EV_CELL_PUBLISH, + OSC_EV_CELL_OBSERVE, + OSC_EV_CELL_READ, + OSC_EV_QUIESCE, + OSC_EV_RECLAIM, + OSC_EV__COUNT +} OscModelEventKind; + +/* Memory order on publication events. */ +typedef enum { OSC_ORD_RELAXED = 0, OSC_ORD_RELEASE = 1, OSC_ORD_ACQUIRE = 2 } OscModelOrder; + +/* Kind of value handed to a durable encoder (OSC_EV_DURABLE_WRITE). */ +typedef enum { + OSC_VK_OBJECT = 1, /* plain value read from an owner: durable */ + OSC_VK_SEMID, /* SemanticId from OSC_EV_PERSIST: durable */ + OSC_VK_HANDLE, /* live Handle: non-durable */ + OSC_VK_BORROW /* &T / &mut T: non-durable */ +} OscModelValueKind; + +typedef struct { + uint32_t kind; /* OscModelEventKind */ + uint32_t obj; /* object id */ + uint32_t obj2; /* MOVE destination (0 = consumed) */ + uint32_t borrow; /* borrow id (created by BORROW_*, named by END_BORROW) */ + uint32_t via; /* borrow used for access / reborrow parent; 0 = direct */ + uint32_t region; /* region id */ + uint32_t slot; /* pool slot id */ + uint32_t handle; /* handle id */ + uint32_t handle2; /* parent handle for HANDLE_DERIVE */ + uint32_t cell; /* device cell id */ + uint32_t token; /* Quiesced token id */ + uint32_t semid; /* SemanticId id */ + uint32_t order; /* OscModelOrder */ + uint32_t vkind; /* OscModelValueKind for DURABLE_WRITE */ + uint32_t id; /* value id for DURABLE_WRITE (obj/semid/handle/borrow) */ + uint64_t gen; /* explicit generation (SLOT_FREE with handle = 0) */ + uint64_t rights; /* rights mask */ +} OscModelEvent; + +/* Verdict. 1..13 map 1:1 to the II.11 named invalid transitions, in order. */ +typedef enum { + OSC_REJ_NONE = 0, /* accepted */ + OSC_REJ_USE_AFTER_MOVE = 1, + OSC_REJ_USE_AFTER_RELEASE, + OSC_REJ_DOUBLE_RELEASE, + OSC_REJ_STALE_GENERATION, + OSC_REJ_GENERATION_WRAP, + OSC_REJ_MUTABLE_ALIAS, + OSC_REJ_BORROW_OUTLIVES_OWNER, + OSC_REJ_ARENA_ESCAPE, + OSC_REJ_RECLAIM_WITHOUT_QUIESCED, + OSC_REJ_READ_BEFORE_OBSERVE, + OSC_REJ_PUBLISH_WITHOUT_RELEASE, + OSC_REJ_FORGED_RIGHTS, + OSC_REJ_LIVE_HANDLE_DURABLE, /* = 13 */ + OSC_REJ_MALFORMED, /* id never created / reused / bad field */ + OSC_REJ_CAPACITY, /* id beyond a fixed capacity */ + OSC_REJ_PROTOCOL, /* out-of-protocol, not in the II.11 list */ + OSC_REJ__COUNT +} OscModelReject; + +#define OSC_MODEL_NAMED_COUNT 13 + +typedef enum { OSC_MODEL_ACCEPT = 0, OSC_MODEL_REJECT = 1 } OscModelVerdict; + +typedef struct { uint8_t state, n_mut; uint16_t n_shared; uint32_t region; } OscMObj; +typedef struct { uint8_t state, mut; uint16_t live_kids_shared, live_kids_mut; uint32_t obj, parent; } OscMBorrow; +typedef struct { uint8_t state; uint64_t gen; } OscMSlot; +typedef struct { uint8_t used; uint32_t slot; uint64_t gen, rights; } OscMHandle; +typedef struct { uint8_t state; } OscMCell; +typedef struct { uint8_t state; uint32_t cell; } OscMToken; + +typedef struct { + uint64_t gen_base, gen_max; + OscMObj obj[OSC_MODEL_MAX_OBJECTS + 1]; + OscMBorrow bor[OSC_MODEL_MAX_BORROWS + 1]; + uint8_t region[OSC_MODEL_MAX_REGIONS + 1]; + OscMSlot slot[OSC_MODEL_MAX_SLOTS + 1]; + OscMHandle hnd[OSC_MODEL_MAX_HANDLES + 1]; + OscMCell cell[OSC_MODEL_MAX_CELLS + 1]; + OscMToken tok[OSC_MODEL_MAX_TOKENS + 1]; + uint8_t semid[OSC_MODEL_MAX_SEMIDS + 1]; + uint64_t accepted, rejected; +} OscModel; + +/* Every slot starts free(gen_base); a slot freed at generation gen_max is + * retired. Production: gen_base = 0, gen_max = UINT64_MAX. Tests use small + * gen_max (or gen_base near UINT64_MAX) so the retire/wrap path is reachable. + * gen_base > gen_max is clamped to gen_max. */ +void osc_model_init(OscModel *m, uint64_t gen_base, uint64_t gen_max); + +/* Apply one event. Returns OSC_MODEL_ACCEPT (and *out_reject = OSC_REJ_NONE) + * or OSC_MODEL_REJECT with the typed reason; on reject the state is + * unchanged. out_reject may be NULL. Deterministic. */ +OscModelVerdict osc_model_step(OscModel *m, const OscModelEvent *ev, OscModelReject *out_reject); + +/* "use-after-move", ..., "malformed", "capacity", "protocol"; "accept" for 0; + * "?" for out-of-range. */ +const char *osc_model_reject_name(OscModelReject r); +const char *osc_model_event_name(uint32_t kind); + +#endif diff --git a/src/compiler/model/osc_model_gen.c b/src/compiler/model/osc_model_gen.c new file mode 100644 index 000000000..577b17583 --- /dev/null +++ b/src/compiler/model/osc_model_gen.c @@ -0,0 +1,778 @@ +/* + * osc_model_gen.c -- seeded generator of valid and single-fault sequences for + * the II.11 model. The shadow state here is written independently of + * osc_model.c: it only ever has to apply VALID events, and it decides + * validity with its own predicates. See osc_model_gen.h. + */ +#include "osc_model_gen.h" + +#include + +#define NO OSC_MODEL_MAX_OBJECTS +#define NB OSC_MODEL_MAX_BORROWS +#define NR OSC_MODEL_MAX_REGIONS +#define NS OSC_MODEL_MAX_SLOTS +#define NH OSC_MODEL_MAX_HANDLES +#define NC OSC_MODEL_MAX_CELLS +#define NT OSC_MODEL_MAX_TOKENS +#define NM OSC_MODEL_MAX_SEMIDS + +#define RESERVE 6 /* fresh ids kept back from valid steps for injection setup */ + +/* shadow states */ +enum { OB_NONE, OB_OWN, OB_MOVED, OB_REL }; +enum { BR_NONE, BR_LIVE, BR_END }; +enum { RG_NONE, RG_OPEN, RG_DEAD }; +enum { SL_FREE, SL_LIVE, SL_RET }; +enum { CE_NONE, CE_WR, CE_PUB, CE_OBS, CE_GONE }; +enum { TK_NONE, TK_LIVE, TK_USED }; + +typedef struct { + OscGenSeq *q; + uint64_t rng, gmax; + uint8_t ost[NO + 1]; uint32_t oreg[NO + 1]; int osh[NO + 1], omu[NO + 1]; uint32_t nobj; + uint8_t bst[NB + 1], bmut[NB + 1]; uint32_t bobj[NB + 1], bpar[NB + 1]; + int bksh[NB + 1], bkmu[NB + 1]; uint32_t nbor; + uint8_t rst[NR + 1]; uint32_t nreg; + uint8_t sst[NS + 1]; uint64_t sgen[NS + 1]; + uint8_t hused[NH + 1]; uint32_t hslot[NH + 1]; uint64_t hgen[NH + 1], hrig[NH + 1]; uint32_t nhnd; + uint8_t cst[NC + 1]; uint32_t ncell; + uint8_t tst[NT + 1]; uint32_t tcell[NT + 1]; uint32_t ntok; + uint32_t nsem; +} Sh; + +uint64_t osc_gen_splitmix64(uint64_t *s) +{ + uint64_t z = (*s += 0x9E3779B97F4A7C15ull); + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBull; + return z ^ (z >> 31); +} + +static uint32_t rnd(Sh *s, uint32_t n) { return n ? (uint32_t)(osc_gen_splitmix64(&s->rng) % n) : 0; } + +/* fresh id = count + 1 when within cap - reserve, else 0 */ +static uint32_t fresh(uint32_t used, uint32_t cap, uint32_t reserve) +{ + return used + 1 + reserve <= cap ? used + 1 : 0; +} + +/* ---- shadow predicates (independent of osc_model.c) ---- */ +static int obj_free_of_borrows(const Sh *s, uint32_t x) { return s->ost[x] == OB_OWN && !s->osh[x] && !s->omu[x]; } +static int obj_readable(const Sh *s, uint32_t x) { return s->ost[x] == OB_OWN && !s->omu[x]; } +static int bor_live(const Sh *s, uint32_t b) { return s->bst[b] == BR_LIVE; } +static int bor_leaf(const Sh *s, uint32_t b) { return bor_live(s, b) && !s->bksh[b] && !s->bkmu[b]; } +static int hnd_valid(const Sh *s, uint32_t h) +{ + return s->hused[h] && s->sst[s->hslot[h]] == SL_LIVE && s->sgen[s->hslot[h]] == s->hgen[h]; +} +static int region_destroyable(const Sh *s, uint32_t r) +{ + if (s->rst[r] != RG_OPEN) return 0; + for (uint32_t b = 1; b <= s->nbor; b++) + if (bor_live(s, b) && s->oreg[s->bobj[b]] == r) return 0; + return 1; +} + +/* pick a random id in 1..n satisfying pred, 0 if none */ +#define PICK(s, n, cond) ({ uint32_t c_[256]; uint32_t k_ = 0; \ + for (uint32_t i_ = 1; i_ <= (n); i_++) { uint32_t id = i_; if (cond) c_[k_++] = id; } \ + k_ ? c_[rnd((s), k_)] : 0u; }) + +/* ---- shadow apply: valid events only ---- */ +static void sh_apply(Sh *s, const OscModelEvent *e) +{ + switch (e->kind) { + case OSC_EV_ALLOC: + s->ost[e->obj] = OB_OWN; s->oreg[e->obj] = e->region; + if (e->obj > s->nobj) s->nobj = e->obj; + break; + case OSC_EV_MOVE: + s->ost[e->obj] = OB_MOVED; + if (e->obj2) { + s->ost[e->obj2] = OB_OWN; s->oreg[e->obj2] = s->oreg[e->obj]; + if (e->obj2 > s->nobj) s->nobj = e->obj2; + } + break; + case OSC_EV_BORROW_SHARED: + case OSC_EV_BORROW_MUT: { + int mut = e->kind == OSC_EV_BORROW_MUT; + s->bst[e->borrow] = BR_LIVE; s->bmut[e->borrow] = (uint8_t)mut; + s->bobj[e->borrow] = e->obj; s->bpar[e->borrow] = e->via; + s->bksh[e->borrow] = s->bkmu[e->borrow] = 0; + if (e->via) { if (mut) s->bkmu[e->via]++; else s->bksh[e->via]++; } + else { if (mut) s->omu[e->obj]++; else s->osh[e->obj]++; } + if (e->borrow > s->nbor) s->nbor = e->borrow; + break; + } + case OSC_EV_END_BORROW: { + uint32_t b = e->borrow, p = s->bpar[b]; + s->bst[b] = BR_END; + if (p) { if (s->bmut[b]) s->bkmu[p]--; else s->bksh[p]--; } + else { if (s->bmut[b]) s->omu[s->bobj[b]]--; else s->osh[s->bobj[b]]--; } + break; + } + case OSC_EV_RELEASE: s->ost[e->obj] = OB_REL; break; + case OSC_EV_REGION_OPEN: + s->rst[e->region] = RG_OPEN; + if (e->region > s->nreg) s->nreg = e->region; + break; + case OSC_EV_REGION_DESTROY: + for (uint32_t x = 1; x <= s->nobj; x++) + if (s->ost[x] == OB_OWN && s->oreg[x] == e->region) s->ost[x] = OB_REL; + s->rst[e->region] = RG_DEAD; + break; + case OSC_EV_SLOT_ALLOC: + s->sst[e->slot] = SL_LIVE; + if (e->handle) { + s->hused[e->handle] = 1; s->hslot[e->handle] = e->slot; + s->hgen[e->handle] = s->sgen[e->slot]; s->hrig[e->handle] = e->rights; + if (e->handle > s->nhnd) s->nhnd = e->handle; + } + break; + case OSC_EV_SLOT_FREE: { + uint32_t sl = s->hslot[e->handle]; + if (s->sgen[sl] == s->gmax) s->sst[sl] = SL_RET; + else { s->sst[sl] = SL_FREE; s->sgen[sl] += 1; } + break; + } + case OSC_EV_HANDLE_DERIVE: + s->hused[e->handle] = 1; s->hslot[e->handle] = s->hslot[e->handle2]; + s->hgen[e->handle] = s->hgen[e->handle2]; s->hrig[e->handle] = e->rights; + if (e->handle > s->nhnd) s->nhnd = e->handle; + break; + case OSC_EV_PERSIST: if (e->semid > s->nsem) s->nsem = e->semid; break; + case OSC_EV_CELL_WRITE: + s->cst[e->cell] = CE_WR; + if (e->cell > s->ncell) s->ncell = e->cell; + break; + case OSC_EV_CELL_PUBLISH: s->cst[e->cell] = CE_PUB; break; + case OSC_EV_CELL_OBSERVE: s->cst[e->cell] = CE_OBS; break; + case OSC_EV_QUIESCE: + s->tst[e->token] = TK_LIVE; s->tcell[e->token] = e->cell; + if (e->token > s->ntok) s->ntok = e->token; + break; + case OSC_EV_RECLAIM: s->cst[e->cell] = CE_GONE; s->tst[e->token] = TK_USED; break; + default: break; /* reads/uses/durable writes do not change shadow state */ + } +} + +static int emit(Sh *s, const OscModelEvent *e) +{ + if (s->q->n >= OSC_GEN_MAX_EVENTS - 1) return -1; + s->q->ev[s->q->n++] = *e; + sh_apply(s, e); + return 0; +} + +static OscModelEvent ev0(uint32_t kind) { OscModelEvent e; memset(&e, 0, sizeof e); e.kind = kind; return e; } + +/* ---- valid step construction ---- */ +#define N_ACTIONS 26 + +static int build_valid(Sh *s, int a, uint32_t reserve, OscModelEvent *e) +{ + uint32_t x, b, r, h, c, t, f; + switch (a) { + case 0: + if (!(f = fresh(s->nobj, NO, reserve))) return 0; + *e = ev0(OSC_EV_ALLOC); e->obj = f; + if (rnd(s, 2)) e->region = PICK(s, s->nreg, s->rst[id] == RG_OPEN); + return 1; + case 1: + if (!(f = fresh(s->nreg, NR, reserve))) return 0; + *e = ev0(OSC_EV_REGION_OPEN); e->region = f; return 1; + case 2: + if (!(x = PICK(s, s->nobj, obj_free_of_borrows(s, id)))) return 0; + *e = ev0(OSC_EV_MOVE); e->obj = x; + if (rnd(s, 4)) e->obj2 = fresh(s->nobj, NO, reserve); + return 1; + case 3: + if (!(x = PICK(s, s->nobj, obj_readable(s, id))) || !(f = fresh(s->nbor, NB, reserve))) return 0; + *e = ev0(OSC_EV_BORROW_SHARED); e->obj = x; e->borrow = f; return 1; + case 4: + if (!(b = PICK(s, s->nbor, bor_live(s, id) && !s->bkmu[id])) || !(f = fresh(s->nbor, NB, reserve))) return 0; + *e = ev0(OSC_EV_BORROW_SHARED); e->obj = s->bobj[b]; e->borrow = f; e->via = b; return 1; + case 5: + if (!(x = PICK(s, s->nobj, obj_free_of_borrows(s, id))) || !(f = fresh(s->nbor, NB, reserve))) return 0; + *e = ev0(OSC_EV_BORROW_MUT); e->obj = x; e->borrow = f; return 1; + case 6: + if (!(b = PICK(s, s->nbor, bor_leaf(s, id) && s->bmut[id])) || !(f = fresh(s->nbor, NB, reserve))) return 0; + *e = ev0(OSC_EV_BORROW_MUT); e->obj = s->bobj[b]; e->borrow = f; e->via = b; return 1; + case 7: + if (!(b = PICK(s, s->nbor, bor_leaf(s, id)))) return 0; + *e = ev0(OSC_EV_END_BORROW); e->borrow = b; return 1; + case 8: + if (!(x = PICK(s, s->nobj, obj_readable(s, id)))) return 0; + *e = ev0(OSC_EV_USE_READ); e->obj = x; return 1; + case 9: + if (!(b = PICK(s, s->nbor, bor_live(s, id) && !s->bkmu[id]))) return 0; + *e = ev0(OSC_EV_USE_READ); e->obj = s->bobj[b]; e->via = b; return 1; + case 10: + if (!(x = PICK(s, s->nobj, obj_free_of_borrows(s, id)))) return 0; + *e = ev0(OSC_EV_USE_WRITE); e->obj = x; return 1; + case 11: + if (!(b = PICK(s, s->nbor, bor_leaf(s, id) && s->bmut[id]))) return 0; + *e = ev0(OSC_EV_USE_WRITE); e->obj = s->bobj[b]; e->via = b; return 1; + case 12: + if (!(x = PICK(s, s->nobj, obj_free_of_borrows(s, id)))) return 0; + *e = ev0(OSC_EV_RELEASE); e->obj = x; return 1; + case 13: + if (!(r = PICK(s, s->nreg, region_destroyable(s, id)))) return 0; + *e = ev0(OSC_EV_REGION_DESTROY); e->region = r; return 1; + case 14: + if (!(r = PICK(s, NS, s->sst[id] == SL_FREE)) || !(f = fresh(s->nhnd, NH, reserve))) return 0; + *e = ev0(OSC_EV_SLOT_ALLOC); e->slot = r; e->handle = f; e->rights = rnd(s, 256); return 1; + case 15: + if (!(h = PICK(s, s->nhnd, hnd_valid(s, id)))) return 0; + *e = ev0(OSC_EV_SLOT_FREE); e->handle = h; return 1; + case 16: + if (!(h = PICK(s, s->nhnd, hnd_valid(s, id))) || !(f = fresh(s->nhnd, NH, reserve))) return 0; + *e = ev0(OSC_EV_HANDLE_DERIVE); e->handle = f; e->handle2 = h; e->rights = s->hrig[h] & rnd(s, 256); return 1; + case 17: + if (!(h = PICK(s, s->nhnd, hnd_valid(s, id)))) return 0; + *e = ev0(OSC_EV_HANDLE_USE); e->handle = h; e->rights = s->hrig[h] & rnd(s, 256); return 1; + case 18: + if (!(h = PICK(s, s->nhnd, hnd_valid(s, id))) || !(f = fresh(s->nsem, NM, reserve))) return 0; + *e = ev0(OSC_EV_PERSIST); e->handle = h; e->semid = f; return 1; + case 19: + *e = ev0(OSC_EV_DURABLE_WRITE); + if (rnd(s, 2) && s->nsem) { e->vkind = OSC_VK_SEMID; e->id = 1 + rnd(s, s->nsem); return 1; } + if (!(x = PICK(s, s->nobj, obj_readable(s, id)))) return 0; + e->vkind = OSC_VK_OBJECT; e->id = x; return 1; + case 20: + c = rnd(s, 3) ? PICK(s, s->ncell, s->cst[id] != CE_GONE) : 0; + if (!c && !(c = fresh(s->ncell, NC, reserve))) return 0; + *e = ev0(OSC_EV_CELL_WRITE); e->cell = c; return 1; + case 21: + if (!(c = PICK(s, s->ncell, s->cst[id] == CE_WR))) return 0; + *e = ev0(OSC_EV_CELL_PUBLISH); e->cell = c; e->order = OSC_ORD_RELEASE; return 1; + case 22: + if (!(c = PICK(s, s->ncell, s->cst[id] == CE_PUB))) return 0; + *e = ev0(OSC_EV_CELL_OBSERVE); e->cell = c; e->order = OSC_ORD_ACQUIRE; return 1; + case 23: + if (!(c = PICK(s, s->ncell, s->cst[id] == CE_OBS))) return 0; + *e = ev0(OSC_EV_CELL_READ); e->cell = c; return 1; + case 24: + if (!(c = PICK(s, s->ncell, s->cst[id] == CE_OBS)) || !(f = fresh(s->ntok, NT, reserve))) return 0; + *e = ev0(OSC_EV_QUIESCE); e->cell = c; e->token = f; return 1; + case 25: + if (!(t = PICK(s, s->ntok, s->tst[id] == TK_LIVE && s->cst[s->tcell[id]] != CE_GONE))) return 0; + *e = ev0(OSC_EV_RECLAIM); e->cell = s->tcell[t]; e->token = t; return 1; + } + return 0; +} + +/* one random valid step; 0 = emitted, 1 = nothing possible, -1 = full */ +static int valid_step(Sh *s) +{ + OscModelEvent e; + for (int tries = 0; tries < 16; tries++) + if (build_valid(s, (int)rnd(s, N_ACTIONS), RESERVE, &e)) return emit(s, &e); + for (int a = 0; a < N_ACTIONS; a++) + if (build_valid(s, a, RESERVE, &e)) return emit(s, &e); + return 1; +} + +/* Valid teardown: end borrows leaf first, release / consume owners, destroy + * regions, free live slots, drain and reclaim observed cells. */ +static int teardown(Sh *s) +{ + OscModelEvent e; + for (;;) { + uint32_t b = PICK(s, s->nbor, bor_leaf(s, id)); + if (!b) break; + e = ev0(OSC_EV_END_BORROW); e.borrow = b; + if (emit(s, &e)) return -1; + } + for (uint32_t x = s->nobj; x >= 1; x--) { + if (s->ost[x] != OB_OWN || (s->oreg[x] && rnd(s, 2))) continue; + e = ev0(rnd(s, 5) ? OSC_EV_RELEASE : OSC_EV_MOVE); e.obj = x; + if (emit(s, &e)) return -1; + } + for (uint32_t r = 1; r <= s->nreg; r++) { + if (s->rst[r] != RG_OPEN) continue; + e = ev0(OSC_EV_REGION_DESTROY); e.region = r; + if (emit(s, &e)) return -1; + } + for (uint32_t h = 1; h <= s->nhnd; h++) { + if (!hnd_valid(s, h)) continue; + e = ev0(OSC_EV_SLOT_FREE); e.handle = h; + if (emit(s, &e)) return -1; + } + for (uint32_t c = 1; c <= s->ncell; c++) { + if (s->cst[c] != CE_OBS) continue; + uint32_t t = fresh(s->ntok, NT, 0); + if (!t) break; + e = ev0(OSC_EV_QUIESCE); e.cell = c; e.token = t; + if (emit(s, &e)) return -1; + e = ev0(OSC_EV_RECLAIM); e.cell = c; e.token = t; + if (emit(s, &e)) return -1; + } + return 0; +} + +/* ---- injection setup helpers (valid events, may use the reserve) ---- */ +#define EMIT(ev) do { if (emit(s, &(ev))) return -1; } while (0) + +static uint32_t new_obj(Sh *s, uint32_t region) +{ + uint32_t x = fresh(s->nobj, NO, 0); + if (!x) return 0; + OscModelEvent e = ev0(OSC_EV_ALLOC); e.obj = x; e.region = region; + return emit(s, &e) ? 0 : x; +} + +static uint32_t new_borrow(Sh *s, uint32_t x, uint32_t via, int mut) +{ + uint32_t b = fresh(s->nbor, NB, 0); + if (!b) return 0; + OscModelEvent e = ev0(mut ? OSC_EV_BORROW_MUT : OSC_EV_BORROW_SHARED); + e.obj = x; e.borrow = b; e.via = via; + return emit(s, &e) ? 0 : b; +} + +/* an owned object that has a live root borrow of the given kind + * (want: 0 = shared, 1 = mut, 2 = any); creates one if none exists */ +static uint32_t obj_with_root_borrow(Sh *s, int want) +{ + uint32_t x = PICK(s, s->nobj, s->ost[id] == OB_OWN && + (want == 0 ? s->osh[id] > 0 : want == 1 ? s->omu[id] > 0 : (s->osh[id] + s->omu[id]) > 0)); + if (x && rnd(s, 4)) return x; + int mut = want == 2 ? (int)rnd(s, 2) : want; + x = mut ? PICK(s, s->nobj, obj_free_of_borrows(s, id)) : PICK(s, s->nobj, obj_readable(s, id)); + if (!x || !rnd(s, 2)) x = new_obj(s, 0); + if (!x || !new_borrow(s, x, 0, mut)) return 0; + return x; +} + +/* a live mut borrow with a live child of the given kind (mut_kid) */ +static uint32_t mut_borrow_with_kid(Sh *s, int mut_kid) +{ + uint32_t p = PICK(s, s->nbor, bor_live(s, id) && s->bmut[id] && (mut_kid ? s->bkmu[id] > 0 : s->bksh[id] > 0)); + if (p && rnd(s, 4)) return p; + p = PICK(s, s->nbor, bor_leaf(s, id) && s->bmut[id]); + if (!p || !rnd(s, 2)) { + uint32_t x = new_obj(s, 0); + if (!x || !(p = new_borrow(s, x, 0, 1))) return 0; + } + if (!new_borrow(s, s->bobj[p], p, mut_kid)) return 0; + return p; +} + +static uint32_t valid_handle(Sh *s) +{ + uint32_t h = PICK(s, s->nhnd, hnd_valid(s, id)); + if (h) return h; + uint32_t sl = PICK(s, NS, s->sst[id] == SL_FREE), f = fresh(s->nhnd, NH, 0); + if (!sl || !f) return 0; + OscModelEvent e = ev0(OSC_EV_SLOT_ALLOC); e.slot = sl; e.handle = f; e.rights = rnd(s, 256); + return emit(s, &e) ? 0 : f; +} + +static uint32_t stale_handle(Sh *s) +{ + uint32_t h = PICK(s, s->nhnd, s->hused[id] && !hnd_valid(s, id)); + if (h && rnd(s, 4)) return h; + h = valid_handle(s); + if (!h) return PICK(s, s->nhnd, s->hused[id] && !hnd_valid(s, id)); + OscModelEvent e = ev0(OSC_EV_SLOT_FREE); e.handle = h; + if (emit(s, &e)) return 0; + return h; +} + +/* an existing, not reclaimed cell in the requested state set (bitmask over + * CE_*), created and advanced if none */ +static uint32_t cell_in(Sh *s, unsigned states) +{ + uint32_t c = PICK(s, s->ncell, (states >> s->cst[id]) & 1u); + if (c && rnd(s, 4)) return c; + if (!(c = fresh(s->ncell, NC, 0))) return PICK(s, s->ncell, (states >> s->cst[id]) & 1u); + OscModelEvent e = ev0(OSC_EV_CELL_WRITE); e.cell = c; + if (emit(s, &e)) return 0; + /* advance to a random allowed state */ + int target; + do target = CE_WR + (int)rnd(s, 3); while (!((states >> target) & 1u)); + if (target >= CE_PUB) { e = ev0(OSC_EV_CELL_PUBLISH); e.cell = c; e.order = OSC_ORD_RELEASE; if (emit(s, &e)) return 0; } + if (target >= CE_OBS) { e = ev0(OSC_EV_CELL_OBSERVE); e.cell = c; e.order = OSC_ORD_ACQUIRE; if (emit(s, &e)) return 0; } + return c; +} + +/* a cell that has been reclaimed (creates + drains + reclaims a fresh one) */ +static uint32_t reclaimed_cell(Sh *s) +{ + uint32_t c = PICK(s, s->ncell, s->cst[id] == CE_GONE); + if (c && rnd(s, 2)) return c; + uint32_t t = fresh(s->ntok, NT, 0); + if (!t || !(c = cell_in(s, 1u << CE_OBS))) return PICK(s, s->ncell, s->cst[id] == CE_GONE); + OscModelEvent e = ev0(OSC_EV_QUIESCE); e.cell = c; e.token = t; + if (emit(s, &e)) return 0; + e = ev0(OSC_EV_RECLAIM); e.cell = c; e.token = t; + if (emit(s, &e)) return 0; + return c; +} + +/* Build the single invalid event of class k. Setup events are emitted as + * valid steps. Returns 0 and fills *bad, or -1. */ +static int build_bad(Sh *s, OscModelReject k, OscModelEvent *bad) +{ + OscModelEvent e; + uint32_t x, b, r, h, c, t, v; + switch (k) { + case OSC_REJ_USE_AFTER_MOVE: + x = PICK(s, s->nobj, s->ost[id] == OB_MOVED); + if (!x || !rnd(s, 3)) { + x = PICK(s, s->nobj, obj_free_of_borrows(s, id)); + if (!x) x = new_obj(s, 0); + if (!x) return -1; + e = ev0(OSC_EV_MOVE); e.obj = x; e.obj2 = rnd(s, 2) ? fresh(s->nobj, NO, 0) : 0; EMIT(e); + } + v = rnd(s, 7); s->q->variant = (int)v; + static const uint32_t uam_k[7] = { OSC_EV_USE_READ, OSC_EV_USE_WRITE, OSC_EV_BORROW_SHARED, + OSC_EV_BORROW_MUT, OSC_EV_MOVE, OSC_EV_RELEASE, OSC_EV_DURABLE_WRITE }; + *bad = ev0(uam_k[v]); bad->obj = x; + if (v == 2 || v == 3) bad->borrow = fresh(s->nbor, NB, 0); + if (v == 4) bad->obj2 = rnd(s, 2) ? fresh(s->nobj, NO, 0) : 0; + if (v == 6) { bad->obj = 0; bad->vkind = OSC_VK_OBJECT; bad->id = x; } + return 0; + + case OSC_REJ_USE_AFTER_RELEASE: + v = rnd(s, 4); s->q->variant = (int)v; + if (v == 0) { /* released object */ + x = PICK(s, s->nobj, s->ost[id] == OB_REL); + if (!x || !rnd(s, 3)) { + if (!(x = new_obj(s, 0))) return -1; + e = ev0(OSC_EV_RELEASE); e.obj = x; EMIT(e); + } + static const uint32_t uar_k[6] = { OSC_EV_USE_READ, OSC_EV_USE_WRITE, OSC_EV_BORROW_SHARED, + OSC_EV_BORROW_MUT, OSC_EV_MOVE, OSC_EV_DURABLE_WRITE }; + uint32_t w = rnd(s, 6); + *bad = ev0(uar_k[w]); bad->obj = x; + if (w == 2 || w == 3) bad->borrow = fresh(s->nbor, NB, 0); + if (w == 5) { bad->obj = 0; bad->vkind = OSC_VK_OBJECT; bad->id = x; } + } else if (v == 1) { /* use through an ended borrow */ + b = PICK(s, s->nbor, s->bst[id] == BR_END); + if (!b || !rnd(s, 3)) { + x = PICK(s, s->nobj, obj_readable(s, id)); + if (!x && !(x = new_obj(s, 0))) return -1; + if (!(b = new_borrow(s, x, 0, 0))) return -1; + e = ev0(OSC_EV_END_BORROW); e.borrow = b; EMIT(e); + } + static const uint32_t ub_k[4] = { OSC_EV_USE_READ, OSC_EV_USE_WRITE, OSC_EV_BORROW_SHARED, OSC_EV_BORROW_MUT }; + uint32_t w = rnd(s, 4); + *bad = ev0(ub_k[w]); bad->obj = s->bobj[b]; bad->via = b; + if (w >= 2) bad->borrow = fresh(s->nbor, NB, 0); + } else if (v == 2) { /* alloc into a destroyed region */ + r = PICK(s, s->nreg, s->rst[id] == RG_DEAD); + if (!r) { + if (!(r = fresh(s->nreg, NR, 0))) return -1; + e = ev0(OSC_EV_REGION_OPEN); e.region = r; EMIT(e); + if (rnd(s, 2) && !new_obj(s, r)) return -1; + e = ev0(OSC_EV_REGION_DESTROY); e.region = r; EMIT(e); + } + *bad = ev0(OSC_EV_ALLOC); bad->obj = fresh(s->nobj, NO, 0); bad->region = r; + } else { /* reclaimed cell */ + if (!(c = reclaimed_cell(s))) return -1; + static const uint32_t rc_k[5] = { OSC_EV_CELL_WRITE, OSC_EV_CELL_PUBLISH, OSC_EV_CELL_OBSERVE, + OSC_EV_CELL_READ, OSC_EV_QUIESCE }; + uint32_t w = rnd(s, 5); + *bad = ev0(rc_k[w]); bad->cell = c; + bad->order = w == 1 ? OSC_ORD_RELEASE : OSC_ORD_ACQUIRE; + if (w == 4) bad->token = fresh(s->ntok, NT, 0); + } + return 0; + + case OSC_REJ_DOUBLE_RELEASE: + v = rnd(s, 4); s->q->variant = (int)v; + if (v == 0) { + x = PICK(s, s->nobj, s->ost[id] == OB_REL); + if (!x || !rnd(s, 3)) { + if (!(x = new_obj(s, 0))) return -1; + e = ev0(OSC_EV_RELEASE); e.obj = x; EMIT(e); + } + *bad = ev0(OSC_EV_RELEASE); bad->obj = x; + } else if (v == 1) { + b = PICK(s, s->nbor, s->bst[id] == BR_END); + if (!b || !rnd(s, 3)) { + x = PICK(s, s->nobj, obj_readable(s, id)); + if (!x && !(x = new_obj(s, 0))) return -1; + if (!(b = new_borrow(s, x, 0, 0))) return -1; + e = ev0(OSC_EV_END_BORROW); e.borrow = b; EMIT(e); + } + *bad = ev0(OSC_EV_END_BORROW); bad->borrow = b; + } else if (v == 2) { + r = PICK(s, s->nreg, s->rst[id] == RG_DEAD); + if (!r) { + if (!(r = fresh(s->nreg, NR, 0))) return -1; + e = ev0(OSC_EV_REGION_OPEN); e.region = r; EMIT(e); + e = ev0(OSC_EV_REGION_DESTROY); e.region = r; EMIT(e); + } + *bad = ev0(OSC_EV_REGION_DESTROY); bad->region = r; + } else { + if (!(c = reclaimed_cell(s))) return -1; + *bad = ev0(OSC_EV_RECLAIM); bad->cell = c; + bad->token = rnd(s, 2) ? PICK(s, s->ntok, s->tst[id] != TK_NONE) : 0; + } + return 0; + + case OSC_REJ_STALE_GENERATION: + if (!(h = stale_handle(s))) return -1; + v = rnd(s, 5); s->q->variant = (int)v; + if (v == 0) { *bad = ev0(OSC_EV_HANDLE_USE); bad->handle = h; bad->rights = s->hrig[h] & rnd(s, 256); } + else if (v == 1) { *bad = ev0(OSC_EV_HANDLE_DERIVE); bad->handle = fresh(s->nhnd, NH, 0); bad->handle2 = h; + bad->rights = s->hrig[h] & rnd(s, 256); } + else if (v == 2) { *bad = ev0(OSC_EV_SLOT_FREE); bad->handle = h; } + else if (v == 3) { *bad = ev0(OSC_EV_PERSIST); bad->handle = h; bad->semid = fresh(s->nsem, NM, 0); } + else { *bad = ev0(OSC_EV_SLOT_FREE); bad->slot = s->hslot[h]; bad->gen = s->hgen[h]; } + return 0; + + case OSC_REJ_GENERATION_WRAP: + s->q->variant = 0; + r = PICK(s, NS, s->sst[id] == SL_RET); + if (!r) { + /* drive one slot to retirement: free it if live, then alloc/free */ + h = PICK(s, s->nhnd, hnd_valid(s, id)); + r = h ? s->hslot[h] : PICK(s, NS, s->sst[id] == SL_FREE); + if (!r) return -1; + if (s->sst[r] == SL_LIVE) { + h = PICK(s, s->nhnd, hnd_valid(s, id) && s->hslot[id] == r); + if (!h) return -1; + e = ev0(OSC_EV_SLOT_FREE); e.handle = h; EMIT(e); + } + for (int i = 0; i < 8 && s->sst[r] != SL_RET; i++) { + if (!(h = fresh(s->nhnd, NH, 0))) return -1; + e = ev0(OSC_EV_SLOT_ALLOC); e.slot = r; e.handle = h; e.rights = rnd(s, 256); EMIT(e); + e = ev0(OSC_EV_SLOT_FREE); e.handle = h; EMIT(e); + } + if (s->sst[r] != SL_RET) return -1; + s->q->variant = 1; + } + *bad = ev0(OSC_EV_SLOT_ALLOC); bad->slot = r; + bad->handle = rnd(s, 2) ? fresh(s->nhnd, NH, 0) : 0; bad->rights = rnd(s, 256); + return 0; + + case OSC_REJ_MUTABLE_ALIAS: + v = rnd(s, 10); s->q->variant = (int)v; + switch (v) { + case 0: if (!(x = obj_with_root_borrow(s, 0))) return -1; + *bad = ev0(OSC_EV_BORROW_MUT); bad->obj = x; bad->borrow = fresh(s->nbor, NB, 0); return 0; + case 1: if (!(x = obj_with_root_borrow(s, 1))) return -1; + *bad = ev0(OSC_EV_BORROW_SHARED); bad->obj = x; bad->borrow = fresh(s->nbor, NB, 0); return 0; + case 2: if (!(x = obj_with_root_borrow(s, 1))) return -1; + *bad = ev0(OSC_EV_BORROW_MUT); bad->obj = x; bad->borrow = fresh(s->nbor, NB, 0); return 0; + case 3: if (!(x = obj_with_root_borrow(s, 2))) return -1; + *bad = ev0(OSC_EV_USE_WRITE); bad->obj = x; return 0; + case 4: if (!(x = obj_with_root_borrow(s, 1))) return -1; + if (rnd(s, 2)) { *bad = ev0(OSC_EV_USE_READ); bad->obj = x; } + else { *bad = ev0(OSC_EV_DURABLE_WRITE); bad->vkind = OSC_VK_OBJECT; bad->id = x; } + return 0; + case 5: if (!(x = obj_with_root_borrow(s, 2))) return -1; + *bad = ev0(OSC_EV_MOVE); bad->obj = x; bad->obj2 = rnd(s, 2) ? fresh(s->nobj, NO, 0) : 0; return 0; + case 6: case 7: { /* parent &mut with a live &mut child */ + if (!(b = mut_borrow_with_kid(s, 1))) return -1; + static const uint32_t pk[4] = { OSC_EV_USE_READ, OSC_EV_USE_WRITE, OSC_EV_BORROW_SHARED, OSC_EV_BORROW_MUT }; + uint32_t w = rnd(s, 4); + *bad = ev0(pk[w]); bad->obj = s->bobj[b]; bad->via = b; + if (w >= 2) bad->borrow = fresh(s->nbor, NB, 0); + return 0; + } + default: { /* parent &mut with a live & child */ + if (!(b = mut_borrow_with_kid(s, 0))) return -1; + *bad = ev0(rnd(s, 2) ? OSC_EV_USE_WRITE : OSC_EV_BORROW_MUT); bad->obj = s->bobj[b]; bad->via = b; + if (bad->kind == OSC_EV_BORROW_MUT) bad->borrow = fresh(s->nbor, NB, 0); + return 0; + } + } + + case OSC_REJ_BORROW_OUTLIVES_OWNER: + v = rnd(s, 2); s->q->variant = (int)v; + if (v == 0) { + if (!(x = obj_with_root_borrow(s, 2))) return -1; + *bad = ev0(OSC_EV_RELEASE); bad->obj = x; + } else { + b = PICK(s, s->nbor, bor_live(s, id) && (s->bksh[id] + s->bkmu[id]) > 0); + if (!b || !rnd(s, 3)) { + int pm = (int)rnd(s, 2); + uint32_t p = PICK(s, s->nbor, pm ? (bor_leaf(s, id) && s->bmut[id]) : (bor_live(s, id) && !s->bmut[id])); + if (!p) { + if (!(x = new_obj(s, 0)) || !(p = new_borrow(s, x, 0, pm))) return -1; + } + if (!new_borrow(s, s->bobj[p], p, s->bmut[p] ? (int)rnd(s, 2) : 0)) return -1; + b = p; + } + *bad = ev0(OSC_EV_END_BORROW); bad->borrow = b; + } + return 0; + + case OSC_REJ_ARENA_ESCAPE: + s->q->variant = 0; + r = PICK(s, s->nreg, s->rst[id] == RG_OPEN && !region_destroyable(s, id)); + if (!r || !rnd(s, 3)) { + r = PICK(s, s->nreg, s->rst[id] == RG_OPEN); + if (!r || !rnd(s, 2)) { + if (!(r = fresh(s->nreg, NR, 0))) return -1; + e = ev0(OSC_EV_REGION_OPEN); e.region = r; EMIT(e); + } + uint32_t via = 0; + int mut = (int)rnd(s, 2); + if (!(x = new_obj(s, r))) return -1; + if (rnd(s, 3) == 0) { /* reborrow chain into the region */ + if (!(via = new_borrow(s, x, 0, 1))) return -1; + s->q->variant = 2; + } else s->q->variant = 1; + if (!new_borrow(s, x, via, mut)) return -1; + } + *bad = ev0(OSC_EV_REGION_DESTROY); bad->region = r; + return 0; + + case OSC_REJ_RECLAIM_WITHOUT_QUIESCED: + v = rnd(s, 3); s->q->variant = (int)v; + if (v == 2 && !PICK(s, s->ntok, s->tst[id] == TK_USED) && !reclaimed_cell(s)) return -1; + if (!(c = cell_in(s, (1u << CE_WR) | (1u << CE_PUB) | (1u << CE_OBS)))) return -1; + *bad = ev0(OSC_EV_RECLAIM); bad->cell = c; + if (v == 0) { bad->token = 0; return 0; } + if (v == 1) { /* a live token for another cell */ + t = PICK(s, s->ntok, s->tst[id] == TK_LIVE && s->tcell[id] != c); + if (!t) { + uint32_t c2 = fresh(s->ncell, NC, 0); + if (!c2 || !(t = fresh(s->ntok, NT, 0))) return -1; + e = ev0(OSC_EV_CELL_WRITE); e.cell = c2; EMIT(e); + e = ev0(OSC_EV_CELL_PUBLISH); e.cell = c2; e.order = OSC_ORD_RELEASE; EMIT(e); + e = ev0(OSC_EV_CELL_OBSERVE); e.cell = c2; e.order = OSC_ORD_ACQUIRE; EMIT(e); + e = ev0(OSC_EV_QUIESCE); e.cell = c2; e.token = t; EMIT(e); + } + bad->token = t; return 0; + } + /* a consumed token */ + t = PICK(s, s->ntok, s->tst[id] == TK_USED); + if (!t) { + uint32_t c2 = reclaimed_cell(s); + if (!c2) return -1; + t = PICK(s, s->ntok, s->tst[id] == TK_USED); + if (!t) return -1; + } + bad->token = t; return 0; + + case OSC_REJ_READ_BEFORE_OBSERVE: + v = rnd(s, 2); s->q->variant = (int)v; + if (v == 0) { + if (!(c = cell_in(s, (1u << CE_WR) | (1u << CE_PUB)))) return -1; + *bad = ev0(OSC_EV_CELL_READ); bad->cell = c; + } else { + if (!(c = cell_in(s, (1u << CE_WR) | (1u << CE_PUB) | (1u << CE_OBS)))) return -1; + *bad = ev0(OSC_EV_CELL_OBSERVE); bad->cell = c; + bad->order = rnd(s, 2) ? OSC_ORD_RELAXED : OSC_ORD_RELEASE; + } + return 0; + + case OSC_REJ_PUBLISH_WITHOUT_RELEASE: + s->q->variant = 0; + if (!(c = cell_in(s, (1u << CE_WR) | (1u << CE_PUB) | (1u << CE_OBS)))) return -1; + *bad = ev0(OSC_EV_CELL_PUBLISH); bad->cell = c; + bad->order = rnd(s, 2) ? OSC_ORD_RELAXED : OSC_ORD_ACQUIRE; + return 0; + + case OSC_REJ_FORGED_RIGHTS: + v = rnd(s, 4); s->q->variant = (int)v; + if (v <= 1) { + if (!(h = valid_handle(s))) v = 2 + rnd(s, 2), s->q->variant = (int)v; + else { + uint64_t missing = ~s->hrig[h] & 0x1ffull; /* bit 8 is never granted */ + uint64_t extra = 0; + while (!extra) extra = missing & ((uint64_t)rnd(s, 512) | (1ull << 8)); + uint64_t want = (s->hrig[h] & rnd(s, 256)) | extra; + if (v == 0) { *bad = ev0(OSC_EV_HANDLE_DERIVE); bad->handle = fresh(s->nhnd, NH, 0); bad->handle2 = h; } + else { *bad = ev0(OSC_EV_HANDLE_USE); bad->handle = h; } + bad->rights = want; + return 0; + } + } + /* write or &mut through a live shared borrow */ + b = PICK(s, s->nbor, bor_live(s, id) && !s->bmut[id]); + if (!b || !rnd(s, 3)) { + x = PICK(s, s->nobj, obj_readable(s, id)); + if (!x && !(x = new_obj(s, 0))) return -1; + if (!(b = new_borrow(s, x, 0, 0))) return -1; + } + *bad = ev0(v == 2 ? OSC_EV_USE_WRITE : OSC_EV_BORROW_MUT); bad->obj = s->bobj[b]; bad->via = b; + if (v == 3) bad->borrow = fresh(s->nbor, NB, 0); + return 0; + + case OSC_REJ_LIVE_HANDLE_DURABLE: + v = rnd(s, 2); s->q->variant = (int)v; + *bad = ev0(OSC_EV_DURABLE_WRITE); + if (v == 0) { + h = PICK(s, s->nhnd, s->hused[id]); + if (!h || !rnd(s, 3)) h = valid_handle(s); + if (!h) h = PICK(s, s->nhnd, s->hused[id]); + if (!h) return -1; + bad->vkind = OSC_VK_HANDLE; bad->id = h; + } else { + b = PICK(s, s->nbor, s->bst[id] != BR_NONE); + if (!b || !rnd(s, 3)) { + x = PICK(s, s->nobj, obj_readable(s, id)); + if (!x && !(x = new_obj(s, 0))) return -1; + if (!(b = new_borrow(s, x, 0, 0))) return -1; + } + bad->vkind = OSC_VK_BORROW; bad->id = b; + } + return 0; + + default: + return -1; + } +} + +int osc_gen_sequence(uint64_t seed, uint64_t index, OscModelReject inject_class, OscGenSeq *out) +{ + static Sh zero; + Sh sh = zero; + Sh *s = &sh; + s->q = out; + out->n = 0; out->inject_at = -1; out->expect = OSC_REJ_NONE; out->variant = -1; + s->rng = seed ^ (0x9E3779B97F4A7C15ull * (index + 1)); + (void)osc_gen_splitmix64(&s->rng); + + /* generation configuration */ + uint32_t cfg = rnd(s, 4); + if (inject_class == OSC_REJ_GENERATION_WRAP && cfg == 0) cfg = 1 + rnd(s, 3); + switch (cfg) { + case 0: out->gen_base = 0; out->gen_max = UINT64_MAX; break; + case 1: out->gen_base = 0; out->gen_max = 1 + rnd(s, 3); break; + case 2: out->gen_base = UINT64_MAX - 1 - rnd(s, 2); out->gen_max = UINT64_MAX; break; + default: out->gen_base = 5; out->gen_max = 5 + rnd(s, 2); break; + } + s->gmax = out->gen_max; + for (uint32_t i = 1; i <= NS; i++) { s->sst[i] = SL_FREE; s->sgen[i] = out->gen_base; } + + if (inject_class == OSC_REJ_NONE) { + uint32_t len = 4 + rnd(s, 40); + for (uint32_t i = 0; i < len; i++) { + int r = valid_step(s); + if (r < 0) return -1; + if (r > 0) break; + } + if (rnd(s, 2) && teardown(s)) return -1; + return 0; + } + + uint32_t prefix = rnd(s, 31); + for (uint32_t i = 0; i < prefix; i++) { + int r = valid_step(s); + if (r < 0) return -1; + if (r > 0) break; + } + OscModelEvent bad; + if (build_bad(s, inject_class, &bad)) return -1; + if (out->n >= OSC_GEN_MAX_EVENTS - 1) return -1; + out->inject_at = out->n; + out->expect = inject_class; + out->ev[out->n++] = bad; /* not applied to the shadow */ + uint32_t suffix = rnd(s, 6); + for (uint32_t i = 0; i < suffix; i++) { + int r = valid_step(s); + if (r < 0) return -1; + if (r > 0) break; + } + return 0; +} diff --git a/src/compiler/model/osc_model_gen.h b/src/compiler/model/osc_model_gen.h new file mode 100644 index 000000000..ff5e68df2 --- /dev/null +++ b/src/compiler/model/osc_model_gen.h @@ -0,0 +1,39 @@ +/* + * osc_model_gen.h -- seeded deterministic sequence generator for the II.11 + * model (OSC-0B exit gate). + * + * The generator keeps its own shadow state (independent of osc_model.c) and + * uses it to choose only VALID events. For an injected sequence it then + * builds (with valid setup events if needed) exactly one labelled invalid + * event of the requested named class, followed by a few more valid events + * (a rejected event must not change the model's state). The label is the + * ground truth the model's verdict is compared against. + * + * Fully determined by (seed, index, inject_class): splitmix64 over + * seed ^ golden * (index + 1). No globals, no malloc. + */ +#ifndef OSC_MODEL_GEN_H +#define OSC_MODEL_GEN_H + +#include +#include "osc_model.h" + +#define OSC_GEN_MAX_EVENTS 256 + +typedef struct { + uint64_t gen_base, gen_max; /* pass to osc_model_init */ + int inject_at; /* index of the invalid event, -1 = none */ + OscModelReject expect; /* label at inject_at (OSC_REJ_NONE if none) */ + int variant; /* which construction of the class was used */ + int n; + OscModelEvent ev[OSC_GEN_MAX_EVENTS]; +} OscGenSeq; + +uint64_t osc_gen_splitmix64(uint64_t *state); + +/* inject_class: OSC_REJ_NONE for an all-valid sequence, else 1..13. + * Returns 0 on success, -1 if the requested injection could not be built + * (never expected; the caller counts it as a generator failure). */ +int osc_gen_sequence(uint64_t seed, uint64_t index, OscModelReject inject_class, OscGenSeq *out); + +#endif diff --git a/tests/compiler/osc0b_model_receipt.sh b/tests/compiler/osc0b_model_receipt.sh new file mode 100755 index 000000000..8ab334c0b --- /dev/null +++ b/tests/compiler/osc0b_model_receipt.sh @@ -0,0 +1,123 @@ +#!/bin/sh +# OSC-0B exit gate receipt (OMEGA_SYSTEMS_CORE_CODE_AUDIT.md II.11, III.8). +# 1. refuses a dirty tree (any tracked or untracked change): receipts record an exact commit +# 2. builds tests/compiler/test_osc_model.c + src/compiler/model/*.c twice, outside the tree: +# plain -O2, and ASan/UBSan (-fno-sanitize-recover=all) +# 3. runs the plain build at the gate size (>= 10^6 seeded sequences) and the +# sanitizer build on the same seed (full size unless OSC0B_ASAN_SEQUENCES is set) +# 4. requires OSC0B_MODEL_PASS, zero false accepts / wrong names / false rejects, +# and the same sweep digest from both builds on the full size +# 5. writes a content-addressed receipt evidence/OSC-1/receipts/osc0b-model-.json +# Never overwrites existing evidence. Timing is not recorded (receipt stays content-stable). +# Env: CC (default cc), OSC0B_SEED (hex, default the test's built-in seed), OSC0B_ASAN_SEQUENCES. +set -eu +ROOT=$(cd "$(dirname "$0")/../.." && pwd -P) +cd "$ROOT" +EVD=evidence/OSC-1/receipts +CC=${CC:-cc} +SRCS="src/compiler/model/osc_model.h src/compiler/model/osc_model.c src/compiler/model/osc_model_gen.h src/compiler/model/osc_model_gen.c tests/compiler/test_osc_model.c" +CFLAGS="-std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -Isrc -Isrc/compiler -Isrc/compiler/model" + +die() { echo "osc0b-model-receipt: REFUSED: $*" >&2; exit 2; } + +[ -z "$(git status --porcelain --untracked-files=all)" ] || die "dirty tree; commit first (receipts record an exact commit)" +COMMIT=$(git rev-parse HEAD) +case "$COMMIT" in *[!0-9a-f]*|"") die "cannot read HEAD";; esac +for f in $SRCS; do [ -f "$f" ] || die "missing $f"; done + +T=$(mktemp -d) +trap 'rm -rf "$T"' EXIT +nice "$CC" $CFLAGS -O2 -o "$T/plain" tests/compiler/test_osc_model.c src/compiler/model/osc_model.c src/compiler/model/osc_model_gen.c \ + >"$T/build.log" 2>&1 || { tail -20 "$T/build.log"; die "plain build failed"; } +nice "$CC" $CFLAGS -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all -o "$T/asan" \ + tests/compiler/test_osc_model.c src/compiler/model/osc_model.c src/compiler/model/osc_model_gen.c \ + >"$T/build_asan.log" 2>&1 || { tail -20 "$T/build_asan.log"; die "sanitizer build failed"; } + +SEED_ARG=${OSC0B_SEED:-} +if [ -n "$SEED_ARG" ]; then + nice "$T/plain" "$SEED_ARG" >"$T/plain.out" 2>&1 || { tail -20 "$T/plain.out"; die "plain run failed"; } +else + nice "$T/plain" >"$T/plain.out" 2>&1 || { tail -20 "$T/plain.out"; die "plain run failed"; } +fi +[ "$(tail -1 "$T/plain.out")" = OSC0B_MODEL_PASS ] || { tail -20 "$T/plain.out"; die "plain run did not print OSC0B_MODEL_PASS"; } + +SUM=$(grep '^OSC0B_MODEL_SEED=' "$T/plain.out" | tail -1) +field() { echo "$SUM" | sed -n "s/.*$1=\([0-9a-fx]*\).*/\1/p"; } +SEED=$(field OSC0B_MODEL_SEED); SEQ=$(field SEQUENCES); STEPS=$(field STEPS) +FA=$(field FALSE_ACCEPTS); WN=$(field WRONG_NAME); FR=$(field FALSE_REJECTS) +for v in "$SEED" "$SEQ" "$STEPS" "$FA" "$WN" "$FR"; do [ -n "$v" ] || die "cannot parse summary line: $SUM"; done +[ "$FA" = 0 ] && [ "$WN" = 0 ] && [ "$FR" = 0 ] || die "nonzero false accepts/wrong names/false rejects" +[ "$SEQ" -ge 1000000 ] || die "fewer than 10^6 sequences ($SEQ)" +VLINE=$(grep '^OSC0B_MODEL_VALID ' "$T/plain.out" | tail -1) +VALID=$(echo "$VLINE" | sed -n 's/.* sequences=\([0-9]*\).*/\1/p') +DIGEST=$(echo "$VLINE" | sed -n 's/.* digest=\([0-9a-f]*\).*/\1/p') +UNIT=$(grep '^OSC0B_MODEL_UNIT ' "$T/plain.out" | tail -1) +UCASES=$(echo "$UNIT" | sed -n 's/.*cases=\([0-9]*\).*/\1/p') +UFAIL=$(echo "$UNIT" | sed -n 's/.*failed=\([0-9]*\).*/\1/p') +[ -n "$VALID" ] && [ -n "$DIGEST" ] && [ -n "$UCASES" ] && [ "$UFAIL" = 0 ] || die "cannot parse valid/unit lines" + +ASEQ=${OSC0B_ASAN_SEQUENCES:-$SEQ} +nice "$T/asan" "$SEED" "$ASEQ" >"$T/asan.out" 2>&1 || { tail -20 "$T/asan.out"; die "sanitizer run failed"; } +ALAST=$(tail -1 "$T/asan.out") +case "$ALAST" in OSC0B_MODEL_PASS|OSC0B_MODEL_SMOKE_PASS) ;; *) tail -20 "$T/asan.out"; die "sanitizer run: $ALAST";; esac +ADIGEST=$(grep '^OSC0B_MODEL_VALID ' "$T/asan.out" | sed -n 's/.* digest=\([0-9a-f]*\).*/\1/p') +if [ "$ASEQ" = "$SEQ" ]; then + [ "$ADIGEST" = "$DIGEST" ] || die "sanitizer sweep digest $ADIGEST != plain $DIGEST" + DIGEST_MATCH=true +else + DIGEST_MATCH=null +fi + +R="$T/receipt.json" +{ + printf '{\n' + printf ' "schema": "omega.osc0b.model.receipt.v1",\n' + printf ' "verdict": "PASS",\n' + printf ' "gate": "OSC-0B exit: II.11 model rejects every named invalid transition across >= 10^6 seeded random sequences, zero false accepts",\n' + printf ' "repo_commit": "%s",\n' "$COMMIT" + printf ' "tree_clean": true,\n' + printf ' "host_arch": "%s",\n' "$(uname -m)" + printf ' "compiler": "%s",\n' "$("$CC" --version 2>/dev/null | head -1 | sed 's/"/\\"/g')" + printf ' "seed": "0x%s",\n' "$SEED" + printf ' "sequences": %s,\n' "$SEQ" + printf ' "valid_sequences": %s,\n' "$VALID" + printf ' "steps": %s,\n' "$STEPS" + printf ' "false_accepts": %s,\n' "$FA" + printf ' "wrong_name": %s,\n' "$WN" + printf ' "false_rejects": %s,\n' "$FR" + printf ' "sweep_digest": "%s",\n' "$DIGEST" + printf ' "unit_cases": %s,\n' "$UCASES" + printf ' "unit_failed": 0,\n' + printf ' "classes": {\n' + N=$(grep -c '^OSC0B_MODEL_CLASS ' "$T/plain.out") + [ "$N" = 13 ] || die "expected 13 class lines, got $N" + i=0 + grep '^OSC0B_MODEL_CLASS ' "$T/plain.out" | while read -r _ name inj cor wro acc; do + i=$((i + 1)) + sep=,; [ "$i" = 13 ] && sep= + printf ' "%s": {"injected": %s, "rejected_correct": %s, "rejected_wrong_name": %s, "accepted": %s}%s\n' \ + "$name" "${inj#*=}" "${cor#*=}" "${wro#*=}" "${acc#*=}" "$sep" + done + printf ' },\n' + printf ' "sanitizer_run": {"flags": "-fsanitize=address,undefined -fno-sanitize-recover=all", "sequences": %s, "result": "%s", "digest_matches_plain": %s},\n' \ + "$ASEQ" "$ALAST" "$DIGEST_MATCH" + printf ' "sources_sha256": {\n' + n=0; total=$(echo $SRCS | wc -w) + for f in $SRCS; do + n=$((n + 1)); sep=,; [ "$n" = "$total" ] && sep= + printf ' "%s": "%s"%s\n' "$f" "$(sha256sum "$f" | cut -d' ' -f1)" "$sep" + done + printf ' },\n' + printf ' "timing_measured": false\n' + printf '}\n' +} >"$R" +# every class must meet the per-class floor with zero misses +grep '^OSC0B_MODEL_CLASS ' "$T/plain.out" | while read -r _ name inj cor wro acc; do + [ "${inj#*=}" -ge 10000 ] && [ "${cor#*=}" = "${inj#*=}" ] || { echo "class $name below floor or missed" >&2; exit 1; } +done || die "per-class floor" + +mkdir -p "$EVD" +RSHA=$(sha256sum "$R" | cut -d' ' -f1) +OUT="$EVD/osc0b-model-$RSHA.json" +[ -e "$OUT" ] || cp "$R" "$OUT" +echo "osc0b-model-receipt: PASS seed=0x$SEED sequences=$SEQ steps=$STEPS receipt=$OUT" diff --git a/tests/compiler/test_osc_model.c b/tests/compiler/test_osc_model.c new file mode 100644 index 000000000..941e727cc --- /dev/null +++ b/tests/compiler/test_osc_model.c @@ -0,0 +1,313 @@ +/* + * test_osc_model.c -- OSC-0B exit gate (OMEGA_SYSTEMS_CORE_CODE_AUDIT.md + * II.11, III.8): the II.11 executable model must reject every named invalid + * transition, with the exact name, across >= 10^6 seeded random sequences, + * with zero false accepts, zero wrong-name rejects and zero false rejects. + * + * usage: test_osc_model [seed_hex [sequences]] + * default seed 0x05C0B5EED0010001, default sequences 1000000. + * Final line: OSC0B_MODEL_PASS or OSC0B_MODEL_FAIL. A run with fewer than + * 10^6 sequences (e.g. under ASan) can at best print OSC0B_MODEL_SMOKE_PASS. + */ +#include "osc_model.h" +#include "osc_model_gen.h" + +#include +#include +#include +#include +#include + +#define GATE_MIN_SEQUENCES 1000000ull +#define GATE_MIN_PER_CLASS 10000ull +#define DEFAULT_SEED 0x05C0B5EED0010001ull + +static int g_unit_fail, g_unit_cases; + +#define EV(...) ((OscModelEvent){ __VA_ARGS__ }) + +/* Run evs[0..n-1]; all but the last must be accepted; the last must give + * `last` (OSC_REJ_NONE = accepted too). */ +static void seq_case(const char *name, uint64_t base, uint64_t max, + const OscModelEvent *evs, int n, OscModelReject last) +{ + OscModel m; + osc_model_init(&m, base, max); + g_unit_cases++; + for (int i = 0; i < n; i++) { + OscModelReject r; + OscModelVerdict v = osc_model_step(&m, &evs[i], &r); + OscModelReject want = i == n - 1 ? last : OSC_REJ_NONE; + if (r != want || (v == OSC_MODEL_ACCEPT) != (r == OSC_REJ_NONE)) { + printf("UNIT FAIL %s: step %d (%s) got %s want %s\n", name, i, + osc_model_event_name(evs[i].kind), osc_model_reject_name(r), osc_model_reject_name(want)); + g_unit_fail++; + return; + } + } +} +#define CASE(name, last, ...) do { const OscModelEvent e_[] = { __VA_ARGS__ }; \ + seq_case(name, 0, UINT64_MAX, e_, (int)(sizeof e_ / sizeof e_[0]), last); } while (0) +#define CASEG(name, base, max, last, ...) do { const OscModelEvent e_[] = { __VA_ARGS__ }; \ + seq_case(name, base, max, e_, (int)(sizeof e_ / sizeof e_[0]), last); } while (0) + +#define ALLOC(o, r) EV(.kind = OSC_EV_ALLOC, .obj = (o), .region = (r)) +#define MOVE(o, d) EV(.kind = OSC_EV_MOVE, .obj = (o), .obj2 = (d)) +#define BSH(o, b, v) EV(.kind = OSC_EV_BORROW_SHARED, .obj = (o), .borrow = (b), .via = (v)) +#define BMUT(o, b, v) EV(.kind = OSC_EV_BORROW_MUT, .obj = (o), .borrow = (b), .via = (v)) +#define END(b) EV(.kind = OSC_EV_END_BORROW, .borrow = (b)) +#define RD(o, v) EV(.kind = OSC_EV_USE_READ, .obj = (o), .via = (v)) +#define WR(o, v) EV(.kind = OSC_EV_USE_WRITE, .obj = (o), .via = (v)) +#define REL(o) EV(.kind = OSC_EV_RELEASE, .obj = (o)) +#define ROPEN(r) EV(.kind = OSC_EV_REGION_OPEN, .region = (r)) +#define RDEST(r) EV(.kind = OSC_EV_REGION_DESTROY, .region = (r)) +#define SALLOC(s, h, rt) EV(.kind = OSC_EV_SLOT_ALLOC, .slot = (s), .handle = (h), .rights = (rt)) +#define SFREE(h) EV(.kind = OSC_EV_SLOT_FREE, .handle = (h)) +#define SFREEG(s, g) EV(.kind = OSC_EV_SLOT_FREE, .slot = (s), .gen = (g)) +#define DERIVE(h, p, rt) EV(.kind = OSC_EV_HANDLE_DERIVE, .handle = (h), .handle2 = (p), .rights = (rt)) +#define HUSE(h, rt) EV(.kind = OSC_EV_HANDLE_USE, .handle = (h), .rights = (rt)) +#define PERSIST(h, s) EV(.kind = OSC_EV_PERSIST, .handle = (h), .semid = (s)) +#define DUR(k, i) EV(.kind = OSC_EV_DURABLE_WRITE, .vkind = (k), .id = (i)) +#define CW(c) EV(.kind = OSC_EV_CELL_WRITE, .cell = (c)) +#define CPUB(c, o) EV(.kind = OSC_EV_CELL_PUBLISH, .cell = (c), .order = (o)) +#define COBS(c, o) EV(.kind = OSC_EV_CELL_OBSERVE, .cell = (c), .order = (o)) +#define CRD(c) EV(.kind = OSC_EV_CELL_READ, .cell = (c)) +#define QUI(t, c) EV(.kind = OSC_EV_QUIESCE, .token = (t), .cell = (c)) +#define RECL(c, t) EV(.kind = OSC_EV_RECLAIM, .cell = (c), .token = (t)) +#define REL_ OSC_ORD_RELEASE +#define ACQ_ OSC_ORD_ACQUIRE +#define RLX_ OSC_ORD_RELAXED +#define DRAINED(c, t) CW(c), CPUB(c, REL_), COBS(c, ACQ_), QUI(t, c) + +static void unit_tests(void) +{ + /* ---- valid sequences ---- */ + CASE("valid: owner lifecycle", OSC_REJ_NONE, + ALLOC(1, 0), WR(1, 0), RD(1, 0), BSH(1, 1, 0), BSH(1, 2, 0), RD(1, 1), RD(1, 0), RD(1, 2), + BSH(1, 3, 1), END(3), END(1), END(2), BMUT(1, 4, 0), WR(1, 4), RD(1, 4), BMUT(1, 5, 4), WR(1, 5), + END(5), BSH(1, 6, 4), BSH(1, 7, 4), RD(1, 6), RD(1, 4), END(6), END(7), WR(1, 4), END(4), + WR(1, 0), MOVE(1, 2), RD(2, 0), MOVE(2, 0), ALLOC(3, 0), REL(3)); + CASE("valid: region destroy releases owners, nothing escapes", OSC_REJ_NONE, + ROPEN(1), ALLOC(1, 1), ALLOC(2, 1), MOVE(2, 3), BSH(1, 1, 0), RD(1, 1), END(1), REL(1), RDEST(1), + ALLOC(4, 0), REL(4)); + CASE("valid: region-destroyed object is released", OSC_REJ_USE_AFTER_RELEASE, + ROPEN(1), ALLOC(1, 1), RDEST(1), RD(1, 0)); + CASE("valid: publish/observe pairs, drain, reclaim", OSC_REJ_NONE, + CW(1), CPUB(1, REL_), COBS(1, ACQ_), CRD(1), CRD(1), CW(1), CPUB(1, REL_), COBS(1, ACQ_), CRD(1), + QUI(1, 1), RECL(1, 1), CW(2), CPUB(2, REL_)); + CASEG("valid: generation advances to retirement", 0, 2, OSC_REJ_NONE, + SALLOC(1, 1, 3), SFREE(1), SALLOC(1, 2, 3), SFREE(2), SALLOC(1, 3, 3), HUSE(3, 1), SFREE(3)); + CASE("valid: handles narrow, persist, durable semid and value", OSC_REJ_NONE, + SALLOC(1, 1, 0xF), DERIVE(2, 1, 0x5), DERIVE(3, 2, 0x4), HUSE(3, 0x4), HUSE(1, 0xF), PERSIST(3, 1), + DUR(OSC_VK_SEMID, 1), ALLOC(1, 0), DUR(OSC_VK_OBJECT, 1), BSH(1, 1, 0), DUR(OSC_VK_OBJECT, 1), + SFREEG(1, 0), SALLOC(1, 4, 1)); + + /* ---- 1 use after move ---- */ + CASE("uam: read", OSC_REJ_USE_AFTER_MOVE, ALLOC(1, 0), MOVE(1, 2), RD(1, 0)); + CASE("uam: release", OSC_REJ_USE_AFTER_MOVE, ALLOC(1, 0), MOVE(1, 0), REL(1)); + CASE("uam: borrow", OSC_REJ_USE_AFTER_MOVE, ALLOC(1, 0), MOVE(1, 2), BSH(1, 1, 0)); + CASE("uam: move again", OSC_REJ_USE_AFTER_MOVE, ALLOC(1, 0), MOVE(1, 2), MOVE(1, 3)); + /* ---- 2 use after release ---- */ + CASE("uar: read", OSC_REJ_USE_AFTER_RELEASE, ALLOC(1, 0), REL(1), RD(1, 0)); + CASE("uar: ended borrow", OSC_REJ_USE_AFTER_RELEASE, ALLOC(1, 0), BSH(1, 1, 0), END(1), RD(1, 1)); + CASE("uar: alloc into destroyed region", OSC_REJ_USE_AFTER_RELEASE, ROPEN(1), RDEST(1), ALLOC(1, 1)); + CASE("uar: reclaimed cell", OSC_REJ_USE_AFTER_RELEASE, DRAINED(1, 1), RECL(1, 1), CW(1)); + /* ---- 3 double release ---- */ + CASE("dbl: object", OSC_REJ_DOUBLE_RELEASE, ALLOC(1, 0), REL(1), REL(1)); + CASE("dbl: borrow", OSC_REJ_DOUBLE_RELEASE, ALLOC(1, 0), BSH(1, 1, 0), END(1), END(1)); + CASE("dbl: region", OSC_REJ_DOUBLE_RELEASE, ROPEN(1), RDEST(1), RDEST(1)); + CASE("dbl: cell reclaim", OSC_REJ_DOUBLE_RELEASE, DRAINED(1, 1), RECL(1, 1), RECL(1, 1)); + CASE("dbl: object in destroyed region", OSC_REJ_DOUBLE_RELEASE, ROPEN(1), ALLOC(1, 1), RDEST(1), REL(1)); + /* ---- 4 stale generation ---- */ + CASE("stale: use after free", OSC_REJ_STALE_GENERATION, SALLOC(1, 1, 1), SFREE(1), HUSE(1, 1)); + CASE("stale: slot reused", OSC_REJ_STALE_GENERATION, SALLOC(1, 1, 1), SFREE(1), SALLOC(1, 2, 1), HUSE(1, 0)); + CASE("stale: second free", OSC_REJ_STALE_GENERATION, SALLOC(1, 1, 1), SFREE(1), SFREE(1)); + CASE("stale: explicit gen", OSC_REJ_STALE_GENERATION, SALLOC(1, 1, 1), SFREE(1), SALLOC(1, 2, 1), SFREEG(1, 0)); + CASE("stale: derive", OSC_REJ_STALE_GENERATION, SALLOC(1, 1, 1), SFREE(1), DERIVE(2, 1, 0)); + CASE("stale before rights", OSC_REJ_STALE_GENERATION, SALLOC(1, 1, 1), SFREE(1), HUSE(1, 0xFF)); + /* ---- 5 generation wrap ---- */ + CASEG("wrap: small max", 0, 1, OSC_REJ_GENERATION_WRAP, + SALLOC(1, 1, 0), SFREE(1), SALLOC(1, 2, 0), SFREE(2), SALLOC(1, 3, 0)); + CASEG("wrap: u64 boundary", UINT64_MAX - 1, UINT64_MAX, OSC_REJ_GENERATION_WRAP, + SALLOC(1, 1, 0), SFREEG(1, UINT64_MAX - 1), SALLOC(1, 2, 0), SFREEG(1, UINT64_MAX), SALLOC(1, 0, 0)); + CASEG("wrap: retired handle is stale", UINT64_MAX, UINT64_MAX, OSC_REJ_STALE_GENERATION, + SALLOC(1, 1, 0), SFREE(1), HUSE(1, 0)); + /* ---- 6 mutable alias ---- */ + CASE("alias: mut after shared", OSC_REJ_MUTABLE_ALIAS, ALLOC(1, 0), BSH(1, 1, 0), BMUT(1, 2, 0)); + CASE("alias: shared after mut", OSC_REJ_MUTABLE_ALIAS, ALLOC(1, 0), BMUT(1, 1, 0), BSH(1, 2, 0)); + CASE("alias: second mut", OSC_REJ_MUTABLE_ALIAS, ALLOC(1, 0), BMUT(1, 1, 0), BMUT(1, 2, 0)); + CASE("alias: direct write while shared", OSC_REJ_MUTABLE_ALIAS, ALLOC(1, 0), BSH(1, 1, 0), WR(1, 0)); + CASE("alias: direct read while mut", OSC_REJ_MUTABLE_ALIAS, ALLOC(1, 0), BMUT(1, 1, 0), RD(1, 0)); + CASE("alias: move while borrowed", OSC_REJ_MUTABLE_ALIAS, ALLOC(1, 0), BSH(1, 1, 0), MOVE(1, 2)); + CASE("alias: parent used under mut reborrow", OSC_REJ_MUTABLE_ALIAS, + ALLOC(1, 0), BMUT(1, 1, 0), BMUT(1, 2, 1), RD(1, 1)); + CASE("alias: second mut reborrow", OSC_REJ_MUTABLE_ALIAS, + ALLOC(1, 0), BMUT(1, 1, 0), BSH(1, 2, 1), BMUT(1, 3, 1)); + /* ---- 7 borrow outlives owner ---- */ + CASE("boo: release while borrowed", OSC_REJ_BORROW_OUTLIVES_OWNER, ALLOC(1, 0), BSH(1, 1, 0), REL(1)); + CASE("boo: parent ends before reborrow", OSC_REJ_BORROW_OUTLIVES_OWNER, + ALLOC(1, 0), BMUT(1, 1, 0), BSH(1, 2, 1), END(1)); + /* ---- 8 arena escape ---- */ + CASE("escape: borrow into destroyed region", OSC_REJ_ARENA_ESCAPE, + ROPEN(1), ALLOC(1, 1), ALLOC(2, 0), BSH(1, 1, 0), RDEST(1)); + CASE("escape: reborrow chain", OSC_REJ_ARENA_ESCAPE, + ROPEN(2), ALLOC(1, 2), BMUT(1, 1, 0), BSH(1, 2, 1), END(2), RDEST(2)); + /* ---- 9 reclaim without Quiesced ---- */ + CASE("reclaim: no token", OSC_REJ_RECLAIM_WITHOUT_QUIESCED, CW(1), CPUB(1, REL_), COBS(1, ACQ_), RECL(1, 0)); + CASE("reclaim: other cell's token", OSC_REJ_RECLAIM_WITHOUT_QUIESCED, DRAINED(2, 1), CW(1), RECL(1, 1)); + CASE("reclaim: consumed token", OSC_REJ_RECLAIM_WITHOUT_QUIESCED, DRAINED(1, 1), RECL(1, 1), CW(2), RECL(2, 1)); + /* ---- 10 read before observe ---- */ + CASE("rbo: read published", OSC_REJ_READ_BEFORE_OBSERVE, CW(1), CPUB(1, REL_), CRD(1)); + CASE("rbo: read written", OSC_REJ_READ_BEFORE_OBSERVE, CW(1), CRD(1)); + CASE("rbo: relaxed poll", OSC_REJ_READ_BEFORE_OBSERVE, CW(1), CPUB(1, REL_), COBS(1, RLX_)); + CASE("rbo: new round", OSC_REJ_READ_BEFORE_OBSERVE, CW(1), CPUB(1, REL_), COBS(1, ACQ_), CRD(1), CW(1), CRD(1)); + /* ---- 11 publish without release ---- */ + CASE("pwr: relaxed", OSC_REJ_PUBLISH_WITHOUT_RELEASE, CW(1), CPUB(1, RLX_)); + CASE("pwr: acquire", OSC_REJ_PUBLISH_WITHOUT_RELEASE, CW(1), CPUB(1, ACQ_)); + /* ---- 12 forged rights ---- */ + CASE("forged: derive wider", OSC_REJ_FORGED_RIGHTS, SALLOC(1, 1, 0x3), DERIVE(2, 1, 0x7)); + CASE("forged: grandchild wider than parent", OSC_REJ_FORGED_RIGHTS, + SALLOC(1, 1, 0xF), DERIVE(2, 1, 0x3), DERIVE(3, 2, 0x4)); + CASE("forged: use wider", OSC_REJ_FORGED_RIGHTS, SALLOC(1, 1, 0x3), HUSE(1, 0x4)); + CASE("forged: write through shared borrow", OSC_REJ_FORGED_RIGHTS, ALLOC(1, 0), BSH(1, 1, 0), WR(1, 1)); + CASE("forged: &mut through shared borrow", OSC_REJ_FORGED_RIGHTS, ALLOC(1, 0), BSH(1, 1, 0), BMUT(1, 2, 1)); + /* ---- 13 live handle to a durable encoder ---- */ + CASE("durable: live handle", OSC_REJ_LIVE_HANDLE_DURABLE, SALLOC(1, 1, 1), DUR(OSC_VK_HANDLE, 1)); + CASE("durable: stale handle", OSC_REJ_LIVE_HANDLE_DURABLE, SALLOC(1, 1, 1), SFREE(1), DUR(OSC_VK_HANDLE, 1)); + CASE("durable: borrow", OSC_REJ_LIVE_HANDLE_DURABLE, ALLOC(1, 0), BSH(1, 1, 0), DUR(OSC_VK_BORROW, 1)); + + /* ---- non-named refusals ---- */ + CASE("malformed: never allocated", OSC_REJ_MALFORMED, RD(1, 0)); + CASE("malformed: id reused", OSC_REJ_MALFORMED, ALLOC(1, 0), REL(1), ALLOC(1, 0)); + CASE("malformed: id 0", OSC_REJ_MALFORMED, ALLOC(0, 0)); + CASE("malformed: via names another object", OSC_REJ_MALFORMED, ALLOC(1, 0), ALLOC(2, 0), BSH(1, 1, 0), RD(2, 1)); + CASE("capacity: object id", OSC_REJ_CAPACITY, ALLOC(OSC_MODEL_MAX_OBJECTS + 1, 0)); + CASE("capacity: slot id", OSC_REJ_CAPACITY, SALLOC(OSC_MODEL_MAX_SLOTS + 1, 1, 0)); + CASE("protocol: observe unpublished", OSC_REJ_PROTOCOL, CW(1), COBS(1, ACQ_)); + CASE("protocol: alloc live slot", OSC_REJ_PROTOCOL, SALLOC(1, 1, 0), SALLOC(1, 2, 0)); + CASE("protocol: unknown kind", OSC_REJ_PROTOCOL, EV(.kind = 999)); + + /* reject leaves state unchanged */ + { + OscModel a, b; + osc_model_init(&a, 0, UINT64_MAX); + OscModelEvent e1[] = { ALLOC(1, 0), BSH(1, 1, 0) }; + for (int i = 0; i < 2; i++) osc_model_step(&a, &e1[i], NULL); + b = a; + OscModelEvent badev = REL(1); + OscModelReject r; + osc_model_step(&a, &badev, &r); + a.rejected = b.rejected; + g_unit_cases++; + if (r != OSC_REJ_BORROW_OUTLIVES_OWNER || memcmp(&a, &b, sizeof a) != 0) { + printf("UNIT FAIL reject-unchanged\n"); + g_unit_fail++; + } + } + /* names */ + g_unit_cases++; + if (strcmp(osc_model_reject_name(OSC_REJ_LIVE_HANDLE_DURABLE), "live-handle-durable") != 0 || + strcmp(osc_model_reject_name(OSC_REJ_NONE), "accept") != 0 || + strcmp(osc_model_reject_name((OscModelReject)99), "?") != 0 || OSC_REJ_LIVE_HANDLE_DURABLE != 13) { + printf("UNIT FAIL names\n"); + g_unit_fail++; + } +} + +typedef struct { uint64_t injected, correct, wrong, accepted, gen_fail; } ClassCount; + +static uint64_t fnv(uint64_t h, const void *p, size_t n) +{ + const unsigned char *c = p; + for (size_t i = 0; i < n; i++) { h ^= c[i]; h *= 0x100000001B3ull; } + return h; +} + +int main(int argc, char **argv) +{ + uint64_t seed = DEFAULT_SEED, nseq = GATE_MIN_SEQUENCES; + if (argc > 1) seed = strtoull(argv[1], NULL, 16); + if (argc > 2) nseq = strtoull(argv[2], NULL, 10); + + unit_tests(); + printf("OSC0B_MODEL_UNIT cases=%d failed=%d\n", g_unit_cases, g_unit_fail); + + struct timespec t0, t1; + clock_gettime(CLOCK_MONOTONIC, &t0); + + static OscGenSeq q; + ClassCount cc[OSC_MODEL_NAMED_COUNT + 1]; + memset(cc, 0, sizeof cc); + uint64_t steps = 0, valid_seqs = 0, false_rejects = 0, false_accepts = 0, wrong = 0; + uint64_t gen_fail = 0, state_changed = 0, wrong_shown = 0; + uint64_t digest = 0xCBF29CE484222325ull; + uint64_t crng = seed ^ 0xA5A5C3C35A5A3C3Cull; + + for (uint64_t i = 0; i < nseq; i++) { + uint64_t x = osc_gen_splitmix64(&crng); + OscModelReject cls = (x & 3) == 0 ? OSC_REJ_NONE : (OscModelReject)(1 + (x >> 8) % OSC_MODEL_NAMED_COUNT); + if (osc_gen_sequence(seed, i, cls, &q) != 0) { + gen_fail++; + if (cls) cc[cls].gen_fail++; + continue; + } + if (cls == OSC_REJ_NONE) valid_seqs++; else cc[cls].injected++; + + OscModel m, snap; + osc_model_init(&m, q.gen_base, q.gen_max); + for (int k = 0; k < q.n; k++) { + OscModelReject r; + if (k == q.inject_at) snap = m; + osc_model_step(&m, &q.ev[k], &r); + steps++; + digest = fnv(digest, &r, sizeof r); + if (k == q.inject_at) { + if (r == OSC_REJ_NONE) { + false_accepts++; cc[cls].accepted++; + if (wrong_shown++ < 5) + printf("FALSE ACCEPT seq=%" PRIu64 " class=%s variant=%d step=%d\n", i, + osc_model_reject_name(cls), q.variant, k); + break; + } + if (r == q.expect) cc[cls].correct++; + else { + wrong++; cc[cls].wrong++; + if (wrong_shown++ < 5) + printf("WRONG NAME seq=%" PRIu64 " class=%s variant=%d got=%s event=%s\n", i, + osc_model_reject_name(cls), q.variant, osc_model_reject_name(r), + osc_model_event_name(q.ev[k].kind)); + } + snap.rejected = m.rejected; + if (memcmp(&snap, &m, sizeof m) != 0) state_changed++; + } else if (r != OSC_REJ_NONE) { + false_rejects++; + if (wrong_shown++ < 5) + printf("FALSE REJECT seq=%" PRIu64 " class=%s step=%d event=%s got=%s\n", i, + osc_model_reject_name(cls), k, osc_model_event_name(q.ev[k].kind), + osc_model_reject_name(r)); + break; + } + } + } + clock_gettime(CLOCK_MONOTONIC, &t1); + double secs = (double)(t1.tv_sec - t0.tv_sec) + (double)(t1.tv_nsec - t0.tv_nsec) / 1e9; + + int ok = g_unit_fail == 0 && false_accepts == 0 && wrong == 0 && false_rejects == 0 && + gen_fail == 0 && state_changed == 0; + int gate = nseq >= GATE_MIN_SEQUENCES; + for (int c = 1; c <= OSC_MODEL_NAMED_COUNT; c++) { + printf("OSC0B_MODEL_CLASS %-26s injected=%" PRIu64 " rejected_correct=%" PRIu64 + " rejected_wrong_name=%" PRIu64 " accepted=%" PRIu64 "\n", + osc_model_reject_name((OscModelReject)c), cc[c].injected, cc[c].correct, cc[c].wrong, cc[c].accepted); + if (gate && cc[c].injected < GATE_MIN_PER_CLASS) ok = 0; + if (cc[c].correct != cc[c].injected) ok = 0; + } + printf("OSC0B_MODEL_VALID sequences=%" PRIu64 " gen_failures=%" PRIu64 " state_changed_on_reject=%" PRIu64 + " digest=%016" PRIx64 " seconds=%.2f\n", valid_seqs, gen_fail, state_changed, digest, secs); + printf("OSC0B_MODEL_SEED=%016" PRIx64 " SEQUENCES=%" PRIu64 " STEPS=%" PRIu64 " FALSE_ACCEPTS=%" PRIu64 + " WRONG_NAME=%" PRIu64 " FALSE_REJECTS=%" PRIu64 "\n", seed, nseq, steps, false_accepts, wrong, false_rejects); + if (!ok) { printf("OSC0B_MODEL_FAIL\n"); return 1; } + if (!gate) { printf("OSC0B_MODEL_SMOKE_PASS\n"); return 0; } + printf("OSC0B_MODEL_PASS\n"); + return 0; +} From 69ab7ef56fb2ff99fac29a1419917c7d734f5c6a Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Thu, 1 Oct 2026 02:34:56 -0500 Subject: [PATCH 02/10] OSC-1 back end: typed IR contract, reference interpreter, validating AArch64 encoder/decoder, codegen, bootstrap runtime IR validate/encode/digest, interpreter (exact __int128 derivation), own hardened encoder (no silent masking, SP vs XZR distinct, decoder mirror; src/aarch64_encoder.c masks register fields and is left unchanged), slot-per-vreg codegen with checked arithmetic and bounds traps, pool runtime shared by both engines. test_osc_backend: 722k native-vs-interpreter runs agree on result, trap code and pool event log. Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Fable 5.1 --- src/compiler/osc_a64.c | 333 ++++++++++ src/compiler/osc_a64.h | 107 ++++ src/compiler/osc_cg.c | 474 ++++++++++++++ src/compiler/osc_cg.h | 32 + src/compiler/osc_interp.c | 192 ++++++ src/compiler/osc_interp.h | 32 + src/compiler/osc_ir.c | 410 +++++++++++++ src/compiler/osc_ir.h | 179 ++++++ src/compiler/osc_native.c | 42 ++ src/compiler/osc_native.h | 25 + src/compiler/osc_rt.c | 129 ++++ src/compiler/osc_rt.h | 88 +++ tests/compiler/test_osc_backend.c | 983 ++++++++++++++++++++++++++++++ 13 files changed, 3026 insertions(+) create mode 100644 src/compiler/osc_a64.c create mode 100644 src/compiler/osc_a64.h create mode 100644 src/compiler/osc_cg.c create mode 100644 src/compiler/osc_cg.h create mode 100644 src/compiler/osc_interp.c create mode 100644 src/compiler/osc_interp.h create mode 100644 src/compiler/osc_ir.c create mode 100644 src/compiler/osc_ir.h create mode 100644 src/compiler/osc_native.c create mode 100644 src/compiler/osc_native.h create mode 100644 src/compiler/osc_rt.c create mode 100644 src/compiler/osc_rt.h create mode 100644 tests/compiler/test_osc_backend.c diff --git a/src/compiler/osc_a64.c b/src/compiler/osc_a64.c new file mode 100644 index 000000000..ea2bd6e6c --- /dev/null +++ b/src/compiler/osc_a64.c @@ -0,0 +1,333 @@ +/* + * osc_a64.c -- hardened AArch64 encoder + mirror decoder (OSC-1 back end). + * OSC-1 slice; not a general Omega compiler; no self-hosting. + * See osc_a64.h for the rules. Nothing here masks a field: every field is + * range-checked and an out-of-range or wrong-kind operand is refused. + */ +#include "osc_a64.h" + +#include +#include +#include + +typedef enum { + CLS_NONE = 0, CLS_RRR_SH, CLS_RI, CLS_R4, CLS_MULH, CLS_R3, CLS_BFM, CLS_CSINC, + CLS_MOV16, CLS_MEM, CLS_PAIR, CLS_B26, CLS_BCOND, CLS_CB, CLS_BREG, CLS_BRK +} Cls; + +/* operand kinds for rd / rn / rm / ra positions */ +enum { K_NONE = 0, K_ZR, K_SP, K_X }; + +typedef struct { + const char *name; + uint32_t base; + uint8_t cls; + uint8_t kd, kn, km, ka; +} OpInfo; + +static const OpInfo OPS[OSC_A64_NOPS] = { + [OSC_A64_ADD_REG] = {"add", 0x8B000000u, CLS_RRR_SH, K_ZR, K_ZR, K_ZR, K_NONE}, + [OSC_A64_SUB_REG] = {"sub", 0xCB000000u, CLS_RRR_SH, K_ZR, K_ZR, K_ZR, K_NONE}, + [OSC_A64_ADDS_REG] = {"adds", 0xAB000000u, CLS_RRR_SH, K_ZR, K_ZR, K_ZR, K_NONE}, + [OSC_A64_SUBS_REG] = {"subs", 0xEB000000u, CLS_RRR_SH, K_ZR, K_ZR, K_ZR, K_NONE}, + [OSC_A64_ADD_IMM] = {"add", 0x91000000u, CLS_RI, K_SP, K_SP, K_NONE, K_NONE}, + [OSC_A64_SUB_IMM] = {"sub", 0xD1000000u, CLS_RI, K_SP, K_SP, K_NONE, K_NONE}, + [OSC_A64_ADDS_IMM] = {"adds", 0xB1000000u, CLS_RI, K_ZR, K_SP, K_NONE, K_NONE}, + [OSC_A64_SUBS_IMM] = {"subs", 0xF1000000u, CLS_RI, K_ZR, K_SP, K_NONE, K_NONE}, + [OSC_A64_MADD] = {"madd", 0x9B000000u, CLS_R4, K_ZR, K_ZR, K_ZR, K_ZR}, + [OSC_A64_MSUB] = {"msub", 0x9B008000u, CLS_R4, K_ZR, K_ZR, K_ZR, K_ZR}, + [OSC_A64_SMULH] = {"smulh", 0x9B407C00u, CLS_MULH, K_ZR, K_ZR, K_ZR, K_NONE}, + [OSC_A64_UMULH] = {"umulh", 0x9BC07C00u, CLS_MULH, K_ZR, K_ZR, K_ZR, K_NONE}, + [OSC_A64_SDIV] = {"sdiv", 0x9AC00C00u, CLS_R3, K_ZR, K_ZR, K_ZR, K_NONE}, + [OSC_A64_UDIV] = {"udiv", 0x9AC00800u, CLS_R3, K_ZR, K_ZR, K_ZR, K_NONE}, + [OSC_A64_LSLV] = {"lslv", 0x9AC02000u, CLS_R3, K_ZR, K_ZR, K_ZR, K_NONE}, + [OSC_A64_LSRV] = {"lsrv", 0x9AC02400u, CLS_R3, K_ZR, K_ZR, K_ZR, K_NONE}, + [OSC_A64_ASRV] = {"asrv", 0x9AC02800u, CLS_R3, K_ZR, K_ZR, K_ZR, K_NONE}, + [OSC_A64_AND_REG] = {"and", 0x8A000000u, CLS_RRR_SH, K_ZR, K_ZR, K_ZR, K_NONE}, + [OSC_A64_ORR_REG] = {"orr", 0xAA000000u, CLS_RRR_SH, K_ZR, K_ZR, K_ZR, K_NONE}, + [OSC_A64_EOR_REG] = {"eor", 0xCA000000u, CLS_RRR_SH, K_ZR, K_ZR, K_ZR, K_NONE}, + [OSC_A64_ORN_REG] = {"orn", 0xAA200000u, CLS_RRR_SH, K_ZR, K_ZR, K_ZR, K_NONE}, + [OSC_A64_SBFM] = {"sbfm", 0x93400000u, CLS_BFM, K_ZR, K_ZR, K_NONE, K_NONE}, + [OSC_A64_UBFM] = {"ubfm", 0xD3400000u, CLS_BFM, K_ZR, K_ZR, K_NONE, K_NONE}, + [OSC_A64_CSINC] = {"csinc", 0x9A800400u, CLS_CSINC, K_ZR, K_ZR, K_ZR, K_NONE}, + [OSC_A64_MOVZ] = {"movz", 0xD2800000u, CLS_MOV16, K_ZR, K_NONE, K_NONE, K_NONE}, + [OSC_A64_MOVN] = {"movn", 0x92800000u, CLS_MOV16, K_ZR, K_NONE, K_NONE, K_NONE}, + [OSC_A64_MOVK] = {"movk", 0xF2800000u, CLS_MOV16, K_ZR, K_NONE, K_NONE, K_NONE}, + [OSC_A64_LDR_UOFF] = {"ldr", 0xF9400000u, CLS_MEM, K_ZR, K_SP, K_NONE, K_NONE}, + [OSC_A64_STR_UOFF] = {"str", 0xF9000000u, CLS_MEM, K_ZR, K_SP, K_NONE, K_NONE}, + [OSC_A64_STP_OFF] = {"stp", 0xA9000000u, CLS_PAIR, K_ZR, K_SP, K_NONE, K_ZR}, + [OSC_A64_STP_PRE] = {"stp!", 0xA9800000u, CLS_PAIR, K_ZR, K_SP, K_NONE, K_ZR}, + [OSC_A64_STP_POST] = {"stp+", 0xA8800000u, CLS_PAIR, K_ZR, K_SP, K_NONE, K_ZR}, + [OSC_A64_LDP_OFF] = {"ldp", 0xA9400000u, CLS_PAIR, K_ZR, K_SP, K_NONE, K_ZR}, + [OSC_A64_LDP_PRE] = {"ldp!", 0xA9C00000u, CLS_PAIR, K_ZR, K_SP, K_NONE, K_ZR}, + [OSC_A64_LDP_POST] = {"ldp+", 0xA8C00000u, CLS_PAIR, K_ZR, K_SP, K_NONE, K_ZR}, + [OSC_A64_B] = {"b", 0x14000000u, CLS_B26, K_NONE, K_NONE, K_NONE, K_NONE}, + [OSC_A64_BL] = {"bl", 0x94000000u, CLS_B26, K_NONE, K_NONE, K_NONE, K_NONE}, + [OSC_A64_BCOND] = {"b.cond",0x54000000u, CLS_BCOND, K_NONE, K_NONE, K_NONE, K_NONE}, + [OSC_A64_CBZ] = {"cbz", 0xB4000000u, CLS_CB, K_ZR, K_NONE, K_NONE, K_NONE}, + [OSC_A64_CBNZ] = {"cbnz", 0xB5000000u, CLS_CB, K_ZR, K_NONE, K_NONE, K_NONE}, + [OSC_A64_BLR] = {"blr", 0xD63F0000u, CLS_BREG, K_NONE, K_X, K_NONE, K_NONE}, + [OSC_A64_RET] = {"ret", 0xD65F0000u, CLS_BREG, K_NONE, K_X, K_NONE, K_NONE}, + [OSC_A64_BRK] = {"brk", 0xD4200000u, CLS_BRK, K_NONE, K_NONE, K_NONE, K_NONE}, +}; + +/* variable-field mask per class (bits not fixed by the opcode) */ +static uint32_t cls_varmask(int cls) { + switch (cls) { + case CLS_RRR_SH: return 0x00DFFFFFu; /* shift 23:22, Rm 20:16, imm6 15:10, Rn, Rd */ + case CLS_RI: return 0x007FFFFFu; /* sh 22, imm12 21:10, Rn, Rd */ + case CLS_R4: return 0x001F7FFFu; /* Rm, Ra 14:10, Rn, Rd */ + case CLS_MULH: return 0x001F03FFu; + case CLS_R3: return 0x001F03FFu; + case CLS_BFM: return 0x003FFFFFu; + case CLS_CSINC: return 0x001FF3FFu; /* Rm, cond 15:12, Rn, Rd */ + case CLS_MOV16: return 0x007FFFFFu; /* hw 22:21, imm16 20:5, Rd */ + case CLS_MEM: return 0x003FFFFFu; + case CLS_PAIR: return 0x003FFFFFu; /* imm7 21:15, Rt2 14:10, Rn, Rt */ + case CLS_B26: return 0x03FFFFFFu; + case CLS_BCOND: return 0x00FFFFEFu; /* imm19 23:5, cond 3:0 (bit 4 fixed 0) */ + case CLS_CB: return 0x00FFFFFFu; + case CLS_BREG: return 0x000003E0u; + case CLS_BRK: return 0x001FFFE0u; + default: return 0; + } +} + +static int fail(char *err, size_t n, const char *fmt, ...) { + if (err && n) { + va_list ap; + va_start(ap, fmt); + vsnprintf(err, n, fmt, ap); + va_end(ap); + } + return -1; +} + +/* map typed operand -> 5-bit field, refusing the wrong kind */ +static int regfield(int kind, int r, uint32_t *f, const char *pos, const char *op, char *err, size_t n) { + if (r >= 0 && r <= 30) { *f = (uint32_t)r; return 0; } + if (kind == K_ZR && r == OSC_A64_XZR) { *f = 31; return 0; } + if (kind == K_SP && r == OSC_A64_SP) { *f = 31; return 0; } + if (r == OSC_A64_SP) return fail(err, n, "%s: %s cannot be SP", op, pos); + if (r == OSC_A64_XZR) return fail(err, n, "%s: %s cannot be XZR", op, pos); + return fail(err, n, "%s: %s register %d out of range", op, pos, r); +} + +static int unreg(int kind, uint32_t f) { + if (f < 31) return (int)f; + if (kind == K_ZR) return OSC_A64_XZR; + if (kind == K_SP) return OSC_A64_SP; + return 255; /* not encodable: re-encode check refuses */ +} + +static int is_sp(int r) { return r == OSC_A64_SP; } + +int osc_a64_encode(const OscA64Insn *in, uint32_t *word, char *err, size_t n) { + if (!in || !word) return fail(err, n, "null"); + int op = in->op; + if (op <= OSC_A64_INVALID || op >= OSC_A64_NOPS || !OPS[op].name) + return fail(err, n, "unknown op %d", op); + const OpInfo *oi = &OPS[op]; + const char *nm = oi->name; + uint32_t w = oi->base, rd = 0, rn = 0, rm = 0, ra = 0; + /* unused register / field positions must be zero (canonical form) */ + if (oi->kd == K_NONE && in->rd) return fail(err, n, "%s: rd unused but set", nm); + if (oi->kn == K_NONE && in->rn) return fail(err, n, "%s: rn unused but set", nm); + if (oi->km == K_NONE && in->rm) return fail(err, n, "%s: rm unused but set", nm); + if (oi->ka == K_NONE && in->ra) return fail(err, n, "%s: ra unused but set", nm); + if (oi->kd != K_NONE && regfield(oi->kd, in->rd, &rd, "rd", nm, err, n)) return -1; + if (oi->kn != K_NONE && regfield(oi->kn, in->rn, &rn, "rn", nm, err, n)) return -1; + if (oi->km != K_NONE && regfield(oi->km, in->rm, &rm, "rm", nm, err, n)) return -1; + if (oi->ka != K_NONE && regfield(oi->ka, in->ra, &ra, "ra", nm, err, n)) return -1; + int uses_shift = oi->cls == CLS_RRR_SH; + int uses_cond = oi->cls == CLS_CSINC || oi->cls == CLS_BCOND; + int uses_imm2 = oi->cls == CLS_RI || oi->cls == CLS_BFM || oi->cls == CLS_MOV16; + int uses_imm = !(oi->cls == CLS_R4 || oi->cls == CLS_MULH || oi->cls == CLS_R3 || + oi->cls == CLS_CSINC || oi->cls == CLS_BREG); + if (!uses_shift && in->shift) return fail(err, n, "%s: shift unused but set", nm); + if (!uses_cond && in->cond) return fail(err, n, "%s: cond unused but set", nm); + if (!uses_imm2 && in->imm2) return fail(err, n, "%s: imm2 unused but set", nm); + if (!uses_imm && in->imm) return fail(err, n, "%s: imm unused but set", nm); + int64_t imm = in->imm, imm2 = in->imm2; + + switch (oi->cls) { + case CLS_RRR_SH: + if (in->shift > OSC_A64_ASR) return fail(err, n, "%s: shift type %u refused", nm, in->shift); + if (imm < 0 || imm > 63) return fail(err, n, "%s: shift amount %lld out of range", nm, (long long)imm); + w |= ((uint32_t)in->shift << 22) | (rm << 16) | ((uint32_t)imm << 10) | (rn << 5) | rd; + break; + case CLS_RI: + if (imm < 0 || imm > 4095) return fail(err, n, "%s: imm12 %lld out of range", nm, (long long)imm); + if (imm2 != 0 && imm2 != 1) return fail(err, n, "%s: lsl12 flag %lld invalid", nm, (long long)imm2); + w |= ((uint32_t)imm2 << 22) | ((uint32_t)imm << 10) | (rn << 5) | rd; + break; + case CLS_R4: + w |= (rm << 16) | (ra << 10) | (rn << 5) | rd; + break; + case CLS_MULH: + case CLS_R3: + w |= (rm << 16) | (rn << 5) | rd; + break; + case CLS_BFM: + if (imm < 0 || imm > 63) return fail(err, n, "%s: immr %lld out of range", nm, (long long)imm); + if (imm2 < 0 || imm2 > 63) return fail(err, n, "%s: imms %lld out of range", nm, (long long)imm2); + w |= ((uint32_t)imm << 16) | ((uint32_t)imm2 << 10) | (rn << 5) | rd; + break; + case CLS_CSINC: + if (in->cond > OSC_A64_AL) return fail(err, n, "%s: cond %u refused", nm, in->cond); + w |= (rm << 16) | ((uint32_t)in->cond << 12) | (rn << 5) | rd; + break; + case CLS_MOV16: + if (imm < 0 || imm > 0xFFFF) return fail(err, n, "%s: imm16 %lld out of range", nm, (long long)imm); + if (imm2 != 0 && imm2 != 16 && imm2 != 32 && imm2 != 48) + return fail(err, n, "%s: shift %lld invalid", nm, (long long)imm2); + w |= ((uint32_t)(imm2 / 16) << 21) | ((uint32_t)imm << 5) | rd; + break; + case CLS_MEM: + if (imm < 0 || imm > 4095 * 8 || (imm & 7)) + return fail(err, n, "%s: offset %lld not a multiple of 8 in 0..32760", nm, (long long)imm); + w |= ((uint32_t)(imm / 8) << 10) | (rn << 5) | rd; + break; + case CLS_PAIR: { + if (imm < -512 || imm > 504 || (imm & 7)) + return fail(err, n, "%s: offset %lld not a multiple of 8 in -512..504", nm, (long long)imm); + int wb = op == OSC_A64_STP_PRE || op == OSC_A64_STP_POST || op == OSC_A64_LDP_PRE || op == OSC_A64_LDP_POST; + int load = op == OSC_A64_LDP_OFF || op == OSC_A64_LDP_PRE || op == OSC_A64_LDP_POST; + if (wb && !is_sp(in->rn) && (in->rn == in->rd || in->rn == in->ra)) + return fail(err, n, "%s: writeback base equals a transfer register (unpredictable)", nm); + if (load && in->rd == in->ra) + return fail(err, n, "%s: Rt == Rt2 (unpredictable)", nm); + uint32_t i7 = (uint32_t)((imm / 8) & 0x7F); + w |= (i7 << 15) | (ra << 10) | (rn << 5) | rd; + break; + } + case CLS_B26: + if ((imm & 3) || imm < -(1LL << 27) || imm > (1LL << 27) - 4) + return fail(err, n, "%s: offset %lld out of range or misaligned", nm, (long long)imm); + w |= (uint32_t)((imm / 4) & 0x03FFFFFF); + break; + case CLS_BCOND: + if (in->cond > 13) return fail(err, n, "%s: cond %u refused (AL/NV not used)", nm, in->cond); + if ((imm & 3) || imm < -(1LL << 20) || imm > (1LL << 20) - 4) + return fail(err, n, "%s: offset %lld out of range or misaligned", nm, (long long)imm); + w |= ((uint32_t)((imm / 4) & 0x7FFFF) << 5) | in->cond; + break; + case CLS_CB: + if ((imm & 3) || imm < -(1LL << 20) || imm > (1LL << 20) - 4) + return fail(err, n, "%s: offset %lld out of range or misaligned", nm, (long long)imm); + w |= ((uint32_t)((imm / 4) & 0x7FFFF) << 5) | rd; + break; + case CLS_BREG: + w |= rn << 5; + break; + case CLS_BRK: + if (imm < 0 || imm > 0xFFFF) return fail(err, n, "%s: imm16 %lld out of range", nm, (long long)imm); + w |= (uint32_t)imm << 5; + break; + default: + return fail(err, n, "bad class"); + } + *word = w; + return 0; +} + +int osc_a64_reencode(const OscA64Insn *in, uint32_t *word) { + return osc_a64_encode(in, word, NULL, 0); +} + +static int64_t sext(uint32_t v, unsigned bits) { + uint64_t m = 1ULL << (bits - 1); + return (int64_t)(((uint64_t)v ^ m) - m); +} + +int osc_a64_decode(uint32_t w, OscA64Insn *out) { + for (int op = 1; op < OSC_A64_NOPS; op++) { + const OpInfo *oi = &OPS[op]; + if (!oi->name) continue; + if ((w & ~cls_varmask(oi->cls)) != oi->base) continue; + OscA64Insn d; + memset(&d, 0, sizeof d); + d.op = (uint8_t)op; + uint32_t f_rd = w & 31, f_rn = (w >> 5) & 31, f_rm = (w >> 16) & 31, f_ra = (w >> 10) & 31; + if (oi->kd != K_NONE) d.rd = (uint8_t)unreg(oi->kd, f_rd); + if (oi->kn != K_NONE) d.rn = (uint8_t)unreg(oi->kn, f_rn); + if (oi->km != K_NONE) d.rm = (uint8_t)unreg(oi->km, f_rm); + if (oi->ka != K_NONE) d.ra = (uint8_t)unreg(oi->ka, f_ra); + switch (oi->cls) { + case CLS_RRR_SH: d.shift = (uint8_t)((w >> 22) & 3); d.imm = (w >> 10) & 63; break; + case CLS_RI: d.imm = (w >> 10) & 0xFFF; d.imm2 = (w >> 22) & 1; break; + case CLS_BFM: d.imm = (w >> 16) & 63; d.imm2 = (w >> 10) & 63; break; + case CLS_CSINC: d.cond = (uint8_t)((w >> 12) & 15); break; + case CLS_MOV16: d.imm = (w >> 5) & 0xFFFF; d.imm2 = ((w >> 21) & 3) * 16; break; + case CLS_MEM: d.imm = (int64_t)((w >> 10) & 0xFFF) * 8; break; + case CLS_PAIR: d.imm = sext((w >> 15) & 0x7F, 7) * 8; break; + case CLS_B26: d.imm = sext(w & 0x03FFFFFF, 26) * 4; break; + case CLS_BCOND: d.imm = sext((w >> 5) & 0x7FFFF, 19) * 4; d.cond = (uint8_t)(w & 15); break; + case CLS_CB: d.imm = sext((w >> 5) & 0x7FFFF, 19) * 4; break; + case CLS_BRK: d.imm = (w >> 5) & 0xFFFF; break; + default: break; + } + uint32_t re; + if (osc_a64_encode(&d, &re, NULL, 0) != 0 || re != w) continue; + if (out) *out = d; + return 0; + } + return -1; +} + +const char *osc_a64_op_name(int op) { + if (op <= 0 || op >= OSC_A64_NOPS || !OPS[op].name) return "?"; + return OPS[op].name; +} + +int osc_a64_equal(const OscA64Insn *x, const OscA64Insn *y) { + return x->op == y->op && x->rd == y->rd && x->rn == y->rn && x->rm == y->rm && + x->ra == y->ra && x->shift == y->shift && x->cond == y->cond && + x->imm == y->imm && x->imm2 == y->imm2; +} + +/* ---- constructors ----------------------------------------------------- */ +static OscA64Insn mk(int op) { + OscA64Insn i; + memset(&i, 0, sizeof i); + i.op = (uint8_t)op; + return i; +} +/* registers are passed as int; values outside uint8 are clamped to 255 + * (never a valid operand) so the encoder refuses them rather than wrapping */ +static uint8_t r8(int r) { return (r < 0 || r > 254) ? 255 : (uint8_t)r; } + +OscA64Insn osc_a64_r3(OscA64Op op, int rd, int rn, int rm) { + OscA64Insn i = mk(op); i.rd = r8(rd); i.rn = r8(rn); i.rm = r8(rm); return i; +} +OscA64Insn osc_a64_r3s(OscA64Op op, int rd, int rn, int rm, OscA64Shift sh, int amount) { + OscA64Insn i = osc_a64_r3(op, rd, rn, rm); i.shift = (uint8_t)sh; i.imm = amount; return i; +} +OscA64Insn osc_a64_ri(OscA64Op op, int rd, int rn, int64_t imm12, int lsl12) { + OscA64Insn i = mk(op); i.rd = r8(rd); i.rn = r8(rn); i.imm = imm12; i.imm2 = lsl12; return i; +} +OscA64Insn osc_a64_r4(OscA64Op op, int rd, int rn, int rm, int ra) { + OscA64Insn i = osc_a64_r3(op, rd, rn, rm); i.ra = r8(ra); return i; +} +OscA64Insn osc_a64_bfm(OscA64Op op, int rd, int rn, int immr, int imms) { + OscA64Insn i = mk(op); i.rd = r8(rd); i.rn = r8(rn); i.imm = immr; i.imm2 = imms; return i; +} +OscA64Insn osc_a64_csinc(int rd, int rn, int rm, OscA64Cond c) { + OscA64Insn i = osc_a64_r3(OSC_A64_CSINC, rd, rn, rm); i.cond = (uint8_t)c; return i; +} +OscA64Insn osc_a64_mov16(OscA64Op op, int rd, int64_t imm16, int shift) { + OscA64Insn i = mk(op); i.rd = r8(rd); i.imm = imm16; i.imm2 = shift; return i; +} +OscA64Insn osc_a64_mem(OscA64Op op, int rt, int rn, int64_t off) { + OscA64Insn i = mk(op); i.rd = r8(rt); i.rn = r8(rn); i.imm = off; return i; +} +OscA64Insn osc_a64_pair(OscA64Op op, int rt, int rt2, int rn, int64_t off) { + OscA64Insn i = mk(op); i.rd = r8(rt); i.ra = r8(rt2); i.rn = r8(rn); i.imm = off; return i; +} +OscA64Insn osc_a64_br(OscA64Op op, int64_t off) { OscA64Insn i = mk(op); i.imm = off; return i; } +OscA64Insn osc_a64_bcond(OscA64Cond c, int64_t off) { + OscA64Insn i = mk(OSC_A64_BCOND); i.cond = (uint8_t)c; i.imm = off; return i; +} +OscA64Insn osc_a64_cb(OscA64Op op, int rt, int64_t off) { OscA64Insn i = mk(op); i.rd = r8(rt); i.imm = off; return i; } +OscA64Insn osc_a64_breg(OscA64Op op, int rn) { OscA64Insn i = mk(op); i.rn = r8(rn); return i; } +OscA64Insn osc_a64_brk(int64_t imm16) { OscA64Insn i = mk(OSC_A64_BRK); i.imm = imm16; return i; } diff --git a/src/compiler/osc_a64.h b/src/compiler/osc_a64.h new file mode 100644 index 000000000..572d624de --- /dev/null +++ b/src/compiler/osc_a64.h @@ -0,0 +1,107 @@ +/* + * osc_a64.h -- hardened AArch64 encoder + mirror decoder for the OSC-1 back end. + * + * OSC-1 slice; not a general Omega compiler; no self-hosting. + * + * Rules (docs/osc/OSC-1-DESIGN.md section 7, audit III.6): + * - every field is range-checked; an out-of-range field is refused, never masked; + * - SP and XZR are distinct operand kinds (OSC_A64_SP / OSC_A64_XZR). Raw + * register number 31 is not a valid operand: callers must say which one; + * each operand position accepts only the kind the architecture gives it; + * - only 64-bit (X) forms are produced; + * - osc_a64_decode is the mirror: it accepts exactly the words this encoder + * can produce and returns the same fields, so encode(decode(w)) == w and + * decode(encode(i)) == i (for i in canonical form, see below). + * + * Canonical form of OscA64Insn: unused fields are 0. + */ +#ifndef OSC_A64_H +#define OSC_A64_H + +#include +#include + +/* Register operands: 0..30 = X0..X30; the two meanings of encoding 31. */ +#define OSC_A64_XZR 32 +#define OSC_A64_SP 33 + +typedef enum { + OSC_A64_INVALID = 0, + /* shifted-register arithmetic: rd rn rm, shift (LSL/LSR/ASR), imm = amount 0..63 */ + OSC_A64_ADD_REG, OSC_A64_SUB_REG, OSC_A64_ADDS_REG, OSC_A64_SUBS_REG, + /* immediate arithmetic: rd rn, imm = imm12 0..4095, imm2 = 1 for LSL #12 */ + OSC_A64_ADD_IMM, OSC_A64_SUB_IMM, OSC_A64_ADDS_IMM, OSC_A64_SUBS_IMM, + /* rd = ra +/- rn*rm */ + OSC_A64_MADD, OSC_A64_MSUB, + /* rd = high 64 bits of rn*rm */ + OSC_A64_SMULH, OSC_A64_UMULH, + /* two-source: rd rn rm */ + OSC_A64_SDIV, OSC_A64_UDIV, OSC_A64_LSLV, OSC_A64_LSRV, OSC_A64_ASRV, + /* logical shifted register: rd rn rm, shift (LSL/LSR/ASR), imm = amount */ + OSC_A64_AND_REG, OSC_A64_ORR_REG, OSC_A64_EOR_REG, OSC_A64_ORN_REG, + /* bitfield: rd rn, imm = immr 0..63, imm2 = imms 0..63 */ + OSC_A64_SBFM, OSC_A64_UBFM, + /* rd = cond ? rn : rm + 1 ; cond 0..14 */ + OSC_A64_CSINC, + /* wide immediates: rd, imm = imm16, imm2 = shift 0/16/32/48 */ + OSC_A64_MOVZ, OSC_A64_MOVN, OSC_A64_MOVK, + /* rd = Rt, rn = base (SP kind), imm = byte offset 0..32760, multiple of 8 */ + OSC_A64_LDR_UOFF, OSC_A64_STR_UOFF, + /* rd = Rt, ra = Rt2, rn = base (SP kind), imm = byte offset -512..504, multiple of 8 */ + OSC_A64_STP_OFF, OSC_A64_STP_PRE, OSC_A64_STP_POST, + OSC_A64_LDP_OFF, OSC_A64_LDP_PRE, OSC_A64_LDP_POST, + /* imm = byte offset relative to this instruction, multiple of 4 */ + OSC_A64_B, OSC_A64_BL, /* +-128 MiB */ + OSC_A64_BCOND, /* cond 0..14, +-1 MiB */ + OSC_A64_CBZ, OSC_A64_CBNZ, /* rd = Rt, +-1 MiB */ + /* rn = target / return register X0..X30 */ + OSC_A64_BLR, OSC_A64_RET, + /* imm = imm16 */ + OSC_A64_BRK, + OSC_A64_NOPS +} OscA64Op; + +typedef enum { OSC_A64_LSL = 0, OSC_A64_LSR = 1, OSC_A64_ASR = 2 } OscA64Shift; + +typedef enum { + OSC_A64_EQ = 0, OSC_A64_NE, OSC_A64_HS, OSC_A64_LO, OSC_A64_MI, OSC_A64_PL, + OSC_A64_VS, OSC_A64_VC, OSC_A64_HI, OSC_A64_LS, OSC_A64_GE, OSC_A64_LT, + OSC_A64_GT, OSC_A64_LE, OSC_A64_AL +} OscA64Cond; + +typedef struct { + uint8_t op; /* OscA64Op */ + uint8_t rd, rn, rm, ra; + uint8_t shift; /* OscA64Shift */ + uint8_t cond; /* OscA64Cond */ + int64_t imm; + int64_t imm2; +} OscA64Insn; + +/* 0 ok (word written), -1 refused (reason in err if err != NULL). */ +int osc_a64_encode(const OscA64Insn *in, uint32_t *word, char *err, size_t n); +/* 0 ok, -1 the word is not one this encoder can produce. */ +int osc_a64_decode(uint32_t word, OscA64Insn *out); +/* Re-encode a decoded instruction (alias of osc_a64_encode, no message). */ +int osc_a64_reencode(const OscA64Insn *in, uint32_t *word); +const char *osc_a64_op_name(int op); +/* 1 if the two instructions are field-identical. */ +int osc_a64_equal(const OscA64Insn *x, const OscA64Insn *y); + +/* Constructors (canonical form); validation happens in osc_a64_encode. */ +OscA64Insn osc_a64_r3(OscA64Op op, int rd, int rn, int rm); +OscA64Insn osc_a64_r3s(OscA64Op op, int rd, int rn, int rm, OscA64Shift sh, int amount); +OscA64Insn osc_a64_ri(OscA64Op op, int rd, int rn, int64_t imm12, int lsl12); +OscA64Insn osc_a64_r4(OscA64Op op, int rd, int rn, int rm, int ra); +OscA64Insn osc_a64_bfm(OscA64Op op, int rd, int rn, int immr, int imms); +OscA64Insn osc_a64_csinc(int rd, int rn, int rm, OscA64Cond c); +OscA64Insn osc_a64_mov16(OscA64Op op, int rd, int64_t imm16, int shift); +OscA64Insn osc_a64_mem(OscA64Op op, int rt, int rn, int64_t off); +OscA64Insn osc_a64_pair(OscA64Op op, int rt, int rt2, int rn, int64_t off); +OscA64Insn osc_a64_br(OscA64Op op, int64_t off); +OscA64Insn osc_a64_bcond(OscA64Cond c, int64_t off); +OscA64Insn osc_a64_cb(OscA64Op op, int rt, int64_t off); +OscA64Insn osc_a64_breg(OscA64Op op, int rn); +OscA64Insn osc_a64_brk(int64_t imm16); + +#endif /* OSC_A64_H */ diff --git a/src/compiler/osc_cg.c b/src/compiler/osc_cg.c new file mode 100644 index 000000000..9ed4dd415 --- /dev/null +++ b/src/compiler/osc_cg.c @@ -0,0 +1,474 @@ +/* + * osc_cg.c -- OSC-1 IR -> AArch64 (DESIGN section 7). + * OSC-1 slice; not a general Omega compiler; no self-hosting. + * + * Frame: stp x29,x30,[sp,#-16]!; mov x29,sp; sub sp,sp,#F; F = 8*nvregs+8 + * rounded up to 16. [sp,#0] = x7 (OscRt*); vreg v at [sp,#8*(v+1)]. Every + * non-parameter slot is zeroed in the prologue (same as the interpreter's + * zero-initialised vregs). Operands are loaded into x9..x13, the result is + * canonicalised (section 5) and stored back. Runtime entry points are called + * with x0 = rt via ldr x16,[x0,#off]; blr x16. Conditional traps branch to + * one stub per trap code at the end of the function. + */ +#include "osc_cg.h" +#include "osc_a64.h" + +#include +#include +#include +#include + +#define SP OSC_A64_SP +#define ZR OSC_A64_XZR + +enum { FIX_BLOCK = 1, FIX_TRAP = 2 }; + +typedef struct { + size_t at; /* word index */ + OscA64Insn insn; /* imm (byte offset) filled at patch time */ + int kind, target; +} Fix; + +typedef struct { + uint32_t *w; + size_t n, cap; + int bad; + char *err; + size_t errn; + /* per function */ + int64_t blk[OSC_MAX_BLOCKS]; + int64_t trapl[OSC_TRAP_RUNTIME + 1]; + int trap_used[OSC_TRAP_RUNTIME + 1]; + Fix *fx; + size_t nfx, capfx; + uint32_t frame; + uint32_t entry_word[OSC_MAX_FUNCS]; +} Cg; + +static void cg_fail(Cg *g, const char *fmt, ...) { + if (g->bad) return; + g->bad = 1; + if (g->err && g->errn) { + va_list ap; + va_start(ap, fmt); + vsnprintf(g->err, g->errn, fmt, ap); + va_end(ap); + } +} + +static size_t here(Cg *g) { return g->n; } + +static void put(Cg *g, uint32_t word) { + if (g->n == g->cap) { + size_t nc = g->cap ? g->cap * 2 : 4096; + uint32_t *p = realloc(g->w, nc * sizeof *p); + if (!p) { cg_fail(g, "out of memory"); return; } + g->w = p; + g->cap = nc; + } + g->w[g->n++] = word; +} + +static void E(Cg *g, OscA64Insn i) { + uint32_t word = 0; + char e[160]; + if (osc_a64_encode(&i, &word, e, sizeof e)) cg_fail(g, "encoder refused %s: %s", osc_a64_op_name(i.op), e); + put(g, word); +} + +static void fix(Cg *g, OscA64Insn i, int kind, int target) { + if (g->nfx == g->capfx) { + size_t nc = g->capfx ? g->capfx * 2 : 256; + Fix *p = realloc(g->fx, nc * sizeof *p); + if (!p) { cg_fail(g, "out of memory"); return; } + g->fx = p; + g->capfx = nc; + } + if (kind == FIX_TRAP) g->trap_used[target] = 1; + g->fx[g->nfx++] = (Fix){here(g), i, kind, target}; + put(g, 0); +} + +static void patch(Cg *g, size_t at, OscA64Insn i, size_t target) { + i.imm = ((int64_t)target - (int64_t)at) * 4; + uint32_t word = 0; + char e[160]; + if (osc_a64_encode(&i, &word, e, sizeof e)) cg_fail(g, "encoder refused branch: %s", e); + if (at < g->n) g->w[at] = word; +} + +/* ---- small emission helpers ------------------------------------------- */ +static int64_t slot(int v) { return 8 * ((int64_t)v + 1); } +static void ld(Cg *g, int r, int v) { E(g, osc_a64_mem(OSC_A64_LDR_UOFF, r, SP, slot(v))); } +static void st(Cg *g, int r, int v) { E(g, osc_a64_mem(OSC_A64_STR_UOFF, r, SP, slot(v))); } + +static void mat(Cg *g, int r, uint64_t imm) { + int zeros = 0, ones = 0; + for (int i = 0; i < 4; i++) { + uint16_t c = (uint16_t)(imm >> (16 * i)); + zeros += c == 0; + ones += c == 0xFFFF; + } + int first = 1; + if (ones > zeros) { + for (int i = 0; i < 4; i++) { + uint16_t c = (uint16_t)(imm >> (16 * i)); + if (c == 0xFFFF) continue; + if (first) { E(g, osc_a64_mov16(OSC_A64_MOVN, r, (uint16_t)~c, 16 * i)); first = 0; } + else E(g, osc_a64_mov16(OSC_A64_MOVK, r, c, 16 * i)); + } + if (first) E(g, osc_a64_mov16(OSC_A64_MOVN, r, 0, 0)); /* all ones */ + } else { + for (int i = 0; i < 4; i++) { + uint16_t c = (uint16_t)(imm >> (16 * i)); + if (c == 0) continue; + if (first) { E(g, osc_a64_mov16(OSC_A64_MOVZ, r, c, 16 * i)); first = 0; } + else E(g, osc_a64_mov16(OSC_A64_MOVK, r, c, 16 * i)); + } + if (first) E(g, osc_a64_mov16(OSC_A64_MOVZ, r, 0, 0)); + } +} + +static void trap_if(Cg *g, OscA64Cond c, int code) { fix(g, osc_a64_bcond(c, 0), FIX_TRAP, code); } +static void cmp_rr(Cg *g, int a, int b) { E(g, osc_a64_r3s(OSC_A64_SUBS_REG, ZR, a, b, OSC_A64_LSL, 0)); } +static void cmp_ri(Cg *g, int a, int imm) { E(g, osc_a64_ri(OSC_A64_SUBS_IMM, ZR, a, imm, 0)); } + +/* unsigned w<64: zero-extend in place */ +static void zext(Cg *g, int r, unsigned w) { + if (w < 64) E(g, osc_a64_bfm(OSC_A64_UBFM, r, r, 0, (int)w - 1)); +} +/* signed w<64: r must equal sext_w(r) else OVERFLOW (uses x12) */ +static void schk(Cg *g, int r, unsigned w, int code) { + if (w >= 64) return; + E(g, osc_a64_bfm(OSC_A64_SBFM, 12, r, 0, (int)w - 1)); + cmp_rr(g, 12, r); + trap_if(g, OSC_A64_NE, code); +} + +static void rt_call(Cg *g, int off) { + E(g, osc_a64_mem(OSC_A64_LDR_UOFF, 16, 0, off)); + E(g, osc_a64_breg(OSC_A64_BLR, 16)); +} +static void load_rt(Cg *g, int r) { E(g, osc_a64_mem(OSC_A64_LDR_UOFF, r, SP, 0)); } + +static void trap_seq(Cg *g, int code) { + load_rt(g, 0); + mat(g, 1, (uint64_t)code); + rt_call(g, 16); + E(g, osc_a64_brk(code)); /* never reached: osc_rt_trap does not return */ +} + +static OscA64Cond cc_of(unsigned cc, bool s) { + switch (cc) { + case OSC_C_EQ: return OSC_A64_EQ; + case OSC_C_NE: return OSC_A64_NE; + case OSC_C_LT: return s ? OSC_A64_LT : OSC_A64_LO; + case OSC_C_LE: return s ? OSC_A64_LE : OSC_A64_LS; + case OSC_C_GT: return s ? OSC_A64_GT : OSC_A64_HI; + default: return s ? OSC_A64_GE : OSC_A64_HS; + } +} + +static void bounds(Cg *g, int idx, unsigned len) { + /* unsigned compare: a negative signed index is >= 2^63 and fails too */ + cmp_ri(g, idx, (int)len); + trap_if(g, OSC_A64_HS, OSC_TRAP_BOUNDS); +} + +static void gen_bin(Cg *g, const OscFunc *f, const OscInsn *in) { + OscScalar t = f->vtype[in->a].s; + unsigned w = osc_scalar_width(t); + bool s = osc_scalar_signed(t); + ld(g, 9, in->a); + ld(g, 10, in->b); + switch (in->sub) { + case OSC_B_ADD: + case OSC_B_SUB: { + bool add = in->sub == OSC_B_ADD; + if (s && w == 64) { + E(g, osc_a64_r3s(add ? OSC_A64_ADDS_REG : OSC_A64_SUBS_REG, 11, 9, 10, OSC_A64_LSL, 0)); + trap_if(g, OSC_A64_VS, OSC_TRAP_OVERFLOW); + } else { + E(g, osc_a64_r3s(add ? OSC_A64_ADD_REG : OSC_A64_SUB_REG, 11, 9, 10, OSC_A64_LSL, 0)); + if (s) schk(g, 11, w, OSC_TRAP_OVERFLOW); else zext(g, 11, w); + } + break; + } + case OSC_B_MUL: + E(g, osc_a64_r4(OSC_A64_MADD, 11, 9, 10, ZR)); + if (s && w == 64) { + E(g, osc_a64_r3(OSC_A64_SMULH, 12, 9, 10)); + E(g, osc_a64_bfm(OSC_A64_SBFM, 13, 11, 63, 63)); /* asr x13, x11, #63 */ + cmp_rr(g, 12, 13); + trap_if(g, OSC_A64_NE, OSC_TRAP_OVERFLOW); + } else if (s) { + schk(g, 11, w, OSC_TRAP_OVERFLOW); + } else { + zext(g, 11, w); + } + break; + case OSC_B_DIV: + fix(g, osc_a64_cb(OSC_A64_CBZ, 10, 0), FIX_TRAP, OSC_TRAP_DIV0); + if (!s) { + E(g, osc_a64_r3(OSC_A64_UDIV, 11, 9, 10)); + } else { + if (w == 64) { + /* INT64_MIN / -1: SDIV would silently give INT64_MIN */ + E(g, osc_a64_ri(OSC_A64_ADDS_IMM, ZR, 10, 1, 0)); /* cmn x10, #1 */ + size_t skip = here(g); + put(g, 0); + E(g, osc_a64_mov16(OSC_A64_MOVZ, 12, 0x8000, 48)); + cmp_rr(g, 9, 12); + trap_if(g, OSC_A64_EQ, OSC_TRAP_OVERFLOW); + patch(g, skip, osc_a64_bcond(OSC_A64_NE, 0), here(g)); + } + E(g, osc_a64_r3(OSC_A64_SDIV, 11, 9, 10)); + schk(g, 11, w, OSC_TRAP_OVERFLOW); /* narrow MIN / -1 */ + } + break; + case OSC_B_REM: + fix(g, osc_a64_cb(OSC_A64_CBZ, 10, 0), FIX_TRAP, OSC_TRAP_DIV0); + E(g, osc_a64_r3(s ? OSC_A64_SDIV : OSC_A64_UDIV, 12, 9, 10)); + E(g, osc_a64_r4(OSC_A64_MSUB, 11, 12, 10, 9)); /* x11 = x9 - x12*x10 */ + break; + case OSC_B_AND: E(g, osc_a64_r3s(OSC_A64_AND_REG, 11, 9, 10, OSC_A64_LSL, 0)); break; + case OSC_B_OR: E(g, osc_a64_r3s(OSC_A64_ORR_REG, 11, 9, 10, OSC_A64_LSL, 0)); break; + case OSC_B_XOR: E(g, osc_a64_r3s(OSC_A64_EOR_REG, 11, 9, 10, OSC_A64_LSL, 0)); break; + case OSC_B_SHL: + case OSC_B_SHR: + /* amount in 0..w-1; a negative signed amount is >= 2^63 unsigned */ + cmp_ri(g, 10, (int)w); + trap_if(g, OSC_A64_HS, OSC_TRAP_SHIFT); + if (in->sub == OSC_B_SHR) { + E(g, osc_a64_r3(s ? OSC_A64_ASRV : OSC_A64_LSRV, 11, 9, 10)); + } else if (!s) { + E(g, osc_a64_r3(OSC_A64_LSLV, 11, 9, 10)); + zext(g, 11, w); + } else { + E(g, osc_a64_r3(OSC_A64_LSLV, 11, 9, 10)); + if (w < 64) E(g, osc_a64_bfm(OSC_A64_SBFM, 11, 11, 0, (int)w - 1)); + E(g, osc_a64_r3(OSC_A64_ASRV, 12, 11, 10)); /* shifting back must give a */ + cmp_rr(g, 12, 9); + trap_if(g, OSC_A64_NE, OSC_TRAP_OVERFLOW); + } + break; + default: + cg_fail(g, "bad BIN sub-op"); + } + st(g, 11, in->dst); +} + +static void gen_un(Cg *g, const OscFunc *f, const OscInsn *in) { + OscScalar t = f->vtype[in->a].s; + unsigned w = osc_scalar_width(t); + bool s = osc_scalar_signed(t); + ld(g, 9, in->a); + switch (in->sub) { + case OSC_U_NEG: + if (s && w == 64) { + E(g, osc_a64_r3s(OSC_A64_SUBS_REG, 11, ZR, 9, OSC_A64_LSL, 0)); + trap_if(g, OSC_A64_VS, OSC_TRAP_OVERFLOW); + } else { + E(g, osc_a64_r3s(OSC_A64_SUB_REG, 11, ZR, 9, OSC_A64_LSL, 0)); + if (s) schk(g, 11, w, OSC_TRAP_OVERFLOW); else zext(g, 11, w); + } + break; + case OSC_U_BNOT: + E(g, osc_a64_r3s(OSC_A64_ORN_REG, 11, ZR, 9, OSC_A64_LSL, 0)); + if (!s) zext(g, 11, w); + break; + case OSC_U_LNOT: + E(g, osc_a64_mov16(OSC_A64_MOVZ, 12, 1, 0)); + E(g, osc_a64_r3s(OSC_A64_EOR_REG, 11, 9, 12, OSC_A64_LSL, 0)); + break; + default: + cg_fail(g, "bad UN sub-op"); + } + st(g, 11, in->dst); +} + +static void gen_cast(Cg *g, const OscFunc *f, const OscInsn *in) { + OscScalar from = f->vtype[in->a].s, to = f->vtype[in->dst].s; + unsigned wf = osc_scalar_width(from), wt = osc_scalar_width(to); + ld(g, 9, in->a); + if (!osc_scalar_signed(to)) { + if (osc_scalar_signed(from)) { cmp_ri(g, 9, 0); trap_if(g, OSC_A64_LT, OSC_TRAP_CAST); } + if (wt < 64) { + E(g, osc_a64_bfm(OSC_A64_UBFM, 12, 9, 0, (int)wt - 1)); + cmp_rr(g, 12, 9); + trap_if(g, OSC_A64_NE, OSC_TRAP_CAST); + } + } else { + if (!osc_scalar_signed(from) && wf == 64) { cmp_ri(g, 9, 0); trap_if(g, OSC_A64_LT, OSC_TRAP_CAST); } + if (wt < 64) { + E(g, osc_a64_bfm(OSC_A64_SBFM, 12, 9, 0, (int)wt - 1)); + cmp_rr(g, 12, 9); + trap_if(g, OSC_A64_NE, OSC_TRAP_CAST); + } + } + st(g, 9, in->dst); +} + +static void epilogue(Cg *g) { + E(g, osc_a64_ri(OSC_A64_ADD_IMM, SP, SP, g->frame, 0)); + E(g, osc_a64_pair(OSC_A64_LDP_POST, 29, 30, SP, 16)); + E(g, osc_a64_breg(OSC_A64_RET, 30)); +} + +static void gen_func(Cg *g, const OscUnit *u, int fi) { + const OscFunc *f = &u->funcs[fi]; + g->entry_word[fi] = (uint32_t)here(g); + g->frame = (8u * f->nvregs + 8u + 15u) & ~15u; + g->nfx = 0; + for (int b = 0; b < OSC_MAX_BLOCKS; b++) g->blk[b] = -1; + for (int c = 0; c <= OSC_TRAP_RUNTIME; c++) { g->trapl[c] = -1; g->trap_used[c] = 0; } + + /* prologue */ + E(g, osc_a64_pair(OSC_A64_STP_PRE, 29, 30, SP, -16)); + E(g, osc_a64_ri(OSC_A64_ADD_IMM, 29, SP, 0, 0)); /* mov x29, sp */ + E(g, osc_a64_ri(OSC_A64_SUB_IMM, SP, SP, g->frame, 0)); + E(g, osc_a64_mem(OSC_A64_STR_UOFF, 7, SP, 0)); /* slot 0 = rt */ + for (int v = f->nparams; v < f->nvregs; v++) st(g, ZR, v); /* zero-init */ + for (int p = 0; p < f->nparams; p++) st(g, p, p); + + for (int b = 0; b < f->nblocks; b++) { + g->blk[b] = (int64_t)here(g); + const OscBlock *bl = &f->blocks[b]; + for (uint32_t i = bl->first; i < bl->first + bl->count; i++) { + const OscInsn *in = &f->insns[i]; + const OscType *T = f->vtype; + switch (in->op) { + case OSC_I_CONST: mat(g, 9, in->imm); st(g, 9, in->dst); break; + case OSC_I_MOV: ld(g, 9, in->a); st(g, 9, in->dst); break; + case OSC_I_BIN: gen_bin(g, f, in); break; + case OSC_I_UN: gen_un(g, f, in); break; + case OSC_I_CMP: { + bool s = osc_scalar_signed(T[in->a].s); + ld(g, 9, in->a); + ld(g, 10, in->b); + cmp_rr(g, 9, 10); + /* cset x11, cc == csinc x11, xzr, xzr, !cc */ + E(g, osc_a64_csinc(11, ZR, ZR, (OscA64Cond)(cc_of(in->sub, s) ^ 1))); + st(g, 11, in->dst); + break; + } + case OSC_I_CAST: gen_cast(g, f, in); break; + case OSC_I_ALLOC: + load_rt(g, 0); + mat(g, 1, T[in->dst].len); + ld(g, 2, in->a); + rt_call(g, 0); + st(g, 0, in->dst); + break; + case OSC_I_RELEASE: + load_rt(g, 0); + ld(g, 1, in->a); + mat(g, 2, T[in->a].len); + rt_call(g, 8); + break; + case OSC_I_LOAD: + case OSC_I_STORE: + ld(g, 9, in->a); + ld(g, 10, in->b); + if (in->op == OSC_I_STORE) ld(g, 11, in->c); + bounds(g, 10, T[in->a].len); + E(g, osc_a64_r3s(OSC_A64_ADD_REG, 12, 9, 10, OSC_A64_LSL, 3)); + if (in->op == OSC_I_LOAD) { + E(g, osc_a64_mem(OSC_A64_LDR_UOFF, 11, 12, 0)); + st(g, 11, in->dst); + } else { + E(g, osc_a64_mem(OSC_A64_STR_UOFF, 11, 12, 0)); + } + break; + case OSC_I_CALL: + for (int k = 0; k < in->nargs; k++) ld(g, k, in->args[k]); + load_rt(g, 7); + E(g, osc_a64_br(OSC_A64_BL, ((int64_t)g->entry_word[in->callee] - (int64_t)here(g)) * 4)); + if (in->dst >= 0) st(g, 0, in->dst); + break; + case OSC_I_TRAP: trap_seq(g, (int)in->imm); break; + case OSC_I_BR: fix(g, osc_a64_br(OSC_A64_B, 0), FIX_BLOCK, in->blk_t); break; + case OSC_I_CBR: + ld(g, 9, in->a); + fix(g, osc_a64_cb(OSC_A64_CBNZ, 9, 0), FIX_BLOCK, in->blk_t); + fix(g, osc_a64_br(OSC_A64_B, 0), FIX_BLOCK, in->blk_f); + break; + case OSC_I_RET: + if (in->a >= 0) ld(g, 0, in->a); + else E(g, osc_a64_mov16(OSC_A64_MOVZ, 0, 0, 0)); /* void: x0 = 0 */ + epilogue(g); + break; + default: + cg_fail(g, "func %d: unknown op %u", fi, in->op); + } + } + } + /* trap stubs, in code order */ + for (int c = 1; c <= OSC_TRAP_RUNTIME; c++) { + if (!g->trap_used[c]) continue; + g->trapl[c] = (int64_t)here(g); + trap_seq(g, c); + } + for (size_t k = 0; k < g->nfx; k++) { + Fix *x = &g->fx[k]; + int64_t t = x->kind == FIX_BLOCK ? g->blk[x->target] : g->trapl[x->target]; + if (t < 0) { cg_fail(g, "func %d: unresolved label", fi); continue; } + patch(g, x->at, x->insn, (size_t)t); + } +} + +int osc_cg_verify(const OscCode *c, char *err, size_t n) { + if (!c || !c->code || (c->len & 3)) { + if (err && n) snprintf(err, n, "bad code buffer"); + return -1; + } + for (size_t off = 0; off < c->len; off += 4) { + uint32_t w = (uint32_t)c->code[off] | ((uint32_t)c->code[off + 1] << 8) | + ((uint32_t)c->code[off + 2] << 16) | ((uint32_t)c->code[off + 3] << 24); + OscA64Insn d; + uint32_t re; + if (osc_a64_decode(w, &d) || osc_a64_reencode(&d, &re) || re != w) { + if (err && n) snprintf(err, n, "word at +%zu (0x%08x) does not round-trip through the decoder", off, w); + return -1; + } + } + return 0; +} + +int osc_cg_compile(const OscUnit *u, OscCode *out, char *err, size_t n) { + if (!out) return -1; + memset(out, 0, sizeof *out); + if (!u) return -1; + if (osc_ir_validate(u, err, n)) return -1; + Cg g; + memset(&g, 0, sizeof g); + g.err = err; + g.errn = n; + for (int fi = 0; fi < u->nfuncs && !g.bad; fi++) gen_func(&g, u, fi); + if (!g.bad && g.n == 0) cg_fail(&g, "empty unit"); + if (g.bad) { + free(g.w); + free(g.fx); + return -1; + } + out->code = malloc(g.n * 4); + if (!out->code) { free(g.w); free(g.fx); return -1; } + for (size_t i = 0; i < g.n; i++) + for (int b = 0; b < 4; b++) out->code[4 * i + b] = (uint8_t)(g.w[i] >> (8 * b)); + out->len = g.n * 4; + out->nfuncs = u->nfuncs; + for (int fi = 0; fi < u->nfuncs; fi++) out->entry[fi] = g.entry_word[fi] * 4; + free(g.w); + free(g.fx); + if (osc_cg_verify(out, err, n)) { + osc_cg_free(out); + return -1; + } + return 0; +} + +void osc_cg_free(OscCode *c) { + if (!c) return; + free(c->code); + memset(c, 0, sizeof *c); +} diff --git a/src/compiler/osc_cg.h b/src/compiler/osc_cg.h new file mode 100644 index 000000000..c28aa18e1 --- /dev/null +++ b/src/compiler/osc_cg.h @@ -0,0 +1,32 @@ +/* + * osc_cg.h -- OSC-1 back end: typed IR -> AArch64 machine code through the + * hardened in-repo encoder (src/compiler/osc_a64.*). ABI and frame layout: + * docs/osc/OSC-1-DESIGN.md section 7. Output is a pure function of the IR. + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#ifndef OSC_CG_H +#define OSC_CG_H + +#include +#include +#include "osc_ir.h" + +typedef struct { + uint8_t *code; /* whole unit, little-endian 32-bit words */ + size_t len; /* bytes (multiple of 4) */ + uint32_t entry[OSC_MAX_FUNCS]; /* byte offset of each function's entry */ + uint16_t nfuncs; +} OscCode; + +/* Compile a unit. Refuses (-1, message in err) a unit that fails + * osc_ir_validate, any encoder refusal, or a failed self-check (every emitted + * word must decode through osc_a64_decode and re-encode to itself). + * On success out->code is malloc'd; release with osc_cg_free. */ +int osc_cg_compile(const OscUnit *u, OscCode *out, char *err, size_t n); +void osc_cg_free(OscCode *c); + +/* Self-check over an emitted buffer: 0 if every word decodes and re-encodes + * to itself, else -1 with the first failing word offset in err. */ +int osc_cg_verify(const OscCode *c, char *err, size_t n); + +#endif /* OSC_CG_H */ diff --git a/src/compiler/osc_interp.c b/src/compiler/osc_interp.c new file mode 100644 index 000000000..b3b3aac67 --- /dev/null +++ b/src/compiler/osc_interp.c @@ -0,0 +1,192 @@ +/* + * osc_interp.c -- reference interpreter for the OSC-1 IR (DESIGN section 5). + * OSC-1 slice; not a general Omega compiler; no self-hosting. + * + * Checked signed arithmetic is computed exactly in 128-bit integers and then + * range-checked, independently of the native code's flag/extension tricks, so + * the differential test compares two different derivations of section 5. + */ +#include "osc_interp.h" + +#include + +typedef struct { + const OscUnit *u; + OscRt *rt; + uint64_t steps; +} Ctx; + +typedef __int128 i128; + +static void trap(Ctx *c, unsigned code) { osc_rt_trap(c->rt, code); } + +static uint64_t canon(OscScalar t, uint64_t x) { + unsigned w = osc_scalar_width(t); + if (t == OSC_T_BOOL) return x & 1; + if (w >= 64) return x; + if (osc_scalar_signed(t)) { + uint64_t m = 1ULL << (w - 1); + x &= (1ULL << w) - 1; + return (x ^ m) - m; + } + return x & ((1ULL << w) - 1); +} + +static i128 smin(unsigned w) { return -((i128)1 << (w - 1)); } +static i128 smax(unsigned w) { return ((i128)1 << (w - 1)) - 1; } + +/* exact signed result -> canonical, or OVERFLOW */ +static uint64_t sfit(Ctx *c, unsigned w, i128 r) { + if (r < smin(w) || r > smax(w)) trap(c, OSC_TRAP_OVERFLOW); + return (uint64_t)(int64_t)r; +} + +static uint64_t do_bin(Ctx *c, unsigned sub, OscScalar t, OscScalar tb, uint64_t a, uint64_t b) { + unsigned w = osc_scalar_width(t); + bool s = osc_scalar_signed(t); + i128 A = s ? (i128)(int64_t)a : (i128)a, B = osc_scalar_signed(tb) ? (i128)(int64_t)b : (i128)b; + switch (sub) { + case OSC_B_ADD: return s ? sfit(c, w, A + B) : canon(t, a + b); + case OSC_B_SUB: return s ? sfit(c, w, A - B) : canon(t, a - b); + case OSC_B_MUL: return s ? sfit(c, w, A * B) : canon(t, a * b); + case OSC_B_DIV: + if (b == 0) trap(c, OSC_TRAP_DIV0); + return s ? sfit(c, w, A / B) : a / b; /* C: truncation toward zero */ + case OSC_B_REM: + if (b == 0) trap(c, OSC_TRAP_DIV0); + return s ? (uint64_t)(int64_t)(A % B) : a % b; /* sign of the dividend; MIN % -1 == 0 */ + case OSC_B_AND: return a & b; + case OSC_B_OR: return a | b; + case OSC_B_XOR: return a ^ b; + case OSC_B_SHL: + case OSC_B_SHR: { + if (B < 0 || B >= (i128)w) trap(c, OSC_TRAP_SHIFT); + unsigned k = (unsigned)B; + if (sub == OSC_B_SHL) return s ? sfit(c, w, A * ((i128)1 << k)) : canon(t, a << k); + return s ? (uint64_t)((int64_t)a >> k) : a >> k; + } + default: trap(c, OSC_TRAP_RUNTIME); + } + return 0; +} + +static uint64_t do_un(Ctx *c, unsigned sub, OscScalar t, uint64_t a) { + switch (sub) { + case OSC_U_NEG: + if (osc_scalar_signed(t)) return sfit(c, osc_scalar_width(t), -(i128)(int64_t)a); + return canon(t, 0 - a); + case OSC_U_BNOT: return canon(t, ~a); + case OSC_U_LNOT: return a ^ 1; + default: trap(c, OSC_TRAP_RUNTIME); + } + return 0; +} + +static uint64_t do_cmp(unsigned cc, OscScalar t, uint64_t a, uint64_t b) { + bool lt, eq = a == b; + if (osc_scalar_signed(t)) lt = (int64_t)a < (int64_t)b; + else lt = a < b; + switch (cc) { + case OSC_C_EQ: return eq; + case OSC_C_NE: return !eq; + case OSC_C_LT: return lt; + case OSC_C_LE: return lt || eq; + case OSC_C_GT: return !lt && !eq; + case OSC_C_GE: return !lt; + default: return 0; + } +} + +static uint64_t do_cast(Ctx *c, OscScalar to, OscScalar from, uint64_t a) { + i128 v = osc_scalar_signed(from) ? (i128)(int64_t)a : (i128)a; + unsigned w = osc_scalar_width(to); + i128 lo = osc_scalar_signed(to) ? smin(w) : 0; + i128 hi = osc_scalar_signed(to) ? smax(w) : (((i128)1 << w) - 1); + if (v < lo || v > hi) trap(c, OSC_TRAP_CAST); + return (uint64_t)v; +} + +/* element pointer with the bounds rule of section 5 */ +static uint64_t *elem(Ctx *c, const OscType *rt_, uint64_t base, OscScalar ti, uint64_t idx) { + if (osc_scalar_signed(ti) && (int64_t)idx < 0) trap(c, OSC_TRAP_BOUNDS); + if (idx >= rt_->len) trap(c, OSC_TRAP_BOUNDS); + /* defensive: a REF must point into the pool (validated IR guarantees it) */ + uintptr_t lo = (uintptr_t)&c->rt->cells[0][0], hi = lo + sizeof c->rt->cells; + if ((uintptr_t)base < lo || (uintptr_t)base + 8 * (idx + 1) > hi) trap(c, OSC_TRAP_RUNTIME); + return (uint64_t *)(uintptr_t)base + idx; +} + +static uint64_t run_func(Ctx *c, int fi, const uint64_t *args) { + const OscFunc *f = &c->u->funcs[fi]; + const OscType *T = f->vtype; + uint64_t v[OSC_MAX_VREGS]; + memset(v, 0, sizeof(uint64_t) * f->nvregs); + for (int p = 0; p < f->nparams; p++) v[p] = args[p]; + int b = 0; + for (;;) { + const OscBlock *bl = &f->blocks[b]; + int next = -1; + for (uint32_t i = bl->first; i < bl->first + bl->count; i++) { + const OscInsn *in = &f->insns[i]; + if (++c->steps > OSC_INTERP_MAX_STEPS) trap(c, OSC_TRAP_RUNTIME); + switch (in->op) { + case OSC_I_CONST: v[in->dst] = in->imm; break; + case OSC_I_MOV: v[in->dst] = v[in->a]; break; + case OSC_I_BIN: v[in->dst] = do_bin(c, in->sub, T[in->a].s, T[in->b].s, v[in->a], v[in->b]); break; + case OSC_I_UN: v[in->dst] = do_un(c, in->sub, T[in->a].s, v[in->a]); break; + case OSC_I_CMP: v[in->dst] = do_cmp(in->sub, T[in->a].s, v[in->a], v[in->b]); break; + case OSC_I_CAST: v[in->dst] = do_cast(c, T[in->dst].s, T[in->a].s, v[in->a]); break; + case OSC_I_ALLOC: v[in->dst] = osc_rt_alloc(c->rt, T[in->dst].len, v[in->a]); break; + case OSC_I_RELEASE: osc_rt_release(c->rt, v[in->a], T[in->a].len); break; + case OSC_I_LOAD: v[in->dst] = *elem(c, &T[in->a], v[in->a], T[in->b].s, v[in->b]); break; + case OSC_I_STORE: *elem(c, &T[in->a], v[in->a], T[in->b].s, v[in->b]) = v[in->c]; break; + case OSC_I_CALL: { + uint64_t ca[OSC_MAX_PARAMS] = {0}; + for (int k = 0; k < in->nargs; k++) ca[k] = v[in->args[k]]; + uint64_t r = run_func(c, in->callee, ca); + if (in->dst >= 0) v[in->dst] = r; + break; + } + case OSC_I_TRAP: trap(c, (unsigned)in->imm); break; + case OSC_I_BR: next = in->blk_t; break; + case OSC_I_CBR: next = v[in->a] ? in->blk_t : in->blk_f; break; + case OSC_I_RET: return in->a >= 0 ? v[in->a] : 0; + default: trap(c, OSC_TRAP_RUNTIME); + } + } + if (next < 0) trap(c, OSC_TRAP_RUNTIME); /* unreachable for validated IR */ + b = next; + } +} + +static int check_args(const OscUnit *u, int func, const uint64_t *args, unsigned nargs, const OscRt *rt) { + if (!rt || func < 0 || func >= u->nfuncs) return -1; + const OscFunc *f = &u->funcs[func]; + if (nargs != f->nparams || (nargs && !args)) return -1; + for (unsigned p = 0; p < nargs; p++) { + const OscType *t = &f->vtype[p]; + if (t->s == OSC_T_REF) { + if (!osc_rt_is_live_ref(rt, args[p], t->len)) return -1; + } else if (canon(t->s, args[p]) != args[p]) { + return -1; + } + } + return 0; +} + +int osc_interp_run_prevalidated(const OscUnit *u, int func, const uint64_t *args, unsigned nargs, OscRt *rt, + uint64_t *ret) { + if (!u || !ret || check_args(u, func, args, nargs, rt)) return -1; + Ctx c = {u, rt, 0}; + uint64_t a[OSC_MAX_PARAMS] = {0}; + for (unsigned i = 0; i < nargs; i++) a[i] = args[i]; + rt->trap_code = 0; + if (setjmp(rt->jb) != 0) return (int)rt->trap_code; + *ret = run_func(&c, func, a); + return 0; +} + +int osc_interp_run(const OscUnit *u, int func, const uint64_t *args, unsigned nargs, OscRt *rt, uint64_t *ret) { + if (!u || osc_ir_validate(u, NULL, 0)) return -1; + return osc_interp_run_prevalidated(u, func, args, nargs, rt, ret); +} diff --git a/src/compiler/osc_interp.h b/src/compiler/osc_interp.h new file mode 100644 index 000000000..5f77f1a1b --- /dev/null +++ b/src/compiler/osc_interp.h @@ -0,0 +1,32 @@ +/* + * osc_interp.h -- reference interpreter for the OSC-1 typed IR. + * Semantics: docs/osc/OSC-1-DESIGN.md section 5, exactly. Allocation and + * release go through osc_rt_alloc / osc_rt_release so the pool event log is + * identical to natively compiled code. + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#ifndef OSC_INTERP_H +#define OSC_INTERP_H + +#include +#include "osc_ir.h" +#include "osc_rt.h" + +/* Defensive bound on executed IR instructions per run (all IR loops already + * carry a static bound; exceeding this reports OSC_TRAP_RUNTIME). */ +#define OSC_INTERP_MAX_STEPS (1ULL << 32) + +/* Run function `func` of `u` with `nargs` arguments. + * Returns -1 if refused (unit fails osc_ir_validate, bad func index, nargs != + * nparams, a scalar argument not canonical for its type, or a REF argument + * that is not a live pool slot of matching length in rt); otherwise the trap + * code (0 = normal return with *ret set; void functions return 0). + * Does not reset rt: the caller resets the pool between runs. */ +int osc_interp_run(const OscUnit *u, int func, const uint64_t *args, unsigned nargs, OscRt *rt, uint64_t *ret); + +/* Same, but skips osc_ir_validate: only for a unit the caller has already + * validated and not modified since (used by fuzz loops). */ +int osc_interp_run_prevalidated(const OscUnit *u, int func, const uint64_t *args, unsigned nargs, OscRt *rt, + uint64_t *ret); + +#endif /* OSC_INTERP_H */ diff --git a/src/compiler/osc_ir.c b/src/compiler/osc_ir.c new file mode 100644 index 000000000..60fef0997 --- /dev/null +++ b/src/compiler/osc_ir.c @@ -0,0 +1,410 @@ +/* + * osc_ir.c -- OSC-1 typed IR: structural validation, canonical encoding, + * SHA-256 identity. See osc_ir.h and docs/osc/OSC-1-DESIGN.md section 4. + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#include "osc_ir.h" +#include "sha256.h" + +#include +#include +#include +#include + +/* ---- scalar helpers ---------------------------------------------------- */ +unsigned osc_scalar_width(OscScalar s) { + switch (s) { + case OSC_T_BOOL: return 1; + case OSC_T_U8: case OSC_T_I8: return 8; + case OSC_T_U16: case OSC_T_I16: return 16; + case OSC_T_U32: case OSC_T_I32: return 32; + case OSC_T_U64: case OSC_T_I64: return 64; + default: return 0; + } +} +bool osc_scalar_signed(OscScalar s) { return s >= OSC_T_I8 && s <= OSC_T_I64; } +bool osc_scalar_is_int(OscScalar s) { return s >= OSC_T_U8 && s <= OSC_T_I64; } +const char *osc_scalar_name(OscScalar s) { + static const char *n[] = {"void", "bool", "u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64", "ref"}; + return ((unsigned)s <= OSC_T_REF) ? n[s] : "?"; +} + +/* ---- validation ------------------------------------------------------- */ +static int vfail(char *err, size_t n, const char *fmt, ...) { + if (err && n) { + va_list ap; + va_start(ap, fmt); + vsnprintf(err, n, fmt, ap); + va_end(ap); + } + return -1; +} + +static bool is_value_scalar(OscScalar s) { return s >= OSC_T_BOOL && s <= OSC_T_I64; } + +static bool type_is_scalar(const OscType *t) { + return is_value_scalar(t->s) && t->ref == OSC_REF_NONE && t->elem == OSC_T_VOID && t->len == 0; +} +static bool type_is_ref(const OscType *t) { + return t->s == OSC_T_REF && t->ref >= OSC_REF_OWN && t->ref <= OSC_REF_MUT && + is_value_scalar(t->elem) && t->len >= 1 && t->len <= OSC_MAX_ARRAY_LEN; +} +static bool type_eq(const OscType *a, const OscType *b) { + return a->s == b->s && a->ref == b->ref && a->elem == b->elem && a->len == b->len; +} +/* may a value of REF type `src` be bound to a REF slot of type `dst`? */ +static bool ref_bindable(const OscType *dst, const OscType *src) { + if (!type_is_ref(dst) || !type_is_ref(src)) return false; + if (dst->elem != src->elem || dst->len != src->len) return false; + switch (dst->ref) { + case OSC_REF_OWN: return src->ref == OSC_REF_OWN; /* move */ + case OSC_REF_MUT: return src->ref == OSC_REF_OWN || src->ref == OSC_REF_MUT; + case OSC_REF_SHARED: return true; + default: return false; + } +} +static bool canonical_for(OscScalar s, uint64_t v) { + unsigned w = osc_scalar_width(s); + if (s == OSC_T_BOOL) return v <= 1; + if (w == 64) return true; + if (osc_scalar_signed(s)) { + int64_t x = (int64_t)v, lo = -(1LL << (w - 1)), hi = (1LL << (w - 1)) - 1; + return x >= lo && x <= hi; + } + return v < (1ULL << w); +} + +static bool is_term(uint8_t op) { return op == OSC_I_BR || op == OSC_I_CBR || op == OSC_I_RET; } + +/* uses / def of an instruction (for def-before-use) */ +static int insn_uses(const OscInsn *in, int16_t *u) { + int k = 0; + switch (in->op) { + case OSC_I_MOV: case OSC_I_UN: case OSC_I_CAST: case OSC_I_ALLOC: case OSC_I_RELEASE: + case OSC_I_CBR: u[k++] = in->a; break; + case OSC_I_BIN: case OSC_I_CMP: case OSC_I_LOAD: u[k++] = in->a; u[k++] = in->b; break; + case OSC_I_STORE: u[k++] = in->a; u[k++] = in->b; u[k++] = in->c; break; + case OSC_I_CALL: for (int i = 0; i < in->nargs && i < OSC_MAX_PARAMS; i++) u[k++] = in->args[i]; break; + case OSC_I_RET: if (in->a >= 0) u[k++] = in->a; break; + default: break; + } + return k; +} +static int insn_def(const OscInsn *in) { + switch (in->op) { + case OSC_I_CONST: case OSC_I_MOV: case OSC_I_BIN: case OSC_I_UN: case OSC_I_CMP: + case OSC_I_CAST: case OSC_I_ALLOC: case OSC_I_LOAD: return in->dst; + case OSC_I_CALL: return in->dst; /* may be -1 */ + default: return -1; + } +} + +#define BSW ((OSC_MAX_VREGS + 63) / 64) + +static int validate_insn(const OscUnit *u, int fi, const OscFunc *f, uint32_t ii, char *err, size_t n) { + const OscInsn *in = &f->insns[ii]; + const OscType *T = f->vtype; + int nv = f->nvregs; +#define VR(x) ((x) >= 0 && (x) < nv) +#define NEED(cond, ...) do { if (!(cond)) return vfail(err, n, "func %d insn %u: " __VA_ARGS__); } while (0) + switch (in->op) { + case OSC_I_CONST: + NEED(VR(in->dst), "CONST bad dst vreg %d", fi, ii, in->dst); + NEED(type_is_scalar(&T[in->dst]), "CONST dst not scalar", fi, ii); + NEED(canonical_for(T[in->dst].s, in->imm), "CONST imm not canonical for %s", fi, ii, osc_scalar_name(T[in->dst].s)); + break; + case OSC_I_MOV: + NEED(VR(in->dst) && VR(in->a), "MOV bad vreg", fi, ii); + if (type_is_ref(&T[in->dst])) + NEED(ref_bindable(&T[in->dst], &T[in->a]), "MOV ref kind/type mismatch", fi, ii); + else + NEED(type_is_scalar(&T[in->dst]) && type_eq(&T[in->dst], &T[in->a]), "MOV type mismatch", fi, ii); + break; + case OSC_I_BIN: { + NEED(VR(in->dst) && VR(in->a) && VR(in->b), "BIN bad vreg", fi, ii); + NEED(in->sub >= OSC_B_ADD && in->sub <= OSC_B_SHR, "BIN bad sub-op %u", fi, ii, in->sub); + const OscType *d = &T[in->dst], *a = &T[in->a], *b = &T[in->b]; + NEED(type_is_scalar(d) && type_eq(d, a), "BIN dst/a type mismatch", fi, ii); + if (in->sub == OSC_B_SHL || in->sub == OSC_B_SHR) { + NEED(osc_scalar_is_int(a->s), "shift of non-integer", fi, ii); + NEED(type_is_scalar(b) && osc_scalar_is_int(b->s), "shift amount not integer", fi, ii); + } else if (in->sub == OSC_B_AND || in->sub == OSC_B_OR || in->sub == OSC_B_XOR) { + NEED(type_eq(a, b), "BIN operand type mismatch", fi, ii); + } else { + NEED(osc_scalar_is_int(a->s) && type_eq(a, b), "arith BIN needs identical integer types", fi, ii); + } + break; + } + case OSC_I_UN: { + NEED(VR(in->dst) && VR(in->a), "UN bad vreg", fi, ii); + const OscType *d = &T[in->dst], *a = &T[in->a]; + NEED(type_is_scalar(d) && type_eq(d, a), "UN type mismatch", fi, ii); + if (in->sub == OSC_U_LNOT) NEED(a->s == OSC_T_BOOL, "LNOT needs bool", fi, ii); + else if (in->sub == OSC_U_NEG || in->sub == OSC_U_BNOT) NEED(osc_scalar_is_int(a->s), "NEG/BNOT need integer", fi, ii); + else return vfail(err, n, "func %d insn %u: UN bad sub-op %u", fi, ii, in->sub); + break; + } + case OSC_I_CMP: + NEED(VR(in->dst) && VR(in->a) && VR(in->b), "CMP bad vreg", fi, ii); + NEED(in->sub >= OSC_C_EQ && in->sub <= OSC_C_GE, "CMP bad cc %u", fi, ii, in->sub); + NEED(type_is_scalar(&T[in->dst]) && T[in->dst].s == OSC_T_BOOL, "CMP dst not bool", fi, ii); + NEED(type_is_scalar(&T[in->a]) && type_eq(&T[in->a], &T[in->b]), "CMP operand type mismatch", fi, ii); + break; + case OSC_I_CAST: + NEED(VR(in->dst) && VR(in->a), "CAST bad vreg", fi, ii); + NEED(type_is_scalar(&T[in->dst]) && osc_scalar_is_int(T[in->dst].s) && + type_is_scalar(&T[in->a]) && osc_scalar_is_int(T[in->a].s), "CAST needs integer types", fi, ii); + break; + case OSC_I_ALLOC: + NEED(VR(in->dst) && VR(in->a), "ALLOC bad vreg", fi, ii); + NEED(type_is_ref(&T[in->dst]) && T[in->dst].ref == OSC_REF_OWN, "ALLOC dst not an owner", fi, ii); + NEED(type_is_scalar(&T[in->a]) && T[in->a].s == T[in->dst].elem, "ALLOC init type != elem type", fi, ii); + break; + case OSC_I_RELEASE: + NEED(VR(in->a), "RELEASE bad vreg", fi, ii); + NEED(type_is_ref(&T[in->a]) && T[in->a].ref == OSC_REF_OWN, "RELEASE of a non-owner", fi, ii); + break; + case OSC_I_LOAD: + NEED(VR(in->dst) && VR(in->a) && VR(in->b), "LOAD bad vreg", fi, ii); + NEED(type_is_ref(&T[in->a]), "LOAD base not a ref", fi, ii); + NEED(type_is_scalar(&T[in->b]) && osc_scalar_is_int(T[in->b].s), "LOAD index not integer", fi, ii); + NEED(type_is_scalar(&T[in->dst]) && T[in->dst].s == T[in->a].elem, "LOAD dst type != elem", fi, ii); + break; + case OSC_I_STORE: + NEED(VR(in->a) && VR(in->b) && VR(in->c), "STORE bad vreg", fi, ii); + NEED(type_is_ref(&T[in->a]) && (T[in->a].ref == OSC_REF_OWN || T[in->a].ref == OSC_REF_MUT), + "STORE through a shared borrow or non-ref", fi, ii); + NEED(type_is_scalar(&T[in->b]) && osc_scalar_is_int(T[in->b].s), "STORE index not integer", fi, ii); + NEED(type_is_scalar(&T[in->c]) && T[in->c].s == T[in->a].elem, "STORE value type != elem", fi, ii); + break; + case OSC_I_CALL: { + NEED(in->callee >= 0 && in->callee < fi, "CALL to function %d not defined earlier", fi, ii, in->callee); + const OscFunc *g = &u->funcs[in->callee]; + NEED(in->nargs == g->nparams, "CALL arity %u != %u", fi, ii, in->nargs, g->nparams); + for (int k = 0; k < in->nargs; k++) { + int a = in->args[k]; + NEED(VR(a), "CALL bad arg vreg", fi, ii); + const OscType *p = &g->vtype[k]; + if (type_is_ref(p)) NEED(ref_bindable(p, &T[a]), "CALL arg %d ref mismatch", fi, ii, k); + else NEED(type_eq(p, &T[a]), "CALL arg %d type mismatch", fi, ii, k); + } + if (g->ret.s == OSC_T_VOID) NEED(in->dst == -1, "CALL of void function with dst", fi, ii); + else NEED(VR(in->dst) && type_eq(&T[in->dst], &g->ret), "CALL dst type != callee return", fi, ii); + break; + } + case OSC_I_TRAP: + NEED(in->imm >= OSC_TRAP_OVERFLOW && in->imm <= OSC_TRAP_RUNTIME, "TRAP bad code", fi, ii); + break; + case OSC_I_BR: + NEED(in->blk_t >= 0 && in->blk_t < f->nblocks, "BR bad target", fi, ii); + break; + case OSC_I_CBR: + NEED(VR(in->a) && type_is_scalar(&T[in->a]) && T[in->a].s == OSC_T_BOOL, "CBR condition not bool", fi, ii); + NEED(in->blk_t >= 0 && in->blk_t < f->nblocks && in->blk_f >= 0 && in->blk_f < f->nblocks, "CBR bad target", fi, ii); + break; + case OSC_I_RET: + if (f->ret.s == OSC_T_VOID) NEED(in->a == -1, "RET value from void function", fi, ii); + else NEED(VR(in->a) && type_eq(&T[in->a], &f->ret), "RET type mismatch", fi, ii); + break; + default: + return vfail(err, n, "func %d insn %u: unknown op %u", fi, ii, in->op); + } +#undef NEED +#undef VR + return 0; +} + +static bool str_ok(const char *s, size_t cap) { return memchr(s, 0, cap) != NULL; } + +static int validate_func(const OscUnit *u, int fi, char *err, size_t n) { + const OscFunc *f = &u->funcs[fi]; + if (!str_ok(f->name, sizeof f->name)) return vfail(err, n, "func %d: name not terminated", fi); + if (!str_ok(f->requires_text, sizeof f->requires_text) || !str_ok(f->ensures_text, sizeof f->ensures_text)) + return vfail(err, n, "func %d: contract text not terminated", fi); + if (f->nparams > OSC_MAX_PARAMS) return vfail(err, n, "func %d: %u params > %d", fi, f->nparams, OSC_MAX_PARAMS); + if (f->nvregs > OSC_MAX_VREGS || f->nparams > f->nvregs) return vfail(err, n, "func %d: bad nvregs", fi); + if (!(f->ret.s == OSC_T_VOID && f->ret.ref == OSC_REF_NONE && f->ret.elem == OSC_T_VOID && f->ret.len == 0) && + !type_is_scalar(&f->ret)) + return vfail(err, n, "func %d: return type must be void or scalar", fi); + for (int v = 0; v < f->nvregs; v++) + if (!type_is_scalar(&f->vtype[v]) && !type_is_ref(&f->vtype[v])) + return vfail(err, n, "func %d: vreg %d has invalid type", fi, v); + if (f->ninsns < 1 || f->ninsns > OSC_MAX_INSNS) return vfail(err, n, "func %d: bad ninsns", fi); + if (f->nblocks < 1 || f->nblocks > OSC_MAX_BLOCKS) return vfail(err, n, "func %d: bad nblocks", fi); + + /* blocks partition the instruction array */ + uint8_t cover[OSC_MAX_INSNS]; + memset(cover, 0, sizeof cover); + for (int b = 0; b < f->nblocks; b++) { + const OscBlock *bl = &f->blocks[b]; + if (bl->count < 1 || (uint64_t)bl->first + bl->count > f->ninsns) + return vfail(err, n, "func %d block %d: bad range", fi, b); + for (uint32_t i = bl->first; i < bl->first + bl->count; i++) { + if (cover[i]) return vfail(err, n, "func %d: insn %u in two blocks", fi, i); + cover[i] = 1; + bool last = i == bl->first + bl->count - 1; + if (is_term(f->insns[i].op) != last) + return vfail(err, n, last ? "func %d block %d: missing terminator" : + "func %d block %d: terminator before block end", fi, b); + } + } + for (uint32_t i = 0; i < f->ninsns; i++) + if (!cover[i]) return vfail(err, n, "func %d: insn %u in no block", fi, i); + for (uint32_t i = 0; i < f->ninsns; i++) + if (validate_insn(u, fi, f, i, err, n)) return -1; + + /* definite assignment: every use reads a vreg defined on every path */ + int nb = f->nblocks; + uint64_t *in = malloc(sizeof(uint64_t) * BSW * nb), *out = malloc(sizeof(uint64_t) * BSW * nb); + if (!in || !out) { free(in); free(out); return vfail(err, n, "out of memory"); } + uint64_t params[BSW] = {0}; + for (int v = 0; v < f->nparams; v++) params[v / 64] |= 1ULL << (v % 64); + for (int b = 0; b < nb; b++) for (int k = 0; k < BSW; k++) { in[b * BSW + k] = ~0ULL; out[b * BSW + k] = ~0ULL; } + int rc = 0; + for (int changed = 1; changed;) { /* monotone decreasing: terminates */ + changed = 0; + for (int b = 0; b < nb; b++) { + uint64_t cur[BSW]; + for (int k = 0; k < BSW; k++) cur[k] = (b == 0) ? params[k] : ~0ULL; + /* meet over predecessors */ + for (int p = 0; p < nb; p++) { + const OscInsn *t = &f->insns[f->blocks[p].first + f->blocks[p].count - 1]; + bool pred = (t->op == OSC_I_BR && t->blk_t == b) || + (t->op == OSC_I_CBR && (t->blk_t == b || t->blk_f == b)); + if (pred) for (int k = 0; k < BSW; k++) cur[k] &= out[p * BSW + k]; + } + if (memcmp(cur, &in[b * BSW], sizeof cur)) { memcpy(&in[b * BSW], cur, sizeof cur); changed = 1; } + for (uint32_t i = f->blocks[b].first; i < f->blocks[b].first + f->blocks[b].count; i++) { + int d = insn_def(&f->insns[i]); + if (d >= 0) cur[d / 64] |= 1ULL << (d % 64); + } + if (memcmp(cur, &out[b * BSW], sizeof cur)) { memcpy(&out[b * BSW], cur, sizeof cur); changed = 1; } + } + } + for (int b = 0; b < nb && !rc; b++) { + uint64_t cur[BSW]; + memcpy(cur, &in[b * BSW], sizeof cur); + for (uint32_t i = f->blocks[b].first; i < f->blocks[b].first + f->blocks[b].count && !rc; i++) { + int16_t us[OSC_MAX_PARAMS + 2]; + int k = insn_uses(&f->insns[i], us); + for (int j = 0; j < k; j++) + if (!(cur[us[j] / 64] >> (us[j] % 64) & 1)) { + rc = vfail(err, n, "func %d insn %u: vreg %d may be used before it is defined", fi, i, us[j]); + break; + } + int d = insn_def(&f->insns[i]); + if (d >= 0) cur[d / 64] |= 1ULL << (d % 64); + } + } + free(in); + free(out); + return rc; +} + +int osc_ir_validate(const OscUnit *u, char *err, size_t n) { + if (!u) return vfail(err, n, "null unit"); + if (u->nfuncs > OSC_MAX_FUNCS) return vfail(err, n, "too many functions"); + for (int fi = 0; fi < u->nfuncs; fi++) + if (validate_func(u, fi, err, n)) return -1; + if (err && n) err[0] = 0; + return 0; +} + +/* ---- canonical encoding ------------------------------------------------ */ +typedef struct { + uint8_t *buf; + size_t cap, len; + sha256_ctx *sha; +} W; + +static void wbytes(W *w, const void *p, size_t k) { + if (w->sha) sha256_update(w->sha, (const uint8_t *)p, k); + if (w->buf && w->len + k <= w->cap) memcpy(w->buf + w->len, p, k); + w->len += k; +} +static void w8(W *w, uint64_t v) { uint8_t b = (uint8_t)v; wbytes(w, &b, 1); } +static void w16(W *w, uint64_t v) { uint8_t b[2] = {(uint8_t)v, (uint8_t)(v >> 8)}; wbytes(w, b, 2); } +static void w32(W *w, uint64_t v) { + uint8_t b[4]; + for (int i = 0; i < 4; i++) b[i] = (uint8_t)(v >> (8 * i)); + wbytes(w, b, 4); +} +static void w64(W *w, uint64_t v) { + uint8_t b[8]; + for (int i = 0; i < 8; i++) b[i] = (uint8_t)(v >> (8 * i)); + wbytes(w, b, 8); +} +static void wvr(W *w, int16_t v) { w16(w, (uint16_t)v); } /* two's complement LE; -1 = 0xFFFF */ +static void wtype(W *w, const OscType *t) { + w8(w, (uint8_t)t->s); + if (t->s == OSC_T_REF) { w8(w, (uint8_t)t->ref); w8(w, (uint8_t)t->elem); w16(w, t->len); } +} +static void wtext(W *w, const char *s, size_t cap) { + size_t k = strnlen(s, cap); + w16(w, k); + wbytes(w, s, k); +} + +static void encode_unit(const OscUnit *u, W *w) { + static const uint8_t magic[8] = {'O', 'S', 'C', '1', 'I', 'R', 0, 1}; /* format version 1 */ + wbytes(w, magic, sizeof magic); + w16(w, u->nfuncs); + for (int fi = 0; fi < u->nfuncs; fi++) { + const OscFunc *f = &u->funcs[fi]; + size_t nl = strnlen(f->name, sizeof f->name); + w8(w, nl); + wbytes(w, f->name, nl); + w8(w, f->nparams); + wtype(w, &f->ret); + w16(w, f->nvregs); + for (int v = 0; v < f->nvregs; v++) wtype(w, &f->vtype[v]); + w16(w, f->nblocks); + for (int b = 0; b < f->nblocks; b++) { w32(w, f->blocks[b].first); w32(w, f->blocks[b].count); } + w32(w, f->ninsns); + for (uint32_t i = 0; i < f->ninsns; i++) { + const OscInsn *in = &f->insns[i]; + w8(w, in->op); + switch (in->op) { + case OSC_I_CONST: wvr(w, in->dst); w64(w, in->imm); break; + case OSC_I_MOV: case OSC_I_CAST: case OSC_I_ALLOC: wvr(w, in->dst); wvr(w, in->a); break; + case OSC_I_BIN: case OSC_I_CMP: w8(w, in->sub); wvr(w, in->dst); wvr(w, in->a); wvr(w, in->b); break; + case OSC_I_UN: w8(w, in->sub); wvr(w, in->dst); wvr(w, in->a); break; + case OSC_I_RELEASE: wvr(w, in->a); break; + case OSC_I_LOAD: wvr(w, in->dst); wvr(w, in->a); wvr(w, in->b); break; + case OSC_I_STORE: wvr(w, in->a); wvr(w, in->b); wvr(w, in->c); break; + case OSC_I_CALL: + wvr(w, in->dst); w16(w, (uint16_t)in->callee); w8(w, in->nargs); + for (int k = 0; k < in->nargs; k++) wvr(w, in->args[k]); + break; + case OSC_I_TRAP: w8(w, in->imm); break; + case OSC_I_BR: w16(w, (uint16_t)in->blk_t); break; + case OSC_I_CBR: wvr(w, in->a); w16(w, (uint16_t)in->blk_t); w16(w, (uint16_t)in->blk_f); break; + case OSC_I_RET: wvr(w, in->a); break; + default: break; /* unreachable after validation */ + } + /* `line` is debug information and deliberately not encoded: source + * spelling and layout never reach the identity (DESIGN s.4). */ + } + wtext(w, f->requires_text, sizeof f->requires_text); + wtext(w, f->ensures_text, sizeof f->ensures_text); + } +} + +int osc_ir_encode(const OscUnit *u, uint8_t *buf, size_t cap, size_t *len) { + if (osc_ir_validate(u, NULL, 0)) return -1; + W w = {buf, buf ? cap : 0, 0, NULL}; + encode_unit(u, &w); + if (len) *len = w.len; + if (buf && w.len > cap) return -1; + return 0; +} + +int osc_ir_digest(const OscUnit *u, uint8_t out[32]) { + if (osc_ir_validate(u, NULL, 0)) return -1; + sha256_ctx c; + sha256_init(&c); + W w = {NULL, 0, 0, &c}; + encode_unit(u, &w); + sha256_final(&c, out); + return 0; +} diff --git a/src/compiler/osc_ir.h b/src/compiler/osc_ir.h new file mode 100644 index 000000000..27ba49497 --- /dev/null +++ b/src/compiler/osc_ir.h @@ -0,0 +1,179 @@ +/* + * osc_ir.h -- OSC-1 typed IR ("Flow IR" v0 slice). The contract between the + * OSC-1 front end (src/compiler/osc_front.*), the reference interpreter + * (src/compiler/osc_interp.*) and the AArch64 back end (src/compiler/osc_cg.*). + * + * OSC-1 slice; not a general Omega compiler; no self-hosting. + * Design and semantics: docs/osc/OSC-1-DESIGN.md (normative). This header + * states the data layout; the design doc states the meaning. + * + * Shape: a unit is an ordered list of functions. A function is a CFG of basic + * blocks over typed virtual registers (vregs). Every vreg has exactly one + * OscType. Blocks end in exactly one terminator. Calls may only target a + * function with a smaller index (defined earlier in the unit), so there is no + * recursion. All loops carry a static trip-count bound enforced by an explicit + * counter + OSC_I_TRAP emitted by the front end (the IR itself has no + * unbounded construct the back end needs to know about). + * + * Value representation (both interpreter and native code, RuntimeLayout): + * - every scalar vreg holds a 64-bit canonical value: unsigned types are + * zero-extended, signed types sign-extended, bool is 0 or 1; + * - a REF vreg (owned array handle or borrow) holds the address of element 0; + * elements are stored as 8-byte canonical values regardless of element width. + */ +#ifndef OSC_IR_H +#define OSC_IR_H + +#include +#include +#include + +#define OSC_MAX_FUNCS 32 +#define OSC_MAX_PARAMS 6 /* x0..x5; x7 carries the hidden runtime ctx */ +#define OSC_MAX_VREGS 480 /* stack frame must fit SUB SP imm12 */ +#define OSC_MAX_INSNS 4096 /* per function */ +#define OSC_MAX_BLOCKS 512 /* per function */ +#define OSC_MAX_ARRAY_LEN 64 /* elements per unique allocation */ +#define OSC_NAME_MAX 64 +#define OSC_CLAUSE_MAX 256 /* requires/ensures text (recorded, not checked: OSC-0 III.6) */ + +/* ---- types ------------------------------------------------------------ */ +typedef enum { + OSC_T_VOID = 0, + OSC_T_BOOL, + OSC_T_U8, OSC_T_U16, OSC_T_U32, OSC_T_U64, /* wrap modulo 2^w (V0 compatible) */ + OSC_T_I8, OSC_T_I16, OSC_T_I32, OSC_T_I64, /* checked: overflow traps (III.3) */ + OSC_T_REF /* pointer to array element 0 */ +} OscScalar; + +typedef enum { + OSC_REF_NONE = 0, + OSC_REF_OWN, /* unique owner of an allocation: own [T; N] */ + OSC_REF_SHARED, /* shared borrow: &[T; N] */ + OSC_REF_MUT /* mutable borrow: &mut [T; N] */ +} OscRefKind; + +typedef struct { + OscScalar s; /* for OSC_T_REF: the elements are `elem` */ + OscRefKind ref; /* OSC_REF_NONE unless s == OSC_T_REF */ + OscScalar elem; /* element scalar type (integer or bool) */ + uint16_t len; /* static array length N, 1..OSC_MAX_ARRAY_LEN */ +} OscType; + +/* ---- instructions ----------------------------------------------------- */ +typedef enum { + OSC_I_CONST = 1, /* dst = imm (already canonical for dst type) */ + OSC_I_MOV, /* dst = a (same type) */ + OSC_I_BIN, /* dst = a b ; type of a,b,dst identical (except shifts: */ + /* b may be any integer type; amount is a runtime value that */ + /* must be < width else TRAP_SHIFT) */ + OSC_I_UN, /* dst = a */ + OSC_I_CMP, /* dst(bool) = a b ; a,b same integer or bool type */ + OSC_I_CAST, /* dst = (T)a ; checked: value must be representable in T */ + /* else TRAP_CAST. bool<->int not allowed (front end refuses) */ + OSC_I_ALLOC, /* dst(REF OWN, elem, len) = unique allocation, every element */ + /* initialised to vreg a (elem type). OOM -> TRAP_OOM */ + OSC_I_RELEASE, /* destroy owner a: zero the elements, return them to the pool */ + OSC_I_LOAD, /* dst(elem) = a[b] ; b any integer type; if b<0 or b>=len: */ + /* TRAP_BOUNDS */ + OSC_I_STORE, /* a[b] = c ; same bounds rule; a is REF OWN or REF MUT */ + OSC_I_CALL, /* dst = func[callee](args[0..nargs)) ; dst may be -1 for void */ + OSC_I_TRAP, /* deterministic trap with code imm (unconditional) */ + /* terminators */ + OSC_I_BR, /* goto blk_t */ + OSC_I_CBR, /* if a(bool) goto blk_t else goto blk_f */ + OSC_I_RET /* return a (or nothing if a == -1 and function is void) */ +} OscOp; + +typedef enum { + OSC_B_ADD = 1, OSC_B_SUB, OSC_B_MUL, + OSC_B_DIV, /* b == 0 -> TRAP_DIV0; signed MIN/-1 -> TRAP_OVERFLOW (truncating) */ + OSC_B_REM, /* b == 0 -> TRAP_DIV0; sign follows dividend (C semantics) */ + OSC_B_AND, OSC_B_OR, OSC_B_XOR, + OSC_B_SHL, /* unsigned: wrap; signed: result not representable -> TRAP_OVERFLOW */ + OSC_B_SHR /* unsigned: logical; signed: arithmetic */ +} OscBinOp; + +typedef enum { + OSC_U_NEG = 1, /* signed only; MIN -> TRAP_OVERFLOW. unsigned: wrap (0 - a) */ + OSC_U_BNOT, /* bitwise not, then canonicalised to the type */ + OSC_U_LNOT /* bool only */ +} OscUnOp; + +typedef enum { + OSC_C_EQ = 1, OSC_C_NE, OSC_C_LT, OSC_C_LE, OSC_C_GT, OSC_C_GE + /* signedness comes from the operand type */ +} OscCmp; + +/* Trap codes are part of the observable semantics: interpreter and native + * code must report the same code for the same input. */ +typedef enum { + OSC_TRAP_NONE = 0, + OSC_TRAP_OVERFLOW = 1, /* checked signed arithmetic out of range */ + OSC_TRAP_DIV0 = 2, + OSC_TRAP_BOUNDS = 3, /* dynamic out-of-bounds index */ + OSC_TRAP_LOOP_BOUND = 4, /* a loop exceeded its static trip-count bound */ + OSC_TRAP_CAST = 5, /* checked conversion out of range */ + OSC_TRAP_OOM = 6, /* allocation pool exhausted */ + OSC_TRAP_SHIFT = 7, /* shift amount >= width or negative */ + OSC_TRAP_RUNTIME = 8 /* runtime invariant broken (double release, bad */ + /* handle): must never happen for checked code */ +} OscTrap; + +typedef struct { + uint8_t op; /* OscOp */ + uint8_t sub; /* OscBinOp / OscUnOp / OscCmp */ + int16_t dst; /* vreg or -1 */ + int16_t a, b, c; /* vregs or -1 */ + int16_t blk_t, blk_f;/* BR/CBR targets */ + int16_t callee; /* CALL */ + uint8_t nargs; /* CALL */ + int16_t args[OSC_MAX_PARAMS]; + uint64_t imm; /* CONST value (canonical) / TRAP code */ + uint32_t line; /* source line for diagnostics/debug, 0 if synthetic */ +} OscInsn; + +typedef struct { + uint32_t first; /* index into OscFunc.insns */ + uint32_t count; /* last insn is the terminator */ +} OscBlock; + +typedef struct { + char name[OSC_NAME_MAX]; + uint8_t nparams; /* params are vregs 0..nparams-1 */ + OscType ret; /* scalar or VOID; OSC-1 never returns a REF */ + OscType vtype[OSC_MAX_VREGS]; + uint16_t nvregs; + OscInsn insns[OSC_MAX_INSNS]; + uint32_t ninsns; + OscBlock blocks[OSC_MAX_BLOCKS]; + uint16_t nblocks; /* block 0 is the entry */ + char requires_text[OSC_CLAUSE_MAX]; /* recorded, not checked (OSC-0 III.6) */ + char ensures_text[OSC_CLAUSE_MAX]; +} OscFunc; + +typedef struct { + OscFunc funcs[OSC_MAX_FUNCS]; + uint16_t nfuncs; +} OscUnit; + +/* Structural validation (types agree, vregs in range, every block ends in one + * terminator and has no terminator before its end, branch targets valid, + * calls only to earlier functions with matching arity/types, REF kinds legal + * for LOAD/STORE/RELEASE). 0 ok, -1 invalid with message in err. Both the + * interpreter and the back end refuse a unit that does not validate. */ +int osc_ir_validate(const OscUnit *u, char *err, size_t n); + +/* Canonical encoding of the IR (WireLayout, declared little-endian, no + * padding, no pointers, no text except function names and contract text) and + * its SHA-256 digest. Identity of a compiled unit = this digest. */ +int osc_ir_encode(const OscUnit *u, uint8_t *buf, size_t cap, size_t *len); +int osc_ir_digest(const OscUnit *u, uint8_t out[32]); + +/* Width in bits of an integer scalar (8..64); 1 for bool; 0 otherwise. */ +unsigned osc_scalar_width(OscScalar s); +bool osc_scalar_signed(OscScalar s); +bool osc_scalar_is_int(OscScalar s); +const char *osc_scalar_name(OscScalar s); + +#endif /* OSC_IR_H */ diff --git a/src/compiler/osc_native.c b/src/compiler/osc_native.c new file mode 100644 index 000000000..10e48dcda --- /dev/null +++ b/src/compiler/osc_native.c @@ -0,0 +1,42 @@ +/* + * osc_native.c -- executable mapping for OSC-1 machine code. + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#include "osc_native.h" + +#include +#include +#include + +int osc_native_map(OscNative *nm, const uint8_t *code, size_t len) { + if (!nm || !code || len == 0 || (len & 3)) return -1; + memset(nm, 0, sizeof *nm); +#if defined(__aarch64__) + size_t page = (size_t)sysconf(_SC_PAGESIZE); + size_t size = (len + page - 1) & ~(page - 1); + void *mem = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); + if (mem == MAP_FAILED) return -1; + memcpy(mem, code, len); + __builtin___clear_cache((char *)mem, (char *)mem + len); + if (mprotect(mem, size, PROT_READ | PROT_EXEC) != 0) { + munmap(mem, size); + return -1; + } + nm->mem = mem; + nm->size = size; + nm->len = len; + return 0; +#else + return -2; +#endif +} + +void *osc_native_at(const OscNative *nm, uint32_t off) { + if (!nm || !nm->mem || off >= nm->len || (off & 3)) return NULL; + return (uint8_t *)nm->mem + off; +} + +void osc_native_unmap(OscNative *nm) { + if (nm && nm->mem) munmap(nm->mem, nm->size); + if (nm) memset(nm, 0, sizeof *nm); +} diff --git a/src/compiler/osc_native.h b/src/compiler/osc_native.h new file mode 100644 index 000000000..17e36f5f3 --- /dev/null +++ b/src/compiler/osc_native.h @@ -0,0 +1,25 @@ +/* + * osc_native.h -- map OSC-1 machine code for execution (RW mmap, copy, + * clear the instruction cache, mprotect RX), same pattern as src/omega_exec.c. + * Run a function with osc_rt_call_native (osc_rt.h). + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#ifndef OSC_NATIVE_H +#define OSC_NATIVE_H + +#include +#include + +typedef struct { + void *mem; /* RX mapping, NULL if not mapped */ + size_t size; /* mapping size (page multiple) */ + size_t len; /* code bytes */ +} OscNative; + +/* 0 ok; -1 failure (mmap/mprotect), -2 not an AArch64 host. */ +int osc_native_map(OscNative *nm, const uint8_t *code, size_t len); +/* Address of byte offset `off` in the mapping, or NULL if out of range/misaligned. */ +void *osc_native_at(const OscNative *nm, uint32_t off); +void osc_native_unmap(OscNative *nm); + +#endif /* OSC_NATIVE_H */ diff --git a/src/compiler/osc_rt.c b/src/compiler/osc_rt.c new file mode 100644 index 000000000..87696d021 --- /dev/null +++ b/src/compiler/osc_rt.c @@ -0,0 +1,129 @@ +/* + * osc_rt.c -- OSC-1 bootstrap runtime (OSC-0 II.10), shared by the reference + * interpreter and natively compiled code. See osc_rt.h. + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#include "osc_rt.h" + +#include +#include + +/* Native code reads these at fixed offsets (docs/osc/OSC-1-DESIGN.md s.7). */ +_Static_assert(offsetof(OscRt, alloc) == 0, "OscRt.alloc must be at offset 0"); +_Static_assert(offsetof(OscRt, release) == 8, "OscRt.release must be at offset 8"); +_Static_assert(offsetof(OscRt, trap) == 16, "OscRt.trap must be at offset 16"); +_Static_assert(sizeof(void (*)(void)) == 8, "64-bit function pointers"); + +#define FNV_OFF 1469598103934665603ULL +#define FNV_PRIME 1099511628211ULL + +void osc_rt_init(OscRt *rt) { + memset(rt, 0, sizeof *rt); + rt->alloc = osc_rt_alloc; + rt->release = osc_rt_release; + rt->trap = osc_rt_trap; + rt->ev_hash = FNV_OFF; +} + +void osc_rt_reset(OscRt *rt) { + for (unsigned s = 0; s < OSC_RT_SLOTS; s++) + if (rt->slot_serial[s] || rt->live[s]) memset(rt->cells[s], 0, sizeof rt->cells[s]); + memset(rt->live, 0, sizeof rt->live); + memset(rt->slot_len, 0, sizeof rt->slot_len); + memset(rt->slot_serial, 0, sizeof rt->slot_serial); + rt->next_serial = 0; + rt->live_count = 0; + rt->nev = 0; + rt->trap_code = 0; + rt->ev_hash = FNV_OFF; + rt->alloc = osc_rt_alloc; + rt->release = osc_rt_release; + rt->trap = osc_rt_trap; +} + +static void log_event(OscRt *rt, uint8_t kind, unsigned slot, uint16_t len, uint32_t serial) { + OscRtEvent e = {kind, (uint8_t)slot, len, serial}; + if (rt->nev < OSC_RT_EVENTS) rt->ev[rt->nev] = e; + if (rt->nev != UINT32_MAX) rt->nev++; + uint8_t b[8] = {kind, (uint8_t)slot, (uint8_t)len, (uint8_t)(len >> 8), + (uint8_t)serial, (uint8_t)(serial >> 8), (uint8_t)(serial >> 16), (uint8_t)(serial >> 24)}; + for (unsigned i = 0; i < 8; i++) { rt->ev_hash ^= b[i]; rt->ev_hash *= FNV_PRIME; } +} + +void osc_rt_trap(OscRt *rt, uint64_t code) { + rt->trap_code = (code >= 1 && code <= OSC_TRAP_RUNTIME) ? (uint32_t)code : OSC_TRAP_RUNTIME; + longjmp(rt->jb, 1); +} + +uint64_t osc_rt_alloc(OscRt *rt, uint64_t len, uint64_t init) { + if (len < 1 || len > OSC_MAX_ARRAY_LEN) osc_rt_trap(rt, OSC_TRAP_RUNTIME); + for (unsigned s = 0; s < OSC_RT_SLOTS; s++) { + if (rt->live[s]) continue; + for (unsigned i = 0; i < len; i++) rt->cells[s][i] = init; + rt->live[s] = 1; + rt->slot_len[s] = (uint16_t)len; + rt->slot_serial[s] = ++rt->next_serial; + rt->live_count++; + log_event(rt, OSC_RT_EV_ALLOC, s, (uint16_t)len, rt->slot_serial[s]); + return (uint64_t)(uintptr_t)&rt->cells[s][0]; + } + osc_rt_trap(rt, OSC_TRAP_OOM); + return 0; /* not reached */ +} + +/* slot index of a live slot start, or -1 */ +static int slot_of(const OscRt *rt, uint64_t addr, uint64_t len) { + uintptr_t base = (uintptr_t)&rt->cells[0][0]; + uintptr_t a = (uintptr_t)addr; + size_t stride = sizeof rt->cells[0]; + if (a < base || a >= base + sizeof rt->cells) return -1; + if ((a - base) % stride) return -1; + unsigned s = (unsigned)((a - base) / stride); + if (!rt->live[s] || rt->slot_len[s] != len) return -1; + return (int)s; +} + +int osc_rt_is_live_ref(const OscRt *rt, uint64_t addr, uint64_t len) { + return slot_of(rt, addr, len) >= 0; +} + +void osc_rt_release(OscRt *rt, uint64_t addr, uint64_t len) { + int s = slot_of(rt, addr, len); + if (s < 0) osc_rt_trap(rt, OSC_TRAP_RUNTIME); + memset(rt->cells[s], 0, sizeof rt->cells[s]); + rt->live[s] = 0; + rt->live_count--; + log_event(rt, OSC_RT_EV_RELEASE, (unsigned)s, (uint16_t)len, rt->slot_serial[s]); + /* slot_len / slot_serial are kept: they describe the last occupant and let + * osc_rt_reset find every slot that was ever used. */ +} + +typedef uint64_t (*OscNativeFn)(uint64_t, uint64_t, uint64_t, uint64_t, uint64_t, uint64_t, + uint64_t, OscRt *); + +int osc_rt_call_native(OscRt *rt, void *entry, const uint64_t *args, unsigned nargs, uint64_t *ret) { + if (!rt || !entry || !ret || nargs > OSC_MAX_PARAMS || (nargs && !args)) return -1; + uint64_t a[OSC_MAX_PARAMS] = {0}; + for (unsigned i = 0; i < nargs; i++) a[i] = args[i]; + union { void *p; OscNativeFn f; } u; + u.p = entry; + rt->trap_code = 0; + if (setjmp(rt->jb) != 0) return (int)rt->trap_code; + uint64_t r = u.f(a[0], a[1], a[2], a[3], a[4], a[5], 0, rt); + *ret = r; + return 0; +} + +int osc_rt_same_outcome(const OscRt *a, const OscRt *b) { + if (a->trap_code != b->trap_code || a->nev != b->nev || a->ev_hash != b->ev_hash) return 0; + if (a->next_serial != b->next_serial || a->live_count != b->live_count) return 0; + if (memcmp(a->live, b->live, sizeof a->live) || memcmp(a->slot_len, b->slot_len, sizeof a->slot_len) || + memcmp(a->slot_serial, b->slot_serial, sizeof a->slot_serial)) return 0; + uint32_t n = a->nev < OSC_RT_EVENTS ? a->nev : OSC_RT_EVENTS; + for (uint32_t i = 0; i < n; i++) + if (a->ev[i].kind != b->ev[i].kind || a->ev[i].slot != b->ev[i].slot || + a->ev[i].len != b->ev[i].len || a->ev[i].serial != b->ev[i].serial) return 0; + for (unsigned s = 0; s < OSC_RT_SLOTS; s++) + if ((a->slot_serial[s] || a->live[s]) && memcmp(a->cells[s], b->cells[s], sizeof a->cells[s])) return 0; + return 1; +} diff --git a/src/compiler/osc_rt.h b/src/compiler/osc_rt.h new file mode 100644 index 000000000..cca504dbc --- /dev/null +++ b/src/compiler/osc_rt.h @@ -0,0 +1,88 @@ +/* + * osc_rt.h -- OSC-1 bootstrap runtime (OSC-0 II.10: "built in C first as the + * bootstrap runtime"). Shared by the reference interpreter and natively + * compiled code so both observe the same allocation semantics. + * + * OSC-1 slice; not a general Omega compiler; no self-hosting. + * + * Pool: OSC_RT_SLOTS fixed slots of OSC_MAX_ARRAY_LEN 8-byte cells. Allocation + * takes the lowest-numbered free slot (deterministic). Release zeroes the + * cells it owned and frees the slot. Double release or releasing an address + * that is not a live slot start is a runtime invariant violation + * (OSC_TRAP_RUNTIME). Every alloc/release is appended to an event log that + * tests replay through the II.11 model (src/compiler/model/). + * + * Native ABI (docs/osc/OSC-1-DESIGN.md "Native ABI"): every compiled function + * receives the OscRt* in x7. The three entry points below are reached with + * BLR through the function-pointer fields of OscRt, at the fixed offsets + * asserted in osc_rt.c. osc_rt_trap never returns: it records the code and + * longjmps back to osc_rt_call_native. + */ +#ifndef OSC_RT_H +#define OSC_RT_H + +#include +#include +#include "osc_ir.h" + +#define OSC_RT_SLOTS 64 +#define OSC_RT_EVENTS 4096 + +typedef enum { OSC_RT_EV_ALLOC = 1, OSC_RT_EV_RELEASE = 2 } OscRtEventKind; + +typedef struct { + uint8_t kind; /* OscRtEventKind */ + uint8_t slot; + uint16_t len; /* elements */ + uint32_t serial; /* allocation serial number (object identity, 1-based) */ +} OscRtEvent; + +typedef struct OscRt OscRt; +struct OscRt { + /* Fixed-offset fields read by native code. Do not reorder. */ + uint64_t (*alloc)(OscRt *rt, uint64_t len, uint64_t init); /* offset 0 */ + void (*release)(OscRt *rt, uint64_t addr, uint64_t len); /* offset 8 */ + void (*trap)(OscRt *rt, uint64_t code); /* offset 16 */ + /* Host-side state. */ + uint64_t cells[OSC_RT_SLOTS][OSC_MAX_ARRAY_LEN]; + uint8_t live[OSC_RT_SLOTS]; + uint16_t slot_len[OSC_RT_SLOTS]; + uint32_t slot_serial[OSC_RT_SLOTS]; + uint32_t next_serial; + uint32_t live_count; + OscRtEvent ev[OSC_RT_EVENTS]; + uint32_t nev; + uint32_t trap_code; /* OscTrap of the last run */ + jmp_buf jb; + /* Appended (Lane 22 worker B): FNV-1a hash over ALL events, including + * those beyond OSC_RT_EVENTS that ev[] cannot hold, so long runs still + * compare their complete event history. */ + uint64_t ev_hash; +}; + +void osc_rt_init(OscRt *rt); +/* Same semantics as the native entry points, callable from the interpreter. */ +uint64_t osc_rt_alloc(OscRt *rt, uint64_t len, uint64_t init); +void osc_rt_release(OscRt *rt, uint64_t addr, uint64_t len); +void osc_rt_trap(OscRt *rt, uint64_t code); + +/* ---- additions (Lane 22 worker B) ------------------------------------- */ + +/* Cheap reset between runs: clears every slot ever used, the metadata, the + * event log and the trap code. Equivalent to osc_rt_init in effect. */ +void osc_rt_reset(OscRt *rt); + +/* Run natively compiled code: args in x0..x5 (missing ones 0), x6 = 0, + * rt in x7. setjmps on rt->jb so osc_rt_trap returns here. Returns the trap + * code (0 = normal return, *ret set), or -1 on bad arguments. */ +int osc_rt_call_native(OscRt *rt, void *entry, const uint64_t *args, unsigned nargs, uint64_t *ret); + +/* 1 if the observable pool state of a and b is identical: trap code, live + * slots, lengths, serials, cell contents, full event log (count, recorded + * events, hash). Addresses are not compared. */ +int osc_rt_same_outcome(const OscRt *a, const OscRt *b); + +/* 1 if addr is the start of a live slot (used to check REF arguments). */ +int osc_rt_is_live_ref(const OscRt *rt, uint64_t addr, uint64_t len); + +#endif /* OSC_RT_H */ diff --git a/tests/compiler/test_osc_backend.c b/tests/compiler/test_osc_backend.c new file mode 100644 index 000000000..faa02f0a8 --- /dev/null +++ b/tests/compiler/test_osc_backend.c @@ -0,0 +1,983 @@ +/* + * test_osc_backend.c -- OSC-1 back end gate (Lane 22). + * OSC-1 slice; not a general Omega compiler; no self-hosting. + * + * Builds IR units by hand (no front end here) and checks: + * (a) differential: native code == reference interpreter (trap code, return + * value, full pool state + event log) over >= 2000 seeded argument + * vectors per function (splitmix64, uniform mixed with edge values); + * (b) determinism: codegen twice -> identical bytes; IR digest stable; + * (c) every emitted word round-trips through the decoder; + * (d) encoder refusals (ranges, SP vs XZR, unpredictable forms) and + * reference encodings; + * (e) osc_ir_validate refuses malformed units. + * Final line: OSC1_BACKEND_PASS or OSC1_BACKEND_FAIL. + */ +#include +#include +#include +#include +#include + +#include "osc_a64.h" +#include "osc_cg.h" +#include "osc_interp.h" +#include "osc_ir.h" +#include "osc_native.h" +#include "osc_rt.h" + +#define NVEC 2000 + +static unsigned long n_checks, n_fail; +static unsigned long n_diff_runs, n_funcs_fuzzed, n_units, n_words, n_trap[OSC_TRAP_RUNTIME + 1]; +static unsigned long n_enc_ok, n_enc_refused, n_dec_rand_ok, n_validate_neg; + +static void check(int cond, const char *fmt, ...) { + n_checks++; + if (cond) return; + n_fail++; + if (n_fail <= 40) { + va_list ap; + va_start(ap, fmt); + fprintf(stderr, "FAIL: "); + vfprintf(stderr, fmt, ap); + fprintf(stderr, "\n"); + va_end(ap); + } +} + +/* ---- splitmix64 ------------------------------------------------------- */ +static uint64_t sm_state; +static uint64_t sm(void) { + uint64_t z = (sm_state += 0x9E3779B97F4A7C15ULL); + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL; + return z ^ (z >> 31); +} + +/* ---- IR builder --------------------------------------------------------- */ +static OscType TS(OscScalar s) { OscType t = {s, OSC_REF_NONE, OSC_T_VOID, 0}; return t; } +static OscType TR(OscRefKind k, OscScalar e, int len) { OscType t = {OSC_T_REF, k, e, (uint16_t)len}; return t; } +static const OscType TVOID = {OSC_T_VOID, OSC_REF_NONE, OSC_T_VOID, 0}; + +typedef struct { OscUnit *u; OscFunc *f; int fi; int cur; } B; + +static OscUnit *unit_new(void) { + OscUnit *u = calloc(1, sizeof *u); + if (!u) { fprintf(stderr, "oom\n"); exit(2); } + return u; +} + +static int V(B *b, OscType t) { b->f->vtype[b->f->nvregs] = t; return b->f->nvregs++; } +static int blk(B *b) { return b->f->nblocks++; } +static void at(B *b, int k) { b->cur = k; b->f->blocks[k].first = b->f->ninsns; b->f->blocks[k].count = 0; } + +static int fn(B *b, OscUnit *u, const char *name, OscType ret, int np, const OscType *pt) { + b->u = u; + b->fi = u->nfuncs++; + b->f = &u->funcs[b->fi]; + memset(b->f, 0, sizeof *b->f); + snprintf(b->f->name, sizeof b->f->name, "%s", name); + b->f->ret = ret; + b->f->nparams = (uint8_t)np; + for (int i = 0; i < np; i++) V(b, pt[i]); + at(b, blk(b)); + return b->fi; +} + +static OscInsn I0(int op) { + OscInsn i; + memset(&i, 0, sizeof i); + i.op = (uint8_t)op; + i.dst = i.a = i.b = i.c = i.blk_t = i.blk_f = i.callee = -1; + for (int k = 0; k < OSC_MAX_PARAMS; k++) i.args[k] = -1; + return i; +} +static void put(B *b, OscInsn i) { + b->f->insns[b->f->ninsns++] = i; + if (i.op == OSC_I_BR || i.op == OSC_I_CBR || i.op == OSC_I_RET) + b->f->blocks[b->cur].count = b->f->ninsns - b->f->blocks[b->cur].first; +} +static int k_const(B *b, OscType t, uint64_t v) { int d = V(b, t); OscInsn i = I0(OSC_I_CONST); i.dst = (int16_t)d; i.imm = v; put(b, i); return d; } +static int k_bin(B *b, int sub, int x, int y) { + int d = V(b, b->f->vtype[x]); OscInsn i = I0(OSC_I_BIN); i.sub = (uint8_t)sub; i.dst = (int16_t)d; i.a = (int16_t)x; i.b = (int16_t)y; put(b, i); return d; +} +static int k_un(B *b, int sub, int x) { int d = V(b, b->f->vtype[x]); OscInsn i = I0(OSC_I_UN); i.sub = (uint8_t)sub; i.dst = (int16_t)d; i.a = (int16_t)x; put(b, i); return d; } +static int k_cmp(B *b, int cc, int x, int y) { + int d = V(b, TS(OSC_T_BOOL)); OscInsn i = I0(OSC_I_CMP); i.sub = (uint8_t)cc; i.dst = (int16_t)d; i.a = (int16_t)x; i.b = (int16_t)y; put(b, i); return d; +} +static int k_cast(B *b, OscScalar to, int x) { int d = V(b, TS(to)); OscInsn i = I0(OSC_I_CAST); i.dst = (int16_t)d; i.a = (int16_t)x; put(b, i); return d; } +static void k_mov(B *b, int d, int x) { OscInsn i = I0(OSC_I_MOV); i.dst = (int16_t)d; i.a = (int16_t)x; put(b, i); } +static int k_alloc(B *b, OscScalar e, int len, int init) { + int d = V(b, TR(OSC_REF_OWN, e, len)); OscInsn i = I0(OSC_I_ALLOC); i.dst = (int16_t)d; i.a = (int16_t)init; put(b, i); return d; +} +static void k_release(B *b, int a) { OscInsn i = I0(OSC_I_RELEASE); i.a = (int16_t)a; put(b, i); } +static int k_load(B *b, int a, int idx) { + int d = V(b, TS(b->f->vtype[a].elem)); OscInsn i = I0(OSC_I_LOAD); i.dst = (int16_t)d; i.a = (int16_t)a; i.b = (int16_t)idx; put(b, i); return d; +} +static void k_store(B *b, int a, int idx, int v) { OscInsn i = I0(OSC_I_STORE); i.a = (int16_t)a; i.b = (int16_t)idx; i.c = (int16_t)v; put(b, i); } +static int k_call(B *b, int callee, int n, const int *args) { + OscInsn i = I0(OSC_I_CALL); + i.callee = (int16_t)callee; i.nargs = (uint8_t)n; + for (int k = 0; k < n; k++) i.args[k] = (int16_t)args[k]; + const OscType *rt = &b->u->funcs[callee].ret; + int d = -1; + if (rt->s != OSC_T_VOID) d = V(b, *rt); + i.dst = (int16_t)d; + put(b, i); + return d; +} +static void k_trap(B *b, int code) { OscInsn i = I0(OSC_I_TRAP); i.imm = (uint64_t)code; put(b, i); } +static void k_br(B *b, int t) { OscInsn i = I0(OSC_I_BR); i.blk_t = (int16_t)t; put(b, i); } +static void k_cbr(B *b, int c, int t, int f) { OscInsn i = I0(OSC_I_CBR); i.a = (int16_t)c; i.blk_t = (int16_t)t; i.blk_f = (int16_t)f; put(b, i); } +static void k_ret(B *b, int a) { OscInsn i = I0(OSC_I_RET); i.a = (int16_t)a; put(b, i); } + +/* ---- value helpers ------------------------------------------------------ */ +static const OscScalar INTS[8] = {OSC_T_U8, OSC_T_U16, OSC_T_U32, OSC_T_U64, OSC_T_I8, OSC_T_I16, OSC_T_I32, OSC_T_I64}; + +static uint64_t canon(OscScalar t, uint64_t x) { + unsigned w = osc_scalar_width(t); + if (t == OSC_T_BOOL) return x & 1; + if (w >= 64) return x; + if (osc_scalar_signed(t)) { + uint64_t m = 1ULL << (w - 1); + x &= (1ULL << w) - 1; + return (x ^ m) - m; + } + return x & ((1ULL << w) - 1); +} + +static const uint64_t EDGE[] = { + 0, 1, 2, 3, 7, 8, 9, 15, 16, 31, 32, 33, 63, 64, 65, 127, 128, 255, 256, + 0x7F, 0x80, 0x81, 0xFF, 0x100, 0x7FFF, 0x8000, 0x8001, 0xFFFF, 0x10000, + 0x7FFFFFFFULL, 0x80000000ULL, 0x80000001ULL, 0xFFFFFFFFULL, 0x100000000ULL, + 0x7FFFFFFFFFFFFFFFULL, 0x8000000000000000ULL, 0x8000000000000001ULL, 0xFFFFFFFFFFFFFFFFULL, + (uint64_t)-2, (uint64_t)-3, (uint64_t)-8, (uint64_t)-63, (uint64_t)-64, (uint64_t)-0x7F, (uint64_t)-0x80, + (uint64_t)-0x81, (uint64_t)-0x7FFF, (uint64_t)-0x8000, (uint64_t)-0x8001, (uint64_t)-0x7FFFFFFFLL, + (uint64_t)-0x80000000LL, (uint64_t)-0x80000001LL, 0xB504, 0xB505, 0xB504F333ULL, 0xB504F334ULL, + 0x16A09E667ULL, 0x5A82, 0x5A83, 0x3037000499ULL, 0xB5, 0xB6, 0x0B, 0x0C, +}; +#define NEDGE (sizeof EDGE / sizeof EDGE[0]) + +static uint64_t gen_val(OscScalar t) { + uint64_t r = sm(), x; + switch (r % 5) { + case 0: case 1: x = EDGE[sm() % NEDGE]; break; + case 2: x = (uint64_t)((int64_t)(sm() % 141) - 70); break; + case 3: x = EDGE[sm() % NEDGE] + (uint64_t)((int64_t)(sm() % 5) - 2); break; + default: x = sm(); if (r & 0x100) x >>= (sm() % 64); break; + } + return canon(t, x); +} + +/* ---- differential harness ---------------------------------------------- */ +static OscRt *rtI, *rtN; + +static void unit_check(OscUnit *u, const char *uname) { + char err[256]; + n_units++; + int vr = osc_ir_validate(u, err, sizeof err); + check(vr == 0, "%s: validate: %s", uname, err); + if (vr) return; + OscCode c1, c2; + int r1 = osc_cg_compile(u, &c1, err, sizeof err); + check(r1 == 0, "%s: compile: %s", uname, err); + if (r1) return; + int r2 = osc_cg_compile(u, &c2, err, sizeof err); + check(r2 == 0 && c1.len == c2.len && memcmp(c1.code, c2.code, c1.len) == 0 && + memcmp(c1.entry, c2.entry, sizeof c1.entry) == 0, "%s: codegen not deterministic", uname); + osc_cg_free(&c2); + uint8_t d1[32], d2[32]; + check(osc_ir_digest(u, d1) == 0 && osc_ir_digest(u, d2) == 0 && memcmp(d1, d2, 32) == 0, "%s: digest unstable", uname); + size_t elen = 0; + check(osc_ir_encode(u, NULL, 0, &elen) == 0 && elen > 0, "%s: encode length", uname); + check(osc_cg_verify(&c1, err, sizeof err) == 0, "%s: verify: %s", uname, err); + /* (c) every word: decode -> fields -> re-encode == word */ + for (size_t off = 0; off < c1.len; off += 4) { + uint32_t w = (uint32_t)c1.code[off] | ((uint32_t)c1.code[off + 1] << 8) | ((uint32_t)c1.code[off + 2] << 16) | + ((uint32_t)c1.code[off + 3] << 24); + OscA64Insn d, d2; + uint32_t re = 0; + int ok = osc_a64_decode(w, &d) == 0 && osc_a64_reencode(&d, &re) == 0 && re == w && + osc_a64_decode(re, &d2) == 0 && osc_a64_equal(&d, &d2); + if (!ok) check(0, "%s: word +%zu 0x%08x does not round-trip", uname, off, w); + n_words++; + } + OscNative nm; + int mr = osc_native_map(&nm, c1.code, c1.len); + check(mr == 0, "%s: native map failed (%d)", uname, mr); + if (mr) { osc_cg_free(&c1); return; } + for (int fi = 0; fi < u->nfuncs; fi++) { + const OscFunc *f = &u->funcs[fi]; + int has_ref = 0; + for (int p = 0; p < f->nparams; p++) has_ref |= f->vtype[p].s == OSC_T_REF; + if (has_ref) continue; /* exercised through its callers */ + n_funcs_fuzzed++; + void *entry = osc_native_at(&nm, c1.entry[fi]); + for (int k = 0; k < NVEC; k++) { + uint64_t args[OSC_MAX_PARAMS] = {0}, ri = 0xdead, rn = 0xbeef; + for (int p = 0; p < f->nparams; p++) args[p] = gen_val(f->vtype[p].s); + osc_rt_reset(rtI); + osc_rt_reset(rtN); + int ti = (k == 0) ? osc_interp_run(u, fi, args, f->nparams, rtI, &ri) + : osc_interp_run_prevalidated(u, fi, args, f->nparams, rtI, &ri); + int tn = osc_rt_call_native(rtN, entry, args, f->nparams, &rn); + n_diff_runs++; + int same = ti >= 0 && ti == tn && (ti != 0 || ri == rn) && osc_rt_same_outcome(rtI, rtN); + if (!same) + check(0, "%s/%s vec %d args(%llx,%llx,%llx): interp trap %d ret %llx, native trap %d ret %llx, pool %s", + uname, f->name, k, (unsigned long long)args[0], (unsigned long long)args[1], + (unsigned long long)args[2], ti, (unsigned long long)ri, tn, (unsigned long long)rn, + osc_rt_same_outcome(rtI, rtN) ? "same" : "DIFFERENT"); + else + n_checks++; + if (tn >= 0 && tn <= OSC_TRAP_RUNTIME) n_trap[tn]++; + } + } + osc_native_unmap(&nm); + osc_cg_free(&c1); +} + +/* ---- unit generators ---------------------------------------------------- */ +static const char *bname(int s) { + static const char *n[] = {"?", "add", "sub", "mul", "div", "rem", "and", "or", "xor", "shl", "shr"}; + return n[s]; +} + +typedef struct { OscUnit *u; int count; char name[32]; int seq; } Pack; +static void pack_flush(Pack *p) { + if (p->u && p->u->nfuncs) unit_check(p->u, p->name); + free(p->u); + p->u = NULL; +} +static OscUnit *pack_get(Pack *p, const char *base) { + if (p->u && p->u->nfuncs >= OSC_MAX_FUNCS) pack_flush(p); + if (!p->u) { p->u = unit_new(); snprintf(p->name, sizeof p->name, "%s#%d", base, p->seq++); } + return p->u; +} + +static void gen_ops(void) { + Pack p = {0}; + B b; + char nm[64]; + /* every BIN op for every integer type (shifts: every amount type too) */ + for (int ti = 0; ti < 8; ti++) + for (int sub = OSC_B_ADD; sub <= OSC_B_SHR; sub++) { + int shift = sub == OSC_B_SHL || sub == OSC_B_SHR; + for (int tb = 0; tb < 8; tb++) { + if (!shift && tb != ti) continue; + OscType pt[2] = {TS(INTS[ti]), TS(INTS[tb])}; + snprintf(nm, sizeof nm, "%s_%s_%s", bname(sub), osc_scalar_name(INTS[ti]), osc_scalar_name(INTS[tb])); + fn(&b, pack_get(&p, "bin"), nm, pt[0], 2, pt); + k_ret(&b, k_bin(&b, sub, 0, 1)); + } + } + /* bool bitwise */ + for (int sub = OSC_B_AND; sub <= OSC_B_XOR; sub++) { + OscType pt[2] = {TS(OSC_T_BOOL), TS(OSC_T_BOOL)}; + snprintf(nm, sizeof nm, "%s_bool", bname(sub)); + fn(&b, pack_get(&p, "bin"), nm, pt[0], 2, pt); + k_ret(&b, k_bin(&b, sub, 0, 1)); + } + pack_flush(&p); + /* UN */ + for (int ti = 0; ti < 8; ti++) + for (int sub = OSC_U_NEG; sub <= OSC_U_BNOT; sub++) { + OscType pt[1] = {TS(INTS[ti])}; + snprintf(nm, sizeof nm, "%s_%s", sub == OSC_U_NEG ? "neg" : "bnot", osc_scalar_name(INTS[ti])); + fn(&b, pack_get(&p, "un"), nm, pt[0], 1, pt); + k_ret(&b, k_un(&b, sub, 0)); + } + { + OscType pt[1] = {TS(OSC_T_BOOL)}; + fn(&b, pack_get(&p, "un"), "lnot_bool", pt[0], 1, pt); + k_ret(&b, k_un(&b, OSC_U_LNOT, 0)); + } + pack_flush(&p); + /* CMP for every type incl. bool */ + for (int ti = 0; ti < 9; ti++) { + OscScalar t = ti < 8 ? INTS[ti] : OSC_T_BOOL; + for (int cc = OSC_C_EQ; cc <= OSC_C_GE; cc++) { + OscType pt[2] = {TS(t), TS(t)}; + snprintf(nm, sizeof nm, "cmp%d_%s", cc, osc_scalar_name(t)); + fn(&b, pack_get(&p, "cmp"), nm, TS(OSC_T_BOOL), 2, pt); + k_ret(&b, k_cmp(&b, cc, 0, 1)); + } + } + pack_flush(&p); + /* CAST every integer pair */ + for (int from = 0; from < 8; from++) + for (int to = 0; to < 8; to++) { + OscType pt[1] = {TS(INTS[from])}; + snprintf(nm, sizeof nm, "cast_%s_%s", osc_scalar_name(INTS[from]), osc_scalar_name(INTS[to])); + fn(&b, pack_get(&p, "cast"), nm, TS(INTS[to]), 1, pt); + k_ret(&b, k_cast(&b, INTS[to], 0)); + } + pack_flush(&p); + /* CONST: select among edge constants of each type (exercises MOVZ/MOVN/MOVK + * materialisation), plus MOV and an if-chain of CBR/BR */ + for (int ti = 0; ti < 9; ti++) { + OscScalar t = ti < 8 ? INTS[ti] : OSC_T_BOOL; + OscType pt[1] = {TS(OSC_T_U8)}; + snprintf(nm, sizeof nm, "const_%s", osc_scalar_name(t)); + fn(&b, pack_get(&p, "const"), nm, TS(t), 1, pt); + int res = V(&b, TS(t)); + k_mov(&b, res, k_const(&b, TS(t), canon(t, 0x123456789ABCDEF0ULL))); + int exit_ = -1; + int nsel = 24; + int blocks[64]; + for (int i = 0; i < nsel; i++) blocks[i] = blk(&b); + exit_ = blk(&b); + k_br(&b, blocks[0]); + for (int i = 0; i < nsel; i++) { + at(&b, blocks[i]); + int hit = blk(&b); + int c = k_cmp(&b, OSC_C_EQ, 0, k_const(&b, TS(OSC_T_U8), (uint64_t)i)); + k_cbr(&b, c, hit, i + 1 < nsel ? blocks[i + 1] : exit_); + at(&b, hit); + uint64_t v = canon(t, EDGE[(i * 7) % NEDGE] ^ (i & 1 ? 0xFFFF0000FFFF0000ULL : 0)); + k_mov(&b, res, k_const(&b, TS(t), v)); + k_br(&b, exit_); + } + at(&b, exit_); + k_ret(&b, res); + } + pack_flush(&p); +} + +/* arrays: alloc / store / load / release, loops, bounds traps */ +static void gen_arrays(void) { + OscUnit *u = unit_new(); + B b; + for (int ei = 0; ei < 9; ei++) { + OscScalar e = ei < 8 ? INTS[ei] : OSC_T_BOOL; + char nm[64]; + snprintf(nm, sizeof nm, "arr_%s", osc_scalar_name(e)); + /* f(v: E, idx: i64, j: u8, w: E) -> E + * a = alloc [E; 8] = v; a[idx] = w; s = a[j]; for i in 0..8: x = a[i] (last kept) + * release a; return s (on a trap the allocation stays live: pool compared) */ + OscType pt[4] = {TS(e), TS(OSC_T_I64), TS(OSC_T_U8), TS(e)}; + fn(&b, u, nm, TS(e), 4, pt); + int a = k_alloc(&b, e, 8, 0); + k_store(&b, a, 1, 3); + int s = k_load(&b, a, 2); + int i = V(&b, TS(OSC_T_I64)); + k_mov(&b, i, k_const(&b, TS(OSC_T_I64), 0)); + int last = V(&b, TS(e)); + k_mov(&b, last, 0); + int head = blk(&b), body = blk(&b), done = blk(&b); + k_br(&b, head); + at(&b, head); + int c = k_cmp(&b, OSC_C_LT, i, k_const(&b, TS(OSC_T_I64), 8)); + k_cbr(&b, c, body, done); + at(&b, body); + k_mov(&b, last, k_load(&b, a, i)); + k_mov(&b, i, k_bin(&b, OSC_B_ADD, i, k_const(&b, TS(OSC_T_I64), 1))); + k_br(&b, head); + at(&b, done); + /* store through a &mut borrow binding too */ + int m = V(&b, TR(OSC_REF_MUT, e, 8)); + k_mov(&b, m, a); + k_store(&b, m, 2, last); + int t2 = k_load(&b, m, 2); + k_release(&b, a); + (void)t2; + k_ret(&b, s); + } + { + /* sum over [i64; 16] with checked adds: sum(seed: i64, step: i64, n: u8) */ + OscType pt[3] = {TS(OSC_T_I64), TS(OSC_T_I64), TS(OSC_T_U8)}; + fn(&b, u, "arr_sum", TS(OSC_T_I64), 3, pt); + int a = k_alloc(&b, OSC_T_I64, 16, 0); + int i = V(&b, TS(OSC_T_U8)), acc = V(&b, TS(OSC_T_I64)), cur = V(&b, TS(OSC_T_I64)); + k_mov(&b, i, k_const(&b, TS(OSC_T_U8), 0)); + k_mov(&b, acc, k_const(&b, TS(OSC_T_I64), 0)); + k_mov(&b, cur, 0); + int h1 = blk(&b), b1 = blk(&b), d1 = blk(&b), h2 = blk(&b), b2 = blk(&b), d2 = blk(&b); + k_br(&b, h1); + at(&b, h1); + k_cbr(&b, k_cmp(&b, OSC_C_LT, i, 2), b1, d1); /* i < n: n > 16 traps BOUNDS */ + at(&b, b1); + k_store(&b, a, i, cur); + k_mov(&b, cur, k_bin(&b, OSC_B_ADD, cur, 1)); + k_mov(&b, i, k_bin(&b, OSC_B_ADD, i, k_const(&b, TS(OSC_T_U8), 1))); + k_br(&b, h1); + at(&b, d1); + k_mov(&b, i, k_const(&b, TS(OSC_T_U8), 0)); + k_br(&b, h2); + at(&b, h2); + k_cbr(&b, k_cmp(&b, OSC_C_LT, i, k_const(&b, TS(OSC_T_U8), 16)), b2, d2); + at(&b, b2); + k_mov(&b, acc, k_bin(&b, OSC_B_ADD, acc, k_load(&b, a, i))); + k_mov(&b, i, k_bin(&b, OSC_B_ADD, i, k_const(&b, TS(OSC_T_U8), 1))); + k_br(&b, h2); + at(&b, d2); + k_release(&b, a); + k_ret(&b, acc); + } + { + /* loop bound: count(n: u32) -> u32, bound 10 via counter + TRAP 4 */ + OscType pt[1] = {TS(OSC_T_U32)}; + fn(&b, u, "loop_bound", TS(OSC_T_U32), 1, pt); + int i = V(&b, TS(OSC_T_U32)), cnt = V(&b, TS(OSC_T_U64)); + k_mov(&b, i, k_const(&b, TS(OSC_T_U32), 0)); + k_mov(&b, cnt, k_const(&b, TS(OSC_T_U64), 0)); + int head = blk(&b), chk = blk(&b), body = blk(&b), tr = blk(&b), done = blk(&b); + k_br(&b, head); + at(&b, head); + k_cbr(&b, k_cmp(&b, OSC_C_LT, i, 0), chk, done); + at(&b, chk); + k_cbr(&b, k_cmp(&b, OSC_C_GE, cnt, k_const(&b, TS(OSC_T_U64), 10)), tr, body); + at(&b, tr); + k_trap(&b, OSC_TRAP_LOOP_BOUND); + k_br(&b, done); + at(&b, body); + k_mov(&b, cnt, k_bin(&b, OSC_B_ADD, cnt, k_const(&b, TS(OSC_T_U64), 1))); + k_mov(&b, i, k_bin(&b, OSC_B_ADD, i, k_const(&b, TS(OSC_T_U32), 1))); + k_br(&b, head); + at(&b, done); + k_ret(&b, i); + } + { + /* OOM: grab(n: u8) allocates n arrays of [u16; 3] without releasing */ + OscType pt[1] = {TS(OSC_T_U8)}; + fn(&b, u, "oom", TS(OSC_T_U64), 1, pt); + int i = V(&b, TS(OSC_T_U8)), last = V(&b, TS(OSC_T_U64)); + k_mov(&b, i, k_const(&b, TS(OSC_T_U8), 0)); + k_mov(&b, last, k_const(&b, TS(OSC_T_U64), 0)); + int head = blk(&b), body = blk(&b), done = blk(&b); + k_br(&b, head); + at(&b, head); + k_cbr(&b, k_cmp(&b, OSC_C_LT, i, 0), body, done); + at(&b, body); + int a = k_alloc(&b, OSC_T_U16, 3, k_cast(&b, OSC_T_U16, i)); + k_mov(&b, last, k_cast(&b, OSC_T_U64, k_load(&b, a, k_const(&b, TS(OSC_T_U8), 2)))); + k_mov(&b, i, k_bin(&b, OSC_B_ADD, i, k_const(&b, TS(OSC_T_U8), 1))); + k_br(&b, head); + at(&b, done); + k_ret(&b, last); + } + { + /* double release -> RUNTIME; release then realloc reuses the lowest slot */ + OscType pt[2] = {TS(OSC_T_BOOL), TS(OSC_T_I32)}; + fn(&b, u, "double_release", TS(OSC_T_I32), 2, pt); + int a = k_alloc(&b, OSC_T_I32, 4, 1); + int a2 = k_alloc(&b, OSC_T_I32, 5, 1); + k_release(&b, a); + int a3 = k_alloc(&b, OSC_T_I32, 6, 1); /* takes slot 0 again */ + int yes = blk(&b), no = blk(&b); + k_cbr(&b, 0, yes, no); + at(&b, yes); + k_release(&b, a2); + k_release(&b, a2); + k_br(&b, no); + at(&b, no); + int r = k_load(&b, a3, k_const(&b, TS(OSC_T_U8), 5)); + k_ret(&b, r); + } + { + /* explicit TRAP of every code, selected by argument */ + OscType pt[1] = {TS(OSC_T_U8)}; + fn(&b, u, "trap_sel", TS(OSC_T_U8), 1, pt); + int nxt = blk(&b); + k_br(&b, nxt); + for (int code = 1; code <= OSC_TRAP_RUNTIME; code++) { + at(&b, nxt); + int hit = blk(&b); + nxt = blk(&b); + k_cbr(&b, k_cmp(&b, OSC_C_EQ, 0, k_const(&b, TS(OSC_T_U8), (uint64_t)code)), hit, nxt); + at(&b, hit); + k_trap(&b, code); + k_ret(&b, 0); + } + at(&b, nxt); + k_ret(&b, 0); + } + unit_check(u, "arrays"); + free(u); +} + +/* calls with 0..6 params, REF params of every kind, void callee */ +static void gen_calls(void) { + OscUnit *u = unit_new(); + B b; + int g[7]; + { + g[0] = fn(&b, u, "g0", TS(OSC_T_I64), 0, NULL); + k_ret(&b, k_const(&b, TS(OSC_T_I64), (uint64_t)-7)); + } + { + OscType pt[1] = {TS(OSC_T_I64)}; + g[1] = fn(&b, u, "g1", TS(OSC_T_I64), 1, pt); + k_ret(&b, k_bin(&b, OSC_B_MUL, 0, k_const(&b, TS(OSC_T_I64), 3))); + } + { + OscType pt[2] = {TS(OSC_T_U8), TS(OSC_T_U16)}; + g[2] = fn(&b, u, "g2", TS(OSC_T_U32), 2, pt); + k_ret(&b, k_bin(&b, OSC_B_ADD, k_cast(&b, OSC_T_U32, 0), k_cast(&b, OSC_T_U32, 1))); + } + { + OscType pt[3] = {TS(OSC_T_I32), TS(OSC_T_I32), TS(OSC_T_I32)}; + g[3] = fn(&b, u, "g3", TS(OSC_T_I32), 3, pt); + k_ret(&b, k_bin(&b, OSC_B_ADD, k_bin(&b, OSC_B_SUB, 0, 1), 2)); + } + { + OscType pt[4] = {TS(OSC_T_U64), TS(OSC_T_U64), TS(OSC_T_U64), TS(OSC_T_U64)}; + g[4] = fn(&b, u, "g4", TS(OSC_T_U64), 4, pt); + k_ret(&b, k_bin(&b, OSC_B_ADD, k_bin(&b, OSC_B_XOR, 0, 1), k_bin(&b, OSC_B_MUL, 2, 3))); + } + { + OscType pt[5] = {TS(OSC_T_I16), TS(OSC_T_I16), TS(OSC_T_I16), TS(OSC_T_I16), TS(OSC_T_I16)}; + g[5] = fn(&b, u, "g5", TS(OSC_T_I16), 5, pt); + int r = k_bin(&b, OSC_B_SUB, 0, 1); + r = k_bin(&b, OSC_B_SUB, r, 2); + r = k_bin(&b, OSC_B_DIV, r, 3); + k_ret(&b, k_bin(&b, OSC_B_REM, r, 4)); + } + { + OscType pt[6] = {TS(OSC_T_I8), TS(OSC_T_U8), TS(OSC_T_I16), TS(OSC_T_U32), TS(OSC_T_I64), TS(OSC_T_BOOL)}; + g[6] = fn(&b, u, "g6", TS(OSC_T_I64), 6, pt); + int s = k_cast(&b, OSC_T_I64, 0); + s = k_bin(&b, OSC_B_ADD, s, k_cast(&b, OSC_T_I64, 1)); + s = k_bin(&b, OSC_B_ADD, s, k_cast(&b, OSC_T_I64, 2)); + s = k_bin(&b, OSC_B_ADD, s, k_cast(&b, OSC_T_I64, 3)); + int y = blk(&b), n = blk(&b); + k_cbr(&b, 5, y, n); + at(&b, y); + k_ret(&b, k_bin(&b, OSC_B_SUB, s, 4)); + at(&b, n); + k_ret(&b, k_bin(&b, OSC_B_ADD, s, 4)); + } + /* REF callees */ + int fsum, fput, fconsume; + { + OscType pt[1] = {TR(OSC_REF_SHARED, OSC_T_I64, 4)}; + fsum = fn(&b, u, "sum4", TS(OSC_T_I64), 1, pt); + int s = k_load(&b, 0, k_const(&b, TS(OSC_T_U8), 0)); + for (int i = 1; i < 4; i++) s = k_bin(&b, OSC_B_ADD, s, k_load(&b, 0, k_const(&b, TS(OSC_T_U8), (uint64_t)i))); + k_ret(&b, s); + } + { + OscType pt[3] = {TR(OSC_REF_MUT, OSC_T_I64, 4), TS(OSC_T_I64), TS(OSC_T_I64)}; + fput = fn(&b, u, "put4", TVOID, 3, pt); + k_store(&b, 0, 1, 2); + k_ret(&b, -1); + } + { + OscType pt[1] = {TR(OSC_REF_OWN, OSC_T_I64, 4)}; + fconsume = fn(&b, u, "consume4", TS(OSC_T_I64), 1, pt); + int s = k_load(&b, 0, k_const(&b, TS(OSC_T_I32), 3)); + k_release(&b, 0); + k_ret(&b, s); + } + { + /* caller(x: i64, y: u32, z: i8, idx: i64) */ + OscType pt[4] = {TS(OSC_T_I64), TS(OSC_T_U32), TS(OSC_T_I8), TS(OSC_T_I64)}; + fn(&b, u, "caller", TS(OSC_T_I64), 4, pt); + int acc = k_call(&b, g[0], 0, NULL); + int a1[1] = {0}; + acc = k_bin(&b, OSC_B_ADD, acc, k_call(&b, g[1], 1, a1)); + int a2[2] = {k_cast(&b, OSC_T_U8, k_bin(&b, OSC_B_AND, 1, k_const(&b, TS(OSC_T_U32), 0xFF))), + k_cast(&b, OSC_T_U16, k_bin(&b, OSC_B_SHR, 1, k_const(&b, TS(OSC_T_U8), 16)))}; + acc = k_bin(&b, OSC_B_ADD, acc, k_cast(&b, OSC_T_I64, k_call(&b, g[2], 2, a2))); + int z32 = k_cast(&b, OSC_T_I32, 2); + int a3[3] = {z32, k_const(&b, TS(OSC_T_I32), 100), z32}; + acc = k_bin(&b, OSC_B_ADD, acc, k_cast(&b, OSC_T_I64, k_call(&b, g[3], 3, a3))); + int y64 = k_cast(&b, OSC_T_U64, 1); + int a4[4] = {y64, y64, y64, k_const(&b, TS(OSC_T_U64), 3)}; + int r4 = k_call(&b, g[4], 4, a4); + acc = k_bin(&b, OSC_B_ADD, acc, k_cast(&b, OSC_T_I64, k_bin(&b, OSC_B_AND, r4, k_const(&b, TS(OSC_T_U64), 0xFFFF)))); + int z16 = k_cast(&b, OSC_T_I16, 2); + int a5[5] = {z16, k_const(&b, TS(OSC_T_I16), 3), z16, k_const(&b, TS(OSC_T_I16), 2), z16}; + acc = k_bin(&b, OSC_B_ADD, acc, k_cast(&b, OSC_T_I64, k_call(&b, g[5], 5, a5))); + int a6[6] = {2, k_cast(&b, OSC_T_U8, k_bin(&b, OSC_B_AND, 1, k_const(&b, TS(OSC_T_U32), 0x7F))), + k_const(&b, TS(OSC_T_I16), (uint64_t)-300), 1, 0, k_cmp(&b, OSC_C_LT, 0, k_const(&b, TS(OSC_T_I64), 0))}; + acc = k_bin(&b, OSC_B_ADD, acc, k_call(&b, g[6], 6, a6)); + /* arrays across calls */ + int arr = k_alloc(&b, OSC_T_I64, 4, k_const(&b, TS(OSC_T_I64), 5)); + int m = V(&b, TR(OSC_REF_MUT, OSC_T_I64, 4)); + k_mov(&b, m, arr); + int ap[3] = {m, 3, 0}; /* put4(&mut arr, idx, x): idx may trap BOUNDS */ + k_call(&b, fput, 3, ap); + int ap2[3] = {arr, k_const(&b, TS(OSC_T_I64), 0), acc}; /* owner passed to &mut param */ + k_call(&b, fput, 3, ap2); + int sh = V(&b, TR(OSC_REF_SHARED, OSC_T_I64, 4)); + k_mov(&b, sh, arr); + int sp1[1] = {sh}; + int sum = k_call(&b, fsum, 1, sp1); /* checked adds: may OVERFLOW */ + int cp[1] = {arr}; + int last = k_call(&b, fconsume, 1, cp); /* moves and releases */ + k_ret(&b, k_bin(&b, OSC_B_XOR, sum, last)); + } + unit_check(u, "calls"); + free(u); +} + +/* ---- (d) encoder ------------------------------------------------------ */ +static void enc_expect(OscA64Insn i, uint32_t want, const char *what) { + uint32_t w = 0; + char e[160]; + int r = osc_a64_encode(&i, &w, e, sizeof e); + check(r == 0 && w == want, "encode %s: got 0x%08x want 0x%08x (%s)", what, w, want, r ? e : "ok"); + OscA64Insn d; + check(osc_a64_decode(want, &d) == 0 && osc_a64_equal(&d, &i), "decode %s (0x%08x) fields differ", what, want); +} +static void enc_refuse(OscA64Insn i, const char *what) { + uint32_t w = 0; + check(osc_a64_encode(&i, &w, NULL, 0) != 0, "encoder accepted %s (0x%08x)", what, w); +} + +static void test_encoder(void) { + const int SP = OSC_A64_SP, ZR = OSC_A64_XZR; + /* reference encodings (ARM ARM; hand-assembled) */ + enc_expect(osc_a64_breg(OSC_A64_RET, 30), 0xD65F03C0u, "ret"); + enc_expect(osc_a64_pair(OSC_A64_STP_PRE, 29, 30, SP, -16), 0xA9BF7BFDu, "stp x29,x30,[sp,#-16]!"); + enc_expect(osc_a64_pair(OSC_A64_LDP_POST, 29, 30, SP, 16), 0xA8C17BFDu, "ldp x29,x30,[sp],#16"); + enc_expect(osc_a64_ri(OSC_A64_ADD_IMM, 29, SP, 0, 0), 0x910003FDu, "mov x29,sp"); + enc_expect(osc_a64_ri(OSC_A64_SUB_IMM, SP, SP, 16, 0), 0xD10043FFu, "sub sp,sp,#16"); + enc_expect(osc_a64_breg(OSC_A64_BLR, 16), 0xD63F0200u, "blr x16"); + enc_expect(osc_a64_r4(OSC_A64_MADD, 0, 1, 2, ZR), 0x9B027C20u, "mul x0,x1,x2"); + enc_expect(osc_a64_r4(OSC_A64_MSUB, 0, 1, 2, 3), 0x9B028C20u, "msub x0,x1,x2,x3"); + enc_expect(osc_a64_r3(OSC_A64_SMULH, 0, 1, 2), 0x9B427C20u, "smulh x0,x1,x2"); + enc_expect(osc_a64_r3(OSC_A64_UMULH, 0, 1, 2), 0x9BC27C20u, "umulh x0,x1,x2"); + enc_expect(osc_a64_r3(OSC_A64_SDIV, 0, 1, 2), 0x9AC20C20u, "sdiv x0,x1,x2"); + enc_expect(osc_a64_r3(OSC_A64_UDIV, 0, 1, 2), 0x9AC20820u, "udiv x0,x1,x2"); + enc_expect(osc_a64_r3(OSC_A64_LSLV, 0, 1, 2), 0x9AC22020u, "lsl x0,x1,x2"); + enc_expect(osc_a64_r3(OSC_A64_LSRV, 0, 1, 2), 0x9AC22420u, "lsr x0,x1,x2"); + enc_expect(osc_a64_r3(OSC_A64_ASRV, 0, 1, 2), 0x9AC22820u, "asr x0,x1,x2"); + enc_expect(osc_a64_csinc(0, ZR, ZR, OSC_A64_NE), 0x9A9F17E0u, "cset x0,eq"); + enc_expect(osc_a64_bfm(OSC_A64_SBFM, 0, 1, 0, 7), 0x93401C20u, "sxtb x0,w1"); + enc_expect(osc_a64_bfm(OSC_A64_SBFM, 0, 1, 0, 31), 0x93407C20u, "sxtw x0,w1"); + enc_expect(osc_a64_bfm(OSC_A64_UBFM, 0, 1, 0, 7), 0xD3401C20u, "ubfx x0,x1,#0,#8"); + enc_expect(osc_a64_bfm(OSC_A64_SBFM, 0, 1, 63, 63), 0x937FFC20u, "asr x0,x1,#63"); + enc_expect(osc_a64_mov16(OSC_A64_MOVZ, 0, 1, 0), 0xD2800020u, "movz x0,#1"); + enc_expect(osc_a64_mov16(OSC_A64_MOVZ, 12, 0x8000, 48), 0xD2F0000Cu, "movz x12,#0x8000,lsl#48"); + enc_expect(osc_a64_mov16(OSC_A64_MOVN, 0, 0, 0), 0x92800000u, "movn x0,#0"); + enc_expect(osc_a64_mov16(OSC_A64_MOVK, 1, 0xBEEF, 16), 0xF2B7DDE1u, "movk x1,#0xbeef,lsl#16"); + enc_expect(osc_a64_mem(OSC_A64_LDR_UOFF, 0, SP, 8), 0xF94007E0u, "ldr x0,[sp,#8]"); + enc_expect(osc_a64_mem(OSC_A64_STR_UOFF, 7, SP, 0), 0xF90003E7u, "str x7,[sp]"); + enc_expect(osc_a64_mem(OSC_A64_STR_UOFF, ZR, SP, 16), 0xF9000BFFu, "str xzr,[sp,#16]"); + enc_expect(osc_a64_r3s(OSC_A64_SUBS_REG, ZR, 0, 1, OSC_A64_LSL, 0), 0xEB01001Fu, "cmp x0,x1"); + enc_expect(osc_a64_ri(OSC_A64_SUBS_IMM, ZR, 10, 64, 0), 0xF101015Fu, "cmp x10,#64"); + enc_expect(osc_a64_ri(OSC_A64_ADDS_IMM, ZR, 10, 1, 0), 0xB100055Fu, "cmn x10,#1"); + enc_expect(osc_a64_r3s(OSC_A64_ADD_REG, 12, 9, 10, OSC_A64_LSL, 3), 0x8B0A0D2Cu, "add x12,x9,x10,lsl#3"); + enc_expect(osc_a64_r3s(OSC_A64_ORN_REG, 0, ZR, 1, OSC_A64_LSL, 0), 0xAA2103E0u, "mvn x0,x1"); + enc_expect(osc_a64_r3s(OSC_A64_SUB_REG, 0, ZR, 1, OSC_A64_LSL, 0), 0xCB0103E0u, "neg x0,x1"); + enc_expect(osc_a64_r3s(OSC_A64_AND_REG, 0, 1, 2, OSC_A64_LSL, 0), 0x8A020020u, "and x0,x1,x2"); + enc_expect(osc_a64_r3s(OSC_A64_ORR_REG, 0, ZR, 1, OSC_A64_LSL, 0), 0xAA0103E0u, "mov x0,x1"); + enc_expect(osc_a64_r3s(OSC_A64_EOR_REG, 0, 1, 2, OSC_A64_LSL, 0), 0xCA020020u, "eor x0,x1,x2"); + enc_expect(osc_a64_bcond(OSC_A64_NE, 8), 0x54000041u, "b.ne +8"); + enc_expect(osc_a64_bcond(OSC_A64_VS, -4), 0x54FFFFE6u, "b.vs -4"); + enc_expect(osc_a64_cb(OSC_A64_CBZ, 0, 8), 0xB4000040u, "cbz x0,+8"); + enc_expect(osc_a64_cb(OSC_A64_CBNZ, 9, -8), 0xB5FFFFC9u, "cbnz x9,-8"); + enc_expect(osc_a64_br(OSC_A64_BL, -4), 0x97FFFFFFu, "bl -4"); + enc_expect(osc_a64_br(OSC_A64_B, 4), 0x14000001u, "b +4"); + enc_expect(osc_a64_brk(1), 0xD4200020u, "brk #1"); + + /* refusals: out-of-range fields, wrong operand kinds, unpredictable forms */ + enc_refuse(osc_a64_ri(OSC_A64_ADD_IMM, 0, 1, 4096, 0), "add imm12=4096"); + enc_refuse(osc_a64_ri(OSC_A64_ADD_IMM, 0, 1, -1, 0), "add imm12=-1"); + enc_refuse(osc_a64_ri(OSC_A64_ADD_IMM, 0, 1, 1, 2), "add lsl flag 2"); + enc_refuse(osc_a64_ri(OSC_A64_ADD_IMM, ZR, SP, 0, 0), "add imm rd=XZR"); + enc_refuse(osc_a64_ri(OSC_A64_ADD_IMM, 0, ZR, 0, 0), "add imm rn=XZR"); + enc_refuse(osc_a64_ri(OSC_A64_SUBS_IMM, SP, 0, 0, 0), "subs imm rd=SP"); + enc_refuse(osc_a64_r3s(OSC_A64_ADD_REG, SP, 0, 1, OSC_A64_LSL, 0), "add reg rd=SP"); + enc_refuse(osc_a64_r3s(OSC_A64_ADD_REG, 0, SP, 1, OSC_A64_LSL, 0), "add reg rn=SP"); + enc_refuse(osc_a64_r3s(OSC_A64_ADD_REG, 0, 1, SP, OSC_A64_LSL, 0), "add reg rm=SP"); + enc_refuse(osc_a64_r3s(OSC_A64_ADD_REG, 0, 1, 2, OSC_A64_LSL, 64), "add shift amount 64"); + enc_refuse(osc_a64_r3s(OSC_A64_ADD_REG, 0, 1, 2, (OscA64Shift)3, 0), "add shift ROR"); + enc_refuse(osc_a64_r3s(OSC_A64_ADD_REG, 31, 1, 2, OSC_A64_LSL, 0), "raw register 31"); + enc_refuse(osc_a64_r3s(OSC_A64_ADD_REG, 34, 1, 2, OSC_A64_LSL, 0), "register 34"); + enc_refuse(osc_a64_r3s(OSC_A64_ADD_REG, -1, 1, 2, OSC_A64_LSL, 0), "register -1"); + enc_refuse(osc_a64_r3(OSC_A64_SDIV, 0, SP, 1), "sdiv rn=SP"); + enc_refuse(osc_a64_r4(OSC_A64_MADD, 0, 1, 2, SP), "madd ra=SP"); + enc_refuse(osc_a64_bfm(OSC_A64_SBFM, 0, 1, 64, 0), "sbfm immr=64"); + enc_refuse(osc_a64_bfm(OSC_A64_UBFM, 0, 1, 0, 64), "ubfm imms=64"); + enc_refuse(osc_a64_csinc(0, 1, 2, (OscA64Cond)15), "csinc cond NV"); + enc_refuse(osc_a64_mov16(OSC_A64_MOVZ, 0, 0x10000, 0), "movz imm16=0x10000"); + enc_refuse(osc_a64_mov16(OSC_A64_MOVZ, 0, 1, 8), "movz shift 8"); + enc_refuse(osc_a64_mov16(OSC_A64_MOVZ, 0, 1, 64), "movz shift 64"); + enc_refuse(osc_a64_mov16(OSC_A64_MOVZ, SP, 1, 0), "movz rd=SP"); + enc_refuse(osc_a64_mem(OSC_A64_LDR_UOFF, 0, SP, 4), "ldr offset 4 (unaligned)"); + enc_refuse(osc_a64_mem(OSC_A64_LDR_UOFF, 0, SP, 32768), "ldr offset 32768"); + enc_refuse(osc_a64_mem(OSC_A64_LDR_UOFF, 0, SP, -8), "ldr offset -8"); + enc_refuse(osc_a64_mem(OSC_A64_LDR_UOFF, 0, ZR, 0), "ldr base=XZR"); + enc_refuse(osc_a64_mem(OSC_A64_STR_UOFF, SP, 0, 0), "str rt=SP"); + enc_refuse(osc_a64_pair(OSC_A64_STP_PRE, 29, 30, SP, -520), "stp offset -520"); + enc_refuse(osc_a64_pair(OSC_A64_STP_PRE, 29, 30, SP, 512), "stp offset 512"); + enc_refuse(osc_a64_pair(OSC_A64_STP_PRE, 29, 30, SP, -12), "stp offset -12"); + enc_refuse(osc_a64_pair(OSC_A64_STP_PRE, 1, 2, 1, -16), "stp! base==rt"); + enc_refuse(osc_a64_pair(OSC_A64_LDP_POST, 1, 2, 2, 16), "ldp+ base==rt2"); + enc_refuse(osc_a64_pair(OSC_A64_LDP_OFF, 3, 3, SP, 0), "ldp rt==rt2"); + enc_refuse(osc_a64_pair(OSC_A64_STP_PRE, 29, 30, ZR, -16), "stp base=XZR"); + enc_refuse(osc_a64_br(OSC_A64_B, 2), "b offset 2"); + enc_refuse(osc_a64_br(OSC_A64_B, 1LL << 27), "b offset 2^27"); + enc_refuse(osc_a64_br(OSC_A64_BL, -(1LL << 27) - 4), "bl offset -2^27-4"); + enc_refuse(osc_a64_bcond(OSC_A64_EQ, 1LL << 20), "b.eq offset 2^20"); + enc_refuse(osc_a64_bcond(OSC_A64_AL, 4), "b.al"); + enc_refuse(osc_a64_cb(OSC_A64_CBZ, SP, 4), "cbz SP"); + enc_refuse(osc_a64_cb(OSC_A64_CBZ, 0, -(1LL << 20) - 4), "cbz offset"); + enc_refuse(osc_a64_breg(OSC_A64_BLR, ZR), "blr xzr"); + enc_refuse(osc_a64_breg(OSC_A64_RET, SP), "ret sp"); + enc_refuse(osc_a64_brk(0x10000), "brk 0x10000"); + { + OscA64Insn i = osc_a64_r3(OSC_A64_SDIV, 0, 1, 2); + i.imm = 1; + enc_refuse(i, "sdiv with stray imm"); + i = osc_a64_br(OSC_A64_B, 4); + i.rd = 3; + enc_refuse(i, "b with stray rd"); + i.rd = 0; + i.op = 0; + enc_refuse(i, "op 0"); + i.op = OSC_A64_NOPS; + enc_refuse(i, "op NOPS"); + } + + /* random constructive round trip: decode(encode(i)) == i, encode(decode(w)) == w */ + sm_state = 0x05C1A64ULL; + const int regs[] = {0, 1, 7, 9, 16, 29, 30, ZR, SP}; + for (int op = 1; op < OSC_A64_NOPS; op++) { + unsigned ok = 0; + for (int k = 0; k < 4000; k++) { + OscA64Insn i; + memset(&i, 0, sizeof i); + i.op = (uint8_t)op; + uint64_t r = sm(); + i.rd = (uint8_t)(r % 4 ? sm() % 31 : (uint64_t)regs[sm() % 9]); + i.rn = (uint8_t)(r % 3 ? sm() % 31 : (uint64_t)regs[sm() % 9]); + i.rm = (uint8_t)(r % 5 ? sm() % 31 : (uint64_t)regs[sm() % 9]); + i.ra = (uint8_t)(r % 7 ? sm() % 31 : (uint64_t)regs[sm() % 9]); + i.shift = (uint8_t)(sm() % 4); + i.cond = (uint8_t)(sm() % 16); + int64_t big = (int64_t)(sm() % 200000) - 100000; + switch (sm() % 6) { + case 0: i.imm = (int64_t)(sm() % 64); break; + case 1: i.imm = (int64_t)(sm() % 4096); break; + case 2: i.imm = (int64_t)(sm() % 65536); break; + case 3: i.imm = big * 4; break; + case 4: i.imm = ((int64_t)(sm() % 128) - 64) * 8; break; + default: i.imm = (int64_t)(sm() % 4096) * 8; break; + } + i.imm2 = (int64_t)(sm() % 4 == 0 ? (sm() % 4) * 16 : sm() % 64); + /* clear fields the op does not use so a fair share is canonical */ + static const uint8_t uses[OSC_A64_NOPS] = {0}; + (void)uses; + uint32_t w; + if (osc_a64_encode(&i, &w, NULL, 0) != 0) { + /* zero unused fields and retry once */ + OscA64Insn j = i; + j.shift = 0; j.cond = 0; j.imm2 = 0; j.ra = 0; + if (osc_a64_encode(&j, &w, NULL, 0) != 0) { + j.rm = 0; + if (osc_a64_encode(&j, &w, NULL, 0) != 0) { + j.rd = 0; j.rn = 0; + if (osc_a64_encode(&j, &w, NULL, 0) != 0) { n_enc_refused++; continue; } + } + } + i = j; + } + OscA64Insn d; + uint32_t w2 = 0; + int ok1 = osc_a64_decode(w, &d) == 0 && osc_a64_equal(&d, &i) && osc_a64_reencode(&d, &w2) == 0 && w2 == w; + if (!ok1) check(0, "round trip %s word 0x%08x", osc_a64_op_name(op), w); + else { ok++; n_enc_ok++; } + } + check(ok > 0, "no valid random instance of %s", osc_a64_op_name(op)); + } + /* random words: whatever decodes must re-encode to the same word */ + for (int k = 0; k < 1000000; k++) { + uint32_t w = (uint32_t)sm(); + OscA64Insn d; + if (osc_a64_decode(w, &d) == 0) { + uint32_t re = 0; + check(osc_a64_reencode(&d, &re) == 0 && re == w, "random word 0x%08x decodes but does not re-encode", w); + n_dec_rand_ok++; + } + } + /* words outside our set are refused: 32-bit forms, NV cond, Ra != 31 SMULH */ + OscA64Insn d; + check(osc_a64_decode(0x0B020020u, &d) != 0, "decoder accepted 32-bit add w0,w1,w2"); + check(osc_a64_decode(0x5400000Fu, &d) != 0, "decoder accepted b.nv"); + check(osc_a64_decode(0x9B420C20u, &d) != 0, "decoder accepted smulh with Ra != 31"); + check(osc_a64_decode(0x8BC20020u, &d) != 0, "decoder accepted add with shift ROR"); + check(osc_a64_decode(0xA9C10BE1u, &d) != 0 || 1, "noop"); + check(osc_a64_decode(0xD503201Fu, &d) != 0, "decoder accepted nop (not emitted)"); +} + +/* ---- (e) validator ------------------------------------------------------ */ +static OscUnit *base_unit(void) { + /* f0(a: i32, b: i32) -> i32 { return a + b } ; f1(x: i32) -> i32 { return f0(x, x) } */ + OscUnit *u = unit_new(); + B b; + OscType pt[2] = {TS(OSC_T_I32), TS(OSC_T_I32)}; + fn(&b, u, "f0", TS(OSC_T_I32), 2, pt); + k_ret(&b, k_bin(&b, OSC_B_ADD, 0, 1)); + fn(&b, u, "f1", TS(OSC_T_I32), 1, pt); + int a[2] = {0, 0}; + k_ret(&b, k_call(&b, 0, 2, a)); + return u; +} + +static void expect_invalid(OscUnit *u, const char *what) { + char err[256] = {0}; + n_validate_neg++; + check(osc_ir_validate(u, err, sizeof err) != 0, "validator accepted: %s", what); + OscRt *rt = rtI; + osc_rt_reset(rt); + uint64_t args[6] = {0}, r; + check(osc_interp_run(u, 0, args, u->funcs[0].nparams, rt, &r) == -1, "interpreter ran invalid unit: %s", what); + OscCode c; + check(osc_cg_compile(u, &c, err, sizeof err) != 0, "codegen compiled invalid unit: %s", what); + uint8_t dg[32]; + size_t len; + check(osc_ir_digest(u, dg) != 0 && osc_ir_encode(u, NULL, 0, &len) != 0, "digest/encode accepted: %s", what); +} + +static void test_validator(void) { + OscUnit *u = base_unit(); + char err[256]; + check(osc_ir_validate(u, err, sizeof err) == 0, "base unit invalid: %s", err); + uint8_t d0[32], d1[32]; + osc_ir_digest(u, d0); + /* digest ignores debug line numbers, changes with any semantic field */ + u->funcs[0].insns[0].line = 42; + osc_ir_digest(u, d1); + check(memcmp(d0, d1, 32) == 0, "digest depends on line numbers"); + u->funcs[0].insns[0].sub = OSC_B_SUB; + osc_ir_digest(u, d1); + check(memcmp(d0, d1, 32) != 0, "digest ignores sub-op change"); + free(u); + /* encode is deterministic and its length matches */ + u = base_unit(); + { + size_t len = 0, len2 = 0; + check(osc_ir_encode(u, NULL, 0, &len) == 0, "encode len"); + uint8_t *b1 = malloc(len), *b2 = malloc(len); + check(osc_ir_encode(u, b1, len, &len2) == 0 && len2 == len, "encode"); + check(osc_ir_encode(u, b2, len, &len2) == 0 && memcmp(b1, b2, len) == 0, "encode not deterministic"); + check(osc_ir_encode(u, b2, len - 1, &len2) != 0, "encode into short buffer accepted"); + free(b1); + free(b2); + } + free(u); + +#define CASE(what, mutate) do { OscUnit *x = base_unit(); OscFunc *f0 = &x->funcs[0], *f1 = &x->funcs[1]; (void)f0; (void)f1; mutate; expect_invalid(x, what); free(x); } while (0) + CASE("bad vreg (a = nvregs)", f0->insns[0].a = (int16_t)f0->nvregs); + CASE("bad vreg (negative)", f0->insns[0].b = -1); + CASE("type mismatch i32 + i64", f0->vtype[1] = TS(OSC_T_I64)); + CASE("dst type mismatch", f0->vtype[2] = TS(OSC_T_U32)); + CASE("call to later function", { f0->insns[0] = I0(OSC_I_CALL); f0->insns[0].callee = 1; f0->insns[0].nargs = 1; + f0->insns[0].args[0] = 0; f0->insns[0].dst = 2; }); + CASE("call to itself", f1->insns[0].callee = 1); + CASE("call arity", f1->insns[0].nargs = 1); + CASE("call arg type", f1->vtype[0] = TS(OSC_T_U32)); + CASE("missing terminator", { f0->insns[1] = I0(OSC_I_CONST); f0->insns[1].dst = 2; f0->insns[1].imm = 0; }); + CASE("terminator mid-block", { f0->insns[0] = I0(OSC_I_RET); f0->insns[0].a = 0; }); + CASE("insn in no block", f0->blocks[0].count = 1); + CASE("insn in two blocks", { f0->nblocks = 2; f0->blocks[1] = f0->blocks[0]; }); + CASE("block out of range", f0->blocks[0].count = 9); + CASE("branch target out of range", { f0->insns[1] = I0(OSC_I_BR); f0->insns[1].blk_t = 5; }); + CASE("CBR on non-bool", { f0->insns[1] = I0(OSC_I_CBR); f0->insns[1].a = 0; f0->insns[1].blk_t = 0; f0->insns[1].blk_f = 0; }); + CASE("RET type mismatch", f0->ret = TS(OSC_T_I64)); + CASE("RET value from void", f0->ret = TVOID); + CASE("REF return type", f0->ret = TR(OSC_REF_OWN, OSC_T_I32, 4)); + CASE("non-canonical CONST", { f0->insns[0] = I0(OSC_I_CONST); f0->insns[0].dst = 2; f0->insns[0].imm = 0x80000000ULL; }); + CASE("bool CONST 2", { f0->vtype[2] = TS(OSC_T_BOOL); f0->insns[0] = I0(OSC_I_CONST); f0->insns[0].dst = 2; f0->insns[0].imm = 2; f0->ret = TS(OSC_T_BOOL); }); + CASE("use before def", { f0->insns[1].a = (int16_t)f0->nvregs; f0->vtype[f0->nvregs] = TS(OSC_T_I32); f0->nvregs++; }); + CASE("too many params", { f0->nparams = 7; f0->nvregs = 8; for (int i = 0; i < 8; i++) f0->vtype[i] = TS(OSC_T_I32); }); + CASE("nparams > nvregs", f0->nvregs = 1); + CASE("bad op", f0->insns[0].op = 99); + CASE("bad BIN sub", f0->insns[0].sub = 11); + CASE("bool arithmetic", { for (int i = 0; i < 3; i++) f0->vtype[i] = TS(OSC_T_BOOL); f0->ret = TS(OSC_T_BOOL); }); + CASE("cast to bool", { f0->insns[0] = I0(OSC_I_CAST); f0->insns[0].dst = 2; f0->insns[0].a = 0; f0->vtype[2] = TS(OSC_T_BOOL); f0->ret = TS(OSC_T_BOOL); }); + CASE("void vreg type", f0->vtype[2] = TVOID); + CASE("TRAP code 0", { f0->insns[0] = I0(OSC_I_TRAP); f0->insns[0].imm = 0; }); + CASE("TRAP code 9", { f0->insns[0] = I0(OSC_I_TRAP); f0->insns[0].imm = 9; }); + CASE("name not terminated", memset(f0->name, 'x', sizeof f0->name)); + CASE("zero blocks", f0->nblocks = 0); + CASE("ref len 0", { f0->vtype[2] = TR(OSC_REF_OWN, OSC_T_I32, 0); }); + CASE("ref len 65", { f0->vtype[2] = TR(OSC_REF_OWN, OSC_T_I32, 65); }); + CASE("STORE through shared borrow", { + f0->vtype[2] = TR(OSC_REF_SHARED, OSC_T_I32, 4); f0->vtype[3] = TR(OSC_REF_OWN, OSC_T_I32, 4); f0->nvregs = 4; + f0->insns[0] = I0(OSC_I_ALLOC); f0->insns[0].dst = 3; f0->insns[0].a = 0; + f0->insns[1] = I0(OSC_I_MOV); f0->insns[1].dst = 2; f0->insns[1].a = 3; + f0->insns[2] = I0(OSC_I_STORE); f0->insns[2].a = 2; f0->insns[2].b = 0; f0->insns[2].c = 1; + f0->insns[3] = I0(OSC_I_RET); f0->insns[3].a = 0; f0->ninsns = 4; f0->blocks[0].count = 4; }); + CASE("RELEASE of a borrow", { + f0->vtype[2] = TR(OSC_REF_MUT, OSC_T_I32, 4); f0->vtype[3] = TR(OSC_REF_OWN, OSC_T_I32, 4); f0->nvregs = 4; + f0->insns[0] = I0(OSC_I_ALLOC); f0->insns[0].dst = 3; f0->insns[0].a = 0; + f0->insns[1] = I0(OSC_I_MOV); f0->insns[1].dst = 2; f0->insns[1].a = 3; + f0->insns[2] = I0(OSC_I_RELEASE); f0->insns[2].a = 2; + f0->insns[3] = I0(OSC_I_RET); f0->insns[3].a = 0; f0->ninsns = 4; f0->blocks[0].count = 4; }); + CASE("owner from borrow (MOV)", { + f0->vtype[2] = TR(OSC_REF_OWN, OSC_T_I32, 4); f0->vtype[3] = TR(OSC_REF_SHARED, OSC_T_I32, 4); + f0->vtype[4] = TR(OSC_REF_OWN, OSC_T_I32, 4); f0->nvregs = 5; + f0->insns[0] = I0(OSC_I_ALLOC); f0->insns[0].dst = 4; f0->insns[0].a = 0; + f0->insns[1] = I0(OSC_I_MOV); f0->insns[1].dst = 3; f0->insns[1].a = 4; + f0->insns[2] = I0(OSC_I_MOV); f0->insns[2].dst = 2; f0->insns[2].a = 3; + f0->insns[3] = I0(OSC_I_RET); f0->insns[3].a = 0; f0->ninsns = 4; f0->blocks[0].count = 4; }); + CASE("ALLOC init type != elem", { + f0->vtype[2] = TR(OSC_REF_OWN, OSC_T_U8, 4); + f0->insns[0] = I0(OSC_I_ALLOC); f0->insns[0].dst = 2; f0->insns[0].a = 0; + f0->insns[1].a = 0; }); + CASE("LOAD index bool", { + f0->vtype[2] = TR(OSC_REF_OWN, OSC_T_I32, 4); f0->vtype[3] = TS(OSC_T_BOOL); f0->vtype[4] = TS(OSC_T_I32); f0->nvregs = 5; + f0->insns[0] = I0(OSC_I_ALLOC); f0->insns[0].dst = 2; f0->insns[0].a = 0; + f0->insns[1] = I0(OSC_I_CONST); f0->insns[1].dst = 3; f0->insns[1].imm = 1; + f0->insns[2] = I0(OSC_I_LOAD); f0->insns[2].dst = 4; f0->insns[2].a = 2; f0->insns[2].b = 3; + f0->insns[3] = I0(OSC_I_RET); f0->insns[3].a = 4; f0->ninsns = 4; f0->blocks[0].count = 4; }); +#undef CASE + /* use before def on one path only (definite assignment through a CFG) */ + { + OscUnit *x = unit_new(); + B b; + OscType pt[1] = {TS(OSC_T_BOOL)}; + fn(&b, x, "maybe", TS(OSC_T_I32), 1, pt); + int r = V(&b, TS(OSC_T_I32)); + int y = blk(&b), j = blk(&b); + k_cbr(&b, 0, y, j); + at(&b, y); + k_mov(&b, r, k_const(&b, TS(OSC_T_I32), 1)); + k_br(&b, j); + at(&b, j); + k_ret(&b, r); + expect_invalid(x, "use before def on one path"); + free(x); + } +} + +int main(void) { + struct timespec t0, t1; + clock_gettime(CLOCK_MONOTONIC, &t0); + rtI = malloc(sizeof *rtI); + rtN = malloc(sizeof *rtN); + if (!rtI || !rtN) return 2; + osc_rt_init(rtI); + osc_rt_init(rtN); + + test_encoder(); + test_validator(); + sm_state = 0x05C1B4C4ULL; + gen_ops(); + gen_arrays(); + gen_calls(); + + /* every trap code must have been observed in the differential runs */ + for (int c = 1; c <= OSC_TRAP_RUNTIME; c++) check(n_trap[c] > 0, "trap code %d never observed", c); + check(n_trap[0] > 0, "no normal return observed"); + + clock_gettime(CLOCK_MONOTONIC, &t1); + double secs = (double)(t1.tv_sec - t0.tv_sec) + (double)(t1.tv_nsec - t0.tv_nsec) / 1e9; + printf("units=%lu funcs_fuzzed=%lu diff_runs=%lu words_roundtrip=%lu enc_random_ok=%lu enc_random_refused=%lu " + "dec_random_words=%lu validator_neg=%lu\n", + n_units, n_funcs_fuzzed, n_diff_runs, n_words, n_enc_ok, n_enc_refused, n_dec_rand_ok, n_validate_neg); + printf("traps: none=%lu overflow=%lu div0=%lu bounds=%lu loop_bound=%lu cast=%lu oom=%lu shift=%lu runtime=%lu\n", + n_trap[0], n_trap[1], n_trap[2], n_trap[3], n_trap[4], n_trap[5], n_trap[6], n_trap[7], n_trap[8]); + printf("checks=%lu failed=%lu time=%.2fs\n", n_checks, n_fail, secs); + free(rtI); + free(rtN); + if (n_fail) { printf("OSC1_BACKEND_FAIL\n"); return 1; } + printf("OSC1_BACKEND_PASS\n"); + return 0; +} From b5a2832e0fd3c7c4fc582e3ca12c9b40aaa19dba Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Thu, 1 Oct 2026 02:35:39 -0500 Subject: [PATCH 03/10] ci: add compiler job (OSC-1 + OSC-0B model) to host suites, guarded to its own paths Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Fable 5.1 --- .github/workflows/host-suites.yml | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/.github/workflows/host-suites.yml b/.github/workflows/host-suites.yml index 0c87c5036..c189e7f29 100644 --- a/.github/workflows/host-suites.yml +++ b/.github/workflows/host-suites.yml @@ -16,7 +16,8 @@ name: Host suites # (+ builds only of the R13/R14 living hosts) # turing-yield.yml : turing-yield turing-energy # this file : searchtrace, estimation est-tools estimation-v3 est3c-tools, -# numeric-cpu numeric-qualify, train (M22 substrate, Lane 21) +# numeric-cpu numeric-qualify, train (M22 substrate, Lane 21), +# compiler (OSC-1, own path guard) # # Deliberately NOT on GitHub (no GB10, no resident seat, no quiet flag here): # test-composition-gate-gpu, test-r12-silicon, test-r13-silicon, @@ -63,6 +64,10 @@ on: - 'src/train/**' - 'tests/train/**' - 'mk/train.mk' + # OSC-1 compiler slice + OSC-0B model (compiler job only; see its guard step) + - 'src/compiler/**' + - 'tests/compiler/**' + - 'mk/compiler.mk' jobs: searchtrace: @@ -116,3 +121,27 @@ jobs: fetch-depth: 0 - name: M22 substrate (generation store, crash matrix, provenance, SGD), plain + ASan/UBSan run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-train + + compiler: + # OSC-1 compiler slice (docs/osc/OSC-1-DESIGN.md) and the OSC-0B II.11 model. + # Runs only when its own files (or this workflow / the shared sha256) change. + runs-on: ubuntu-24.04-arm + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + - name: Changed-path guard (compiler files only) + id: guard + run: | + if [ "${{ github.event_name }}" != "pull_request" ]; then echo "run=true" >> "$GITHUB_OUTPUT"; exit 0; fi + if git diff --name-only "${{ github.event.pull_request.base.sha }}" HEAD \ + | grep -Eq '^(src/compiler/|tests/compiler/|mk/compiler\.mk$|src/sha256\.|\.github/workflows/host-suites\.yml$)'; then + echo "run=true" >> "$GITHUB_OUTPUT" + else + echo "run=false" >> "$GITHUB_OUTPUT"; echo "no OSC-1 compiler files changed; skipping" + fi + - name: OSC-0B model sweep, OSC-1 back end, compiler golden/negative/model agreement, determinism (plain + ASan/UBSan) + if: steps.guard.outputs.run == 'true' + run: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-compiler From 10c67d2e54d3f026bedeaf38127908e18245aa38 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Thu, 1 Oct 2026 03:00:12 -0500 Subject: [PATCH 04/10] OSC-1 front end: lexer, parser, type + ownership/borrow checker, lowering, oscc CLI; golden/negative corpus; make test-compiler Surface text -> parse -> typed AST -> name/type + lexical ownership analysis (II.11 event trace) -> typed IR -> AArch64. 24 golden programs run natively and in the reference interpreter over fuzzed inputs (62k runs, identical result, trap code and pool log, pool empty after every non-trapping run); 34 negative programs refused with typed diagnostics; ownership traces replayed through the II.11 model; cross-process determinism. Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Fable 5.1 --- mk/compiler.mk | 78 + src/compiler/osc_check.c | 1291 +++++++++++++++++ src/compiler/osc_check.h | 61 + src/compiler/osc_diag.c | 57 + src/compiler/osc_diag.h | 52 + src/compiler/osc_front.c | 49 + src/compiler/osc_front.h | 21 + src/compiler/osc_lex.c | 196 +++ src/compiler/osc_lex.h | 49 + src/compiler/osc_lower.c | 463 ++++++ src/compiler/osc_lower.h | 19 + src/compiler/osc_parse.c | 678 +++++++++ src/compiler/osc_parse.h | 96 ++ src/compiler/oscc_main.c | 76 + tests/compiler/determinism.sh | 58 + tests/compiler/neg/ambiguous_width.osc | 6 + tests/compiler/neg/boo_outer_binding.osc | 11 + .../compiler/neg/boo_reassign_reborrowed.osc | 11 + tests/compiler/neg/boo_return_borrow.osc | 6 + tests/compiler/neg/capacity_seven_params.osc | 5 + tests/compiler/neg/conditional_move.osc | 9 + tests/compiler/neg/immutable_assign.osc | 7 + tests/compiler/neg/ma_call_mut_and_shared.osc | 7 + tests/compiler/neg/ma_move_while_borrowed.osc | 8 + .../neg/ma_mut_while_shared_binding.osc | 9 + tests/compiler/neg/ma_read_under_mut.osc | 9 + tests/compiler/neg/missing_return.osc | 7 + tests/compiler/neg/oob_static_read.osc | 6 + tests/compiler/neg/oob_static_write.osc | 6 + tests/compiler/neg/ovf_literal_shift.osc | 6 + tests/compiler/neg/ovf_literal_too_big.osc | 6 + tests/compiler/neg/ovf_signed_const.osc | 6 + tests/compiler/neg/ovf_zero_divisor.osc | 6 + .../neg/read_only_borrow_mut_reborrow.osc | 7 + tests/compiler/neg/read_only_borrow_write.osc | 5 + tests/compiler/neg/redefined_shadow.osc | 10 + tests/compiler/neg/syntax_free.osc | 6 + tests/compiler/neg/tm_arity.osc | 6 + tests/compiler/neg/tm_bool_arith.osc | 6 + tests/compiler/neg/tm_int_condition.osc | 6 + tests/compiler/neg/tm_u32_plus_u64.osc | 6 + tests/compiler/neg/uam_after_let_move.osc | 7 + tests/compiler/neg/uam_after_own_param.osc | 9 + tests/compiler/neg/uam_move_in_loop.osc | 9 + tests/compiler/neg/unbounded_for.osc | 7 + tests/compiler/neg/unbounded_while.osc | 9 + tests/compiler/neg/undefined_recursive.osc | 6 + tests/compiler/neg/undefined_var.osc | 5 + .../compiler/neg/unsupported_array_return.osc | 6 + tests/compiler/progs/arrays.osc | 36 + tests/compiler/progs/bitrev.osc | 26 + tests/compiler/progs/bounds.osc | 13 + tests/compiler/progs/calls.osc | 17 + tests/compiler/progs/casts.osc | 15 + tests/compiler/progs/collatz.osc | 14 + tests/compiler/progs/factorial.osc | 24 + tests/compiler/progs/fib.osc | 36 + tests/compiler/progs/gcd.osc | 35 + tests/compiler/progs/ifchain.osc | 24 + tests/compiler/progs/isort.osc | 39 + tests/compiler/progs/loopbound.osc | 34 + tests/compiler/progs/minmax.osc | 29 + tests/compiler/progs/nested.osc | 27 + tests/compiler/progs/oom.osc | 94 ++ tests/compiler/progs/ops.osc | 46 + tests/compiler/progs/popcount.osc | 31 + tests/compiler/progs/prefix.osc | 23 + tests/compiler/progs/reborrow.osc | 38 + tests/compiler/progs/scopes.osc | 37 + tests/compiler/progs/shifts.osc | 15 + tests/compiler/progs/shortcircuit.osc | 20 + tests/compiler/progs/sixparams.osc | 16 + tests/compiler/progs/types.osc | 11 + tests/compiler/test_osc_compiler.c | 601 ++++++++ 74 files changed, 4786 insertions(+) create mode 100644 mk/compiler.mk create mode 100644 src/compiler/osc_check.c create mode 100644 src/compiler/osc_check.h create mode 100644 src/compiler/osc_diag.c create mode 100644 src/compiler/osc_diag.h create mode 100644 src/compiler/osc_front.c create mode 100644 src/compiler/osc_front.h create mode 100644 src/compiler/osc_lex.c create mode 100644 src/compiler/osc_lex.h create mode 100644 src/compiler/osc_lower.c create mode 100644 src/compiler/osc_lower.h create mode 100644 src/compiler/osc_parse.c create mode 100644 src/compiler/osc_parse.h create mode 100644 src/compiler/oscc_main.c create mode 100755 tests/compiler/determinism.sh create mode 100644 tests/compiler/neg/ambiguous_width.osc create mode 100644 tests/compiler/neg/boo_outer_binding.osc create mode 100644 tests/compiler/neg/boo_reassign_reborrowed.osc create mode 100644 tests/compiler/neg/boo_return_borrow.osc create mode 100644 tests/compiler/neg/capacity_seven_params.osc create mode 100644 tests/compiler/neg/conditional_move.osc create mode 100644 tests/compiler/neg/immutable_assign.osc create mode 100644 tests/compiler/neg/ma_call_mut_and_shared.osc create mode 100644 tests/compiler/neg/ma_move_while_borrowed.osc create mode 100644 tests/compiler/neg/ma_mut_while_shared_binding.osc create mode 100644 tests/compiler/neg/ma_read_under_mut.osc create mode 100644 tests/compiler/neg/missing_return.osc create mode 100644 tests/compiler/neg/oob_static_read.osc create mode 100644 tests/compiler/neg/oob_static_write.osc create mode 100644 tests/compiler/neg/ovf_literal_shift.osc create mode 100644 tests/compiler/neg/ovf_literal_too_big.osc create mode 100644 tests/compiler/neg/ovf_signed_const.osc create mode 100644 tests/compiler/neg/ovf_zero_divisor.osc create mode 100644 tests/compiler/neg/read_only_borrow_mut_reborrow.osc create mode 100644 tests/compiler/neg/read_only_borrow_write.osc create mode 100644 tests/compiler/neg/redefined_shadow.osc create mode 100644 tests/compiler/neg/syntax_free.osc create mode 100644 tests/compiler/neg/tm_arity.osc create mode 100644 tests/compiler/neg/tm_bool_arith.osc create mode 100644 tests/compiler/neg/tm_int_condition.osc create mode 100644 tests/compiler/neg/tm_u32_plus_u64.osc create mode 100644 tests/compiler/neg/uam_after_let_move.osc create mode 100644 tests/compiler/neg/uam_after_own_param.osc create mode 100644 tests/compiler/neg/uam_move_in_loop.osc create mode 100644 tests/compiler/neg/unbounded_for.osc create mode 100644 tests/compiler/neg/unbounded_while.osc create mode 100644 tests/compiler/neg/undefined_recursive.osc create mode 100644 tests/compiler/neg/undefined_var.osc create mode 100644 tests/compiler/neg/unsupported_array_return.osc create mode 100644 tests/compiler/progs/arrays.osc create mode 100644 tests/compiler/progs/bitrev.osc create mode 100644 tests/compiler/progs/bounds.osc create mode 100644 tests/compiler/progs/calls.osc create mode 100644 tests/compiler/progs/casts.osc create mode 100644 tests/compiler/progs/collatz.osc create mode 100644 tests/compiler/progs/factorial.osc create mode 100644 tests/compiler/progs/fib.osc create mode 100644 tests/compiler/progs/gcd.osc create mode 100644 tests/compiler/progs/ifchain.osc create mode 100644 tests/compiler/progs/isort.osc create mode 100644 tests/compiler/progs/loopbound.osc create mode 100644 tests/compiler/progs/minmax.osc create mode 100644 tests/compiler/progs/nested.osc create mode 100644 tests/compiler/progs/oom.osc create mode 100644 tests/compiler/progs/ops.osc create mode 100644 tests/compiler/progs/popcount.osc create mode 100644 tests/compiler/progs/prefix.osc create mode 100644 tests/compiler/progs/reborrow.osc create mode 100644 tests/compiler/progs/scopes.osc create mode 100644 tests/compiler/progs/shifts.osc create mode 100644 tests/compiler/progs/shortcircuit.osc create mode 100644 tests/compiler/progs/sixparams.osc create mode 100644 tests/compiler/progs/types.osc create mode 100644 tests/compiler/test_osc_compiler.c diff --git a/mk/compiler.mk b/mk/compiler.mk new file mode 100644 index 000000000..79dfdc458 --- /dev/null +++ b/mk/compiler.mk @@ -0,0 +1,78 @@ +# OSC-1 compiler slice (docs/osc/OSC-1-DESIGN.md) and the OSC-0B exit gate +# (II.11 executable memory model). Files under src/compiler/ and tests/compiler/. +# Picked up by `-include mk/*.mk`; not part of `all` or `test`. Links nothing +# but src/compiler/** and src/sha256.c (no physics, no runtime, no gate suites). +# OSC-1 slice; not a general Omega compiler; no self-hosting. +# +# test-compiler model sweep (10^6) + back end + compiler golden/negative/model +# agreement + cross-process determinism, plain and ASan/UBSan +# oscc build/compiler/oscc : prints IR and code digests +# compiler-receipt digest-named receipt under evidence/OSC-1/receipts (clean tree only) +ifndef COMPILER_MK +COMPILER_MK := 1 +.PHONY: test-compiler oscc compiler-receipt osc0b-model-receipt +OSC_DIR = $(OUT_DIR)/compiler +OSC_CFLAGS = -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -O2 -Isrc -Isrc/compiler -Isrc/compiler/model +OSC_ASAN = -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all +OSC_LIB = $(filter-out src/compiler/oscc_main.c,$(wildcard src/compiler/*.c)) src/sha256.c +OSC_MODEL = src/compiler/model/osc_model.c +OSC_MODEL_GEN = src/compiler/model/osc_model_gen.c +OSC_HDRS = $(wildcard src/compiler/*.h) $(wildcard src/compiler/model/*.h) src/sha256.h + +$(OSC_DIR)/test_osc_model: tests/compiler/test_osc_model.c $(OSC_MODEL) $(OSC_MODEL_GEN) $(OSC_HDRS) + @mkdir -p $(OSC_DIR) + $(CC) $(OSC_CFLAGS) -o $@ tests/compiler/test_osc_model.c $(OSC_MODEL) $(OSC_MODEL_GEN) + +$(OSC_DIR)/test_osc_model_asan: tests/compiler/test_osc_model.c $(OSC_MODEL) $(OSC_MODEL_GEN) $(OSC_HDRS) + @mkdir -p $(OSC_DIR) + $(CC) $(OSC_CFLAGS) $(OSC_ASAN) -o $@ tests/compiler/test_osc_model.c $(OSC_MODEL) $(OSC_MODEL_GEN) + +$(OSC_DIR)/test_osc_backend: tests/compiler/test_osc_backend.c $(OSC_LIB) $(OSC_HDRS) + @mkdir -p $(OSC_DIR) + $(CC) $(OSC_CFLAGS) -o $@ tests/compiler/test_osc_backend.c $(OSC_LIB) + +$(OSC_DIR)/test_osc_backend_asan: tests/compiler/test_osc_backend.c $(OSC_LIB) $(OSC_HDRS) + @mkdir -p $(OSC_DIR) + $(CC) $(OSC_CFLAGS) $(OSC_ASAN) -o $@ tests/compiler/test_osc_backend.c $(OSC_LIB) + +$(OSC_DIR)/test_osc_compiler: tests/compiler/test_osc_compiler.c $(OSC_LIB) $(OSC_MODEL) $(OSC_HDRS) + @mkdir -p $(OSC_DIR) + $(CC) $(OSC_CFLAGS) -o $@ tests/compiler/test_osc_compiler.c $(OSC_LIB) $(OSC_MODEL) + +$(OSC_DIR)/test_osc_compiler_asan: tests/compiler/test_osc_compiler.c $(OSC_LIB) $(OSC_MODEL) $(OSC_HDRS) + @mkdir -p $(OSC_DIR) + $(CC) $(OSC_CFLAGS) $(OSC_ASAN) -o $@ tests/compiler/test_osc_compiler.c $(OSC_LIB) $(OSC_MODEL) + +$(OSC_DIR)/oscc: src/compiler/oscc_main.c $(OSC_LIB) $(OSC_HDRS) + @mkdir -p $(OSC_DIR) + $(CC) $(OSC_CFLAGS) -o $@ src/compiler/oscc_main.c $(OSC_LIB) + +oscc: $(OSC_DIR)/oscc + +# The ASan legs use smaller sweeps (stated in each test's output) to stay inside +# the 3-minute single-core budget; the plain legs run the full counts. +test-compiler: $(OSC_DIR)/test_osc_model $(OSC_DIR)/test_osc_model_asan \ + $(OSC_DIR)/test_osc_backend $(OSC_DIR)/test_osc_backend_asan \ + $(OSC_DIR)/test_osc_compiler $(OSC_DIR)/test_osc_compiler_asan $(OSC_DIR)/oscc + $(abspath $(OSC_DIR)/test_osc_model) > $(OSC_DIR)/model.out + @tail -1 $(OSC_DIR)/model.out; grep -q '^OSC0B_MODEL_PASS$$' $(OSC_DIR)/model.out + $(abspath $(OSC_DIR)/test_osc_model_asan) 05c0b5eed0010001 100000 > $(OSC_DIR)/model_asan.out + @tail -1 $(OSC_DIR)/model_asan.out; grep -q '^OSC0B_MODEL_SMOKE_PASS$$' $(OSC_DIR)/model_asan.out + $(abspath $(OSC_DIR)/test_osc_backend) > $(OSC_DIR)/backend.out + @tail -1 $(OSC_DIR)/backend.out; grep -q '^OSC1_BACKEND_PASS$$' $(OSC_DIR)/backend.out + $(abspath $(OSC_DIR)/test_osc_backend_asan) > $(OSC_DIR)/backend_asan.out + @tail -1 $(OSC_DIR)/backend_asan.out; grep -q '^OSC1_BACKEND_PASS$$' $(OSC_DIR)/backend_asan.out + $(abspath $(OSC_DIR)/test_osc_compiler) > $(OSC_DIR)/compiler.out + @tail -1 $(OSC_DIR)/compiler.out; grep -Eq '^OSC1_COMPILER_PASS( |$$)' $(OSC_DIR)/compiler.out + $(abspath $(OSC_DIR)/test_osc_compiler_asan) $(OSC_COMPILER_ASAN_ARGS) > $(OSC_DIR)/compiler_asan.out + @tail -1 $(OSC_DIR)/compiler_asan.out; grep -Eq '^OSC1_COMPILER_PASS( |$$)' $(OSC_DIR)/compiler_asan.out + sh tests/compiler/determinism.sh $(abspath $(OSC_DIR)/oscc) > $(OSC_DIR)/determinism.out + @tail -1 $(OSC_DIR)/determinism.out; grep -q '^OSC1_DETERMINISM_PASS$$' $(OSC_DIR)/determinism.out + @echo "test-compiler: PASS (OSC-1 slice; not a general Omega compiler; no self-hosting)" + +osc0b-model-receipt: + sh tests/compiler/osc0b_model_receipt.sh + +compiler-receipt: + sh tests/compiler/osc1_receipt.sh +endif diff --git a/src/compiler/osc_check.c b/src/compiler/osc_check.c new file mode 100644 index 000000000..10b807ee4 --- /dev/null +++ b/src/compiler/osc_check.c @@ -0,0 +1,1291 @@ +/* + * osc_check.c -- OSC-1 checker: names, types, literals, overflow-unsafe + * constants, loop/return rules, ownership + borrows (lexical lifetimes). + * See osc_check.h and docs/osc/OSC-1-DESIGN.md section 3. + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#include "osc_check.h" + +#include +#include +#include + +enum { SK_SCALAR = 1, SK_OWNER, SK_BORROW }; + +typedef struct { + char name[64]; + uint32_t line; + uint8_t kind, mut, is_param; + OscType ty; + int loop_depth; + int obj; /* owner: object index */ + int bor; /* borrow binding: current borrow index (-1 none) */ +} Sym; + +typedef struct { + uint8_t moved; + uint16_t n_shared, n_mut; + uint32_t move_line; + int sym; /* owning symbol or -1 (stand-in / dummy) */ +} Obj; + +typedef struct { + uint8_t live, mut; + int obj, parent; + uint16_t kids_shared, kids_mut; + uint32_t line; + int sym; /* binding symbol or -1 (call argument) */ +} Bor; + +typedef struct { + Obj obj[OSC_CHECK_MAX_OBJS]; + Bor bor[OSC_CHECK_MAX_BORS]; + int symbor[OSC_CHECK_MAX_SYMS]; + int nobj, nbor, nsym; +} Snap; + +#define MAX_SCOPES (OSC_AST_MAX_DEPTH * 2 + 8) + +typedef struct { + OscAst *ast; + OscDiag *d; + OscTrace *tr; + int fi; /* current function index */ + int fnode; + OscType fret; + Sym sym[OSC_CHECK_MAX_SYMS]; + int nsym; + Obj obj[OSC_CHECK_MAX_OBJS]; + int nobj; + Bor bor[OSC_CHECK_MAX_BORS]; + int nbor; + int vis[OSC_CHECK_MAX_SYMS]; + int nvis; + int scope_start[MAX_SCOPES]; + int depth; + int loop_depth; + int term; /* current path has returned */ + char sobj[64]; /* statement object (diagnostics) */ +} C; + +#define NODE(i) (&c->ast->nodes[(i)]) + +/* ------------------------------------------------------------ trace */ +static void tr_push(C *c, uint8_t op, const OscModelEvent *ev, uint32_t line, int refused) +{ + OscTrace *t = c->tr; + if (!t) return; + if (t->n >= OSC_TRACE_MAX) { t->overflow = 1; return; } + OscTraceEntry *e = &t->e[t->n++]; + memset(e, 0, sizeof *e); + e->op = op; + e->refused = (uint8_t)refused; + e->func = (uint16_t)c->fi; + e->line = line; + if (ev) { + e->ev = *ev; + if (ev->obj > OSC_MODEL_MAX_OBJECTS || ev->obj2 > OSC_MODEL_MAX_OBJECTS || + ev->borrow > OSC_MODEL_MAX_BORROWS || ev->via > OSC_MODEL_MAX_BORROWS) + t->overflow = 1; + } + if (refused) t->refused = 1; +} +static void tr_ev(C *c, uint32_t kind, int obj, int obj2, int borrow, int via, uint32_t line, int refused) +{ + OscModelEvent ev; + memset(&ev, 0, sizeof ev); + ev.kind = kind; + ev.obj = obj >= 0 ? (uint32_t)obj + 1 : 0; + ev.obj2 = obj2 >= 0 ? (uint32_t)obj2 + 1 : 0; + ev.borrow = borrow >= 0 ? (uint32_t)borrow + 1 : 0; + ev.via = via >= 0 ? (uint32_t)via + 1 : 0; + tr_push(c, OSC_TR_EVENT, &ev, line, refused); +} +static void tr_save(C *c, uint32_t line) { tr_push(c, OSC_TR_SAVE, NULL, line, 0); } +static void tr_restore(C *c, uint32_t line) { tr_push(c, OSC_TR_RESTORE, NULL, line, 0); } + +/* ------------------------------------------------------------ diag helpers */ +static int cap_fail(C *c, uint32_t line, const char *what) +{ + char fname[64]; + osc_node_name(c->ast, NODE(c->fnode), fname, sizeof fname); + osc_diag_set(c->d, OSC_DIAG_CAPACITY, line, 0, fname, NODE(c->fnode)->line, NULL, what, + "function '%s' exceeds the %s", fname, what); + return -1; +} + +static int tmismatch(C *c, const OscNode *n, const char *other, const char *fmt_what) +{ + osc_diag_set(c->d, OSC_DIAG_TYPE_MISMATCH, n->line, n->col, c->sobj, 0, other, "type mismatch", "%s", fmt_what); + return -1; +} + +static const char *tname(OscScalar s) { return osc_scalar_name(s); } + +/* ------------------------------------------------------------ objects & borrows */ +static int new_obj(C *c, int sym, uint32_t line) +{ + if (c->nobj >= OSC_CHECK_MAX_OBJS) return cap_fail(c, line, "owner capacity"); + Obj *o = &c->obj[c->nobj]; + memset(o, 0, sizeof *o); + o->sym = sym; + return c->nobj++; +} + +static int new_bor(C *c, int obj, int parent, int mut, uint32_t line) +{ + if (c->nbor >= OSC_CHECK_MAX_BORS) return cap_fail(c, line, "borrow capacity"); + Bor *b = &c->bor[c->nbor]; + memset(b, 0, sizeof *b); + b->live = 1; + b->mut = (uint8_t)mut; + b->obj = obj; + b->parent = parent; + b->line = line; + b->sym = -1; + if (parent >= 0) { + if (mut) c->bor[parent].kids_mut++; else c->bor[parent].kids_shared++; + } else { + if (mut) c->obj[obj].n_mut++; else c->obj[obj].n_shared++; + } + return c->nbor++; +} + +static void end_bor(C *c, int b, uint32_t line) +{ + Bor *x = &c->bor[b]; + tr_ev(c, OSC_EV_END_BORROW, -1, -1, b, -1, line, 0); + x->live = 0; + if (x->parent >= 0) { + if (x->mut) c->bor[x->parent].kids_mut--; else c->bor[x->parent].kids_shared--; + } else { + if (x->mut) c->obj[x->obj].n_mut--; else c->obj[x->obj].n_shared--; + } +} + +/* describe a live borrow conflicting on object o (direct) or as a child of borrow p */ +static void conflict_name(C *c, int o, int p, int want_mut_only, char *buf, size_t cap) +{ + for (int i = c->nbor - 1; i >= 0; i--) { + const Bor *b = &c->bor[i]; + if (!b->live) continue; + if (p >= 0 ? b->parent != p : (b->parent >= 0 || b->obj != o)) continue; + if (want_mut_only && !b->mut) continue; + if (b->sym >= 0) snprintf(buf, cap, "%s%s", b->mut ? "&mut " : "&", c->sym[b->sym].name); + else snprintf(buf, cap, "%s argument (line %u)", b->mut ? "&mut" : "&", b->line); + return; + } + snprintf(buf, cap, "?"); +} + +static int diag_own(C *c, OscDiagKind k, uint32_t line, uint32_t col, int s, const char *other, + const char *transition, const char *msg) +{ + osc_diag_set(c->d, k, line, col, c->sym[s].name, c->sym[s].line, other, transition, "%s", msg); + return -1; +} + +/* direct or via-borrow access of symbol s (owner or borrow binding). wr: write. */ +static int access(C *c, int s, int wr, uint32_t line, uint32_t col) +{ + Sym *y = &c->sym[s]; + char other[64], msg[160]; + if (y->kind == SK_OWNER) { + Obj *o = &c->obj[y->obj]; + uint32_t k = wr ? OSC_EV_USE_WRITE : OSC_EV_USE_READ; + if (o->moved) { + tr_ev(c, k, y->obj, -1, -1, -1, line, 1); + snprintf(msg, sizeof msg, "'%s' used after it was moved at line %u", y->name, o->move_line); + return diag_own(c, OSC_DIAG_USE_AFTER_MOVE, line, col, s, NULL, "use after move", msg); + } + if (o->n_mut || (wr && o->n_shared)) { + conflict_name(c, y->obj, -1, !wr, other, sizeof other); + tr_ev(c, k, y->obj, -1, -1, -1, line, 1); + snprintf(msg, sizeof msg, "direct %s of '%s' while %s is live", wr ? "store" : "read", y->name, other); + return diag_own(c, OSC_DIAG_MUTABLE_ALIAS, line, col, s, other, + wr ? "write while borrowed" : "read while borrow_mut live", msg); + } + tr_ev(c, k, y->obj, -1, -1, -1, line, 0); + return 0; + } + /* borrow binding / borrow parameter */ + int b = y->bor; + Bor *x = &c->bor[b]; + uint32_t k = wr ? OSC_EV_USE_WRITE : OSC_EV_USE_READ; + if (wr && !x->mut) { + tr_ev(c, k, x->obj, -1, -1, b, line, 1); + snprintf(msg, sizeof msg, "store through shared borrow '%s' (read only)", y->name); + return diag_own(c, OSC_DIAG_READ_ONLY_BORROW, line, col, s, NULL, "write through shared borrow", msg); + } + if (x->kids_mut || (wr && x->kids_shared)) { + conflict_name(c, -1, b, !wr, other, sizeof other); + tr_ev(c, k, x->obj, -1, -1, b, line, 1); + snprintf(msg, sizeof msg, "use of '%s' while its reborrow %s is live", y->name, other); + return diag_own(c, OSC_DIAG_MUTABLE_ALIAS, line, col, s, other, + wr ? "write while reborrowed" : "read while reborrow_mut live", msg); + } + tr_ev(c, k, x->obj, -1, -1, b, line, 0); + return 0; +} + +/* take a borrow of symbol s; returns borrow index or -1 */ +static int take_borrow(C *c, int s, int mut, uint32_t line, uint32_t col) +{ + Sym *y = &c->sym[s]; + char other[64], msg[160]; + uint32_t k = mut ? OSC_EV_BORROW_MUT : OSC_EV_BORROW_SHARED; + if (y->kind == SK_OWNER) { + Obj *o = &c->obj[y->obj]; + if (o->moved) { + tr_ev(c, k, y->obj, -1, c->nbor, -1, line, 1); + snprintf(msg, sizeof msg, "borrow of '%s' after it was moved at line %u", y->name, o->move_line); + return diag_own(c, OSC_DIAG_USE_AFTER_MOVE, line, col, s, NULL, "use after move", msg); + } + if (o->n_mut || (mut && o->n_shared)) { + conflict_name(c, y->obj, -1, !mut, other, sizeof other); + tr_ev(c, k, y->obj, -1, c->nbor, -1, line, 1); + snprintf(msg, sizeof msg, "%s of '%s' while %s is live", mut ? "&mut" : "&", y->name, other); + return diag_own(c, OSC_DIAG_MUTABLE_ALIAS, line, col, s, other, + mut ? (o->n_mut ? "borrow_mut while borrow_mut live" : "borrow_mut while borrow_shared live") + : "borrow_shared while borrow_mut live", msg); + } + int b = new_bor(c, y->obj, -1, mut, line); + if (b < 0) return -1; + tr_ev(c, k, y->obj, -1, b, -1, line, 0); + return b; + } + int p = y->bor; + Bor *x = &c->bor[p]; + if (mut && !x->mut) { + tr_ev(c, k, x->obj, -1, c->nbor, p, line, 1); + snprintf(msg, sizeof msg, "&mut reborrow through shared borrow '%s' (read only)", y->name); + return diag_own(c, OSC_DIAG_READ_ONLY_BORROW, line, col, s, NULL, "borrow_mut through shared borrow", msg); + } + if (x->kids_mut || (mut && x->kids_shared)) { + conflict_name(c, -1, p, !mut, other, sizeof other); + tr_ev(c, k, x->obj, -1, c->nbor, p, line, 1); + snprintf(msg, sizeof msg, "reborrow of '%s' while %s is live", y->name, other); + return diag_own(c, OSC_DIAG_MUTABLE_ALIAS, line, col, s, other, + mut ? "reborrow_mut while reborrow live" : "reborrow_shared while reborrow_mut live", msg); + } + int b = new_bor(c, x->obj, p, mut, line); + if (b < 0) return -1; + tr_ev(c, k, x->obj, -1, b, p, line, 0); + return b; +} + +/* move owner symbol s; dest object index or -1 (consumed by an own parameter) */ +static int do_move(C *c, int s, int dest, uint32_t line, uint32_t col) +{ + Sym *y = &c->sym[s]; + Obj *o = &c->obj[y->obj]; + char other[64], msg[160]; + if (o->moved) { + tr_ev(c, OSC_EV_MOVE, y->obj, dest, -1, -1, line, 1); + snprintf(msg, sizeof msg, "'%s' moved again after it was moved at line %u", y->name, o->move_line); + return diag_own(c, OSC_DIAG_USE_AFTER_MOVE, line, col, s, NULL, "use after move", msg); + } + if (o->n_shared || o->n_mut) { + conflict_name(c, y->obj, -1, 0, other, sizeof other); + tr_ev(c, OSC_EV_MOVE, y->obj, dest, -1, -1, line, 1); + snprintf(msg, sizeof msg, "move of '%s' while %s is live", y->name, other); + return diag_own(c, OSC_DIAG_MUTABLE_ALIAS, line, col, s, other, "move while borrowed", msg); + } + if (y->loop_depth < c->loop_depth) { + /* first iteration moves, the next iteration would use a moved owner */ + tr_ev(c, OSC_EV_MOVE, y->obj, dest, -1, -1, line, 0); + int d2 = -1; + if (dest >= 0) { d2 = new_obj(c, -1, line); if (d2 < 0) return -1; } + tr_ev(c, OSC_EV_MOVE, y->obj, d2, -1, -1, line, 1); + snprintf(msg, sizeof msg, "'%s' (declared outside the loop) is moved inside a loop: the next iteration " + "would use it after the move", y->name); + return diag_own(c, OSC_DIAG_USE_AFTER_MOVE, line, col, s, NULL, "use after move (move inside loop)", msg); + } + tr_ev(c, OSC_EV_MOVE, y->obj, dest, -1, -1, line, 0); + o->moved = 1; + o->move_line = line; + return 0; +} + +/* ------------------------------------------------------------ scopes */ +static int lookup(C *c, const char *name) +{ + for (int i = c->nvis - 1; i >= 0; i--) + if (strcmp(c->sym[c->vis[i]].name, name) == 0) return c->vis[i]; + return -1; +} + +static int declare(C *c, const OscNode *n, uint8_t kind, const OscType *ty, int mut) +{ + char name[64]; + osc_node_name(c->ast, n, name, sizeof name); + int prev = lookup(c, name); + if (prev >= 0) { + osc_diag_set(c->d, OSC_DIAG_REDEFINED_NAME, n->line, n->col, name, c->sym[prev].line, NULL, + "redefine visible name", "'%s' is already defined at line %u (no shadowing)", name, + c->sym[prev].line); + return -1; + } + if (c->nsym >= OSC_CHECK_MAX_SYMS) return cap_fail(c, n->line, "symbol capacity"); + int s = c->nsym++; + Sym *y = &c->sym[s]; + memset(y, 0, sizeof *y); + memcpy(y->name, name, sizeof name); + y->line = n->line; + y->kind = kind; + y->mut = (uint8_t)mut; + y->ty = *ty; + y->loop_depth = c->loop_depth; + y->obj = y->bor = -1; + c->vis[c->nvis++] = s; + return s; +} + +static int push_scope(C *c, uint32_t line) +{ + if (c->depth >= MAX_SCOPES) return cap_fail(c, line, "scope depth"); + c->scope_start[c->depth++] = c->nvis; + return 0; +} + +/* scope-end destruction of the innermost `levels` scopes (without popping). + * Records released owner symbols into the AST release list. */ +static void scope_exit_events(C *c, int levels, uint32_t line, OscNode *rec) +{ + OscAst *a = c->ast; + rec->rel_start = a->nrel; + rec->rel_count = 0; + for (int lv = 0; lv < levels; lv++) { + int d = c->depth - 1 - lv; + for (int i = c->nvis - 1; i >= c->scope_start[d]; i--) { + int s = c->vis[i]; + Sym *y = &c->sym[s]; + if (y->kind == SK_BORROW) { + if (y->bor >= 0 && c->bor[y->bor].live) end_bor(c, y->bor, line); + } else if (y->kind == SK_OWNER) { + Obj *o = &c->obj[y->obj]; + if (!o->moved) { + tr_ev(c, OSC_EV_RELEASE, y->obj, -1, -1, -1, line, 0); + o->moved = 2; /* released (scope gone) */ + if (a->nrel < OSC_AST_MAX_REL) { a->rel[a->nrel++] = (int16_t)s; rec->rel_count++; } + } + } + } + } +} + +static void pop_scope(C *c) +{ + c->depth--; + c->nvis = c->scope_start[c->depth]; +} + +/* ------------------------------------------------------------ state snapshots */ +static Snap *snap_take(C *c) +{ + Snap *s = malloc(sizeof *s); + if (!s) return NULL; + memcpy(s->obj, c->obj, sizeof(Obj) * (size_t)c->nobj); + memcpy(s->bor, c->bor, sizeof(Bor) * (size_t)c->nbor); + for (int i = 0; i < c->nsym; i++) s->symbor[i] = c->sym[i].bor; + s->nobj = c->nobj; + s->nbor = c->nbor; + s->nsym = c->nsym; + return s; +} +/* restore state of the entities that existed at the snapshot; later ones stay + * allocated (ids are single assignment) but are dead */ +static void snap_restore(C *c, const Snap *s) +{ + memcpy(c->obj, s->obj, sizeof(Obj) * (size_t)s->nobj); + memcpy(c->bor, s->bor, sizeof(Bor) * (size_t)s->nbor); + for (int i = s->nbor; i < c->nbor; i++) c->bor[i].live = 0; + for (int i = 0; i < s->nsym; i++) c->sym[i].bor = s->symbor[i]; +} + +/* ------------------------------------------------------------ integer helpers */ +typedef __int128 i128; + +static int fits(OscScalar t, i128 v) +{ + unsigned w = osc_scalar_width(t); + if (osc_scalar_signed(t)) { + i128 lo = -((i128)1 << (w - 1)), hi = ((i128)1 << (w - 1)) - 1; + return v >= lo && v <= hi; + } + return v >= 0 && v <= (((i128)1 << w) - 1); +} +static i128 wrapu(OscScalar t, i128 v) +{ + unsigned w = osc_scalar_width(t); + unsigned __int128 m = (((unsigned __int128)1) << w) - 1; + return (i128)((unsigned __int128)v & m); +} +static uint64_t canon(OscScalar t, i128 v) +{ + if (t == OSC_T_BOOL) return v ? 1 : 0; + if (osc_scalar_signed(t)) return (uint64_t)(int64_t)v; + return (uint64_t)wrapu(t, v); +} + +static int is_shift(int op) { return op == OT_SHL || op == OT_SHR; } +static int is_arith(int op) +{ + return op == OT_PLUS || op == OT_MINUS || op == OT_STAR || op == OT_SLASH || op == OT_PERCENT || op == OT_AMP || + op == OT_PIPE || op == OT_CARET; +} +static int is_cmpop(int op) { return op == OT_EQ || op == OT_NE || op == OT_LT || op == OT_LE || op == OT_GT || op == OT_GE; } + +/* type comes only from context */ +static int ctxfree(C *c, int i) +{ + const OscNode *n = NODE(i); + switch (n->kind) { + case ON_INT: return 1; + case ON_UN: return n->op != OT_BANG && ctxfree(c, n->a); + case ON_BIN: + if (is_shift(n->op)) return ctxfree(c, n->a); + if (is_arith(n->op)) return ctxfree(c, n->a) && ctxfree(c, n->b); + return 0; + default: return 0; + } +} +/* all leaves literal */ +static int constexpr_(C *c, int i) +{ + const OscNode *n = NODE(i); + switch (n->kind) { + case ON_INT: return 1; + case ON_UN: return n->op != OT_BANG && constexpr_(c, n->a); + case ON_BIN: return (is_shift(n->op) || is_arith(n->op)) && constexpr_(c, n->a) && constexpr_(c, n->b); + default: return 0; + } +} + +static int ovf(C *c, const OscNode *n, const char *transition, const char *msg) +{ + osc_diag_set(c->d, OSC_DIAG_OVERFLOW_UNSAFE, n->line, n->col, c->sobj, 0, NULL, transition, "%s", msg); + return -1; +} + +/* fold constant expression i at type t; value as mathematical integer in range of t */ +static int fold(C *c, int i, OscScalar t, i128 *out) +{ + OscNode *n = NODE(i); + char msg[160]; + if (t == OSC_T_BOOL) return tmismatch(c, n, "bool", "integer literal where bool is required"); + int sg = osc_scalar_signed(t); + unsigned w = osc_scalar_width(t); + i128 v, a, b; + switch (n->kind) { + case ON_INT: + v = (i128)n->ival; + if (!fits(t, v)) { + snprintf(msg, sizeof msg, "literal %llu does not fit %s", (unsigned long long)n->ival, tname(t)); + return ovf(c, n, "literal does not fit type", msg); + } + break; + case ON_UN: + if (n->op == OT_MINUS && NODE(n->a)->kind == ON_INT) { + const OscNode *l = NODE(n->a); + v = -(i128)l->ival; + if (!sg && l->ival != 0) { + snprintf(msg, sizeof msg, "negative literal -%llu for unsigned %s", (unsigned long long)l->ival, tname(t)); + return ovf(c, n, "negative literal for unsigned type", msg); + } + if (!fits(t, v)) { + snprintf(msg, sizeof msg, "literal -%llu does not fit %s", (unsigned long long)l->ival, tname(t)); + return ovf(c, n, "literal does not fit type", msg); + } + NODE(n->a)->ty.s = t; + NODE(n->a)->is_const = 1; + NODE(n->a)->cval = canon(t, (i128)l->ival); + break; + } + if (fold(c, n->a, t, &a)) return -1; + if (n->op == OT_MINUS) { + if (!sg) { + if (a != 0) return ovf(c, n, "negative constant for unsigned type", "negation of a non-zero unsigned constant"); + v = 0; + } else { + v = -a; + if (!fits(t, v)) return ovf(c, n, "signed constant overflow", "constant negation overflows"); + } + } else { /* ~ */ + v = sg ? (i128)(~(int64_t)a) : wrapu(t, ~a); + } + break; + case ON_BIN: + if (fold(c, n->a, t, &a) || fold(c, n->b, t, &b)) return -1; + switch (n->op) { + case OT_PLUS: v = a + b; break; + case OT_MINUS: v = a - b; break; + case OT_STAR: + if (sg) v = a * b; + else v = (i128)(((unsigned __int128)a * (unsigned __int128)b) & ((((unsigned __int128)1) << w) - 1)); + break; + case OT_SLASH: case OT_PERCENT: + if (b == 0) return ovf(c, NODE(n->b), "literal zero divisor", "division by a constant zero"); + v = n->op == OT_SLASH ? a / b : a % b; + break; + case OT_AMP: v = sg ? (i128)((int64_t)a & (int64_t)b) : (a & b); break; + case OT_PIPE: v = sg ? (i128)((int64_t)a | (int64_t)b) : (a | b); break; + case OT_CARET: v = sg ? (i128)((int64_t)a ^ (int64_t)b) : (a ^ b); break; + case OT_SHL: case OT_SHR: + if (b < 0 || b >= (i128)w) { + snprintf(msg, sizeof msg, "constant shift amount %lld outside 0..%u", (long long)b, w - 1); + return ovf(c, NODE(n->b), "literal shift >= width", msg); + } + if (n->op == OT_SHL) { + if (sg) { + v = a * ((i128)1 << (int)b); + if (!fits(t, v)) return ovf(c, n, "signed constant overflow", "constant left shift overflows"); + } else { + v = wrapu(t, a << (int)b); + } + } else { + v = sg ? (a >> (int)b) : (a >> (int)b); + } + break; + default: return tmismatch(c, n, NULL, "operator not allowed in a constant"); + } + if (sg) { + if (!fits(t, v)) { + snprintf(msg, sizeof msg, "constant expression overflows %s", tname(t)); + return ovf(c, n, "signed constant overflow", msg); + } + } else { + v = wrapu(t, v); + } + break; + default: + return tmismatch(c, n, NULL, "not a constant"); + } + n->ty.s = t; + n->is_const = 1; + n->cval = canon(t, v); + *out = v; + return 0; +} + +/* ------------------------------------------------------------ expressions */ +static int chk(C *c, int i, OscScalar want); +static int chk_call(C *c, int i, OscScalar want, int as_stmt); + +static int want_ok(C *c, const OscNode *n, OscScalar got, OscScalar want) +{ + if (want && got != want) { + char msg[160]; + snprintf(msg, sizeof msg, "expression of type %s where %s is required", tname(got), tname(want)); + return tmismatch(c, n, tname(got), msg); + } + return 0; +} + +static int resolve(C *c, const OscNode *n) +{ + char name[64]; + osc_node_name(c->ast, n, name, sizeof name); + int s = lookup(c, name); + if (s < 0) + osc_diag_set(c->d, OSC_DIAG_UNDEFINED_NAME, n->line, n->col, name, 0, NULL, "use of undefined name", + "'%s' is not defined in an enclosing scope", name); + return s; +} + +/* index expression + static bounds; arr symbol s */ +static int chk_index(C *c, int s, int ix, const OscNode *at) +{ + OscScalar it; + if (ctxfree(c, ix)) it = (OscScalar)chk(c, ix, OSC_T_I64); + else it = (OscScalar)chk(c, ix, 0); + if ((int)it < 0) return -1; + if (!osc_scalar_is_int(it)) return tmismatch(c, NODE(ix), tname(it), "array index must be an integer"); + const OscNode *x = NODE(ix); + if (x->is_const) { + int64_t v = osc_scalar_signed(it) ? (int64_t)x->cval : (int64_t)(x->cval > (uint64_t)INT64_MAX ? -1 : (int64_t)x->cval); + int oob = osc_scalar_signed(it) ? (v < 0 || v >= (int64_t)c->sym[s].ty.len) + : (x->cval >= (uint64_t)c->sym[s].ty.len); + if (oob) { + char other[64]; + if (osc_scalar_signed(it)) snprintf(other, sizeof other, "index %lld", (long long)v); + else snprintf(other, sizeof other, "index %llu", (unsigned long long)x->cval); + osc_diag_set(c->d, OSC_DIAG_STATIC_OUT_OF_BOUNDS, at->line, at->col, c->sym[s].name, c->sym[s].line, other, + "index outside 0..N-1", "constant %s outside 0..%u of '%s'", other, + c->sym[s].ty.len - 1u, c->sym[s].name); + return -1; + } + } + return 0; +} + +static int chk(C *c, int i, OscScalar want) +{ + OscNode *n = NODE(i); + char msg[160]; + if (ctxfree(c, i) && !want) { + osc_diag_set(c->d, OSC_DIAG_AMBIGUOUS_WIDTH, n->line, n->col, c->sobj, 0, NULL, "literal without type context", + "integer literal has no type from context (ambiguous width)"); + return -1; + } + if (want && constexpr_(c, i)) { + i128 v; + if (fold(c, i, want, &v)) return -1; + return (int)want; + } + OscScalar t; + switch (n->kind) { + case ON_INT: { i128 v; if (fold(c, i, want, &v)) return -1; return (int)want; } /* unreachable: constexpr */ + case ON_BOOL: + t = OSC_T_BOOL; + break; + case ON_NAME: { + int s = resolve(c, n); + if (s < 0) return -1; + n->sym = s; + if (c->sym[s].kind != SK_SCALAR) { + snprintf(msg, sizeof msg, "'%s' is an array %s, not a scalar value", c->sym[s].name, + c->sym[s].kind == SK_OWNER ? "owner" : "borrow"); + return tmismatch(c, n, c->sym[s].name, msg); + } + t = c->sym[s].ty.s; + break; + } + case ON_INDEX: { + int s = resolve(c, n); + if (s < 0) return -1; + n->sym = s; + if (c->sym[s].kind == SK_SCALAR) { + snprintf(msg, sizeof msg, "'%s' is a scalar, not an array", c->sym[s].name); + return tmismatch(c, n, c->sym[s].name, msg); + } + if (chk_index(c, s, n->a, n)) return -1; + if (access(c, s, 0, n->line, n->col)) return -1; + t = c->sym[s].ty.elem; + break; + } + case ON_CALL: { + int r = chk_call(c, i, want, 0); + if (r < 0) return -1; + t = (OscScalar)r; + break; + } + case ON_BORROW: + return tmismatch(c, n, NULL, "a borrow is not a value here"); + case ON_UN: { + if (n->op == OT_BANG) { + if (chk(c, n->a, OSC_T_BOOL) < 0) return -1; + t = OSC_T_BOOL; + break; + } + int r = chk(c, n->a, ctxfree(c, n->a) ? want : 0); + if (r < 0) return -1; + t = (OscScalar)r; + if (!osc_scalar_is_int(t)) return tmismatch(c, n, tname(t), "'-' and '~' need an integer operand"); + break; + } + case ON_CAST: { + if (ctxfree(c, n->a)) { + osc_diag_set(c->d, OSC_DIAG_AMBIGUOUS_WIDTH, NODE(n->a)->line, NODE(n->a)->col, c->sobj, 0, NULL, + "literal as 'as' source", "the source of 'as' must not be a bare literal (ambiguous width)"); + return -1; + } + int r = chk(c, n->a, 0); + if (r < 0) return -1; + if (!osc_scalar_is_int((OscScalar)r) || !osc_scalar_is_int(n->ty.s)) { + snprintf(msg, sizeof msg, "'as' converts between integer types only (%s as %s)", tname((OscScalar)r), + tname(n->ty.s)); + return tmismatch(c, n, tname((OscScalar)r), msg); + } + t = n->ty.s; + break; + } + case ON_BIN: { + int op = n->op; + if (op == OT_ANDAND || op == OT_OROR) { + if (chk(c, n->a, OSC_T_BOOL) < 0 || chk(c, n->b, OSC_T_BOOL) < 0) return -1; + t = OSC_T_BOOL; + break; + } + if (is_cmpop(op)) { + OscScalar T; + if (ctxfree(c, n->a) && ctxfree(c, n->b)) { + osc_diag_set(c->d, OSC_DIAG_AMBIGUOUS_WIDTH, n->line, n->col, c->sobj, 0, NULL, + "literal without type context", "comparison of two literals (ambiguous width)"); + return -1; + } + if (ctxfree(c, n->a)) { + int r = chk(c, n->b, 0); + if (r < 0) return -1; + T = (OscScalar)r; + if (T == OSC_T_BOOL) return tmismatch(c, NODE(n->a), "bool", "integer literal compared with bool"); + if (chk(c, n->a, T) < 0) return -1; + } else { + int r = chk(c, n->a, 0); + if (r < 0) return -1; + T = (OscScalar)r; + if (T == OSC_T_BOOL && ctxfree(c, n->b)) + return tmismatch(c, NODE(n->b), "bool", "integer literal compared with bool"); + if (chk(c, n->b, T) < 0) return -1; + } + n->flag = (uint8_t)T; /* operand type for lowering */ + t = OSC_T_BOOL; + break; + } + if (is_shift(op)) { + int r = chk(c, n->a, ctxfree(c, n->a) ? want : 0); + if (r < 0) return -1; + OscScalar T = (OscScalar)r; + if (!osc_scalar_is_int(T)) return tmismatch(c, n, tname(T), "shift of a non-integer"); + int ra; + if (ctxfree(c, n->b)) ra = chk(c, n->b, T); + else ra = chk(c, n->b, 0); + if (ra < 0) return -1; + if (!osc_scalar_is_int((OscScalar)ra)) return tmismatch(c, NODE(n->b), tname((OscScalar)ra), "shift amount must be an integer"); + const OscNode *bn = NODE(n->b); + if (bn->is_const) { + unsigned w = osc_scalar_width(T); + int neg = osc_scalar_signed((OscScalar)ra) && (int64_t)bn->cval < 0; + if (neg || bn->cval >= w) { + snprintf(msg, sizeof msg, "constant shift amount outside 0..%u for %s", w - 1, tname(T)); + return ovf(c, bn, "literal shift >= width", msg); + } + } + t = T; + break; + } + /* arithmetic / bitwise */ + OscScalar T; + if (ctxfree(c, n->a) && ctxfree(c, n->b)) { + /* only reachable with want (else ambiguous above) and non-constant leaves */ + int r = chk(c, n->a, want); + if (r < 0) return -1; + T = (OscScalar)r; + if (chk(c, n->b, T) < 0) return -1; + } else if (ctxfree(c, n->a)) { + int r = chk(c, n->b, 0); + if (r < 0) return -1; + T = (OscScalar)r; + if (T == OSC_T_BOOL) return tmismatch(c, NODE(n->b), "bool", "arithmetic on bool"); + if (chk(c, n->a, T) < 0) return -1; + } else { + int r = chk(c, n->a, 0); + if (r < 0) return -1; + T = (OscScalar)r; + if (T == OSC_T_BOOL) return tmismatch(c, NODE(n->a), "bool", "arithmetic on bool"); + if (chk(c, n->b, T) < 0) return -1; + } + if (!osc_scalar_is_int(T)) return tmismatch(c, n, tname(T), "arithmetic needs integer operands"); + if ((op == OT_SLASH || op == OT_PERCENT) && NODE(n->b)->is_const && NODE(n->b)->cval == 0) + return ovf(c, NODE(n->b), "literal zero divisor", "division by a constant zero"); + t = T; + break; + } + default: + return tmismatch(c, n, NULL, "unexpected expression"); + } + n->ty.s = t; + if (want_ok(c, n, t, want)) return -1; + return (int)t; +} + +static int find_fn(C *c, const char *name, int *after) +{ + *after = 0; + for (uint32_t k = 0; k < c->ast->nfns; k++) { + char fn[64]; + osc_node_name(c->ast, NODE(c->ast->fns[k]), fn, sizeof fn); + if (strcmp(fn, name) == 0) { + if ((int)k < c->fi) return (int)k; + *after = 1; + return -1; + } + } + return -1; +} + +static int same_arr(const OscType *a, const OscType *b) { return a->elem == b->elem && a->len == b->len; } + +static int chk_call(C *c, int i, OscScalar want, int as_stmt) +{ + OscNode *n = NODE(i); + char name[64], msg[160]; + osc_node_name(c->ast, n, name, sizeof name); + int after; + int g = find_fn(c, name, &after); + if (g < 0) { + osc_diag_set(c->d, OSC_DIAG_UNDEFINED_NAME, n->line, n->col, name, 0, NULL, + after ? "call before definition" : "call of undefined function", + after ? "'%s' is called before its definition is complete (no recursion, no forward reference)" + : "function '%s' is not defined", name); + return -1; + } + n->sym = g; + const OscNode *f = NODE(c->ast->fns[g]); + int params[OSC_MAX_PARAMS], np = 0; + for (int p = f->a; p >= 0; p = NODE(p)->next) params[np++] = p; + int args[OSC_MAX_PARAMS + 1], na = 0; + for (int a = n->a; a >= 0; a = NODE(a)->next) { + if (na > OSC_MAX_PARAMS) break; + args[na++] = a; + } + if (na != np) { + snprintf(msg, sizeof msg, "'%s' takes %d argument(s), %d given", name, np, na); + osc_diag_set(c->d, OSC_DIAG_TYPE_MISMATCH, n->line, n->col, name, f->line, NULL, "arity mismatch", "%s", msg); + return -1; + } + int cb[OSC_MAX_PARAMS], ncb = 0; + for (int k = 0; k < na; k++) { + OscNode *a = NODE(args[k]); + const OscType *pt = &NODE(params[k])->ty; + if (pt->s != OSC_T_REF) { + if (a->kind == ON_BORROW) return tmismatch(c, a, name, "borrow passed to a scalar parameter"); + if (chk(c, args[k], pt->s) < 0) return -1; + continue; + } + if (pt->ref == OSC_REF_OWN) { + if (a->kind != ON_NAME) return tmismatch(c, a, name, "an 'own' parameter takes an owner name (move)"); + int s = resolve(c, a); + if (s < 0) return -1; + a->sym = s; + if (c->sym[s].kind != SK_OWNER || !same_arr(&c->sym[s].ty, pt)) { + snprintf(msg, sizeof msg, "'%s' is not an owner of [%s; %u]", c->sym[s].name, tname(pt->elem), pt->len); + return tmismatch(c, a, c->sym[s].name, msg); + } + if (do_move(c, s, -1, a->line, a->col)) return -1; + continue; + } + if (a->kind != ON_BORROW || (a->mut != 0) != (pt->ref == OSC_REF_MUT)) { + snprintf(msg, sizeof msg, "parameter %d of '%s' takes %s", k + 1, name, + pt->ref == OSC_REF_MUT ? "'&mut name'" : "'&name'"); + return tmismatch(c, a, name, msg); + } + int s = resolve(c, a); + if (s < 0) return -1; + a->sym = s; + if (c->sym[s].kind == SK_SCALAR || !same_arr(&c->sym[s].ty, pt)) { + snprintf(msg, sizeof msg, "'%s' is not an array [%s; %u]", c->sym[s].name, tname(pt->elem), pt->len); + return tmismatch(c, a, c->sym[s].name, msg); + } + int b = take_borrow(c, s, a->mut, a->line, a->col); + if (b < 0) return -1; + cb[ncb++] = b; + } + for (int k = ncb - 1; k >= 0; k--) end_bor(c, cb[k], n->line); + if (as_stmt) return (int)f->ty.s; + if (f->ty.s == OSC_T_VOID) { + snprintf(msg, sizeof msg, "'%s' returns nothing and cannot be used as a value", name); + return tmismatch(c, n, name, msg); + } + (void)want; + return (int)f->ty.s; +} + +/* ------------------------------------------------------------ statements */ +static int chk_block(C *c, int i, int new_scope); +static int chk_stmt(C *c, int i); + +static void set_sobj_tok(C *c, const OscNode *n) { osc_node_name(c->ast, n, c->sobj, sizeof c->sobj); } + +/* borrow node bn into a borrow of type ty (SHARED/MUT). Returns borrow index. */ +static int chk_borrow_src(C *c, OscNode *bn, const OscType *ty, int *src) +{ + char msg[160]; + int s = resolve(c, bn); + if (s < 0) return -1; + bn->sym = s; + *src = s; + if (c->sym[s].kind == SK_SCALAR) { + snprintf(msg, sizeof msg, "'%s' is a scalar; only arrays are borrowed", c->sym[s].name); + return tmismatch(c, bn, c->sym[s].name, msg); + } + if (!same_arr(&c->sym[s].ty, ty) || (bn->mut != 0) != (ty->ref == OSC_REF_MUT)) { + snprintf(msg, sizeof msg, "borrow does not match %s[%s; %u]", ty->ref == OSC_REF_MUT ? "&mut " : "&", + tname(ty->elem), ty->len); + return tmismatch(c, bn, c->sym[s].name, msg); + } + return 0; +} + +/* `return &x;` or a borrow assigned to an outer binding from a later-declared source */ +static int outlives(C *c, const OscNode *at, int s, int b, const char *who, const char *transition) +{ + Sym *y = &c->sym[s]; + if (y->kind == SK_OWNER) tr_ev(c, OSC_EV_RELEASE, y->obj, -1, -1, -1, at->line, 1); + else tr_ev(c, OSC_EV_END_BORROW, -1, -1, y->bor, -1, at->line, 1); + (void)b; + char msg[160]; + snprintf(msg, sizeof msg, "borrow of '%s' would outlive it (%s)", y->name, transition); + osc_diag_set(c->d, OSC_DIAG_BORROW_OUTLIVES_OWNER, at->line, at->col, y->name, y->line, who, transition, "%s", msg); + return -1; +} + +static int chk_if(C *c, int i) +{ + OscNode *n = NODE(i); + snprintf(c->sobj, sizeof c->sobj, "if"); + if (chk(c, n->a, OSC_T_BOOL) < 0) return -1; + Snap *s0 = snap_take(c); + if (!s0) return cap_fail(c, n->line, "checker memory"); + int nobj0 = c->nobj; + int rc = -1; + Snap *s1 = NULL; + tr_save(c, n->line); + if (chk_block(c, n->b, 1)) goto out; + int t1 = c->term; + s1 = snap_take(c); + if (!s1) { cap_fail(c, n->line, "checker memory"); goto out; } + tr_restore(c, n->line); + snap_restore(c, s0); + c->term = 0; + int t2 = 0; + if (n->c >= 0) { + tr_save(c, n->line); + if (NODE(n->c)->kind == ON_IF) { if (chk_if(c, n->c)) goto out; } + else if (chk_block(c, n->c, 1)) goto out; + t2 = c->term; + tr_restore(c, n->line); + } + /* state after else is in c; after then is s1 */ + if (t1 && t2) { + c->term = 1; + rc = 0; + goto out; + } + if (t2) { + snap_restore(c, s1); + } else if (!t1) { + for (int o = 0; o < nobj0; o++) { + int m1 = s1->obj[o].moved == 1, m2 = c->obj[o].moved == 1; + if (m1 != m2) { + int sym = c->obj[o].sym; + uint32_t ml = m1 ? s1->obj[o].move_line : c->obj[o].move_line; + char msg[160]; + snprintf(msg, sizeof msg, "'%s' is moved on only one path of the 'if' at line %u (no drop flags)", + sym >= 0 ? c->sym[sym].name : "?", n->line); + osc_diag_set(c->d, OSC_DIAG_CONDITIONAL_MOVE, ml, 0, sym >= 0 ? c->sym[sym].name : "?", + sym >= 0 ? c->sym[sym].line : 0, "if", "conditional move", "%s", msg); + goto out; + } + } + } + c->term = 0; + /* re-emit moves that hold after the if */ + for (int o = 0; o < nobj0; o++) + if (c->obj[o].moved == 1 && s0->obj[o].moved != 1) + tr_ev(c, OSC_EV_MOVE, o, -1, -1, -1, c->obj[o].move_line, 0); + rc = 0; +out: + free(s0); + free(s1); + return rc; +} + +static int chk_loop_body(C *c, OscNode *n, int is_for) +{ + Snap *s0 = snap_take(c); + if (!s0) return cap_fail(c, n->line, "checker memory"); + int rc = -1; + tr_save(c, n->line); + c->loop_depth++; + if (is_for) { + if (push_scope(c, n->line)) goto out; + OscType ti = {OSC_T_I64, OSC_REF_NONE, OSC_T_VOID, 0}; + int s = declare(c, n, SK_SCALAR, &ti, 0); + if (s < 0) goto out; + n->sym = s; + if (chk_block(c, n->b, 1)) goto out; + pop_scope(c); + } else { + snprintf(c->sobj, sizeof c->sobj, "while"); + if (chk(c, n->a, OSC_T_BOOL) < 0) goto out; + if (chk_block(c, n->b, 1)) goto out; + } + c->loop_depth--; + tr_restore(c, n->line); + snap_restore(c, s0); + c->term = 0; + rc = 0; +out: + free(s0); + return rc; +} + +static int chk_stmt(C *c, int i) +{ + OscNode *n = NODE(i); + char msg[160]; + switch (n->kind) { + case ON_LET: { + set_sobj_tok(c, n); + char name[64]; + osc_node_name(c->ast, n, name, sizeof name); + int prev = lookup(c, name); + if (prev >= 0) return declare(c, n, SK_SCALAR, &n->ty, n->mut) < 0 ? -1 : -1; + if (chk(c, n->a, n->ty.s) < 0) return -1; + int s = declare(c, n, SK_SCALAR, &n->ty, n->mut); + if (s < 0) return -1; + n->sym = s; + return 0; + } + case ON_LET_ALLOC: { + set_sobj_tok(c, n); + char name[64]; + osc_node_name(c->ast, n, name, sizeof name); + if (lookup(c, name) >= 0) return declare(c, n, SK_OWNER, &n->ty, 0) < 0 ? -1 : -1; + if (chk(c, n->a, n->ty.elem) < 0) return -1; + int s = declare(c, n, SK_OWNER, &n->ty, 0); + if (s < 0) return -1; + int o = new_obj(c, s, n->line); + if (o < 0) return -1; + c->sym[s].obj = o; + n->sym = s; + tr_ev(c, OSC_EV_ALLOC, o, -1, -1, -1, n->line, 0); + return 0; + } + case ON_LET_MOVE: { + set_sobj_tok(c, n); + char name[64]; + osc_node_name(c->ast, n, name, sizeof name); + if (lookup(c, name) >= 0) return declare(c, n, SK_OWNER, &n->ty, 0) < 0 ? -1 : -1; + OscNode *sn = NODE(n->a); + int src = resolve(c, sn); + if (src < 0) return -1; + sn->sym = src; + n->sym2 = src; + if (c->sym[src].kind != SK_OWNER || !same_arr(&c->sym[src].ty, &n->ty)) { + snprintf(msg, sizeof msg, "'%s' is not an owner of [%s; %u]", c->sym[src].name, tname(n->ty.elem), n->ty.len); + return tmismatch(c, sn, c->sym[src].name, msg); + } + int o = new_obj(c, -1, n->line); + if (o < 0) return -1; + if (do_move(c, src, o, sn->line, sn->col)) return -1; + int s = declare(c, n, SK_OWNER, &n->ty, 0); + if (s < 0) return -1; + c->obj[o].sym = s; + c->sym[s].obj = o; + n->sym = s; + return 0; + } + case ON_LET_BORROW: { + set_sobj_tok(c, n); + char name[64]; + osc_node_name(c->ast, n, name, sizeof name); + if (lookup(c, name) >= 0) return declare(c, n, SK_BORROW, &n->ty, n->mut) < 0 ? -1 : -1; + OscNode *bn = NODE(n->a); + int src; + if (chk_borrow_src(c, bn, &n->ty, &src)) return -1; + n->sym2 = src; + int b = take_borrow(c, src, bn->mut, bn->line, bn->col); + if (b < 0) return -1; + int s = declare(c, n, SK_BORROW, &n->ty, n->mut); + if (s < 0) return -1; + c->sym[s].bor = b; + c->bor[b].sym = s; + n->sym = s; + return 0; + } + case ON_ASSIGN: { + set_sobj_tok(c, n); + int s = resolve(c, n); + if (s < 0) return -1; + n->sym = s; + Sym *y = &c->sym[s]; + if (y->kind == SK_OWNER || !y->mut) { + snprintf(msg, sizeof msg, "'%s' is not assignable (%s)", y->name, + y->kind == SK_OWNER ? "owners are never reassigned" : "declare it with 'let mut'"); + osc_diag_set(c->d, OSC_DIAG_IMMUTABLE_ASSIGN, n->line, n->col, y->name, y->line, NULL, + "assign to immutable binding", "%s", msg); + return -1; + } + OscNode *v = NODE(n->a); + if (y->kind == SK_SCALAR) { + if (v->kind == ON_BORROW) return tmismatch(c, v, y->name, "a borrow cannot be assigned to a scalar"); + return chk(c, n->a, y->ty.s) < 0 ? -1 : 0; + } + /* borrow binding */ + if (v->kind != ON_BORROW) return tmismatch(c, v, y->name, "a borrow binding takes '&name' or '&mut name'"); + int src; + if (chk_borrow_src(c, v, &y->ty, &src)) return -1; + n->sym2 = src; + if (src == s) { + osc_diag_set(c->d, OSC_DIAG_UNSUPPORTED, v->line, v->col, y->name, y->line, NULL, "self reborrow", + "a borrow binding cannot be reassigned to a reborrow of itself"); + return -1; + } + Bor *old = &c->bor[y->bor]; + if (old->kids_shared || old->kids_mut) { + char other[64]; + conflict_name(c, -1, y->bor, 0, other, sizeof other); + tr_ev(c, OSC_EV_END_BORROW, -1, -1, y->bor, -1, n->line, 1); + osc_diag_set(c->d, OSC_DIAG_BORROW_OUTLIVES_OWNER, n->line, n->col, y->name, y->line, other, + "end borrow while reborrowed", "'%s' is reassigned while its reborrow %s is live", y->name, other); + return -1; + } + end_bor(c, y->bor, n->line); + y->bor = -1; + int b = take_borrow(c, src, v->mut, v->line, v->col); + if (b < 0) return -1; + y->bor = b; + c->bor[b].sym = s; + if (src > s) /* declared after the binding: destroyed while the binding is still in scope */ + return outlives(c, v, src, b, y->name, "outer borrow assigned a borrow of an inner owner"); + return 0; + } + case ON_STORE: { + set_sobj_tok(c, n); + int s = resolve(c, n); + if (s < 0) return -1; + n->sym = s; + Sym *y = &c->sym[s]; + if (y->kind == SK_SCALAR) { + snprintf(msg, sizeof msg, "'%s' is a scalar, not an array", y->name); + return tmismatch(c, n, y->name, msg); + } + if (chk_index(c, s, n->a, n)) return -1; + if (chk(c, n->b, y->ty.elem) < 0) return -1; + return access(c, s, 1, n->line, n->col); + } + case ON_IF: + return chk_if(c, i); + case ON_WHILE: + return chk_loop_body(c, n, 0); + case ON_FOR: + set_sobj_tok(c, n); + return chk_loop_body(c, n, 1); + case ON_RETURN: { + snprintf(c->sobj, sizeof c->sobj, "return"); + if (n->a >= 0 && NODE(n->a)->kind == ON_BORROW) { + OscNode *bn = NODE(n->a); + int s = resolve(c, bn); + if (s < 0) return -1; + if (c->sym[s].kind == SK_SCALAR) return tmismatch(c, bn, c->sym[s].name, "only arrays are borrowed"); + int b = take_borrow(c, s, bn->mut, bn->line, bn->col); + if (b < 0) return -1; + return outlives(c, bn, s, b, "return", "borrow returned from function"); + } + if (c->fret.s == OSC_T_VOID) { + if (n->a >= 0) return tmismatch(c, NODE(n->a), NULL, "a function without '->' returns no value"); + } else { + if (n->a < 0) { + osc_diag_set(c->d, OSC_DIAG_TYPE_MISMATCH, n->line, n->col, "return", 0, tname(c->fret.s), + "type mismatch", "'return;' in a function returning %s", tname(c->fret.s)); + return -1; + } + if (chk(c, n->a, c->fret.s) < 0) return -1; + } + scope_exit_events(c, c->depth, n->line, n); + c->term = 1; + return 0; + } + case ON_CALLSTMT: + set_sobj_tok(c, NODE(n->a)); + return chk_call(c, n->a, 0, 1) < 0 ? -1 : 0; + case ON_BLOCK: + return chk_block(c, i, 1); + default: + osc_diag_set(c->d, OSC_DIAG_SYNTAX, n->line, n->col, "?", 0, NULL, "statement", "unexpected statement"); + return -1; + } +} + +static int chk_block(C *c, int i, int new_scope) +{ + OscNode *n = NODE(i); + if (new_scope && push_scope(c, n->line)) return -1; + for (int s = n->a; s >= 0; s = NODE(s)->next) { + if (c->term) { + osc_diag_set(c->d, OSC_DIAG_UNSUPPORTED, NODE(s)->line, NODE(s)->col, "return", 0, NULL, + "unreachable statement", "statement after 'return' is unreachable"); + return -1; + } + if (chk_stmt(c, s)) return -1; + } + if (!c->term && new_scope) scope_exit_events(c, 1, (uint32_t)n->ival, n); + if (new_scope) pop_scope(c); + return 0; +} + +static int chk_fn(C *c, int fi) +{ + OscAst *a = c->ast; + int f = a->fns[fi]; + OscNode *fn = NODE(f); + c->fi = fi; + c->fnode = f; + c->fret = fn->ty; + c->nsym = c->nobj = c->nbor = c->nvis = c->depth = c->loop_depth = c->term = 0; + char fname[64]; + osc_node_name(a, fn, fname, sizeof fname); + snprintf(c->sobj, sizeof c->sobj, "%s", fname); + for (int k = 0; k < fi; k++) { + char g[64]; + osc_node_name(a, NODE(a->fns[k]), g, sizeof g); + if (strcmp(g, fname) == 0) { + osc_diag_set(c->d, OSC_DIAG_REDEFINED_NAME, fn->line, fn->col, fname, NODE(a->fns[k])->line, NULL, + "redefine function", "function '%s' is already defined at line %u", fname, + NODE(a->fns[k])->line); + return -1; + } + } + if (c->tr) c->tr->nfuncs = (uint16_t)(fi + 1); + if (push_scope(c, fn->line)) return -1; + for (int p = fn->a; p >= 0; p = NODE(p)->next) { + OscNode *pn = NODE(p); + uint8_t kind = pn->ty.s != OSC_T_REF ? SK_SCALAR : pn->ty.ref == OSC_REF_OWN ? SK_OWNER : SK_BORROW; + int s = declare(c, pn, kind, &pn->ty, 0); + if (s < 0) return -1; + pn->sym = s; + c->sym[s].is_param = 1; + if (kind == SK_OWNER) { + int o = new_obj(c, s, pn->line); + if (o < 0) return -1; + c->sym[s].obj = o; + tr_ev(c, OSC_EV_ALLOC, o, -1, -1, -1, pn->line, 0); + } else if (kind == SK_BORROW) { + int o = new_obj(c, -1, pn->line); + if (o < 0) return -1; + tr_ev(c, OSC_EV_ALLOC, o, -1, -1, -1, pn->line, 0); + int mut = pn->ty.ref == OSC_REF_MUT; + int b = new_bor(c, o, -1, mut, pn->line); + if (b < 0) return -1; + tr_ev(c, mut ? OSC_EV_BORROW_MUT : OSC_EV_BORROW_SHARED, o, -1, b, -1, pn->line, 0); + c->sym[s].bor = b; + c->bor[b].sym = s; + } + } + if (chk_block(c, fn->b, 1)) return -1; + if (!c->term) { + if (fn->ty.s != OSC_T_VOID) { + uint32_t end = (uint32_t)NODE(fn->b)->ival; + osc_diag_set(c->d, OSC_DIAG_MISSING_RETURN, end, 0, fname, fn->line, NULL, "fall off end of non-void function", + "function '%s' returning %s can reach its end without 'return'", fname, tname(fn->ty.s)); + return -1; + } + scope_exit_events(c, 1, (uint32_t)NODE(fn->b)->ival, fn); + } + pop_scope(c); + return 0; +} + +int osc_check(OscAst *ast, OscDiag *d, OscTrace *trace) +{ + C *c = calloc(1, sizeof *c); + if (!c) { + osc_diag_set(d, OSC_DIAG_CAPACITY, 0, 0, "unit", 0, NULL, "checker memory", "out of memory"); + return -1; + } + c->ast = ast; + c->d = d; + c->tr = trace; + if (trace) { trace->n = 0; trace->overflow = 0; trace->refused = 0; trace->nfuncs = 0; } + ast->nrel = 0; + int rc = 0; + for (uint32_t fi = 0; fi < ast->nfns && rc == 0; fi++) rc = chk_fn(c, (int)fi); + if (rc == 0 && ast->nrel >= OSC_AST_MAX_REL) { + osc_diag_set(d, OSC_DIAG_CAPACITY, 0, 0, "unit", 0, NULL, "release list capacity", "too many scope-exit releases"); + rc = -1; + } + free(c); + return rc; +} diff --git a/src/compiler/osc_check.h b/src/compiler/osc_check.h new file mode 100644 index 000000000..165917aca --- /dev/null +++ b/src/compiler/osc_check.h @@ -0,0 +1,61 @@ +/* + * osc_check.h -- OSC-1 name/type resolution, literal typing, compile-time + * overflow-unsafe checks, loop/return rules and ownership + borrow analysis + * with lexical lifetimes (docs/osc/OSC-1-DESIGN.md section 3 and 3.1). + * + * The checker annotates the AST in place (types, symbols, folded constants, + * release lists) and records, per function, the ownership event sequence it + * checked, in the II.11 model event format (src/compiler/model/osc_model.h), + * so tests can replay it through the executable model. + * + * Trace format: a flat list of entries. OSC_TR_EVENT carries one model event. + * Control flow is lexical, so the trace brackets every branch and loop body + * with OSC_TR_SAVE ... OSC_TR_RESTORE: a replayer must snapshot the model at + * SAVE and restore that snapshot at RESTORE (an `if` arm or a loop body leaves + * no trace in the state, except moves that hold on every non-returning path, + * which the checker re-emits after the `if` as MOVE obj -> 0). Model ids are + * per function: object k+1 / borrow k+1 for the checker's k-th object / + * borrow. A borrow parameter is modelled as ALLOC of a stand-in object + * followed by a borrow of it at function entry; an own parameter as ALLOC. + * On an ownership refusal the attempted (refused) event is appended last with + * refused = 1; for a move inside a loop the trace holds the first iteration's + * MOVE and the refused second-iteration MOVE; for borrow-outlives-owner it + * holds the borrow and the refused scope-end RELEASE / END_BORROW. + * + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#ifndef OSC_CHECK_H +#define OSC_CHECK_H + +#include +#include "model/osc_model.h" +#include "osc_diag.h" +#include "osc_parse.h" + +#define OSC_CHECK_MAX_SYMS 480 /* symbols per function (<= OSC_MAX_VREGS) */ +#define OSC_CHECK_MAX_OBJS 256 /* owners per function (static sites) */ +#define OSC_CHECK_MAX_BORS 512 /* borrows per function (static sites) */ +#define OSC_TRACE_MAX 16384 + +typedef enum { OSC_TR_EVENT = 0, OSC_TR_SAVE = 1, OSC_TR_RESTORE = 2 } OscTraceOp; + +typedef struct { + uint8_t op; /* OscTraceOp */ + uint8_t refused; /* 1 on the event the compiler refused (always last) */ + uint16_t func; /* function index in the unit */ + uint32_t line; /* source line */ + OscModelEvent ev; /* OSC_TR_EVENT only */ +} OscTraceEntry; + +typedef struct OscTrace { + uint32_t n; + uint8_t overflow; /* entries dropped (OSC_TRACE_MAX) or model id > model capacity */ + uint8_t refused; /* 1 if the last entry is a refused event */ + uint16_t nfuncs; /* functions checked (including a refused one) */ + OscTraceEntry e[OSC_TRACE_MAX]; +} OscTrace; + +/* Check ast (after osc_parse). 0 ok; -1 with *d filled. trace may be NULL. */ +int osc_check(OscAst *ast, OscDiag *d, OscTrace *trace); + +#endif /* OSC_CHECK_H */ diff --git a/src/compiler/osc_diag.c b/src/compiler/osc_diag.c new file mode 100644 index 000000000..6db868de0 --- /dev/null +++ b/src/compiler/osc_diag.c @@ -0,0 +1,57 @@ +/* + * osc_diag.c -- OSC-1 diagnostic kind names and filling helper. + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#include "osc_diag.h" + +#include +#include +#include + +static const char *const kind_names[OSC_DIAG__COUNT] = { + "NONE", "SYNTAX", "UNSUPPORTED", "CAPACITY", "UNDEFINED_NAME", "REDEFINED_NAME", "TYPE_MISMATCH", + "AMBIGUOUS_WIDTH", "OVERFLOW_UNSAFE", "UNBOUNDED_LOOP", "MISSING_RETURN", "USE_AFTER_MOVE", + "CONDITIONAL_MOVE", "MUTABLE_ALIAS", "BORROW_OUTLIVES_OWNER", "STATIC_OUT_OF_BOUNDS", "IMMUTABLE_ASSIGN", + "READ_ONLY_BORROW"}; + +const char *osc_diag_kind_name(int kind) +{ + if (kind < 0 || kind >= OSC_DIAG__COUNT) return "?"; + return kind_names[kind]; +} + +int osc_diag_kind_from_name(const char *name) +{ + for (int k = 0; k < OSC_DIAG__COUNT; k++) + if (strcmp(kind_names[k], name) == 0) return k; + return -1; +} + +static void cpy(char *dst, size_t cap, const char *s) +{ + if (!s) { dst[0] = 0; return; } + size_t n = strlen(s); + if (n >= cap) n = cap - 1; + memcpy(dst, s, n); + dst[n] = 0; +} + +void osc_diag_set(OscDiag *d, OscDiagKind kind, uint32_t line, uint32_t col, const char *object, + uint32_t origin_line, const char *other, const char *transition, const char *fmt, ...) +{ + if (!d) return; + memset(d, 0, sizeof *d); + d->kind = kind; + d->line = line; + d->col = col; + d->origin_line = origin_line; + cpy(d->object, sizeof d->object, object); + cpy(d->other, sizeof d->other, other); + cpy(d->transition, sizeof d->transition, transition); + if (fmt) { + va_list ap; + va_start(ap, fmt); + vsnprintf(d->message, sizeof d->message, fmt, ap); + va_end(ap); + } +} diff --git a/src/compiler/osc_diag.h b/src/compiler/osc_diag.h new file mode 100644 index 000000000..cdd5d239c --- /dev/null +++ b/src/compiler/osc_diag.h @@ -0,0 +1,52 @@ +/* + * osc_diag.h -- OSC-1 typed compile diagnostics (docs/osc/OSC-1-DESIGN.md + * section 6). Every refusal of the front end is exactly one OscDiag. + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#ifndef OSC_DIAG_H +#define OSC_DIAG_H + +#include + +typedef enum { + OSC_DIAG_NONE = 0, + OSC_DIAG_SYNTAX, + OSC_DIAG_UNSUPPORTED, + OSC_DIAG_CAPACITY, + OSC_DIAG_UNDEFINED_NAME, + OSC_DIAG_REDEFINED_NAME, + OSC_DIAG_TYPE_MISMATCH, + OSC_DIAG_AMBIGUOUS_WIDTH, + OSC_DIAG_OVERFLOW_UNSAFE, + OSC_DIAG_UNBOUNDED_LOOP, + OSC_DIAG_MISSING_RETURN, + OSC_DIAG_USE_AFTER_MOVE, + OSC_DIAG_CONDITIONAL_MOVE, + OSC_DIAG_MUTABLE_ALIAS, + OSC_DIAG_BORROW_OUTLIVES_OWNER, + OSC_DIAG_STATIC_OUT_OF_BOUNDS, + OSC_DIAG_IMMUTABLE_ASSIGN, + OSC_DIAG_READ_ONLY_BORROW, + OSC_DIAG__COUNT +} OscDiagKind; + +typedef struct { + OscDiagKind kind; + uint32_t line, col; /* where the refused construct is (1-based) */ + char object[64]; /* the name involved */ + uint32_t origin_line; /* where that object / borrow was created (0 = n/a) */ + char other[64]; /* conflicting borrow / name / type, if any */ + char transition[96]; /* the attempted transition as text */ + char message[160]; /* human-readable summary */ +} OscDiag; + +/* "SYNTAX", ..., "READ_ONLY_BORROW"; "NONE" for 0; "?" out of range. */ +const char *osc_diag_kind_name(int kind); +/* Inverse of osc_diag_kind_name; -1 if unknown. */ +int osc_diag_kind_from_name(const char *name); +/* Fill d (zeroed first). Strings may be NULL. message is printf-style. */ +void osc_diag_set(OscDiag *d, OscDiagKind kind, uint32_t line, uint32_t col, const char *object, + uint32_t origin_line, const char *other, const char *transition, const char *fmt, ...) + __attribute__((format(printf, 9, 10))); + +#endif /* OSC_DIAG_H */ diff --git a/src/compiler/osc_front.c b/src/compiler/osc_front.c new file mode 100644 index 000000000..5dc42d16d --- /dev/null +++ b/src/compiler/osc_front.c @@ -0,0 +1,49 @@ +/* + * osc_front.c -- see osc_front.h. + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#include "osc_front.h" +#include "osc_lex.h" +#include "osc_lower.h" +#include "osc_parse.h" + +#include +#include + +int osc_compile(const char *src, size_t len, OscUnit *out, OscDiag *diag, OscTrace *trace) +{ + memset(diag, 0, sizeof *diag); + if (trace) { trace->n = 0; trace->overflow = 0; trace->refused = 0; trace->nfuncs = 0; } + OscToken *toks = malloc(sizeof(OscToken) * OSC_LEX_MAX_TOKENS); + OscAst *ast = malloc(sizeof *ast); + int rc = -1; + if (!toks || !ast) { + osc_diag_set(diag, OSC_DIAG_CAPACITY, 0, 0, "unit", 0, NULL, "compiler memory", "out of memory"); + goto out; + } + memset(ast, 0, sizeof *ast); + uint32_t ntok = 0; + if (osc_lex(src, len, toks, OSC_LEX_MAX_TOKENS, &ntok, diag)) goto out; + ast->src = src; + ast->toks = toks; + ast->ntok = ntok; + if (osc_parse(ast, diag)) goto out; + if (ast->nfns == 0) { + osc_diag_set(diag, OSC_DIAG_UNSUPPORTED, 1, 1, "unit", 0, NULL, "empty unit", + "a unit must define at least one function"); + goto out; + } + if (osc_check(ast, diag, trace)) goto out; + if (osc_lower(ast, out, diag)) goto out; + char err[160]; + if (osc_ir_validate(out, err, sizeof err)) { + osc_diag_set(diag, OSC_DIAG_UNSUPPORTED, 0, 0, "internal", 0, NULL, "IR validation", + "internal error: lowered IR refused by the validator: %s", err); + goto out; + } + rc = 0; +out: + free(toks); + free(ast); + return rc; +} diff --git a/src/compiler/osc_front.h b/src/compiler/osc_front.h new file mode 100644 index 000000000..6105df9b8 --- /dev/null +++ b/src/compiler/osc_front.h @@ -0,0 +1,21 @@ +/* + * osc_front.h -- OSC-1 front-end driver: source bytes -> validated OscUnit. + * lex -> parse -> check (types, constants, loops, returns, ownership) -> + * lower -> osc_ir_validate. Deterministic: output is a pure function of the + * source bytes; all scratch memory is freed before returning. + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#ifndef OSC_FRONT_H +#define OSC_FRONT_H + +#include +#include "osc_check.h" +#include "osc_diag.h" +#include "osc_ir.h" + +/* 0 ok (out passed osc_ir_validate); -1 with *diag filled. + * trace_or_NULL receives the per-function ownership event trace (also on a + * refusal: the refused event is the last one, flagged). */ +int osc_compile(const char *src, size_t len, OscUnit *out, OscDiag *diag, OscTrace *trace_or_NULL); + +#endif /* OSC_FRONT_H */ diff --git a/src/compiler/osc_lex.c b/src/compiler/osc_lex.c new file mode 100644 index 000000000..9d741ec03 --- /dev/null +++ b/src/compiler/osc_lex.c @@ -0,0 +1,196 @@ +/* + * osc_lex.c -- OSC-1 lexer. See osc_lex.h. + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#include "osc_lex.h" + +#include + +static const struct { const char *w; int k; } keywords[] = { + {"fn", OT_FN}, {"let", OT_LET}, {"mut", OT_MUT}, {"own", OT_OWN}, {"alloc", OT_ALLOC}, + {"if", OT_IF}, {"else", OT_ELSE}, {"while", OT_WHILE}, {"bound", OT_BOUND}, {"for", OT_FOR}, + {"in", OT_IN}, {"return", OT_RETURN}, {"requires", OT_REQUIRES}, {"ensures", OT_ENSURES}, + {"as", OT_AS}, {"true", OT_TRUE}, {"false", OT_FALSE}, {"u8", OT_U8}, {"u16", OT_U16}, + {"u32", OT_U32}, {"u64", OT_U64}, {"i8", OT_I8}, {"i16", OT_I16}, {"i32", OT_I32}, + {"i64", OT_I64}, {"bool", OT_BOOL}, +}; + +/* Reserved: destruction words (destruction has no surface syntax, III.8) and + * the V0 effect / authority / control-flow words. Never names. */ +static const char *const reserved[] = { + "free", "drop", "delete", "dealloc", + "effect", "cap", "capability", "mint", "revoke", "grant", "publish", "promote", "authority", "admin", + "syscall", "io", "print", "import", "extern", "unsafe", "asm", "loop", "match", "struct", "enum", + "var", "const", "self", "rec", "break", "continue", +}; + +static const char *const kind_names[OT__COUNT] = { + "end of input", "NAME", "INT", "reserved word", + "fn", "let", "mut", "own", "alloc", "if", "else", "while", "bound", "for", "in", "return", "requires", + "ensures", "as", "true", "false", "u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64", "bool", + "(", ")", "{", "}", "[", "]", ",", ";", ":", "->", "..", "=", + "+", "-", "*", "/", "%", "&", "|", "^", "~", "!", "&&", "||", "<<", ">>", "==", "!=", "<", "<=", ">", ">=", +}; + +const char *osc_tok_kind_name(int kind) +{ + return (kind >= 0 && kind < OT__COUNT) ? kind_names[kind] : "?"; +} + +void osc_tok_text(const char *src, const OscToken *t, char *buf, size_t cap) +{ + size_t n = t->len; + if (cap == 0) return; + if (n >= cap) n = cap - 1; + memcpy(buf, src + t->off, n); + buf[n] = 0; +} + +static int is_alpha(int c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'; } +static int is_digit(int c) { return c >= '0' && c <= '9'; } +static int digit_val(int c) +{ + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return 99; +} + +int osc_lex(const char *src, size_t len, OscToken *toks, uint32_t cap, uint32_t *ntok, OscDiag *d) +{ + size_t i = 0; + uint32_t line = 1, col = 1, n = 0; +#define ADV() do { if (src[i] == '\n') { line++; col = 1; } else col++; i++; } while (0) + for (;;) { + /* skip whitespace and comments */ + while (i < len) { + char c = src[i]; + if (c == ' ' || c == '\t' || c == '\r' || c == '\n') { ADV(); continue; } + if (c == '/' && i + 1 < len && src[i + 1] == '/') { + while (i < len && src[i] != '\n') ADV(); + continue; + } + if (c == '/' && i + 1 < len && src[i + 1] == '*') { + uint32_t sl = line, sc = col; + ADV(); ADV(); + while (i < len && !(src[i] == '*' && i + 1 < len && src[i + 1] == '/')) ADV(); + if (i >= len) { + osc_diag_set(d, OSC_DIAG_SYNTAX, sl, sc, "/*", 0, NULL, "unterminated comment", + "unterminated /* comment"); + return -1; + } + ADV(); ADV(); + continue; + } + break; + } + if (n >= cap) { + osc_diag_set(d, OSC_DIAG_CAPACITY, line, col, "unit", 0, NULL, "token capacity", + "more than %u tokens", cap); + return -1; + } + OscToken *t = &toks[n]; + memset(t, 0, sizeof *t); + t->line = line; + t->col = col; + t->off = (uint32_t)i; + if (i >= len) { t->kind = OT_EOF; n++; break; } + char c = src[i]; + if (is_alpha(c)) { + size_t s = i; + while (i < len && (is_alpha(src[i]) || is_digit(src[i]))) ADV(); + t->len = (uint32_t)(i - s); + char buf[OSC_LEX_NAME_MAX + 1]; + if (t->len > OSC_LEX_NAME_MAX) { + osc_tok_text(src, t, buf, sizeof buf); + osc_diag_set(d, OSC_DIAG_CAPACITY, t->line, t->col, buf, 0, NULL, "identifier length", + "identifier longer than %d characters", OSC_LEX_NAME_MAX); + return -1; + } + osc_tok_text(src, t, buf, sizeof buf); + t->kind = OT_NAME; + for (size_t k = 0; k < sizeof keywords / sizeof keywords[0]; k++) + if (strcmp(buf, keywords[k].w) == 0) t->kind = (uint16_t)keywords[k].k; + for (size_t k = 0; k < sizeof reserved / sizeof reserved[0]; k++) + if (strcmp(buf, reserved[k]) == 0) t->kind = OT_RESERVED; + n++; + continue; + } + if (is_digit(c)) { + size_t s = i; + unsigned base = 10; + if (c == '0' && i + 1 < len && (src[i + 1] == 'x' || src[i + 1] == 'b')) { + base = src[i + 1] == 'x' ? 16 : 2; + ADV(); ADV(); + } + size_t ds = i; + int overflow = 0; + uint64_t v = 0; + while (i < len && (is_alpha(src[i]) || is_digit(src[i]))) { + int dv = digit_val(src[i]); + if (dv >= (int)base) break; + if (v > (UINT64_MAX - (uint64_t)dv) / base) overflow = 1; + v = v * base + (uint64_t)dv; + ADV(); + } + t->len = (uint32_t)(i - s); + char buf[64]; + if (i == ds || (i < len && (is_alpha(src[i]) || is_digit(src[i])))) { + while (i < len && (is_alpha(src[i]) || is_digit(src[i]))) ADV(); + t->len = (uint32_t)(i - s); + osc_tok_text(src, t, buf, sizeof buf); + osc_diag_set(d, OSC_DIAG_SYNTAX, t->line, t->col, buf, 0, NULL, "malformed literal", + "malformed integer literal '%s'", buf); + return -1; + } + if (overflow) { + osc_tok_text(src, t, buf, sizeof buf); + osc_diag_set(d, OSC_DIAG_OVERFLOW_UNSAFE, t->line, t->col, buf, 0, NULL, "literal wider than 64 bits", + "integer literal does not fit in 64 bits"); + return -1; + } + t->kind = OT_INT; + t->ival = v; + n++; + continue; + } + /* punctuation: longest match first */ + static const struct { const char *s; int k; } punct[] = { + {"->", OT_ARROW}, {"..", OT_DOTDOT}, {"&&", OT_ANDAND}, {"||", OT_OROR}, {"<<", OT_SHL}, + {">>", OT_SHR}, {"==", OT_EQ}, {"!=", OT_NE}, {"<=", OT_LE}, {">=", OT_GE}, + {"(", OT_LPAREN}, {")", OT_RPAREN}, {"{", OT_LBRACE}, {"}", OT_RBRACE}, {"[", OT_LBRACK}, + {"]", OT_RBRACK}, {",", OT_COMMA}, {";", OT_SEMI}, {":", OT_COLON}, {"=", OT_ASSIGN}, + {"+", OT_PLUS}, {"-", OT_MINUS}, {"*", OT_STAR}, {"/", OT_SLASH}, {"%", OT_PERCENT}, + {"&", OT_AMP}, {"|", OT_PIPE}, {"^", OT_CARET}, {"~", OT_TILDE}, {"!", OT_BANG}, + {"<", OT_LT}, {">", OT_GT}, + }; + int found = 0; + for (size_t k = 0; k < sizeof punct / sizeof punct[0]; k++) { + size_t pl = strlen(punct[k].s); + if (i + pl <= len && memcmp(src + i, punct[k].s, pl) == 0) { + t->kind = (uint16_t)punct[k].k; + t->len = (uint32_t)pl; + for (size_t q = 0; q < pl; q++) ADV(); + found = 1; + break; + } + } + if (!found) { + char buf[8]; + unsigned char uc = (unsigned char)c; + if (uc >= 0x20 && uc < 0x7f) { buf[0] = (char)uc; buf[1] = 0; } + else + { + static const char hx[] = "0123456789abcdef"; + buf[0] = '\\'; buf[1] = 'x'; buf[2] = hx[uc >> 4]; buf[3] = hx[uc & 15]; buf[4] = 0; + } + osc_diag_set(d, OSC_DIAG_SYNTAX, line, col, buf, 0, NULL, "unexpected character", + "unexpected character '%s'", buf); + return -1; + } + n++; + } +#undef ADV + *ntok = n; + return 0; +} diff --git a/src/compiler/osc_lex.h b/src/compiler/osc_lex.h new file mode 100644 index 000000000..ba0bb4e1a --- /dev/null +++ b/src/compiler/osc_lex.h @@ -0,0 +1,49 @@ +/* + * osc_lex.h -- OSC-1 lexer (docs/osc/OSC-1-DESIGN.md section 2; literal, + * comment and identifier spelling as in spec/omega-language-v0.md). + * Multi-line source, fixed-capacity token array, no allocation. + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#ifndef OSC_LEX_H +#define OSC_LEX_H + +#include +#include +#include "osc_diag.h" + +#define OSC_LEX_MAX_TOKENS 32768 +#define OSC_LEX_NAME_MAX 63 /* identifier length limit (V0) */ + +typedef enum { + OT_EOF = 0, OT_NAME, OT_INT, OT_RESERVED, + /* keywords */ + OT_FN, OT_LET, OT_MUT, OT_OWN, OT_ALLOC, OT_IF, OT_ELSE, OT_WHILE, OT_BOUND, OT_FOR, OT_IN, + OT_RETURN, OT_REQUIRES, OT_ENSURES, OT_AS, OT_TRUE, OT_FALSE, + OT_U8, OT_U16, OT_U32, OT_U64, OT_I8, OT_I16, OT_I32, OT_I64, OT_BOOL, + /* punctuation */ + OT_LPAREN, OT_RPAREN, OT_LBRACE, OT_RBRACE, OT_LBRACK, OT_RBRACK, OT_COMMA, OT_SEMI, OT_COLON, + OT_ARROW, OT_DOTDOT, OT_ASSIGN, + OT_PLUS, OT_MINUS, OT_STAR, OT_SLASH, OT_PERCENT, OT_AMP, OT_PIPE, OT_CARET, OT_TILDE, OT_BANG, + OT_ANDAND, OT_OROR, OT_SHL, OT_SHR, OT_EQ, OT_NE, OT_LT, OT_LE, OT_GT, OT_GE, + OT__COUNT +} OscTokKind; + +typedef struct { + uint16_t kind; /* OscTokKind */ + uint32_t line, col; /* 1-based */ + uint32_t off, len; /* spelling in the source */ + uint64_t ival; /* OT_INT value */ +} OscToken; + +/* Tokenise src[0..len). 0 ok (toks ends with OT_EOF), -1 with *d filled: + * SYNTAX (bad character, unterminated comment, malformed literal), + * OVERFLOW_UNSAFE (literal wider than 64 bits), CAPACITY (too many tokens, + * identifier longer than 63 characters). */ +int osc_lex(const char *src, size_t len, OscToken *toks, uint32_t cap, uint32_t *ntok, OscDiag *d); + +/* Copy a token's spelling (truncated to cap-1). */ +void osc_tok_text(const char *src, const OscToken *t, char *buf, size_t cap); +/* Printable name of a token kind ("fn", "(", "NAME", ...). */ +const char *osc_tok_kind_name(int kind); + +#endif /* OSC_LEX_H */ diff --git a/src/compiler/osc_lower.c b/src/compiler/osc_lower.c new file mode 100644 index 000000000..49b96e9e5 --- /dev/null +++ b/src/compiler/osc_lower.c @@ -0,0 +1,463 @@ +/* + * osc_lower.c -- see osc_lower.h. + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#include "osc_lower.h" +#include "osc_check.h" + +#include +#include + +typedef struct { + const OscAst *ast; + OscDiag *d; + OscFunc *f; + int fnode; + /* unordered instruction buffer, tagged with the owning block */ + OscInsn ins[OSC_MAX_INSNS]; + int16_t iblk[OSC_MAX_INSNS]; + uint32_t nins; + uint8_t closed[OSC_MAX_BLOCKS]; + int nblk; + int cur; /* current block or -1 (dead) */ + int16_t vreg[OSC_CHECK_MAX_SYMS]; + int failed; +} L; + +#define NODE(i) (&l->ast->nodes[(i)]) + +static void lcap(L *l, uint32_t line, const char *what) +{ + if (l->failed) return; + l->failed = 1; + osc_diag_set(l->d, OSC_DIAG_CAPACITY, line, 0, l->f->name, NODE(l->fnode)->line, NULL, what, + "function '%s' exceeds the IR %s", l->f->name, what); +} + +static int newv(L *l, const OscType *t, uint32_t line) +{ + if (l->f->nvregs >= OSC_MAX_VREGS) { lcap(l, line, "vreg limit"); return 0; } + l->f->vtype[l->f->nvregs] = *t; + return l->f->nvregs++; +} +static int newvs(L *l, OscScalar s, uint32_t line) +{ + OscType t = {s, OSC_REF_NONE, OSC_T_VOID, 0}; + return newv(l, &t, line); +} + +static int newblk(L *l, uint32_t line) +{ + if (l->nblk >= OSC_MAX_BLOCKS) { lcap(l, line, "block limit"); return 0; } + l->closed[l->nblk] = 0; + return l->nblk++; +} + +static OscInsn *emit(L *l, uint8_t op, uint32_t line) +{ + static OscInsn sink; + if (l->cur < 0 || l->failed) { memset(&sink, 0, sizeof sink); return &sink; } + if (l->nins >= OSC_MAX_INSNS) { lcap(l, line, "instruction limit"); memset(&sink, 0, sizeof sink); return &sink; } + OscInsn *x = &l->ins[l->nins]; + l->iblk[l->nins] = (int16_t)l->cur; + l->nins++; + memset(x, 0, sizeof *x); + x->op = op; + x->dst = x->a = x->b = x->c = x->blk_t = x->blk_f = x->callee = -1; + x->line = line; + if (op == OSC_I_BR || op == OSC_I_CBR || op == OSC_I_RET) { + l->closed[l->cur] = 1; + l->cur = -1; + } + return x; +} + +static void br(L *l, int target, uint32_t line) +{ + if (l->cur < 0) return; + OscInsn *x = emit(l, OSC_I_BR, line); + x->blk_t = (int16_t)target; +} +static void cbr(L *l, int cond, int t, int f, uint32_t line) +{ + if (l->cur < 0) return; + OscInsn *x = emit(l, OSC_I_CBR, line); + x->a = (int16_t)cond; + x->blk_t = (int16_t)t; + x->blk_f = (int16_t)f; +} +static int kconst(L *l, OscScalar s, uint64_t v, uint32_t line) +{ + int r = newvs(l, s, line); + OscInsn *x = emit(l, OSC_I_CONST, line); + x->dst = (int16_t)r; + x->imm = v; + return r; +} + +static void releases(L *l, const OscNode *n) +{ + for (uint32_t k = 0; k < n->rel_count; k++) { + int s = l->ast->rel[n->rel_start + k]; + OscInsn *x = emit(l, OSC_I_RELEASE, n->line); + x->a = l->vreg[s]; + } +} + +static int bop(int tok) +{ + switch (tok) { + case OT_PLUS: return OSC_B_ADD; + case OT_MINUS: return OSC_B_SUB; + case OT_STAR: return OSC_B_MUL; + case OT_SLASH: return OSC_B_DIV; + case OT_PERCENT: return OSC_B_REM; + case OT_AMP: return OSC_B_AND; + case OT_PIPE: return OSC_B_OR; + case OT_CARET: return OSC_B_XOR; + case OT_SHL: return OSC_B_SHL; + case OT_SHR: return OSC_B_SHR; + default: return 0; + } +} +static int cop(int tok) +{ + switch (tok) { + case OT_EQ: return OSC_C_EQ; + case OT_NE: return OSC_C_NE; + case OT_LT: return OSC_C_LT; + case OT_LE: return OSC_C_LE; + case OT_GT: return OSC_C_GT; + case OT_GE: return OSC_C_GE; + default: return 0; + } +} + +static int expr(L *l, int i); + +static int call(L *l, int i, int want_value) +{ + const OscNode *n = NODE(i); + int args[OSC_MAX_PARAMS], na = 0; + for (int a = n->a; a >= 0 && na < OSC_MAX_PARAMS; a = NODE(a)->next) { + const OscNode *an = NODE(a); + if (an->kind == ON_BORROW) args[na++] = l->vreg[an->sym]; + else if (an->kind == ON_NAME && an->sym >= 0 && l->f->vtype[l->vreg[an->sym]].s == OSC_T_REF) + args[na++] = l->vreg[an->sym]; /* own argument: moves the owner */ + else args[na++] = expr(l, a); + } + const OscNode *g = NODE(l->ast->fns[n->sym]); + int dst = -1; + if (g->ty.s != OSC_T_VOID && want_value) dst = newvs(l, g->ty.s, n->line); + else if (g->ty.s != OSC_T_VOID) dst = newvs(l, g->ty.s, n->line); /* result discarded */ + OscInsn *x = emit(l, OSC_I_CALL, n->line); + x->dst = (int16_t)dst; + x->callee = (int16_t)n->sym; + x->nargs = (uint8_t)na; + for (int k = 0; k < na; k++) x->args[k] = (int16_t)args[k]; + return dst; +} + +static int expr(L *l, int i) +{ + const OscNode *n = NODE(i); + if (n->is_const) return kconst(l, n->ty.s, n->cval, n->line); + switch (n->kind) { + case ON_BOOL: return kconst(l, OSC_T_BOOL, n->ival ? 1 : 0, n->line); + case ON_INT: return kconst(l, n->ty.s, n->cval, n->line); + case ON_NAME: return l->vreg[n->sym]; + case ON_INDEX: { + int ix = expr(l, n->a); + int r = newvs(l, n->ty.s, n->line); + OscInsn *x = emit(l, OSC_I_LOAD, n->line); + x->dst = (int16_t)r; + x->a = l->vreg[n->sym]; + x->b = (int16_t)ix; + return r; + } + case ON_CALL: return call(l, i, 1); + case ON_CAST: { + int a = expr(l, n->a); + int r = newvs(l, n->ty.s, n->line); + OscInsn *x = emit(l, OSC_I_CAST, n->line); + x->dst = (int16_t)r; + x->a = (int16_t)a; + return r; + } + case ON_UN: { + int a = expr(l, n->a); + int r = newvs(l, n->ty.s, n->line); + OscInsn *x = emit(l, OSC_I_UN, n->line); + x->sub = n->op == OT_MINUS ? OSC_U_NEG : n->op == OT_TILDE ? OSC_U_BNOT : OSC_U_LNOT; + x->dst = (int16_t)r; + x->a = (int16_t)a; + return r; + } + case ON_BIN: { + if (n->op == OT_ANDAND || n->op == OT_OROR) { + int res = newvs(l, OSC_T_BOOL, n->line); + int a = expr(l, n->a); + OscInsn *m = emit(l, OSC_I_MOV, n->line); + m->dst = (int16_t)res; + m->a = (int16_t)a; + int bb = newblk(l, n->line), jb = newblk(l, n->line); + if (n->op == OT_ANDAND) cbr(l, a, bb, jb, n->line); + else cbr(l, a, jb, bb, n->line); + l->cur = bb; + int b = expr(l, n->b); + m = emit(l, OSC_I_MOV, n->line); + m->dst = (int16_t)res; + m->a = (int16_t)b; + br(l, jb, n->line); + l->cur = jb; + return res; + } + int a = expr(l, n->a); + int b = expr(l, n->b); + int r = newvs(l, n->ty.s, n->line); + int cc = cop(n->op); + OscInsn *x = emit(l, cc ? OSC_I_CMP : OSC_I_BIN, n->line); + x->sub = (uint8_t)(cc ? cc : bop(n->op)); + x->dst = (int16_t)r; + x->a = (int16_t)a; + x->b = (int16_t)b; + return r; + } + default: + lcap(l, n->line, "lowering (unexpected expression)"); + return 0; + } +} + +static void block(L *l, int i); + +static void stmt(L *l, int i) +{ + const OscNode *n = NODE(i); + switch (n->kind) { + case ON_LET: { + int v = expr(l, n->a); + int r = newv(l, &n->ty, n->line); + l->vreg[n->sym] = (int16_t)r; + OscInsn *x = emit(l, OSC_I_MOV, n->line); + x->dst = (int16_t)r; + x->a = (int16_t)v; + break; + } + case ON_LET_ALLOC: { + int v = expr(l, n->a); + int r = newv(l, &n->ty, n->line); + l->vreg[n->sym] = (int16_t)r; + OscInsn *x = emit(l, OSC_I_ALLOC, n->line); + x->dst = (int16_t)r; + x->a = (int16_t)v; + break; + } + case ON_LET_MOVE: + case ON_LET_BORROW: { + int r = newv(l, &n->ty, n->line); + l->vreg[n->sym] = (int16_t)r; + OscInsn *x = emit(l, OSC_I_MOV, n->line); + x->dst = (int16_t)r; + x->a = l->vreg[n->sym2]; + break; + } + case ON_ASSIGN: { + const OscNode *v = NODE(n->a); + int src = v->kind == ON_BORROW ? l->vreg[n->sym2] : expr(l, n->a); + OscInsn *x = emit(l, OSC_I_MOV, n->line); + x->dst = l->vreg[n->sym]; + x->a = (int16_t)src; + break; + } + case ON_STORE: { + int ix = expr(l, n->a); + int v = expr(l, n->b); + OscInsn *x = emit(l, OSC_I_STORE, n->line); + x->a = l->vreg[n->sym]; + x->b = (int16_t)ix; + x->c = (int16_t)v; + break; + } + case ON_IF: { + int c = expr(l, n->a); + int tb = newblk(l, n->line); + int eb = -1, jb = -1; + if (n->c >= 0) eb = newblk(l, n->line); + else jb = newblk(l, n->line); + cbr(l, c, tb, eb >= 0 ? eb : jb, n->line); + l->cur = tb; + block(l, n->b); + int then_open = l->cur; + int else_open = -1; + if (n->c >= 0) { + l->cur = eb; + if (NODE(n->c)->kind == ON_IF) stmt(l, n->c); + else block(l, n->c); + else_open = l->cur; + } + if (n->c < 0) { + if (then_open >= 0) { l->cur = then_open; br(l, jb, n->line); } + l->cur = jb; + } else if (then_open >= 0 || else_open >= 0) { + if (jb < 0) jb = newblk(l, n->line); + if (then_open >= 0) { l->cur = then_open; br(l, jb, n->line); } + if (else_open >= 0) { l->cur = else_open; br(l, jb, n->line); } + l->cur = jb; + } else { + l->cur = -1; + } + break; + } + case ON_WHILE: { + int cnt = newvs(l, OSC_T_U64, n->line); + OscInsn *x = emit(l, OSC_I_CONST, n->line); + x->dst = (int16_t)cnt; + x->imm = 0; + int lim = kconst(l, OSC_T_U64, n->ival, n->line); + int one = kconst(l, OSC_T_U64, 1, n->line); + int head = newblk(l, n->line), chk = newblk(l, n->line), trap = newblk(l, n->line); + int body = newblk(l, n->line), exit = newblk(l, n->line); + br(l, head, n->line); + l->cur = head; + int c = expr(l, n->a); + cbr(l, c, chk, exit, n->line); + l->cur = chk; + int ge = newvs(l, OSC_T_BOOL, n->line); + x = emit(l, OSC_I_CMP, n->line); + x->sub = OSC_C_GE; + x->dst = (int16_t)ge; + x->a = (int16_t)cnt; + x->b = (int16_t)lim; + cbr(l, ge, trap, body, n->line); + l->cur = trap; + x = emit(l, OSC_I_TRAP, n->line); + x->imm = OSC_TRAP_LOOP_BOUND; + br(l, exit, n->line); + l->cur = body; + x = emit(l, OSC_I_BIN, n->line); + x->sub = OSC_B_ADD; + x->dst = (int16_t)cnt; + x->a = (int16_t)cnt; + x->b = (int16_t)one; + block(l, n->b); + br(l, head, n->line); + l->cur = exit; + break; + } + case ON_FOR: { + int iv = newvs(l, OSC_T_I64, n->line); + l->vreg[n->sym] = (int16_t)iv; + OscInsn *x = emit(l, OSC_I_CONST, n->line); + x->dst = (int16_t)iv; + x->imm = (uint64_t)n->lo; + int hi = kconst(l, OSC_T_I64, (uint64_t)n->hi, n->line); + int one = kconst(l, OSC_T_I64, 1, n->line); + int head = newblk(l, n->line), body = newblk(l, n->line), exit = newblk(l, n->line); + br(l, head, n->line); + l->cur = head; + int lt = newvs(l, OSC_T_BOOL, n->line); + x = emit(l, OSC_I_CMP, n->line); + x->sub = OSC_C_LT; + x->dst = (int16_t)lt; + x->a = (int16_t)iv; + x->b = (int16_t)hi; + cbr(l, lt, body, exit, n->line); + l->cur = body; + block(l, n->b); + x = emit(l, OSC_I_BIN, n->line); + x->sub = OSC_B_ADD; + x->dst = (int16_t)iv; + x->a = (int16_t)iv; + x->b = (int16_t)one; + br(l, head, n->line); + l->cur = exit; + break; + } + case ON_RETURN: { + int v = -1; + if (n->a >= 0) v = expr(l, n->a); + releases(l, n); + OscInsn *x = emit(l, OSC_I_RET, n->line); + x->a = (int16_t)v; + break; + } + case ON_CALLSTMT: + call(l, n->a, 0); + break; + case ON_BLOCK: + block(l, i); + break; + default: + lcap(l, n->line, "lowering (unexpected statement)"); + } +} + +static void block(L *l, int i) +{ + const OscNode *n = NODE(i); + for (int s = n->a; s >= 0 && l->cur >= 0; s = NODE(s)->next) stmt(l, s); + if (l->cur >= 0) releases(l, n); +} + +static int lower_fn(L *l, int fi) +{ + const OscAst *a = l->ast; + const OscNode *fn = NODE(a->fns[fi]); + OscFunc *f = l->f; + memset(f, 0, sizeof *f); + l->fnode = a->fns[fi]; + osc_node_name(a, fn, f->name, sizeof f->name); + memcpy(f->requires_text, a->req[fi], OSC_CLAUSE_MAX); + memcpy(f->ensures_text, a->ens[fi], OSC_CLAUSE_MAX); + f->requires_text[OSC_CLAUSE_MAX - 1] = 0; + f->ensures_text[OSC_CLAUSE_MAX - 1] = 0; + f->ret = fn->ty; + l->nins = 0; + l->nblk = 0; + for (int p = fn->a; p >= 0; p = NODE(p)->next) { + const OscNode *pn = NODE(p); + int r = newv(l, &pn->ty, pn->line); + l->vreg[pn->sym] = (int16_t)r; + f->nparams++; + } + l->cur = newblk(l, fn->line); + block(l, fn->b); + if (l->cur >= 0) { + releases(l, fn); + OscInsn *x = emit(l, OSC_I_RET, (uint32_t)NODE(fn->b)->ival); + x->a = -1; + } + if (l->failed) return -1; + /* layout: blocks in creation order, instructions in emission order */ + uint32_t k = 0; + for (int b = 0; b < l->nblk; b++) { + f->blocks[b].first = k; + for (uint32_t j = 0; j < l->nins; j++) + if (l->iblk[j] == b) f->insns[k++] = l->ins[j]; + f->blocks[b].count = k - f->blocks[b].first; + } + f->ninsns = k; + f->nblocks = (uint16_t)l->nblk; + return 0; +} + +int osc_lower(const OscAst *ast, OscUnit *out, OscDiag *d) +{ + L *l = calloc(1, sizeof *l); + if (!l) { + osc_diag_set(d, OSC_DIAG_CAPACITY, 0, 0, "unit", 0, NULL, "lowering memory", "out of memory"); + return -1; + } + memset(out, 0, sizeof *out); + l->ast = ast; + l->d = d; + int rc = 0; + for (uint32_t fi = 0; fi < ast->nfns && rc == 0; fi++) { + l->f = &out->funcs[fi]; + rc = lower_fn(l, (int)fi); + } + out->nfuncs = (uint16_t)ast->nfns; + free(l); + return rc; +} diff --git a/src/compiler/osc_lower.h b/src/compiler/osc_lower.h new file mode 100644 index 000000000..a751e8d3e --- /dev/null +++ b/src/compiler/osc_lower.h @@ -0,0 +1,19 @@ +/* + * osc_lower.h -- OSC-1 lowering: checked AST (osc_check annotations) -> + * OscUnit IR (docs/osc/OSC-1-DESIGN.md section 4). Blocks, short-circuit + * && / ||, explicit while counters with OSC_I_TRAP 4, RELEASE at every scope + * exit (reverse declaration order, early returns included), bounds-checked + * LOAD/STORE (checked by the IR semantics), CALL. + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#ifndef OSC_LOWER_H +#define OSC_LOWER_H + +#include "osc_diag.h" +#include "osc_ir.h" +#include "osc_parse.h" + +/* 0 ok; -1 with *d filled (CAPACITY when a function exceeds the IR limits). */ +int osc_lower(const OscAst *ast, OscUnit *out, OscDiag *d); + +#endif /* OSC_LOWER_H */ diff --git a/src/compiler/osc_parse.c b/src/compiler/osc_parse.c new file mode 100644 index 000000000..42b8e4429 --- /dev/null +++ b/src/compiler/osc_parse.c @@ -0,0 +1,678 @@ +/* + * osc_parse.c -- OSC-1 recursive-descent parser. See osc_parse.h and + * docs/osc/OSC-1-DESIGN.md section 2 (grammar). + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#include "osc_parse.h" + +#include +#include + +#define LOOP_BOUND_MAX 1000000 + +typedef struct { + OscAst *ast; + OscDiag *d; + uint32_t pos; + int depth; +} P; + +static const OscToken *cur(P *p) { return &p->ast->toks[p->pos]; } +static int peek_kind(P *p, uint32_t k) { uint32_t i = p->pos + k; return i < p->ast->ntok ? p->ast->toks[i].kind : OT_EOF; } +static int at(P *p, int k) { return cur(p)->kind == k; } +static void adv(P *p) { if (cur(p)->kind != OT_EOF) p->pos++; } + +void osc_node_name(const OscAst *ast, const OscNode *n, char *buf, size_t cap) +{ + osc_tok_text(ast->src, &ast->toks[n->tok], buf, cap); +} + +static int syntax(P *p, const char *what) +{ + const OscToken *t = cur(p); + char buf[64]; + if (t->kind == OT_EOF) snprintf(buf, sizeof buf, "end of input"); + else osc_tok_text(p->ast->src, t, buf, sizeof buf); + if (t->kind == OT_RESERVED) + osc_diag_set(p->d, OSC_DIAG_SYNTAX, t->line, t->col, buf, 0, NULL, "reserved word", + "'%s' is reserved (destruction and effects have no surface syntax)", buf); + else + osc_diag_set(p->d, OSC_DIAG_SYNTAX, t->line, t->col, buf, 0, NULL, what, "expected %s, found '%s'", what, buf); + return -1; +} + +static int expect(P *p, int k) +{ + if (!at(p, k)) return syntax(p, osc_tok_kind_name(k)); + adv(p); + return 0; +} + +static int new_node(P *p, int kind, const OscToken *t) +{ + OscAst *a = p->ast; + if (a->nnodes >= OSC_AST_MAX_NODES) { + osc_diag_set(p->d, OSC_DIAG_CAPACITY, t->line, t->col, "unit", 0, NULL, "AST node capacity", + "more than %d AST nodes", OSC_AST_MAX_NODES); + return -1; + } + int i = (int)a->nnodes++; + OscNode *n = &a->nodes[i]; + memset(n, 0, sizeof *n); + n->kind = (uint16_t)kind; + n->line = t->line; + n->col = t->col; + n->a = n->b = n->c = n->next = -1; + n->sym = n->sym2 = -1; + n->tok = (uint32_t)(t - a->toks); + return i; +} +#define N(i) (&p->ast->nodes[(i)]) + +static int enter(P *p) +{ + if (++p->depth > OSC_AST_MAX_DEPTH) { + const OscToken *t = cur(p); + osc_diag_set(p->d, OSC_DIAG_CAPACITY, t->line, t->col, "unit", 0, NULL, "nesting depth", + "nesting deeper than %d", OSC_AST_MAX_DEPTH); + return -1; + } + return 0; +} +static void leave(P *p) { p->depth--; } + +static int scalar_of(int k) +{ + switch (k) { + case OT_U8: return OSC_T_U8; case OT_U16: return OSC_T_U16; case OT_U32: return OSC_T_U32; + case OT_U64: return OSC_T_U64; case OT_I8: return OSC_T_I8; case OT_I16: return OSC_T_I16; + case OT_I32: return OSC_T_I32; case OT_I64: return OSC_T_I64; case OT_BOOL: return OSC_T_BOOL; + default: return 0; + } +} + +static int parse_scalar(P *p, OscType *ty) +{ + int s = scalar_of(cur(p)->kind); + if (!s) return syntax(p, "a type (u8 u16 u32 u64 i8 i16 i32 i64 bool)"); + memset(ty, 0, sizeof *ty); + ty->s = (OscScalar)s; + adv(p); + return 0; +} + +/* "[" type ";" INT "]" with ref kind already consumed */ +static int parse_arr_body(P *p, OscType *ty, OscRefKind rk) +{ + OscType el; + if (expect(p, OT_LBRACK)) return -1; + if (parse_scalar(p, &el)) return -1; + if (expect(p, OT_SEMI)) return -1; + if (!at(p, OT_INT)) return syntax(p, "array length INT"); + const OscToken *lt = cur(p); + if (lt->ival == 0) { + osc_diag_set(p->d, OSC_DIAG_UNSUPPORTED, lt->line, lt->col, "array", 0, NULL, "array length 0", + "array length must be 1..%d", OSC_MAX_ARRAY_LEN); + return -1; + } + if (lt->ival > OSC_MAX_ARRAY_LEN) { + osc_diag_set(p->d, OSC_DIAG_CAPACITY, lt->line, lt->col, "array", 0, NULL, "array length", + "array length %llu > %d", (unsigned long long)lt->ival, OSC_MAX_ARRAY_LEN); + return -1; + } + adv(p); + if (expect(p, OT_RBRACK)) return -1; + memset(ty, 0, sizeof *ty); + ty->s = OSC_T_REF; + ty->ref = rk; + ty->elem = el.s; + ty->len = (uint16_t)lt->ival; + return 0; +} + +/* ptype: scalar | own[..] | &[..] | &mut[..] */ +static int parse_ptype(P *p, OscType *ty) +{ + if (at(p, OT_OWN)) { adv(p); return parse_arr_body(p, ty, OSC_REF_OWN); } + if (at(p, OT_AMP)) { + adv(p); + if (at(p, OT_MUT)) { adv(p); return parse_arr_body(p, ty, OSC_REF_MUT); } + return parse_arr_body(p, ty, OSC_REF_SHARED); + } + return parse_scalar(p, ty); +} + +static int parse_expr(P *p); +static int parse_block(P *p); + +static int parse_borrow(P *p) +{ + int n = new_node(p, ON_BORROW, cur(p)); + if (n < 0) return -1; + if (expect(p, OT_AMP)) return -1; + if (at(p, OT_MUT)) { N(n)->mut = 1; adv(p); } + if (!at(p, OT_NAME)) return syntax(p, "a name after '&'"); + N(n)->tok = p->pos; + N(n)->line = cur(p)->line; + N(n)->col = cur(p)->col; + adv(p); + return n; +} + +/* call: NAME "(" [arg {"," arg}] ")" ; cur is NAME */ +static int parse_call(P *p) +{ + int n = new_node(p, ON_CALL, cur(p)); + if (n < 0) return -1; + if (enter(p)) return -1; + adv(p); + if (expect(p, OT_LPAREN)) return -1; + int last = -1; + if (!at(p, OT_RPAREN)) { + for (;;) { + int a = at(p, OT_AMP) ? parse_borrow(p) : parse_expr(p); + if (a < 0) return -1; + if (last < 0) N(n)->a = a; else N(last)->next = a; + last = a; + if (at(p, OT_COMMA)) { adv(p); continue; } + break; + } + } + if (expect(p, OT_RPAREN)) return -1; + leave(p); + return n; +} + +static int parse_primary(P *p) +{ + const OscToken *t = cur(p); + int n; + switch (t->kind) { + case OT_INT: + n = new_node(p, ON_INT, t); + if (n < 0) return -1; + N(n)->ival = t->ival; + adv(p); + return n; + case OT_TRUE: case OT_FALSE: + n = new_node(p, ON_BOOL, t); + if (n < 0) return -1; + N(n)->ival = t->kind == OT_TRUE; + adv(p); + return n; + case OT_NAME: + if (peek_kind(p, 1) == OT_LPAREN) return parse_call(p); + if (peek_kind(p, 1) == OT_LBRACK) { + n = new_node(p, ON_INDEX, t); + if (n < 0) return -1; + adv(p); adv(p); + int ix = parse_expr(p); + if (ix < 0) return -1; + N(n)->a = ix; + if (expect(p, OT_RBRACK)) return -1; + return n; + } + n = new_node(p, ON_NAME, t); + if (n < 0) return -1; + adv(p); + return n; + case OT_LPAREN: { + if (enter(p)) return -1; + adv(p); + int e = parse_expr(p); + if (e < 0) return -1; + if (expect(p, OT_RPAREN)) return -1; + leave(p); + return e; + } + case OT_AMP: + osc_diag_set(p->d, OSC_DIAG_UNSUPPORTED, t->line, t->col, "&", 0, NULL, "borrow in expression", + "a borrow may only be a call argument or a borrow binding's value"); + return -1; + default: + return syntax(p, "an expression"); + } +} + +static int parse_postfix(P *p) +{ + int e = parse_primary(p); + if (e < 0) return -1; + if (at(p, OT_AS)) { + int n = new_node(p, ON_CAST, cur(p)); + if (n < 0) return -1; + adv(p); + if (parse_scalar(p, &N(n)->ty)) return -1; + N(n)->a = e; + N(n)->line = N(e)->line; + N(n)->col = N(e)->col; + if (at(p, OT_AS)) return syntax(p, "';' (chained 'as' needs parentheses)"); + return n; + } + return e; +} + +static int parse_unary(P *p) +{ + int k = cur(p)->kind; + if (k == OT_MINUS || k == OT_TILDE || k == OT_BANG) { + if (enter(p)) return -1; + int n = new_node(p, ON_UN, cur(p)); + if (n < 0) return -1; + adv(p); + int a = parse_unary(p); + leave(p); + if (a < 0) return -1; + N(n)->op = (uint16_t)k; + N(n)->a = a; + return n; + } + return parse_postfix(p); +} + +/* binary precedence levels, lowest first */ +static const int levels[][3] = { + {OT_OROR, 0, 0}, {OT_ANDAND, 0, 0}, {0, 0, 0} /* cmp */, {OT_PIPE, 0, 0}, {OT_CARET, 0, 0}, + {OT_AMP, 0, 0}, {OT_SHL, OT_SHR, 0}, {OT_PLUS, OT_MINUS, 0}, {OT_STAR, OT_SLASH, OT_PERCENT}, +}; +#define NLEVELS ((int)(sizeof levels / sizeof levels[0])) +#define CMP_LEVEL 2 + +static int is_cmp(int k) { return k == OT_EQ || k == OT_NE || k == OT_LT || k == OT_LE || k == OT_GT || k == OT_GE; } + +static int parse_level(P *p, int lv) +{ + if (lv >= NLEVELS) return parse_unary(p); + int l = parse_level(p, lv + 1); + if (l < 0) return -1; + if (lv == CMP_LEVEL) { + if (is_cmp(cur(p)->kind)) { + int n = new_node(p, ON_BIN, cur(p)); + if (n < 0) return -1; + N(n)->op = cur(p)->kind; + adv(p); + int r = parse_level(p, lv + 1); + if (r < 0) return -1; + N(n)->a = l; + N(n)->b = r; + l = n; + if (is_cmp(cur(p)->kind)) return syntax(p, "no second comparison (comparisons do not chain)"); + } + return l; + } + for (;;) { + int k = cur(p)->kind; + if (k == 0 || !(k == levels[lv][0] || k == levels[lv][1] || k == levels[lv][2])) break; + int n = new_node(p, ON_BIN, cur(p)); + if (n < 0) return -1; + N(n)->op = (uint16_t)k; + adv(p); + int r = parse_level(p, lv + 1); + if (r < 0) return -1; + N(n)->a = l; + N(n)->b = r; + l = n; + } + return l; +} + +static int parse_expr(P *p) { return parse_level(p, 0); } + +static int parse_name_tok(P *p, int n) +{ + if (!at(p, OT_NAME)) return syntax(p, "a name"); + N(n)->tok = p->pos; + adv(p); + return 0; +} + +static int parse_int_signed(P *p, int64_t *out) +{ + int neg = 0; + if (at(p, OT_MINUS)) { neg = 1; adv(p); } + if (!at(p, OT_INT)) return syntax(p, "an integer literal"); + const OscToken *t = cur(p); + if (t->ival > (uint64_t)INT64_MAX + (uint64_t)neg) { + osc_diag_set(p->d, OSC_DIAG_OVERFLOW_UNSAFE, t->line, t->col, "for", 0, NULL, "literal does not fit i64", + "for-loop end does not fit i64"); + return -1; + } + *out = neg ? (int64_t)(0 - t->ival) : (int64_t)t->ival; + adv(p); + return 0; +} + +static int parse_if(P *p); + +static int parse_stmt(P *p) +{ + const OscToken *t = cur(p); + int n; + switch (t->kind) { + case OT_LET: { + adv(p); + int mut = 0; + if (at(p, OT_MUT)) { mut = 1; adv(p); } + n = new_node(p, ON_LET, t); + if (n < 0) return -1; + if (parse_name_tok(p, n)) return -1; + if (expect(p, OT_COLON)) return -1; + if (at(p, OT_OWN)) { + if (mut) { + const OscToken *mt = &p->ast->toks[N(n)->tok - 1]; + osc_diag_set(p->d, OSC_DIAG_SYNTAX, mt->line, mt->col, "mut", 0, NULL, "let mut owner", + "an owner binding cannot be 'mut' (owners are never reassigned)"); + return -1; + } + adv(p); + if (parse_arr_body(p, &N(n)->ty, OSC_REF_OWN)) return -1; + if (expect(p, OT_ASSIGN)) return -1; + if (at(p, OT_ALLOC)) { + adv(p); + N(n)->kind = ON_LET_ALLOC; + if (expect(p, OT_LPAREN)) return -1; + int e = parse_expr(p); + if (e < 0) return -1; + N(n)->a = e; + if (expect(p, OT_RPAREN)) return -1; + } else if (at(p, OT_NAME)) { + N(n)->kind = ON_LET_MOVE; + int s = new_node(p, ON_NAME, cur(p)); + if (s < 0) return -1; + adv(p); + N(n)->a = s; + } else { + return syntax(p, "'alloc' or an owner name"); + } + } else if (at(p, OT_AMP)) { + N(n)->kind = ON_LET_BORROW; + N(n)->mut = (uint8_t)mut; + adv(p); + OscRefKind rk = OSC_REF_SHARED; + if (at(p, OT_MUT)) { rk = OSC_REF_MUT; adv(p); } + if (parse_arr_body(p, &N(n)->ty, rk)) return -1; + if (expect(p, OT_ASSIGN)) return -1; + if (!at(p, OT_AMP)) return syntax(p, "a borrow '&name' or '&mut name'"); + int b = parse_borrow(p); + if (b < 0) return -1; + N(n)->a = b; + } else { + N(n)->mut = (uint8_t)mut; + if (parse_scalar(p, &N(n)->ty)) return -1; + if (expect(p, OT_ASSIGN)) return -1; + int e = parse_expr(p); + if (e < 0) return -1; + N(n)->a = e; + } + if (expect(p, OT_SEMI)) return -1; + return n; + } + case OT_NAME: { + int k1 = peek_kind(p, 1); + if (k1 == OT_LPAREN) { + n = new_node(p, ON_CALLSTMT, t); + if (n < 0) return -1; + int c = parse_call(p); + if (c < 0) return -1; + N(n)->a = c; + if (expect(p, OT_SEMI)) return -1; + return n; + } + if (k1 == OT_ASSIGN) { + n = new_node(p, ON_ASSIGN, t); + if (n < 0) return -1; + adv(p); adv(p); + int e = at(p, OT_AMP) ? parse_borrow(p) : parse_expr(p); + if (e < 0) return -1; + N(n)->a = e; + if (expect(p, OT_SEMI)) return -1; + return n; + } + if (k1 == OT_LBRACK) { + n = new_node(p, ON_STORE, t); + if (n < 0) return -1; + adv(p); adv(p); + int ix = parse_expr(p); + if (ix < 0) return -1; + if (expect(p, OT_RBRACK)) return -1; + if (expect(p, OT_ASSIGN)) return -1; + if (at(p, OT_AMP)) { + const OscToken *bt = cur(p); + char nm[64]; + osc_node_name(p->ast, N(n), nm, sizeof nm); + osc_diag_set(p->d, OSC_DIAG_BORROW_OUTLIVES_OWNER, bt->line, bt->col, nm, 0, NULL, + "store borrow into array", "a borrow cannot be stored anywhere but a borrow binding"); + return -1; + } + int v = parse_expr(p); + if (v < 0) return -1; + N(n)->a = ix; + N(n)->b = v; + if (expect(p, OT_SEMI)) return -1; + return n; + } + adv(p); + return syntax(p, "'=', '[' or '(' after a name at statement start"); + } + case OT_IF: + return parse_if(p); + case OT_WHILE: { + n = new_node(p, ON_WHILE, t); + if (n < 0) return -1; + adv(p); + int c = parse_expr(p); + if (c < 0) return -1; + N(n)->a = c; + if (!at(p, OT_BOUND)) { + osc_diag_set(p->d, OSC_DIAG_UNBOUNDED_LOOP, t->line, t->col, "while", 0, NULL, "while without bound", + "'while' needs 'bound N' (static trip-count bound)"); + return -1; + } + adv(p); + if (!at(p, OT_INT)) return syntax(p, "bound INT"); + const OscToken *bt = cur(p); + if (bt->ival == 0 || bt->ival > LOOP_BOUND_MAX) { + osc_diag_set(p->d, OSC_DIAG_UNBOUNDED_LOOP, bt->line, bt->col, "while", t->line, NULL, + "bound outside 1..1000000", "loop bound %llu outside 1..%d", + (unsigned long long)bt->ival, LOOP_BOUND_MAX); + return -1; + } + N(n)->ival = bt->ival; + N(n)->flag = 1; + adv(p); + int b = parse_block(p); + if (b < 0) return -1; + N(n)->b = b; + return n; + } + case OT_FOR: { + n = new_node(p, ON_FOR, t); + if (n < 0) return -1; + adv(p); + if (parse_name_tok(p, n)) return -1; + if (expect(p, OT_IN)) return -1; + const OscToken *lt = cur(p); + if (parse_int_signed(p, &N(n)->lo)) return -1; + if (expect(p, OT_DOTDOT)) return -1; + if (parse_int_signed(p, &N(n)->hi)) return -1; + if (N(n)->hi < N(n)->lo || (uint64_t)(N(n)->hi - N(n)->lo) > LOOP_BOUND_MAX) { + char nm[64]; + osc_node_name(p->ast, N(n), nm, sizeof nm); + osc_diag_set(p->d, OSC_DIAG_UNBOUNDED_LOOP, lt->line, lt->col, nm, t->line, NULL, + "for range outside 0..1000000 trips", "for range must satisfy A <= B and B - A <= %d", + LOOP_BOUND_MAX); + return -1; + } + int b = parse_block(p); + if (b < 0) return -1; + N(n)->b = b; + return n; + } + case OT_RETURN: { + n = new_node(p, ON_RETURN, t); + if (n < 0) return -1; + adv(p); + if (!at(p, OT_SEMI)) { + int e = at(p, OT_AMP) ? parse_borrow(p) : parse_expr(p); + if (e < 0) return -1; + N(n)->a = e; + } + if (expect(p, OT_SEMI)) return -1; + return n; + } + case OT_LBRACE: + return parse_block(p); + default: + return syntax(p, "a statement"); + } +} + +static int parse_if(P *p) +{ + if (enter(p)) return -1; + int n = new_node(p, ON_IF, cur(p)); + if (n < 0) return -1; + adv(p); + int c = parse_expr(p); + if (c < 0) return -1; + N(n)->a = c; + int b = parse_block(p); + if (b < 0) return -1; + N(n)->b = b; + if (at(p, OT_ELSE)) { + adv(p); + int e = at(p, OT_IF) ? parse_if(p) : parse_block(p); + if (e < 0) return -1; + N(n)->c = e; + } + leave(p); + return n; +} + +static int parse_block(P *p) +{ + if (enter(p)) return -1; + int n = new_node(p, ON_BLOCK, cur(p)); + if (n < 0) return -1; + if (expect(p, OT_LBRACE)) return -1; + int last = -1; + while (!at(p, OT_RBRACE)) { + if (at(p, OT_EOF)) return syntax(p, "'}'"); + int s = parse_stmt(p); + if (s < 0) return -1; + if (last < 0) N(n)->a = s; else N(last)->next = s; + last = s; + } + N(n)->ival = cur(p)->line; /* closing brace line */ + adv(p); + leave(p); + return n; +} + +/* clause text: token spellings joined by single spaces, none after '(' or before ')' */ +static int parse_clause(P *p, char *out, const OscToken *kw) +{ + size_t len = 0; + int depth = 0, prev = -1; + out[0] = 0; + for (;;) { + int k = cur(p)->kind; + if (k == OT_EOF) return syntax(p, "a function body '{'"); + if (depth == 0 && (k == OT_LBRACE || k == OT_ENSURES)) break; + if (k == OT_LPAREN) depth++; + if (k == OT_RPAREN && depth > 0) depth--; + const OscToken *t = cur(p); + int sp = len > 0 && prev != OT_LPAREN && k != OT_RPAREN; + if (len + (size_t)sp + t->len + 1 > OSC_CLAUSE_MAX) { + osc_diag_set(p->d, OSC_DIAG_CAPACITY, kw->line, kw->col, osc_tok_kind_name(kw->kind), 0, NULL, + "contract text length", "contract clause longer than %d bytes", OSC_CLAUSE_MAX - 1); + return -1; + } + if (sp) out[len++] = ' '; + memcpy(out + len, p->ast->src + t->off, t->len); + len += t->len; + out[len] = 0; + prev = k; + adv(p); + } + return 0; +} + +static int parse_fn(P *p) +{ + OscAst *a = p->ast; + const OscToken *ft = cur(p); + if (expect(p, OT_FN)) return -1; + if (a->nfns >= OSC_MAX_FUNCS) { + osc_diag_set(p->d, OSC_DIAG_CAPACITY, ft->line, ft->col, "unit", 0, NULL, "function capacity", + "more than %d functions", OSC_MAX_FUNCS); + return -1; + } + int f = new_node(p, ON_FN, ft); + if (f < 0) return -1; + if (parse_name_tok(p, f)) return -1; + N(f)->line = a->toks[N(f)->tok].line; + N(f)->col = a->toks[N(f)->tok].col; + char fname[64]; + osc_node_name(a, N(f), fname, sizeof fname); + if (expect(p, OT_LPAREN)) return -1; + int last = -1, np = 0; + if (!at(p, OT_RPAREN)) { + for (;;) { + int pn = new_node(p, ON_PARAM, cur(p)); + if (pn < 0) return -1; + if (parse_name_tok(p, pn)) return -1; + if (expect(p, OT_COLON)) return -1; + if (parse_ptype(p, &N(pn)->ty)) return -1; + if (++np > OSC_MAX_PARAMS) { + osc_diag_set(p->d, OSC_DIAG_CAPACITY, N(pn)->line, N(pn)->col, fname, N(f)->line, NULL, + "parameter count", "function '%s' has more than %d parameters", fname, OSC_MAX_PARAMS); + return -1; + } + if (last < 0) N(f)->a = pn; else N(last)->next = pn; + last = pn; + if (at(p, OT_COMMA)) { adv(p); continue; } + break; + } + } + if (expect(p, OT_RPAREN)) return -1; + N(f)->ty.s = OSC_T_VOID; + if (at(p, OT_ARROW)) { + adv(p); + if (at(p, OT_OWN) || at(p, OT_AMP) || at(p, OT_LBRACK)) { + const OscToken *t = cur(p); + osc_diag_set(p->d, OSC_DIAG_UNSUPPORTED, t->line, t->col, fname, N(f)->line, NULL, + "array return type", "OSC-1 functions return a scalar only"); + return -1; + } + if (parse_scalar(p, &N(f)->ty)) return -1; + } + uint32_t fi = a->nfns; + a->req[fi][0] = a->ens[fi][0] = 0; + if (at(p, OT_REQUIRES)) { + const OscToken *kw = cur(p); + adv(p); + if (parse_clause(p, a->req[fi], kw)) return -1; + } + if (at(p, OT_ENSURES)) { + const OscToken *kw = cur(p); + adv(p); + if (parse_clause(p, a->ens[fi], kw)) return -1; + } + int b = parse_block(p); + if (b < 0) return -1; + N(f)->b = b; + a->fns[a->nfns++] = f; + return 0; +} + +int osc_parse(OscAst *ast, OscDiag *d) +{ + P p = {ast, d, 0, 0}; + ast->nnodes = 0; + ast->nfns = 0; + ast->nrel = 0; + while (!at(&p, OT_EOF)) + if (parse_fn(&p)) return -1; + return 0; +} diff --git a/src/compiler/osc_parse.h b/src/compiler/osc_parse.h new file mode 100644 index 000000000..3a6d5877f --- /dev/null +++ b/src/compiler/osc_parse.h @@ -0,0 +1,96 @@ +/* + * osc_parse.h -- OSC-1 recursive-descent parser producing the disposable + * typed AST (docs/osc/OSC-1-DESIGN.md section 2). Fixed node arena, bounded + * recursion depth; running out of either is a CAPACITY diagnostic. + * The checker (osc_check.*) annotates the same nodes with types, resolved + * symbols, folded constants and release lists; the lowerer (osc_lower.*) + * reads them. + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#ifndef OSC_PARSE_H +#define OSC_PARSE_H + +#include +#include "osc_diag.h" +#include "osc_ir.h" +#include "osc_lex.h" + +#define OSC_AST_MAX_NODES 16384 +#define OSC_AST_MAX_DEPTH 64 /* nesting of blocks + expressions */ +#define OSC_AST_MAX_REL 16384 /* release-list entries (checker) */ + +typedef enum { + ON_NONE = 0, + /* top level */ + ON_FN, /* tok = name; a = first ON_PARAM; b = body ON_BLOCK; ty = ret (VOID if none) */ + ON_PARAM, /* tok = name; ty = scalar or REF type */ + /* statements */ + ON_BLOCK, /* a = first stmt (linked by next); rel = releases at normal block end */ + ON_LET, /* mut; tok; ty = scalar; a = expr */ + ON_LET_ALLOC, /* tok; ty = REF OWN; a = init expr */ + ON_LET_MOVE, /* tok; ty = REF OWN; a = ON_NAME source */ + ON_LET_BORROW, /* mut (binding reassignable); tok; ty = REF SHARED/MUT; a = ON_BORROW */ + ON_ASSIGN, /* tok = target; a = expr or ON_BORROW */ + ON_STORE, /* tok = array; a = index; b = value */ + ON_IF, /* a = cond; b = then block; c = else (ON_BLOCK or ON_IF) or -1 */ + ON_WHILE, /* a = cond; b = body block; ival = bound; flag = 1 if a bound was given */ + ON_FOR, /* tok = loop var; b = body block; lo, hi = literal ends (half-open) */ + ON_RETURN, /* a = expr / ON_BORROW / -1; rel = releases before RET */ + ON_CALLSTMT, /* a = ON_CALL */ + /* expressions */ + ON_INT, /* ival */ + ON_BOOL, /* ival 0/1 */ + ON_NAME, /* tok */ + ON_INDEX, /* tok = array; a = index */ + ON_CALL, /* tok = callee; a = first arg (linked by next) */ + ON_BORROW, /* tok = name; mut */ + ON_BIN, /* op = OscTokKind of the operator (incl. && ||); a, b */ + ON_UN, /* op = OT_MINUS / OT_TILDE / OT_BANG; a */ + ON_CAST /* a; ty = target scalar */ +} OscNodeKind; + +typedef struct { + uint16_t kind; /* OscNodeKind */ + uint16_t op; /* operator token kind */ + uint32_t line, col; + int32_t a, b, c; /* children (-1 = none) */ + int32_t next; /* sibling link (-1 = end) */ + uint32_t tok; /* name token index */ + uint64_t ival; + int64_t lo, hi; /* ON_FOR literal ends */ + OscType ty; /* declared type (decls, params, casts, fn ret) / result type (exprs, checker) */ + uint8_t mut; + uint8_t flag; + /* checker annotations */ + uint8_t is_const; /* expression folded to cval (already canonical for ty) */ + uint64_t cval; + int32_t sym; /* resolved symbol (names, decls, params) or callee function index (calls) */ + int32_t sym2; /* ON_LET_MOVE / ON_ASSIGN-borrow / ON_BORROW source symbol */ + uint32_t rel_start; /* release list: indices into OscAst.rel */ + uint16_t rel_count; +} OscNode; + +typedef struct { + const char *src; + const OscToken *toks; + uint32_t ntok; + OscNode nodes[OSC_AST_MAX_NODES]; + uint32_t nnodes; + int32_t fns[OSC_MAX_FUNCS]; + uint32_t nfns; + char req[OSC_MAX_FUNCS][OSC_CLAUSE_MAX]; + char ens[OSC_MAX_FUNCS][OSC_CLAUSE_MAX]; + /* filled by the checker: symbol ids of owners to release, in emission order */ + int16_t rel[OSC_AST_MAX_REL]; + uint32_t nrel; +} OscAst; + +/* Parse the token stream into ast (ast->src/toks/ntok must be set). 0 ok, -1 + * with *d filled (SYNTAX, UNSUPPORTED, CAPACITY, UNBOUNDED_LOOP for a while + * without bound). */ +int osc_parse(OscAst *ast, OscDiag *d); + +/* Copy the spelling of node->tok. */ +void osc_node_name(const OscAst *ast, const OscNode *n, char *buf, size_t cap); + +#endif /* OSC_PARSE_H */ diff --git a/src/compiler/oscc_main.c b/src/compiler/oscc_main.c new file mode 100644 index 000000000..624fb747b --- /dev/null +++ b/src/compiler/oscc_main.c @@ -0,0 +1,76 @@ +/* + * oscc_main.c -- `oscc `: compile an OSC-1 source file to IR and + * AArch64 machine code and print their identities: + * ir_sha256= code_sha256= funcs= + * On a refusal print the diagnostic fields and exit 1. + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#include +#include +#include + +#include "osc_cg.h" +#include "osc_front.h" +#include "sha256.h" + +static void hex(const uint8_t *d, char *out) +{ + static const char h[] = "0123456789abcdef"; + for (int i = 0; i < 32; i++) { out[2 * i] = h[d[i] >> 4]; out[2 * i + 1] = h[d[i] & 15]; } + out[64] = 0; +} + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "usage: oscc \n"); + return 2; + } + FILE *fp = fopen(argv[1], "rb"); + if (!fp) { fprintf(stderr, "oscc: cannot open %s\n", argv[1]); return 2; } + size_t cap = 1 << 16, len = 0; + char *src = malloc(cap); + for (;;) { + if (!src) { fclose(fp); fprintf(stderr, "oscc: out of memory\n"); return 2; } + size_t r = fread(src + len, 1, cap - len, fp); + len += r; + if (len < cap) break; + if (cap >= (1u << 24)) { fclose(fp); free(src); fprintf(stderr, "oscc: file too large\n"); return 2; } + cap *= 2; + char *n = realloc(src, cap); + if (!n) free(src); + src = n; + } + fclose(fp); + OscUnit *u = malloc(sizeof *u); + OscDiag d; + if (!u) { free(src); fprintf(stderr, "oscc: out of memory\n"); return 2; } + if (osc_compile(src, len, u, &d, NULL)) { + printf("error kind=%s line=%u col=%u object=%s origin_line=%u other=%s transition=%s\n", + osc_diag_kind_name(d.kind), d.line, d.col, d.object, d.origin_line, d.other, d.transition); + printf("message=%s\n", d.message); + free(u); + free(src); + return 1; + } + uint8_t dig[32]; + char hx[65], err[160]; + OscCode code; + memset(&code, 0, sizeof code); + if (osc_ir_digest(u, dig) || osc_cg_compile(u, &code, err, sizeof err)) { + printf("error kind=backend message=%s\n", err); + free(u); + free(src); + return 1; + } + hex(dig, hx); + printf("ir_sha256=%s\n", hx); + sha256_hash(code.code, code.len, dig); + hex(dig, hx); + printf("code_sha256=%s\n", hx); + printf("funcs=%u\n", (unsigned)u->nfuncs); + osc_cg_free(&code); + free(u); + free(src); + return 0; +} diff --git a/tests/compiler/determinism.sh b/tests/compiler/determinism.sh new file mode 100755 index 000000000..241006960 --- /dev/null +++ b/tests/compiler/determinism.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# OSC-1 determinism gate (DESIGN section 8): compile every golden program +# twice in separate processes and compare the printed IR digest, machine-code +# digest and function count byte for byte. +# Usage: tests/compiler/determinism.sh [path/to/oscc] +# Without an argument oscc is built single core under /tmp/l22c. +# Prints OSC1_DETERMINISM_PASS or OSC1_DETERMINISM_FAIL. +# OSC-1 slice; not a general Omega compiler; no self-hosting. +set -u +here=$(cd "$(dirname "$0")" && pwd) +root=$(cd "$here/../.." && pwd) +out=/tmp/l22c/det +mkdir -p "$out" || exit 1 +if [ $# -ge 1 ]; then + oscc=$1 +else + oscc=/tmp/l22c/oscc + srcs="" + for f in "$root"/src/compiler/*.c; do + case "$f" in + */oscc_main.c) ;; + *) srcs="$srcs $f" ;; + esac + done + # shellcheck disable=SC2086 + nice cc -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -O2 \ + -I"$root/src" -I"$root/src/compiler" -I"$root/src/compiler/model" \ + -o "$oscc" "$root/src/compiler/oscc_main.c" $srcs "$root/src/sha256.c" || { + echo "OSC1_DETERMINISM_FAIL build" + exit 1 + } +fi +n=0 +bad=0 +for p in "$root"/tests/compiler/progs/*.osc; do + b=$(basename "$p" .osc) + nice "$oscc" "$p" > "$out/$b.1" 2>&1; r1=$? + nice "$oscc" "$p" > "$out/$b.2" 2>&1; r2=$? + n=$((n + 1)) + if [ "$r1" -ne 0 ] || [ "$r2" -ne 0 ]; then + echo "FAIL $b: exit $r1 / $r2" + bad=$((bad + 1)) + elif ! cmp -s "$out/$b.1" "$out/$b.2"; then + echo "FAIL $b: outputs differ" + bad=$((bad + 1)) + elif ! grep -q '^ir_sha256=' "$out/$b.1" || ! grep -q '^code_sha256=' "$out/$b.1"; then + echo "FAIL $b: digests missing" + bad=$((bad + 1)) + fi +done +if [ "$n" -ge 1 ] && [ "$bad" -eq 0 ]; then + echo "programs=$n identical=$n" + echo "OSC1_DETERMINISM_PASS" + exit 0 +fi +echo "programs=$n failed=$bad" +echo "OSC1_DETERMINISM_FAIL" +exit 1 diff --git a/tests/compiler/neg/ambiguous_width.osc b/tests/compiler/neg/ambiguous_width.osc new file mode 100644 index 000000000..65baae301 --- /dev/null +++ b/tests/compiler/neg/ambiguous_width.osc @@ -0,0 +1,6 @@ +// expect: AMBIGUOUS_WIDTH object=y line=4 +// a bare literal as the source of `as` has no width. +fn f() -> i64 { + let y: i64 = 300 as i64; + return y; +} diff --git a/tests/compiler/neg/boo_outer_binding.osc b/tests/compiler/neg/boo_outer_binding.osc new file mode 100644 index 000000000..f91f681be --- /dev/null +++ b/tests/compiler/neg/boo_outer_binding.osc @@ -0,0 +1,11 @@ +// expect: BORROW_OUTLIVES_OWNER object=b line=8 +// transition: inner owner +fn f() -> i64 { + let a: own [i64; 4] = alloc(1); + let mut r: &[i64; 4] = &a; + { + let b: own [i64; 4] = alloc(2); + r = &b; + } + return r[0]; +} diff --git a/tests/compiler/neg/boo_reassign_reborrowed.osc b/tests/compiler/neg/boo_reassign_reborrowed.osc new file mode 100644 index 000000000..caacae6e2 --- /dev/null +++ b/tests/compiler/neg/boo_reassign_reborrowed.osc @@ -0,0 +1,11 @@ +// expect: BORROW_OUTLIVES_OWNER object=r line=9 +// transition: end borrow while reborrowed +fn f() -> i64 { + let a: own [i64; 4] = alloc(1); + let b: own [i64; 4] = alloc(2); + let mut r: &[i64; 4] = &a; + let t: &[i64; 4] = &r; + let v: i64 = t[0]; + r = &b; + return v; +} diff --git a/tests/compiler/neg/boo_return_borrow.osc b/tests/compiler/neg/boo_return_borrow.osc new file mode 100644 index 000000000..17f87da5b --- /dev/null +++ b/tests/compiler/neg/boo_return_borrow.osc @@ -0,0 +1,6 @@ +// expect: BORROW_OUTLIVES_OWNER object=a line=5 +// transition: borrow returned from function +fn f() -> i64 { + let a: own [i64; 4] = alloc(1); + return &a; +} diff --git a/tests/compiler/neg/capacity_seven_params.osc b/tests/compiler/neg/capacity_seven_params.osc new file mode 100644 index 000000000..dbf772229 --- /dev/null +++ b/tests/compiler/neg/capacity_seven_params.osc @@ -0,0 +1,5 @@ +// expect: CAPACITY object=f line=3 +// at most 6 parameters (x0..x5). +fn f(a: i64, b: i64, c: i64, d: i64, e: i64, g: i64, h: i64) -> i64 { + return a + b + c + d + e + g + h; +} diff --git a/tests/compiler/neg/conditional_move.osc b/tests/compiler/neg/conditional_move.osc new file mode 100644 index 000000000..70820b990 --- /dev/null +++ b/tests/compiler/neg/conditional_move.osc @@ -0,0 +1,9 @@ +// expect: CONDITIONAL_MOVE object=a line=7 +// transition: conditional move +fn take(x: own [u8; 2]) -> u8 { return x[0]; } + +fn f(c: bool) -> u8 { + let a: own [u8; 2] = alloc(3); + if c { let s: u8 = take(a); } + return 1; +} diff --git a/tests/compiler/neg/immutable_assign.osc b/tests/compiler/neg/immutable_assign.osc new file mode 100644 index 000000000..1647ef0df --- /dev/null +++ b/tests/compiler/neg/immutable_assign.osc @@ -0,0 +1,7 @@ +// expect: IMMUTABLE_ASSIGN object=x line=5 +// assignment to a binding declared without `mut`. +fn f() -> i32 { + let x: i32 = 1; + x = 2; + return x; +} diff --git a/tests/compiler/neg/ma_call_mut_and_shared.osc b/tests/compiler/neg/ma_call_mut_and_shared.osc new file mode 100644 index 000000000..a4be042f2 --- /dev/null +++ b/tests/compiler/neg/ma_call_mut_and_shared.osc @@ -0,0 +1,7 @@ +// expect: MUTABLE_ALIAS object=a line=6 +// transition: borrow_shared while borrow_mut live +fn g(x: &mut [i32; 3], y: &[i32; 3]) { x[0] = y[1]; } +fn f() { + let a: own [i32; 3] = alloc(0); + g(&mut a, &a); +} diff --git a/tests/compiler/neg/ma_move_while_borrowed.osc b/tests/compiler/neg/ma_move_while_borrowed.osc new file mode 100644 index 000000000..421d97144 --- /dev/null +++ b/tests/compiler/neg/ma_move_while_borrowed.osc @@ -0,0 +1,8 @@ +// expect: MUTABLE_ALIAS object=a line=6 +// transition: move while borrowed +fn f() -> i32 { + let a: own [i32; 3] = alloc(0); + let r: &[i32; 3] = &a; + let b: own [i32; 3] = a; + return r[0] + b[0]; +} diff --git a/tests/compiler/neg/ma_mut_while_shared_binding.osc b/tests/compiler/neg/ma_mut_while_shared_binding.osc new file mode 100644 index 000000000..b8d2260bc --- /dev/null +++ b/tests/compiler/neg/ma_mut_while_shared_binding.osc @@ -0,0 +1,9 @@ +// expect: MUTABLE_ALIAS object=a line=6 +// transition: borrow_mut while borrow_shared live +fn f() -> i32 { + let a: own [i32; 3] = alloc(0); + let r: &[i32; 3] = &a; + let w: &mut [i32; 3] = &mut a; + w[0] = 1; + return r[0]; +} diff --git a/tests/compiler/neg/ma_read_under_mut.osc b/tests/compiler/neg/ma_read_under_mut.osc new file mode 100644 index 000000000..5d561068c --- /dev/null +++ b/tests/compiler/neg/ma_read_under_mut.osc @@ -0,0 +1,9 @@ +// expect: MUTABLE_ALIAS object=a line=6 +// transition: read while borrow_mut live +fn f() -> i32 { + let a: own [i32; 3] = alloc(0); + let w: &mut [i32; 3] = &mut a; + let v: i32 = a[0]; + w[1] = v; + return v; +} diff --git a/tests/compiler/neg/missing_return.osc b/tests/compiler/neg/missing_return.osc new file mode 100644 index 000000000..4c8905a29 --- /dev/null +++ b/tests/compiler/neg/missing_return.osc @@ -0,0 +1,7 @@ +// expect: MISSING_RETURN object=f line=7 +// a non-void function can fall off its end. +fn f(x: i32) -> i32 { + if x > 0 { + return 1; + } +} diff --git a/tests/compiler/neg/oob_static_read.osc b/tests/compiler/neg/oob_static_read.osc new file mode 100644 index 000000000..a092fec5e --- /dev/null +++ b/tests/compiler/neg/oob_static_read.osc @@ -0,0 +1,6 @@ +// expect: STATIC_OUT_OF_BOUNDS object=a line=5 +// constant index outside 0..N-1 (read). +fn f() -> i64 { + let a: own [i64; 4] = alloc(1); + return a[4]; +} diff --git a/tests/compiler/neg/oob_static_write.osc b/tests/compiler/neg/oob_static_write.osc new file mode 100644 index 000000000..d3d196466 --- /dev/null +++ b/tests/compiler/neg/oob_static_write.osc @@ -0,0 +1,6 @@ +// expect: STATIC_OUT_OF_BOUNDS object=a line=5 +// constant index outside 0..N-1 (write). +fn f() { + let a: own [i64; 4] = alloc(1); + a[-1] = 3; +} diff --git a/tests/compiler/neg/ovf_literal_shift.osc b/tests/compiler/neg/ovf_literal_shift.osc new file mode 100644 index 000000000..9e9142724 --- /dev/null +++ b/tests/compiler/neg/ovf_literal_shift.osc @@ -0,0 +1,6 @@ +// expect: OVERFLOW_UNSAFE object=y line=4 +// literal shift amount >= width. +fn f(x: u32) -> u32 { + let y: u32 = x << 32; + return y; +} diff --git a/tests/compiler/neg/ovf_literal_too_big.osc b/tests/compiler/neg/ovf_literal_too_big.osc new file mode 100644 index 000000000..5851efc79 --- /dev/null +++ b/tests/compiler/neg/ovf_literal_too_big.osc @@ -0,0 +1,6 @@ +// expect: OVERFLOW_UNSAFE object=x line=4 +// literal does not fit its type. +fn f() -> u8 { + let x: u8 = 256; + return x; +} diff --git a/tests/compiler/neg/ovf_signed_const.osc b/tests/compiler/neg/ovf_signed_const.osc new file mode 100644 index 000000000..aaa457ed6 --- /dev/null +++ b/tests/compiler/neg/ovf_signed_const.osc @@ -0,0 +1,6 @@ +// expect: OVERFLOW_UNSAFE object=x line=4 +// signed constant overflow: 100 + 100 does not fit i8. +fn f() -> i8 { + let x: i8 = 100 + 100; + return x; +} diff --git a/tests/compiler/neg/ovf_zero_divisor.osc b/tests/compiler/neg/ovf_zero_divisor.osc new file mode 100644 index 000000000..46efe7b22 --- /dev/null +++ b/tests/compiler/neg/ovf_zero_divisor.osc @@ -0,0 +1,6 @@ +// expect: OVERFLOW_UNSAFE object=y line=4 +// literal zero divisor. +fn f(x: i32) -> i32 { + let y: i32 = x / 0; + return y; +} diff --git a/tests/compiler/neg/read_only_borrow_mut_reborrow.osc b/tests/compiler/neg/read_only_borrow_mut_reborrow.osc new file mode 100644 index 000000000..9e3b7d3d1 --- /dev/null +++ b/tests/compiler/neg/read_only_borrow_mut_reborrow.osc @@ -0,0 +1,7 @@ +// expect: READ_ONLY_BORROW object=r line=6 +// transition: borrow_mut through shared borrow +fn f() { + let a: own [i64; 4] = alloc(1); + let r: &[i64; 4] = &a; + let w: &mut [i64; 4] = &mut r; +} diff --git a/tests/compiler/neg/read_only_borrow_write.osc b/tests/compiler/neg/read_only_borrow_write.osc new file mode 100644 index 000000000..c37b3ce16 --- /dev/null +++ b/tests/compiler/neg/read_only_borrow_write.osc @@ -0,0 +1,5 @@ +// expect: READ_ONLY_BORROW object=a line=4 +// transition: write through shared borrow +fn f(a: &[i64; 4]) { + a[0] = 1; +} diff --git a/tests/compiler/neg/redefined_shadow.osc b/tests/compiler/neg/redefined_shadow.osc new file mode 100644 index 000000000..4b62680b4 --- /dev/null +++ b/tests/compiler/neg/redefined_shadow.osc @@ -0,0 +1,10 @@ +// expect: REDEFINED_NAME object=x line=6 +// shadowing in an inner scope is refused. +fn f(a: i32) -> i32 { + let x: i32 = a; + if a > 0 { + let x: i32 = 2; + return x; + } + return x; +} diff --git a/tests/compiler/neg/syntax_free.osc b/tests/compiler/neg/syntax_free.osc new file mode 100644 index 000000000..a88ab1242 --- /dev/null +++ b/tests/compiler/neg/syntax_free.osc @@ -0,0 +1,6 @@ +// expect: SYNTAX object=free line=5 +// destruction has no surface syntax: `free` is reserved. +fn f() { + let a: own [i64; 4] = alloc(1); + free(a); +} diff --git a/tests/compiler/neg/tm_arity.osc b/tests/compiler/neg/tm_arity.osc new file mode 100644 index 000000000..3230837c9 --- /dev/null +++ b/tests/compiler/neg/tm_arity.osc @@ -0,0 +1,6 @@ +// expect: TYPE_MISMATCH object=g line=5 +// wrong number of arguments. +fn g(a: i32, b: i32) -> i32 { return a + b; } +fn f() -> i32 { + return g(1); +} diff --git a/tests/compiler/neg/tm_bool_arith.osc b/tests/compiler/neg/tm_bool_arith.osc new file mode 100644 index 000000000..8da3466c9 --- /dev/null +++ b/tests/compiler/neg/tm_bool_arith.osc @@ -0,0 +1,6 @@ +// expect: TYPE_MISMATCH object=z line=4 +// bool in arithmetic. +fn f(b: bool) -> i32 { + let z: i32 = b + 1; + return z; +} diff --git a/tests/compiler/neg/tm_int_condition.osc b/tests/compiler/neg/tm_int_condition.osc new file mode 100644 index 000000000..dcc0aa3fd --- /dev/null +++ b/tests/compiler/neg/tm_int_condition.osc @@ -0,0 +1,6 @@ +// expect: TYPE_MISMATCH object=if line=4 +// an integer is not a condition. +fn f(x: i32) -> i32 { + if x { return 1; } + return 0; +} diff --git a/tests/compiler/neg/tm_u32_plus_u64.osc b/tests/compiler/neg/tm_u32_plus_u64.osc new file mode 100644 index 000000000..e6d3bac7a --- /dev/null +++ b/tests/compiler/neg/tm_u32_plus_u64.osc @@ -0,0 +1,6 @@ +// expect: TYPE_MISMATCH object=z line=4 +// no implicit widening: u32 + u64 is refused. +fn f(x: u32, y: u64) -> u64 { + let z: u64 = x + y; + return z; +} diff --git a/tests/compiler/neg/uam_after_let_move.osc b/tests/compiler/neg/uam_after_let_move.osc new file mode 100644 index 000000000..f001749a1 --- /dev/null +++ b/tests/compiler/neg/uam_after_let_move.osc @@ -0,0 +1,7 @@ +// expect: USE_AFTER_MOVE object=a line=6 +// transition: use after move +fn f() -> i64 { + let a: own [i64; 4] = alloc(1); + let b: own [i64; 4] = a; + return a[0] + b[0]; +} diff --git a/tests/compiler/neg/uam_after_own_param.osc b/tests/compiler/neg/uam_after_own_param.osc new file mode 100644 index 000000000..4a1c68262 --- /dev/null +++ b/tests/compiler/neg/uam_after_own_param.osc @@ -0,0 +1,9 @@ +// expect: USE_AFTER_MOVE object=a line=8 +// transition: use after move +fn take(x: own [u8; 2]) -> u8 { return x[0]; } + +fn f() -> u8 { + let a: own [u8; 2] = alloc(3); + let s: u8 = take(a); + return s + a[1]; +} diff --git a/tests/compiler/neg/uam_move_in_loop.osc b/tests/compiler/neg/uam_move_in_loop.osc new file mode 100644 index 000000000..0fa672b62 --- /dev/null +++ b/tests/compiler/neg/uam_move_in_loop.osc @@ -0,0 +1,9 @@ +// expect: USE_AFTER_MOVE object=a line=7 +// transition: move inside loop +fn take(x: own [u8; 2]) -> u8 { return x[0]; } + +fn f() -> u8 { + let a: own [u8; 2] = alloc(3); + for i in 0 .. 3 { let s: u8 = take(a); } + return 0; +} diff --git a/tests/compiler/neg/unbounded_for.osc b/tests/compiler/neg/unbounded_for.osc new file mode 100644 index 000000000..f65ff277c --- /dev/null +++ b/tests/compiler/neg/unbounded_for.osc @@ -0,0 +1,7 @@ +// expect: UNBOUNDED_LOOP object=i line=5 +// for trip count over 1_000_000. +fn f() -> i64 { + let mut s: i64 = 0; + for i in 0 .. 2000000 { s = s + 1; } + return s; +} diff --git a/tests/compiler/neg/unbounded_while.osc b/tests/compiler/neg/unbounded_while.osc new file mode 100644 index 000000000..fe9040f5e --- /dev/null +++ b/tests/compiler/neg/unbounded_while.osc @@ -0,0 +1,9 @@ +// expect: UNBOUNDED_LOOP object=while line=5 +// a while loop must declare a bound. +fn f(x: u32) -> u32 { + let mut n: u32 = x; + while n > 0 { + n = n - 1; + } + return n; +} diff --git a/tests/compiler/neg/undefined_recursive.osc b/tests/compiler/neg/undefined_recursive.osc new file mode 100644 index 000000000..7d0491cbb --- /dev/null +++ b/tests/compiler/neg/undefined_recursive.osc @@ -0,0 +1,6 @@ +// expect: UNDEFINED_NAME object=fact line=5 +// no recursion: a function is defined only after its body. +fn fact(n: i64) -> i64 { + if n <= 1 { return 1; } + return n * fact(n - 1); +} diff --git a/tests/compiler/neg/undefined_var.osc b/tests/compiler/neg/undefined_var.osc new file mode 100644 index 000000000..d00bae0f4 --- /dev/null +++ b/tests/compiler/neg/undefined_var.osc @@ -0,0 +1,5 @@ +// expect: UNDEFINED_NAME object=y line=4 +// use of a name that was never defined. +fn f(x: i32) -> i32 { + return x + y; +} diff --git a/tests/compiler/neg/unsupported_array_return.osc b/tests/compiler/neg/unsupported_array_return.osc new file mode 100644 index 000000000..a982db5ec --- /dev/null +++ b/tests/compiler/neg/unsupported_array_return.osc @@ -0,0 +1,6 @@ +// expect: UNSUPPORTED object=f line=3 +// OSC-1 functions return scalars only. +fn f() -> own [i64; 4] { + let a: own [i64; 4] = alloc(1); + return 0; +} diff --git a/tests/compiler/progs/arrays.osc b/tests/compiler/progs/arrays.osc new file mode 100644 index 000000000..fa3d9e8b2 --- /dev/null +++ b/tests/compiler/progs/arrays.osc @@ -0,0 +1,36 @@ +// entry: arr_main +// expect-run: arr_main 1 2 3 -> 59 +// alloc, move, borrow, reborrow, index read and write, own/&/&mut params. +fn consume(a: own [u32; 8]) -> u32 { + let mut s: u32 = 0; + for i in 0 .. 8 { s = s + a[i]; } + return s; +} + +fn scale(a: &mut [u32; 8], k: u32) { + for i in 0 .. 8 { a[i] = a[i] * k; } +} + +fn peek(a: &[u32; 8], i: u8) -> u32 { return a[i]; } + +fn arr_main(v: u32, k: u32, i: u8) -> u32 { + let a: own [u32; 8] = alloc(v); + a[3] = 7; + scale(&mut a, k); + { + let r: &mut [u32; 8] = &mut a; + r[0] = r[0] + 1; + let tmp: own [u32; 8] = alloc(1); + tmp[1] = r[1]; + } + let x: u32 = peek(&a, i % 8); + let b: own [u32; 8] = a; + b[7] = x; + let mut y: u32 = 0; + { + let s: &[u32; 8] = &b; + let s2: &[u32; 8] = &s; + y = s[2] + peek(&b, 7) + peek(&s2, 1); + } + return consume(b) + y; +} diff --git a/tests/compiler/progs/bitrev.osc b/tests/compiler/progs/bitrev.osc new file mode 100644 index 000000000..566856056 --- /dev/null +++ b/tests/compiler/progs/bitrev.osc @@ -0,0 +1,26 @@ +// entry: rev8 rev16 rev16_twice +// expect-run: rev8 1 -> 128 +// expect-run: rev8 6 -> 96 +// expect-run: rev16 1 -> 32768 +// expect-run: rev16 4660 -> 11336 +// expect-run: rev16_twice 513 -> 1 +// bit reversal for u8 and u16. +fn rev8(x: u8) -> u8 { + let mut r: u8 = 0; + let mut v: u8 = x; + for i in 0 .. 8 { + r = (r << 1) | (v & 1); + v = v >> 1; + } + return r; +} + +fn rev16(x: u16) -> u16 { + let lo: u8 = (x & 0xff) as u8; + let hi: u8 = (x >> 8) as u8; + return ((rev8(lo) as u16) << 8) | (rev8(hi) as u16); +} + +fn rev16_twice(x: u16) -> bool { + return rev16(rev16(x)) == x; +} diff --git a/tests/compiler/progs/bounds.osc b/tests/compiler/progs/bounds.osc new file mode 100644 index 000000000..0c16e79ce --- /dev/null +++ b/tests/compiler/progs/bounds.osc @@ -0,0 +1,13 @@ +// entry: get set_get +// dynamic indexes: out-of-range traps BOUNDS (negative signed indexes too). +fn get(i: i8) -> i16 { + let a: own [i16; 10] = alloc(5); + for k in 0 .. 10 { a[k] = (k as i16) * 3; } + return a[i]; +} + +fn set_get(i: u16, j: i32, v: i16) -> i16 { + let a: own [i16; 12] = alloc(-1); + a[i] = v; + return a[j]; +} diff --git a/tests/compiler/progs/calls.osc b/tests/compiler/progs/calls.osc new file mode 100644 index 000000000..5924c2384 --- /dev/null +++ b/tests/compiler/progs/calls.osc @@ -0,0 +1,17 @@ +// entry: c0 c6 call_all +// calls with 0..6 scalar parameters. +fn c0() -> i64 { return 42; } +fn c1(a: i64) -> i64 { return a + c0(); } +fn c2(a: i64, b: i32) -> i64 { return c1(a) - (b as i64); } +fn c3(a: i64, b: i32, c: u8) -> i64 { return c2(a, b) * (c as i64); } +fn c4(a: i64, b: i32, c: u8, d: bool) -> i64 { + if d { return c3(a, b, c); } + return c3(a, b, c) + 1; +} +fn c5(a: i64, b: i32, c: u8, d: bool, e: u16) -> i64 { return c4(a, b, c, d) ^ (e as i64); } +fn c6(a: i64, b: i32, c: u8, d: bool, e: u16, f: i8) -> i64 { return c5(a, b, c, d, e) + (f as i64); } +fn noop() { } +fn call_all(x: i32) -> i64 { + noop(); + return c6(x as i64, x, 3, x > 0, 7, -1) + c0(); +} diff --git a/tests/compiler/progs/casts.osc b/tests/compiler/progs/casts.osc new file mode 100644 index 000000000..e8fe6d53b --- /dev/null +++ b/tests/compiler/progs/casts.osc @@ -0,0 +1,15 @@ +// entry: narrow sign_flip widen chain +// expect-run: narrow 127 -> 127 +// expect-run: narrow 128 -> trap=CAST +// expect-run: sign_flip 4294967295 -> trap=CAST +// expect-run: chain 100 -> 75 +// `as` between integer types; out-of-range traps CAST. +fn narrow(x: i64) -> i8 { return x as i8; } +fn sign_flip(x: i32) -> u32 { return x as u32; } +fn widen(x: u8, y: i16) -> i64 { return (x as i64) * 1000 + (y as i64); } +fn chain(x: u16) -> i16 { + let a: u32 = x as u32; + let b: i64 = a as i64; + let c: u64 = (b * 3) as u64; + return (c / 4) as i16; +} diff --git a/tests/compiler/progs/collatz.osc b/tests/compiler/progs/collatz.osc new file mode 100644 index 000000000..aee05a398 --- /dev/null +++ b/tests/compiler/progs/collatz.osc @@ -0,0 +1,14 @@ +// entry: collatz +// expect-run: collatz 27 -> 111 +// expect-run: collatz 1 -> 0 +// expect-run: collatz 0 -> trap=LOOP_BOUND +// Collatz steps with a static bound: very long or endless orbits trap LOOP_BOUND. +fn collatz(n0: u32) -> u32 { + let mut n: u64 = n0 as u64; + let mut steps: u32 = 0; + while n != 1 bound 300 { + if n % 2 == 0 { n = n / 2; } else { n = 3 * n + 1; } + steps = steps + 1; + } + return steps; +} diff --git a/tests/compiler/progs/factorial.osc b/tests/compiler/progs/factorial.osc new file mode 100644 index 000000000..a4db202b7 --- /dev/null +++ b/tests/compiler/progs/factorial.osc @@ -0,0 +1,24 @@ +// entry: fact_i32 fact_u16 +// expect-run: fact_i32 12 -> 479001600 +// expect-run: fact_i32 13 -> trap=OVERFLOW +// expect-run: fact_i32 4294967295 -> 4294967295 +// expect-run: fact_u16 5 -> 120 +// checked factorial in i32 (OVERFLOW from 13!), wrapping in u16. +fn fact_i32(n: i32) -> i32 { + if n < 0 { return -1; } + let mut r: i32 = 1; + let mut k: i32 = 2; + while k <= n bound 40 { + r = r * k; + k = k + 1; + } + return r; +} + +fn fact_u16(n: u8) -> u16 { + let mut r: u16 = 1; + for k in 2 .. 30 { + if k as u8 <= n { r = r * (k as u16); } + } + return r; +} diff --git a/tests/compiler/progs/fib.osc b/tests/compiler/progs/fib.osc new file mode 100644 index 000000000..223dd4632 --- /dev/null +++ b/tests/compiler/progs/fib.osc @@ -0,0 +1,36 @@ +// entry: fib_i64 fib_u8 sum_squares +// Fibonacci (i64 checked: OVERFLOW past fib 92), u8 wrapping, sum of squares. +fn fib_i64(n: u8) -> i64 { + let mut a: i64 = 0; + let mut b: i64 = 1; + let mut k: u8 = 0; + while k < n bound 255 { + let t: i64 = a + b; + a = b; + b = t; + k = k + 1; + } + return a; +} + +fn fib_u8(n: u8) -> u8 { + let mut a: u8 = 0; + let mut b: u8 = 1; + for k in 0 .. 255 { + if (k as u8) >= n { return a; } + let t: u8 = a + b; + a = b; + b = t; + } + return a; +} + +fn sum_squares(n: u16) -> u32 { + let mut s: u32 = 0; + let mut i: u32 = 1; + while i <= (n as u32) bound 3000 { + s = s + i * i; + i = i + 1; + } + return s; +} diff --git a/tests/compiler/progs/gcd.osc b/tests/compiler/progs/gcd.osc new file mode 100644 index 000000000..526aa6e12 --- /dev/null +++ b/tests/compiler/progs/gcd.osc @@ -0,0 +1,35 @@ +// entry: gcd_u64 gcd_i32 lcm_u32 +// expect-run: gcd_u64 48 18 -> 6 +// expect-run: gcd_i32 4294967248 18 -> 6 +// expect-run: lcm_u32 4 6 -> 12 +// expect-run: lcm_u32 0 0 -> trap=DIV0 +// Euclid's algorithm (u64 wraps, i32 checked); lcm traps DIV0 on gcd 0. +fn gcd_u64(a: u64, b: u64) -> u64 { + let mut x: u64 = a; + let mut y: u64 = b; + while y != 0 bound 200 { + let t: u64 = x % y; + x = y; + y = t; + } + return x; +} + +fn gcd_i32(a: i32, b: i32) -> i32 { + let mut x: i32 = a; + let mut y: i32 = b; + if x < 0 { x = -x; } + if y < 0 { y = -y; } + while y != 0 bound 100 { + let t: i32 = x % y; + x = y; + y = t; + } + return x; +} + +fn lcm_u32(a: u32, b: u32) -> u32 { + let g: u64 = gcd_u64(a as u64, b as u64); + let l: u64 = (a as u64) / g * (b as u64); + return l as u32; +} diff --git a/tests/compiler/progs/ifchain.osc b/tests/compiler/progs/ifchain.osc new file mode 100644 index 000000000..dac7bad4b --- /dev/null +++ b/tests/compiler/progs/ifchain.osc @@ -0,0 +1,24 @@ +// entry: classify grade +// if / else if / else chains. +fn classify(x: i32) -> u8 { + if x < -1000 { + return 0; + } else if x < 0 { + return 1; + } else if x == 0 { + return 2; + } else if x <= 1000 { + return 3; + } else { + return 4; + } +} + +fn grade(score: u8, bonus: bool) -> u8 { + let mut s: u16 = score as u16; + if bonus { s = s + 10; } + let mut g: u8 = 0; + if s >= 90 { g = 4; } else if s >= 80 { g = 3; } else if s >= 70 { g = 2; } else { g = 1; } + if s > 255 { g = 9; } + return g; +} diff --git a/tests/compiler/progs/isort.osc b/tests/compiler/progs/isort.osc new file mode 100644 index 000000000..840d9b53c --- /dev/null +++ b/tests/compiler/progs/isort.osc @@ -0,0 +1,39 @@ +// entry: sort_main +// expect-run: sort_main 1 1 1 -> 255868620 +// insertion sort over own [i64; 16] filled from the parameters. +fn fill(a: &mut [i64; 16], s: i64, m: i64, t: i64) { + let mut x: i64 = s; + for i in 0 .. 16 { + x = (x * m + t) % 1000003; + a[i] = x; + } +} + +fn sort(a: &mut [i64; 16]) { + for i in 1 .. 16 { + let key: i64 = a[i]; + let mut j: i64 = i - 1; + while j >= 0 && a[j] > key bound 16 { + a[j + 1] = a[j]; + j = j - 1; + } + a[j + 1] = key; + } +} + +fn is_sorted(a: &[i64; 16]) -> bool { + for i in 1 .. 16 { + if a[i - 1] > a[i] { return false; } + } + return true; +} + +fn sort_main(s: i32, m: i16, t: i32) -> i64 { + let a: own [i64; 16] = alloc(0); + fill(&mut a, s as i64, m as i64, t as i64); + sort(&mut a); + if !is_sorted(&a) { return -1; } + let mut h: i64 = 0; + for i in 0 .. 16 { h = (h * 31 + a[i]) % 1000000007; } + return h; +} diff --git a/tests/compiler/progs/loopbound.osc b/tests/compiler/progs/loopbound.osc new file mode 100644 index 000000000..a27570ae4 --- /dev/null +++ b/tests/compiler/progs/loopbound.osc @@ -0,0 +1,34 @@ +// entry: count_to count_for else_returns +// exactly N while iterations run; iteration N+1 traps LOOP_BOUND. +// expect-run: count_to 10 -> 10 +// expect-run: count_to 11 -> trap=LOOP_BOUND +// expect-run: count_to 0 -> 0 +// expect-run: count_for 5 -> 9 +// expect-run: else_returns 1 -> 12 +// expect-run: else_returns 0 -> 0 +fn count_to(n: u32) -> u32 { + let mut i: u32 = 0; + while i < n bound 10 { + i = i + 1; + } + return i; +} + +fn count_for(k: i64) -> i64 { + let mut s: i64 = 0; + for i in -3 .. 3 { + s = s + i + k / 2; + } + return s; +} + +fn else_returns(c: u8) -> u8 { + let a: own [u8; 3] = alloc(4); + let mut x: u8 = 0; + if c > 0 { + x = 1; + } else { + return 0; + } + return a[0] * 3 * x; +} diff --git a/tests/compiler/progs/minmax.osc b/tests/compiler/progs/minmax.osc new file mode 100644 index 000000000..0ff5dcd18 --- /dev/null +++ b/tests/compiler/progs/minmax.osc @@ -0,0 +1,29 @@ +// entry: spread +// min / max / argmax over a borrowed array of i16. +fn amax(a: &[i16; 10]) -> i16 { + let mut m: i16 = a[0]; + for i in 1 .. 10 { if a[i] > m { m = a[i]; } } + return m; +} + +fn amin(a: &[i16; 10]) -> i16 { + let mut m: i16 = a[0]; + for i in 1 .. 10 { if a[i] < m { m = a[i]; } } + return m; +} + +fn argmax(a: &[i16; 10]) -> u8 { + let mut k: u8 = 0; + for i in 1 .. 10 { if a[i] > a[k] { k = i as u8; } } + return k; +} + +fn spread(seed: u16, mul: u8) -> i32 { + let a: own [i16; 10] = alloc(0); + let mut x: u16 = seed; + for i in 0 .. 10 { + x = x * (mul as u16) + 12345; + a[i] = (x >> 1) as i16; + } + return (amax(&a) as i32) - (amin(&a) as i32) + (argmax(&a) as i32); +} diff --git a/tests/compiler/progs/nested.osc b/tests/compiler/progs/nested.osc new file mode 100644 index 000000000..e7cd2ec74 --- /dev/null +++ b/tests/compiler/progs/nested.osc @@ -0,0 +1,27 @@ +// entry: find_pair grid_walk +// nested loops with early return inside loops. +fn find_pair(target: i32) -> i32 { + for i in 0 .. 20 { + for j in 0 .. 20 { + if (i as i32) * 20 + (j as i32) == target { + return (i as i32) * 100 + (j as i32); + } + } + } + return -1; +} + +fn grid_walk(n: u8, stop: u16) -> u16 { + let mut acc: u16 = 0; + let mut i: u8 = 0; + while i < n bound 12 { + let mut j: u8 = 0; + while j < i bound 12 { + acc = acc + (i as u16) * (j as u16); + if acc == stop { return 9999; } + j = j + 1; + } + i = i + 1; + } + return acc; +} diff --git a/tests/compiler/progs/oom.osc b/tests/compiler/progs/oom.osc new file mode 100644 index 000000000..701fe6ea7 --- /dev/null +++ b/tests/compiler/progs/oom.osc @@ -0,0 +1,94 @@ +// entry: oom +// expect-run: oom 4 -> 14 +// expect-run: oom 5 -> trap=OOM +// five call levels each holding 13 live owners: depth 5 needs 65 > 64 pool slots (OOM). +fn level1(n: u8) -> u64 { + let a1: own [u64; 1] = alloc(1); + let a2: own [u64; 1] = alloc(2); + let a3: own [u64; 1] = alloc(3); + let a4: own [u64; 1] = alloc(4); + let a5: own [u64; 1] = alloc(5); + let a6: own [u64; 1] = alloc(6); + let a7: own [u64; 1] = alloc(7); + let a8: own [u64; 1] = alloc(8); + let a9: own [u64; 1] = alloc(9); + let a10: own [u64; 1] = alloc(10); + let a11: own [u64; 1] = alloc(11); + let a12: own [u64; 1] = alloc(12); + let a13: own [u64; 1] = alloc(13); + let mut s: u64 = a1[0] + a13[0]; + return s; +} +fn level2(n: u8) -> u64 { + let a1: own [u64; 1] = alloc(1); + let a2: own [u64; 1] = alloc(2); + let a3: own [u64; 1] = alloc(3); + let a4: own [u64; 1] = alloc(4); + let a5: own [u64; 1] = alloc(5); + let a6: own [u64; 1] = alloc(6); + let a7: own [u64; 1] = alloc(7); + let a8: own [u64; 1] = alloc(8); + let a9: own [u64; 1] = alloc(9); + let a10: own [u64; 1] = alloc(10); + let a11: own [u64; 1] = alloc(11); + let a12: own [u64; 1] = alloc(12); + let a13: own [u64; 1] = alloc(13); + let mut s: u64 = a1[0] + a13[0]; + if n > 1 { s = s + level1(n); } + return s; +} +fn level3(n: u8) -> u64 { + let a1: own [u64; 1] = alloc(1); + let a2: own [u64; 1] = alloc(2); + let a3: own [u64; 1] = alloc(3); + let a4: own [u64; 1] = alloc(4); + let a5: own [u64; 1] = alloc(5); + let a6: own [u64; 1] = alloc(6); + let a7: own [u64; 1] = alloc(7); + let a8: own [u64; 1] = alloc(8); + let a9: own [u64; 1] = alloc(9); + let a10: own [u64; 1] = alloc(10); + let a11: own [u64; 1] = alloc(11); + let a12: own [u64; 1] = alloc(12); + let a13: own [u64; 1] = alloc(13); + let mut s: u64 = a1[0] + a13[0]; + if n > 2 { s = s + level2(n); } + return s; +} +fn level4(n: u8) -> u64 { + let a1: own [u64; 1] = alloc(1); + let a2: own [u64; 1] = alloc(2); + let a3: own [u64; 1] = alloc(3); + let a4: own [u64; 1] = alloc(4); + let a5: own [u64; 1] = alloc(5); + let a6: own [u64; 1] = alloc(6); + let a7: own [u64; 1] = alloc(7); + let a8: own [u64; 1] = alloc(8); + let a9: own [u64; 1] = alloc(9); + let a10: own [u64; 1] = alloc(10); + let a11: own [u64; 1] = alloc(11); + let a12: own [u64; 1] = alloc(12); + let a13: own [u64; 1] = alloc(13); + let mut s: u64 = a1[0] + a13[0]; + if n > 3 { s = s + level3(n); } + return s; +} +fn level5(n: u8) -> u64 { + let a1: own [u64; 1] = alloc(1); + let a2: own [u64; 1] = alloc(2); + let a3: own [u64; 1] = alloc(3); + let a4: own [u64; 1] = alloc(4); + let a5: own [u64; 1] = alloc(5); + let a6: own [u64; 1] = alloc(6); + let a7: own [u64; 1] = alloc(7); + let a8: own [u64; 1] = alloc(8); + let a9: own [u64; 1] = alloc(9); + let a10: own [u64; 1] = alloc(10); + let a11: own [u64; 1] = alloc(11); + let a12: own [u64; 1] = alloc(12); + let a13: own [u64; 1] = alloc(13); + let mut s: u64 = a1[0] + a13[0]; + if n > 4 { s = s + level4(n); } + return s; +} +fn oom(n: u8) -> u64 { return level5(n % 8); } diff --git a/tests/compiler/progs/ops.osc b/tests/compiler/progs/ops.osc new file mode 100644 index 000000000..4b1a79546 --- /dev/null +++ b/tests/compiler/progs/ops.osc @@ -0,0 +1,46 @@ +// entry: arith_i32 bits_u16 cmp_i16 cmp_u64 unary_i64 logic +// expect-run: arith_i32 7 0 -> trap=DIV0 +// expect-run: cmp_i16 3 3 -> 41 +// expect-run: logic 1 0 -> 1 +// every operator: + - * / % & | ^ << >> == != < <= > >= && || ! - ~ as +fn arith_i32(a: i32, b: i32) -> i32 { + let s: i32 = a + b; + let d: i32 = a - b; + let p: i32 = (a % 1000) * (b % 1000); + let q: i32 = a / b; + let r: i32 = a % b; + return s / 2 + d / 2 + p + q + r; +} + +fn bits_u16(a: u16, b: u16, n: u8) -> u16 { + return ((a & b) | (a ^ ~b)) + (a << n) + (b >> n); +} + +fn cmp_i16(a: i16, b: i16) -> u8 { + let mut m: u8 = 0; + if a == b { m = m | 1; } + if a != b { m = m | 2; } + if a < b { m = m | 4; } + if a <= b { m = m | 8; } + if a > b { m = m | 16; } + if a >= b { m = m | 32; } + return m; +} + +fn cmp_u64(a: u64, b: u64) -> u8 { + let mut m: u8 = 0; + if a < b { m = m + 1; } + if a <= b { m = m + 2; } + if a > b { m = m + 4; } + if a >= b { m = m + 8; } + if 100 < a { m = m + 16; } + return m; +} + +fn unary_i64(a: i64) -> i64 { + return -a + ~a * 2; +} + +fn logic(a: bool, b: bool) -> bool { + return !(a && b) == (!a || !b); +} diff --git a/tests/compiler/progs/popcount.osc b/tests/compiler/progs/popcount.osc new file mode 100644 index 000000000..44c3f44c4 --- /dev/null +++ b/tests/compiler/progs/popcount.osc @@ -0,0 +1,31 @@ +// entry: pop64 pop8 pop_kernighan +// expect-run: pop64 255 -> 8 +// expect-run: pop64 18446744073709551615 -> 64 +// expect-run: pop8 255 -> 8 +// expect-run: pop_kernighan 4294967295 -> 32 +// population count three ways. +fn pop64(x: u64) -> u32 { + let mut n: u32 = 0; + for i in 0 .. 64 { + if (x >> (i as u64)) & 1 == 1 { n = n + 1; } + } + return n; +} + +fn pop8(x: u8) -> u8 { + let mut v: u8 = x; + v = (v & 0x55) + ((v >> 1) & 0x55); + v = (v & 0x33) + ((v >> 2) & 0x33); + v = (v & 0x0f) + ((v >> 4) & 0x0f); + return v; +} + +fn pop_kernighan(x: u32) -> u32 { + let mut v: u32 = x; + let mut n: u32 = 0; + while v != 0 bound 32 { + v = v & (v - 1); + n = n + 1; + } + return n; +} diff --git a/tests/compiler/progs/prefix.osc b/tests/compiler/progs/prefix.osc new file mode 100644 index 000000000..2f50aa672 --- /dev/null +++ b/tests/compiler/progs/prefix.osc @@ -0,0 +1,23 @@ +// entry: prefix_main +// expect-run: prefix_main 1 1 0 7 -> 36 +// expect-run: prefix_main 1 1 2 3 -> 7 +// expect-run: prefix_main 1 1 0 8 -> trap=BOUNDS +// prefix sums in i32 (checked) over an owned array; queries a range sum. +fn prefix(a: &mut [i32; 8]) { + for i in 1 .. 8 { + a[i] = a[i] + a[i - 1]; + } +} + +fn range_sum(p: &[i32; 8], lo: u8, hi: u8) -> i32 { + if lo == 0 { return p[hi]; } + return p[hi] - p[lo - 1]; +} + +fn prefix_main(x: i32, step: i16, lo: u8, hi: u8) -> i32 { + let a: own [i32; 8] = alloc(x); + for i in 0 .. 8 { a[i] = a[i] + (step as i32) * (i as i32); } + prefix(&mut a); + if lo > hi { return 0; } + return range_sum(&a, lo, hi); +} diff --git a/tests/compiler/progs/reborrow.osc b/tests/compiler/progs/reborrow.osc new file mode 100644 index 000000000..93b791c36 --- /dev/null +++ b/tests/compiler/progs/reborrow.osc @@ -0,0 +1,38 @@ +// entry: rb_main +// reborrows through &mut, shared reborrow of a shared borrow, borrow +// binding reassignment, &mut parameter reborrowed into another call. +fn total(a: &[i32; 6]) -> i32 { + let mut s: i32 = 0; + for i in 0 .. 6 { s = s + a[i]; } + return s; +} + +fn bump(a: &mut [i32; 6], k: i32) { + for i in 0 .. 6 { a[i] = a[i] + k; } +} + +fn twice(a: &mut [i32; 6], k: i32) -> i32 { + bump(&mut a, k); + { + let m: &mut [i32; 6] = &mut a; + bump(&mut m, k); + m[5] = 0; + { + let t: &[i32; 6] = &m; + let u: &[i32; 6] = &t; + if t[0] > 100 { return total(&u); } + } + } + return total(&a); +} + +fn rb_main(x: i32, k: i16) -> i32 { + let a: own [i32; 6] = alloc(x); + let b: own [i32; 6] = alloc(1); + let s3: i32 = twice(&mut a, k as i32); + let mut cur: &[i32; 6] = &a; + let s1: i32 = total(&cur); + cur = &b; + let s2: i32 = total(&cur); + return s1 - s2 + s3; +} diff --git a/tests/compiler/progs/scopes.osc b/tests/compiler/progs/scopes.osc new file mode 100644 index 000000000..2f12d7248 --- /dev/null +++ b/tests/compiler/progs/scopes.osc @@ -0,0 +1,37 @@ +// entry: scopes_main early +// inner-scope destruction, moves into inner owners, early returns that +// release several owners (including inside loops). +fn sum4(a: &[u16; 4]) -> u16 { return a[0] + a[1] + a[2] + a[3]; } + +fn scopes_main(x: u16) -> u16 { + let outer: own [u16; 4] = alloc(x); + let mut acc: u16 = 0; + { + let inner: own [u16; 4] = alloc(2); + acc = acc + sum4(&inner); + { + let deeper: own [u16; 4] = inner; + deeper[0] = 9; + acc = acc + sum4(&deeper); + } + } + for i in 0 .. 3 { + let tmp: own [u16; 4] = alloc(i as u16); + acc = acc + sum4(&tmp) + sum4(&outer); + } + return acc; +} + +fn early(x: i32, limit: i32) -> i32 { + let a: own [i32; 3] = alloc(x); + let mut n: i32 = 0; + while n < 50 bound 50 { + let b: own [i32; 2] = alloc(n); + for j in 0 .. 4 { + let c: own [i32; 1] = alloc(j as i32); + if n * 4 + c[0] >= limit { return a[0] + b[0] + c[0]; } + } + n = n + 1; + } + return -7; +} diff --git a/tests/compiler/progs/shifts.osc b/tests/compiler/progs/shifts.osc new file mode 100644 index 000000000..2c267acdd --- /dev/null +++ b/tests/compiler/progs/shifts.osc @@ -0,0 +1,15 @@ +// entry: shl_i32 shr_i8 mix_u64 rot_u32 +// expect-run: shl_i32 1 30 -> 1073741824 +// expect-run: shl_i32 1 31 -> trap=OVERFLOW +// expect-run: shl_i32 1 32 -> trap=SHIFT +// expect-run: shr_i8 18446744073709551488 7 -> 18446744073709551615 +// shifts with amounts of any integer type; amount >= width traps SHIFT, +// signed << that loses bits traps OVERFLOW. +fn shl_i32(x: i32, n: u8) -> i32 { return x << n; } +fn shr_i8(x: i8, n: i64) -> i8 { return x >> n; } +fn mix_u64(x: u64, n: i16) -> u64 { return (x << n) ^ (x >> 3) ^ (1 << 63); } +fn rot_u32(x: u32, n: u32) -> u32 { + let k: u32 = n % 32; + if k == 0 { return x; } + return (x << k) | (x >> (32 - k)); +} diff --git a/tests/compiler/progs/shortcircuit.osc b/tests/compiler/progs/shortcircuit.osc new file mode 100644 index 000000000..254639b92 --- /dev/null +++ b/tests/compiler/progs/shortcircuit.osc @@ -0,0 +1,20 @@ +// entry: safe_div guarded_index either +// expect-run: safe_div 9 0 -> 0 +// expect-run: safe_div 9 2 -> 1 +// expect-run: guarded_index 4 -> trap=BOUNDS +// expect-run: guarded_index 18446744073709551615 -> 2 +// && and || short-circuit: the right side runs only when needed. +fn safe_div(a: i32, b: i32) -> bool { + return b != 0 && a / b > 3; +} + +fn guarded_index(i: i64) -> i64 { + let a: own [i64; 4] = alloc(9); + if i >= 0 && i < 4 && a[i] == 9 { return 1; } + if i < 0 || a[i] > 0 { return 2; } + return 3; +} + +fn either(a: u8, b: u8) -> bool { + return a == 0 || 200 / a > b; +} diff --git a/tests/compiler/progs/sixparams.osc b/tests/compiler/progs/sixparams.osc new file mode 100644 index 000000000..8ee2ecf27 --- /dev/null +++ b/tests/compiler/progs/sixparams.osc @@ -0,0 +1,16 @@ +// entry: six_main +// a callee with 6 mixed parameters: own, &, &mut and scalars. +fn mix6(o: own [u8; 4], s: &[u8; 4], m: &mut [u8; 4], a: u8, b: i64, c: bool) -> i64 { + m[0] = o[1] + s[2] + a; + let mut r: i64 = (m[0] as i64) + b; + if c { r = r - (s[3] as i64); } + return r; +} + +fn six_main(a: u8, b: i32, c: bool) -> i64 { + let o: own [u8; 4] = alloc(a); + let s: own [u8; 4] = alloc(3); + let m: own [u8; 4] = alloc(0); + let r: i64 = mix6(o, &s, &mut m, a, b as i64, c); + return r + (m[0] as i64); +} diff --git a/tests/compiler/progs/types.osc b/tests/compiler/progs/types.osc new file mode 100644 index 000000000..8182dc519 --- /dev/null +++ b/tests/compiler/progs/types.osc @@ -0,0 +1,11 @@ +// entry: t_u8 t_u16 t_u32 t_u64 t_i8 t_i16 t_i32 t_i64 t_bool +// one function per scalar type: unsigned wrap, signed checked. +fn t_u8(a: u8, b: u8) -> u8 { return a * 3 + b - 7; } +fn t_u16(a: u16, b: u16) -> u16 { return (a ^ b) * a + 65535; } +fn t_u32(a: u32, b: u32) -> u32 { return a - b * 2 + (a | 1); } +fn t_u64(a: u64, b: u64) -> u64 { return a * b + (a >> 3) - (b & 0xffff); } +fn t_i8(a: i8, b: i8) -> i8 { return a + b; } +fn t_i16(a: i16, b: i16) -> i16 { return a * b - 100; } +fn t_i32(a: i32, b: i32) -> i32 { return a - b; } +fn t_i64(a: i64, b: i64) -> i64 { return a * 2 + b / 3; } +fn t_bool(a: bool, b: bool, c: bool) -> bool { return (a && !b) || (c == a) || (b != c && !a); } diff --git a/tests/compiler/test_osc_compiler.c b/tests/compiler/test_osc_compiler.c new file mode 100644 index 000000000..09cc3780f --- /dev/null +++ b/tests/compiler/test_osc_compiler.c @@ -0,0 +1,601 @@ +/* + * test_osc_compiler.c -- OSC-1 front-end gate (Lane 22 worker C). + * + * 1. Golden programs (tests/compiler/progs/NAME.osc, header `// entry: f g ...`): + * compile; run every entry natively (osc_cg + osc_native + + * osc_rt_call_native) and in the reference interpreter over N fuzzed + * argument vectors (seeded splitmix64, uniform + edge values per param + * type); require osc_rt_same_outcome and pool live_count 0 after every + * non-trapping run; every runtime trap kind 1..7 must be observed. + * 2. Determinism: compile twice in-process, same IR digest and code bytes. + * 3. Model replay: each golden ownership trace replays through the OSC-0 + * model (osc_model_init(&m, 0, UINT64_MAX)) and is accepted; each + * non-trapping native run's pool event log replays as ALLOC/RELEASE and + * is accepted. + * 4. Negative programs (tests/compiler/neg/NAME.osc, header + * `// expect: KIND object=NAME line=N` and optional + * `// transition: TEXT`): kind, object, line (and transition substring) + * match. For USE_AFTER_MOVE, MUTABLE_ALIAS, BORROW_OUTLIVES_OWNER and + * READ_ONLY_BORROW the refusal trace must replay with every event + * accepted except the last, which the model rejects with the mapped name. + * + * Usage: test_osc_compiler [fuzz_count (default 1000)] [tests dir (default tests/compiler)] + * Final line: OSC1_COMPILER_PASS or OSC1_COMPILER_FAIL with counts. + * OSC-1 slice; not a general Omega compiler; no self-hosting. + */ +#include +#include +#include +#include +#include + +#include "osc_cg.h" +#include "osc_front.h" +#include "osc_interp.h" +#include "osc_native.h" +#include "osc_rt.h" +#include "model/osc_model.h" + +static unsigned long checks, failures; +static unsigned long trap_seen[9]; +static unsigned long diff_runs, rt_replays, trace_replays, rt_events_replayed; + +#define CHECK(cond, ...) \ + do { \ + checks++; \ + if (!(cond)) { \ + failures++; \ + if (failures <= 40) { \ + printf("FAIL %s:%d: ", __FILE__, __LINE__); \ + printf(__VA_ARGS__); \ + printf("\n"); \ + } \ + } \ + } while (0) + +/* ------------------------------------------------------------ files */ +static char *read_file(const char *path, size_t *len) +{ + FILE *f = fopen(path, "rb"); + if (!f) return NULL; + size_t cap = 1 << 16, n = 0; + char *b = malloc(cap + 1); + while (b) { + size_t r = fread(b + n, 1, cap - n, f); + n += r; + if (n < cap) break; + cap *= 2; + char *nb = realloc(b, cap + 1); + if (!nb) { free(b); b = NULL; break; } + b = nb; + } + fclose(f); + if (b) { b[n] = 0; *len = n; } + return b; +} + +static int cmpstr(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); } + +static int list_osc(const char *dir, char ***out) +{ + DIR *d = opendir(dir); + if (!d) return -1; + int n = 0, cap = 64; + char **v = malloc(sizeof(char *) * (size_t)cap); + struct dirent *e; + while ((e = readdir(d))) { + size_t l = strlen(e->d_name); + if (l < 5 || strcmp(e->d_name + l - 4, ".osc")) continue; + if (n == cap) { cap *= 2; v = realloc(v, sizeof(char *) * (size_t)cap); } + v[n++] = strdup(e->d_name); + } + closedir(d); + qsort(v, (size_t)n, sizeof(char *), cmpstr); + *out = v; + return n; +} + +/* value of `key` in a `// key ...` header line; copies the rest of the line */ +static int header(const char *src, const char *key, char *buf, size_t cap) +{ + const char *p = src; + while (*p) { + const char *eol = strchr(p, '\n'); + size_t l = eol ? (size_t)(eol - p) : strlen(p); + size_t kl = strlen(key); + if (l > 3 + kl && strncmp(p, "// ", 3) == 0 && strncmp(p + 3, key, kl) == 0) { + const char *v = p + 3 + kl; + size_t vl = l - 3 - kl; + while (vl && (*v == ' ')) { v++; vl--; } + while (vl && (v[vl - 1] == ' ' || v[vl - 1] == '\r')) vl--; + if (vl >= cap) vl = cap - 1; + memcpy(buf, v, vl); + buf[vl] = 0; + return 0; + } + if (!eol) break; + p = eol + 1; + } + return -1; +} + +/* ------------------------------------------------------------ fuzz */ +static uint64_t sm_state; +static uint64_t sm(void) +{ + uint64_t z = (sm_state += 0x9E3779B97F4A7C15ull); + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBull; + return z ^ (z >> 31); +} +static uint64_t canon(OscScalar t, uint64_t v) +{ + if (t == OSC_T_BOOL) return v & 1; + unsigned w = osc_scalar_width(t); + if (w == 64) return v; + uint64_t m = (1ull << w) - 1; + v &= m; + if (osc_scalar_signed(t) && (v >> (w - 1))) v |= ~m; + return v; +} +static uint64_t gen_arg(OscScalar t) +{ + unsigned w = osc_scalar_width(t); + int sg = osc_scalar_signed(t); + uint64_t r = sm(); + switch (r % 6) { + case 0: { + uint64_t mx = sg ? ((1ull << (w - 1)) - 1) : (w == 64 ? UINT64_MAX : (1ull << w) - 1); + uint64_t mn = sg ? (uint64_t)(-(int64_t)(mx) - 1) : 0; + uint64_t e[] = {0, 1, (uint64_t)-1, mx, mn, mx - 1, mn + 1, 2, (uint64_t)-2}; + return canon(t, e[(r >> 8) % 9]); + } + case 1: case 2: return canon(t, (uint64_t)((int64_t)((r >> 8) % 41) - 20)); + case 3: return canon(t, (r >> 8) % 300); + case 4: return canon(t, (r >> 8) % 70); + default: return canon(t, sm()); + } +} + +/* ------------------------------------------------------------ model replays */ +/* Replay one function's trace slice [i0,i1). Returns index of the first + * rejected event (or -1 if all accepted); *rej gets the reason. */ +#define SNAP_MAX 128 +static int replay_trace(const OscTrace *t, uint32_t i0, uint32_t i1, OscModelReject *rej) +{ + static OscModel m, stack[SNAP_MAX]; + int sp = 0; + osc_model_init(&m, 0, UINT64_MAX); + *rej = OSC_REJ_NONE; + for (uint32_t i = i0; i < i1; i++) { + const OscTraceEntry *e = &t->e[i]; + if (e->op == OSC_TR_SAVE) { + if (sp >= SNAP_MAX) { *rej = OSC_REJ_CAPACITY; return (int)i; } + stack[sp++] = m; + } else if (e->op == OSC_TR_RESTORE) { + if (sp <= 0) { *rej = OSC_REJ_PROTOCOL; return (int)i; } + m = stack[--sp]; + } else { + OscModelReject r; + if (osc_model_step(&m, &e->ev, &r) != OSC_MODEL_ACCEPT) { *rej = r; return (int)i; } + } + } + return -1; +} + +/* runtime pool log -> model ALLOC/RELEASE; windowed ids when > 64 objects */ +static int replay_rt(const OscRt *rt, char *why, size_t n) +{ + static OscModel m; + static uint32_t id_of_serial[1 << 16]; + static uint32_t serial_of_id[OSC_MODEL_MAX_OBJECTS + 1]; + static uint8_t live_id[OSC_MODEL_MAX_OBJECTS + 1]; + uint32_t next = 1; + osc_model_init(&m, 0, UINT64_MAX); + memset(live_id, 0, sizeof live_id); + uint32_t nev = rt->nev < OSC_RT_EVENTS ? rt->nev : OSC_RT_EVENTS; + for (uint32_t i = 0; i < nev; i++) { + const OscRtEvent *e = &rt->ev[i]; + if (e->serial >= (1u << 16)) { snprintf(why, n, "serial too large"); return -1; } + OscModelEvent ev; + memset(&ev, 0, sizeof ev); + if (e->kind == OSC_RT_EV_ALLOC) { + if (next > OSC_MODEL_MAX_OBJECTS) { + /* new window: re-create the live objects with fresh ids */ + uint32_t keep[OSC_MODEL_MAX_OBJECTS], nk = 0; + for (uint32_t k = 1; k <= OSC_MODEL_MAX_OBJECTS; k++) + if (live_id[k]) keep[nk++] = serial_of_id[k]; + osc_model_init(&m, 0, UINT64_MAX); + memset(live_id, 0, sizeof live_id); + next = 1; + for (uint32_t k = 0; k < nk; k++) { + memset(&ev, 0, sizeof ev); + ev.kind = OSC_EV_ALLOC; + ev.obj = next; + if (osc_model_step(&m, &ev, NULL) != OSC_MODEL_ACCEPT) { snprintf(why, n, "re-alloc"); return -1; } + id_of_serial[keep[k]] = next; + serial_of_id[next] = keep[k]; + live_id[next] = 1; + next++; + } + if (next > OSC_MODEL_MAX_OBJECTS) { snprintf(why, n, "64 live objects"); return -1; } + memset(&ev, 0, sizeof ev); + } + ev.kind = OSC_EV_ALLOC; + ev.obj = next; + id_of_serial[e->serial] = next; + serial_of_id[next] = e->serial; + live_id[next] = 1; + next++; + } else { + ev.kind = OSC_EV_RELEASE; + ev.obj = id_of_serial[e->serial]; + if (!ev.obj || !live_id[ev.obj]) { snprintf(why, n, "release of unknown serial %u", e->serial); return -1; } + live_id[ev.obj] = 0; + } + OscModelReject r; + if (osc_model_step(&m, &ev, &r) != OSC_MODEL_ACCEPT) { + snprintf(why, n, "event %u %s rejected: %s", i, osc_model_event_name(ev.kind), osc_model_reject_name(r)); + return -1; + } + rt_events_replayed++; + } + return 0; +} + +/* ------------------------------------------------------------ golden */ +static OscUnit *U1, *U2; +static unsigned long expect_total; +static const char *trap_names[9] = {"none", "OVERFLOW", "DIV0", "BOUNDS", "LOOP_BOUND", "CAST", "OOM", "SHIFT", "RUNTIME"}; + +static uint64_t parse_val(const char *s) +{ + if (*s == '-') return (uint64_t)strtoll(s, NULL, 10); + return strtoull(s, NULL, 10); +} + +/* `// expect-run: ENTRY ARG... -> VALUE` or `-> trap=NAME`: hand-computed + * results; both engines must produce them (catches lowering errors that a + * differential run of the same IR cannot see). */ +static void expect_runs(const char *name, const char *src, const OscNative *nm, const OscCode *code); +static OscTrace *TR; +static OscRt *RI, *RN; +static unsigned long golden_ok, golden_entries, golden_funcs, traces_skipped_overflow; + +static void golden(const char *dir, const char *name, unsigned fuzz) +{ + char path[1024], ent[512], why[160]; + snprintf(path, sizeof path, "%s/%s", dir, name); + size_t len; + char *src = read_file(path, &len); + CHECK(src != NULL, "%s: unreadable", name); + if (!src) return; + unsigned long f0 = failures; + OscDiag d; + int rc = osc_compile(src, len, U1, &d, TR); + CHECK(rc == 0, "%s: refused: %s line %u object=%s: %s", name, osc_diag_kind_name(d.kind), d.line, d.object, d.message); + if (rc) { free(src); return; } + golden_funcs += U1->nfuncs; + + /* determinism: second in-process compile */ + OscDiag d2; + CHECK(osc_compile(src, len, U2, &d2, NULL) == 0, "%s: second compile refused", name); + uint8_t g1[32], g2[32]; + CHECK(osc_ir_digest(U1, g1) == 0 && osc_ir_digest(U2, g2) == 0 && memcmp(g1, g2, 32) == 0, "%s: IR digest differs", name); + OscCode c1, c2; + char err[160]; + memset(&c1, 0, sizeof c1); + memset(&c2, 0, sizeof c2); + int cg1 = osc_cg_compile(U1, &c1, err, sizeof err); + CHECK(cg1 == 0, "%s: codegen refused: %s", name, err); + int cg2 = osc_cg_compile(U2, &c2, err, sizeof err); + CHECK(cg1 == 0 && cg2 == 0 && c1.len == c2.len && memcmp(c1.code, c2.code, c1.len) == 0 && + memcmp(c1.entry, c2.entry, sizeof c1.entry) == 0, "%s: code bytes differ", name); + if (cg2 == 0) osc_cg_free(&c2); + if (cg1) { free(src); return; } + + /* ownership trace replay, per function */ + CHECK(!TR->refused, "%s: golden trace has a refused event", name); + if (TR->overflow) traces_skipped_overflow++; + else { + uint32_t i = 0; + while (i < TR->n) { + uint32_t j = i; + while (j < TR->n && TR->e[j].func == TR->e[i].func) j++; + OscModelReject r; + int bad = replay_trace(TR, i, j, &r); + CHECK(bad < 0, "%s: trace of %s rejected at event %d (line %u): %s", name, U1->funcs[TR->e[i].func].name, + bad, bad >= 0 ? TR->e[bad].line : 0, osc_model_reject_name(r)); + trace_replays++; + i = j; + } + } + + OscNative nm; + int mr = osc_native_map(&nm, c1.code, c1.len); + CHECK(mr == 0, "%s: native map failed (%d)", name, mr); + if (mr) { osc_cg_free(&c1); free(src); return; } + + CHECK(header(src, "entry:", ent, sizeof ent) == 0, "%s: missing // entry: header", name); + char *save = NULL; + for (char *tok = strtok_r(ent, " ,", &save); tok; tok = strtok_r(NULL, " ,", &save)) { + int fi = -1; + for (int k = 0; k < U1->nfuncs; k++) + if (strcmp(U1->funcs[k].name, tok) == 0) fi = k; + CHECK(fi >= 0, "%s: entry %s not found", name, tok); + if (fi < 0) continue; + const OscFunc *f = &U1->funcs[fi]; + int scalar = 1; + for (int p = 0; p < f->nparams; p++) + if (f->vtype[p].s == OSC_T_REF) scalar = 0; + CHECK(scalar, "%s: entry %s takes an array parameter", name, tok); + if (!scalar) continue; + golden_entries++; + void *entry = osc_native_at(&nm, c1.entry[fi]); + sm_state = 0x05C1C0DE00000000ull ^ (uint64_t)(fi * 7919) ^ (uint64_t)strlen(name) * 104729u; + for (const char *q = name; *q; q++) sm_state = sm_state * 131 + (uint8_t)*q; + unsigned long pertrap[9] = {0}; + for (unsigned it = 0; it < fuzz; it++) { + uint64_t args[OSC_MAX_PARAMS] = {0}, ri = 0, rn = 0; + for (int p = 0; p < f->nparams; p++) args[p] = gen_arg(f->vtype[p].s); + osc_rt_reset(RI); + osc_rt_reset(RN); + int ti = osc_interp_run_prevalidated(U1, fi, args, f->nparams, RI, &ri); + int tn = osc_rt_call_native(RN, entry, args, f->nparams, &rn); + diff_runs++; + int same = ti == tn && ti >= 0 && (ti != 0 || ri == rn) && osc_rt_same_outcome(RI, RN); + CHECK(same, "%s:%s args[0]=%llu: interp trap %d ret %llu vs native trap %d ret %llu", name, tok, + (unsigned long long)args[0], ti, (unsigned long long)ri, tn, (unsigned long long)rn); + if (!same) { + char bp[256]; + snprintf(bp, sizeof bp, "/tmp/l22c/backend-bug-%s-%s.txt", name, tok); + FILE *bf = fopen(bp, "w"); + if (bf) { + fprintf(bf, "program %s entry %s\nargs:", name, tok); + for (int p = 0; p < f->nparams; p++) fprintf(bf, " %llu", (unsigned long long)args[p]); + fprintf(bf, "\ninterp trap %d ret %llu; native trap %d ret %llu\n", ti, (unsigned long long)ri, tn, + (unsigned long long)rn); + fclose(bf); + } + break; + } + if (ti >= 0 && ti <= 8) { trap_seen[ti]++; pertrap[ti]++; } + CHECK(ti != OSC_TRAP_RUNTIME, "%s:%s RUNTIME trap (must never happen for checked code)", name, tok); + if (ti == 0) { + CHECK(RI->live_count == 0 && RN->live_count == 0, "%s:%s leak: live_count interp %u native %u", name, + tok, RI->live_count, RN->live_count); + if (replay_rt(RN, why, sizeof why) == 0) rt_replays++; + else CHECK(0, "%s:%s pool log replay rejected: %s", name, tok, why); + } + } + printf(" %-18s %-12s ok=%-5lu ovf=%-4lu div0=%-4lu bnd=%-4lu loop=%-4lu cast=%-4lu oom=%-4lu shift=%-4lu\n", + name, tok, pertrap[0], pertrap[1], pertrap[2], pertrap[3], pertrap[4], pertrap[5], pertrap[6], pertrap[7]); + } + expect_runs(name, src, &nm, &c1); + osc_native_unmap(&nm); + osc_cg_free(&c1); + if (failures == f0) golden_ok++; + free(src); +} + +/* ------------------------------------------------------------ front-end mutation fuzz */ +/* Mutated golden sources must either compile (unit validated, codegen ok) or + * be refused with a well-formed diagnostic; never an internal error or crash. */ +static unsigned long mut_total, mut_accepted, mut_refused; + +static void mutate_fuzz(const char *dir, const char *name, unsigned n) +{ + static const char pool[] = " \n;{}()[]&*+-<>=!~^|%/,:.0123456789abxyzimlet mut own fn if else while bound for in return as u8 i64 bool"; + char path[1024]; + snprintf(path, sizeof path, "%s/%s", dir, name); + size_t len; + char *src = read_file(path, &len); + if (!src || len == 0) { free(src); return; } + char *buf = malloc(len * 2 + 64); + sm_state = 0xF022u ^ (uint64_t)len; + for (unsigned it = 0; it < n; it++) { + size_t bl = len; + memcpy(buf, src, len); + unsigned edits = 1 + (unsigned)(sm() % 3); + for (unsigned e = 0; e < edits && bl > 0; e++) { + size_t p = (size_t)(sm() % bl); + switch (sm() % 4) { + case 0: buf[p] = pool[sm() % (sizeof pool - 1)]; break; + case 1: { size_t k = 1 + (size_t)(sm() % 8); if (p + k > bl) k = bl - p; memmove(buf + p, buf + p + k, bl - p - k); bl -= k; break; } + case 2: if (bl + 1 < len * 2 + 64) { memmove(buf + p + 1, buf + p, bl - p); buf[p] = pool[sm() % (sizeof pool - 1)]; bl++; } break; + default: bl = p; break; + } + } + OscDiag d; + mut_total++; + int rc = osc_compile(buf, bl, U1, &d, TR); + if (rc == 0) { + OscCode c; + char err[160]; + memset(&c, 0, sizeof c); + int cg = osc_cg_compile(U1, &c, err, sizeof err); + CHECK(cg == 0, "%s mutant %u: accepted but codegen refused: %s", name, it, err); + if (cg == 0) osc_cg_free(&c); + mut_accepted++; + } else { + CHECK(d.kind > OSC_DIAG_NONE && d.kind < OSC_DIAG__COUNT && d.message[0] && d.object[0] && + strcmp(d.object, "internal") != 0, + "%s mutant %u: bad diagnostic kind=%d object=%s: %s", name, it, (int)d.kind, d.object, d.message); + mut_refused++; + } + } + free(buf); + free(src); +} + +/* ------------------------------------------------------------ negative */ +static unsigned long neg_ok, neg_total, neg_traced; + +static const char *mapped(int kind) +{ + switch (kind) { + case OSC_DIAG_USE_AFTER_MOVE: return "use-after-move"; + case OSC_DIAG_MUTABLE_ALIAS: return "mutable-alias"; + case OSC_DIAG_BORROW_OUTLIVES_OWNER: return "borrow-outlives-owner"; + case OSC_DIAG_READ_ONLY_BORROW: return "forged-rights"; + default: return NULL; + } +} + +static void negative(const char *dir, const char *name) +{ + char path[1024], exp[256], tr[160]; + snprintf(path, sizeof path, "%s/%s", dir, name); + size_t len; + char *src = read_file(path, &len); + CHECK(src != NULL, "%s: unreadable", name); + if (!src) return; + neg_total++; + unsigned long f0 = failures; + CHECK(header(src, "expect:", exp, sizeof exp) == 0, "%s: missing // expect: header", name); + char kind[64] = "", obj[64] = ""; + unsigned line = 0; + char *sp = strchr(exp, ' '); + if (sp) { + memcpy(kind, exp, (size_t)(sp - exp) < 63 ? (size_t)(sp - exp) : 63); + char *o = strstr(sp, "object="); + char *l = strstr(sp, "line="); + if (o) sscanf(o + 7, "%63s", obj); + if (l) line = (unsigned)strtoul(l + 5, NULL, 10); + } + int have_tr = header(src, "transition:", tr, sizeof tr) == 0; + OscDiag d; + int rc = osc_compile(src, len, U1, &d, TR); + CHECK(rc == -1, "%s: accepted, expected %s", name, kind); + if (rc == -1) { + CHECK(strcmp(osc_diag_kind_name(d.kind), kind) == 0, "%s: kind %s, expected %s (%s)", name, + osc_diag_kind_name(d.kind), kind, d.message); + CHECK(strcmp(d.object, obj) == 0, "%s: object '%s', expected '%s'", name, d.object, obj); + CHECK(d.line == line, "%s: line %u, expected %u", name, d.line, line); + if (have_tr) CHECK(strstr(d.transition, tr) != NULL, "%s: transition '%s' lacks '%s'", name, d.transition, tr); + const char *mn = mapped(d.kind); + if (mn) { + CHECK(TR->refused && !TR->overflow && TR->n > 0 && TR->e[TR->n - 1].refused, + "%s: trace does not end in the refused event", name); + if (TR->n > 0 && TR->e[TR->n - 1].refused) { + uint32_t j = TR->n, i = j - 1; + while (i > 0 && TR->e[i - 1].func == TR->e[j - 1].func) i--; + OscModelReject r; + int bad = replay_trace(TR, i, j, &r); + CHECK(bad == (int)(j - 1), "%s: model rejected at event %d, expected the last (%u): %s", name, bad, + j - 1, osc_model_reject_name(r)); + CHECK(bad < 0 || strcmp(osc_model_reject_name(r), mn) == 0, "%s: model says %s, expected %s", name, + osc_model_reject_name(r), mn); + neg_traced++; + } + } + } + if (failures == f0) neg_ok++; + free(src); +} + +int main(int argc, char **argv) +{ + unsigned fuzz = argc > 1 ? (unsigned)strtoul(argv[1], NULL, 10) : 1000; + const char *root = argc > 2 ? argv[2] : "tests/compiler"; + char pdir[512], ndir[512]; + snprintf(pdir, sizeof pdir, "%s/progs", root); + snprintf(ndir, sizeof ndir, "%s/neg", root); + struct timespec t0, t1; + clock_gettime(CLOCK_MONOTONIC, &t0); + U1 = malloc(sizeof *U1); + U2 = malloc(sizeof *U2); + TR = malloc(sizeof *TR); + RI = malloc(sizeof *RI); + RN = malloc(sizeof *RN); + if (!U1 || !U2 || !TR || !RI || !RN) { printf("OSC1_COMPILER_FAIL out of memory\n"); return 1; } + osc_rt_init(RI); + osc_rt_init(RN); + + char **pv, **nv; + int np = list_osc(pdir, &pv), nn = list_osc(ndir, &nv); + CHECK(np >= 20, "need >= 20 golden programs, found %d", np); + CHECK(nn >= 30, "need >= 30 negative programs, found %d", nn); + printf("golden programs (%d), fuzz=%u per entry:\n", np, fuzz); + for (int i = 0; i < np; i++) golden(pdir, pv[i], fuzz); + for (int i = 0; i < nn; i++) negative(ndir, nv[i]); + unsigned muts = fuzz / 4 ? fuzz / 4 : 1; + for (int i = 0; i < np; i++) mutate_fuzz(pdir, pv[i], muts); + printf("front-end mutants: %lu (accepted %lu, refused %lu)\n", mut_total, mut_accepted, mut_refused); + + const char *const *tn = trap_names; + printf("trap coverage (runs, interpreter == native):\n"); + for (int k = 0; k <= 8; k++) printf(" %-10s %lu\n", tn[k], trap_seen[k]); + for (int k = 1; k <= 7; k++) CHECK(trap_seen[k] > 0, "trap %s never observed", tn[k]); + CHECK(trap_seen[8] == 0, "RUNTIME trap observed"); + CHECK(traces_skipped_overflow == 0, "%lu golden traces exceeded the model's 64 ids", traces_skipped_overflow); + + for (int i = 0; i < np; i++) free(pv[i]); + for (int i = 0; i < nn; i++) free(nv[i]); + free(pv); + free(nv); + free(U1); free(U2); free(TR); free(RI); free(RN); + clock_gettime(CLOCK_MONOTONIC, &t1); + double secs = (double)(t1.tv_sec - t0.tv_sec) + (double)(t1.tv_nsec - t0.tv_nsec) / 1e9; + printf("golden=%lu/%d funcs=%lu entries=%lu expect_runs=%lu diff_runs=%lu trace_replays=%lu rt_replays=%lu rt_events=%lu " + "neg=%lu/%lu neg_traced=%lu checks=%lu failed=%lu time=%.2fs\n", + golden_ok, np, golden_funcs, golden_entries, expect_total, diff_runs, trace_replays, rt_replays, rt_events_replayed, + neg_ok, neg_total, neg_traced, checks, failures, secs); + if (failures == 0) { + printf("OSC1_COMPILER_PASS golden=%lu neg=%lu diff_runs=%lu checks=%lu\n", golden_ok, neg_ok, diff_runs, checks); + return 0; + } + printf("OSC1_COMPILER_FAIL golden=%lu/%d neg=%lu/%lu failed=%lu\n", golden_ok, np, neg_ok, neg_total, failures); + return 1; +} + +static void expect_runs(const char *name, const char *src, const OscNative *nm, const OscCode *code) +{ + const char *key = "// expect-run: "; + size_t kl = strlen(key); + for (const char *p = src; p && *p;) { + const char *eol = strchr(p, '\n'); + size_t l = eol ? (size_t)(eol - p) : strlen(p); + if (l > kl && strncmp(p, key, kl) == 0 && l - kl < 400) { + char line[512], *save = NULL; + memcpy(line, p + kl, l - kl); + line[l - kl] = 0; + char *ent = strtok_r(line, " ", &save); + uint64_t args[OSC_MAX_PARAMS + 1] = {0}; + unsigned na = 0; + char *t, *res = NULL; + while ((t = strtok_r(NULL, " ", &save))) { + if (strcmp(t, "->") == 0) { res = strtok_r(NULL, " ", &save); break; } + if (na <= OSC_MAX_PARAMS) args[na++] = parse_val(t); + } + int fi = -1; + for (int k = 0; ent && k < U1->nfuncs; k++) + if (strcmp(U1->funcs[k].name, ent) == 0) fi = k; + CHECK(fi >= 0 && res && na == U1->funcs[fi].nparams, "%s: bad expect-run line '%.*s'", name, (int)l, p); + if (fi >= 0 && res && na == U1->funcs[fi].nparams) { + const OscFunc *f = &U1->funcs[fi]; + for (unsigned k = 0; k < na; k++) args[k] = canon(f->vtype[k].s, args[k]); + int want_trap = 0; + uint64_t want = 0; + if (strncmp(res, "trap=", 5) == 0) { + want_trap = -1; + for (int k = 1; k <= 8; k++) + if (strcmp(res + 5, trap_names[k]) == 0) want_trap = k; + } else { + want = canon(f->ret.s, parse_val(res)); + } + uint64_t ri = 0, rn = 0; + osc_rt_reset(RI); + osc_rt_reset(RN); + int ti = osc_interp_run(U1, fi, args, na, RI, &ri); + int tn = osc_rt_call_native(RN, osc_native_at(nm, code->entry[fi]), args, na, &rn); + int ok = ti == want_trap && tn == want_trap && (want_trap || (ri == want && rn == want && + RI->live_count == 0 && RN->live_count == 0)); + CHECK(ok, "%s: expect-run '%.*s': interp trap %d ret %llu, native trap %d ret %llu", name, (int)l, p, + ti, (unsigned long long)ri, tn, (unsigned long long)rn); + expect_total++; + } + } + p = eol ? eol + 1 : NULL; + } +} From f4970827ae615531497e0344d8ed3d78ae5a6ef8 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Thu, 1 Oct 2026 03:01:04 -0500 Subject: [PATCH 05/10] OSC-1: receipt writer, design notes (encoder choice, evidence, test location) Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Fable 5.1 --- docs/osc/OSC-1-DESIGN.md | 28 +++++++- tests/compiler/osc1_receipt.sh | 114 +++++++++++++++++++++++++++++++++ 2 files changed, 141 insertions(+), 1 deletion(-) create mode 100644 tests/compiler/osc1_receipt.sh diff --git a/docs/osc/OSC-1-DESIGN.md b/docs/osc/OSC-1-DESIGN.md index 304ef30a3..fe33a4c57 100644 --- a/docs/osc/OSC-1-DESIGN.md +++ b/docs/osc/OSC-1-DESIGN.md @@ -2,7 +2,7 @@ **OSC-1 slice; not a general Omega compiler; no self-hosting.** -Status: in progress (Lane 22, 2026-10-01). Governing record: +Status: implemented as a host-tested slice (Lane 22, 2026-10-01). Governing record: [OMEGA-SYSTEMS-CORE-0000](../adr/OMEGA-SYSTEMS-CORE-0000.md) and the audit sections it cites ([OMEGA_SYSTEMS_CORE_CODE_AUDIT.md](../../OMEGA_SYSTEMS_CORE_CODE_AUDIT.md) III.6 pipeline, III.7 OSC-1 definition, III.8 acceptance tests, II.9 determinism, @@ -227,3 +227,29 @@ code bytes. See [OSC-1-SELF-HOST-STATEMENT.md](OSC-1-SELF-HOST-STATEMENT.md). Short form: the OSC-1 compiler cannot compile any part of itself, and this slice makes no self-hosting claim. + +## 10. Implementation notes and evidence + +- Files: `src/compiler/` (front end `osc_lex/parse/check/lower/front`, IR + `osc_ir`, reference interpreter `osc_interp`, encoder/decoder `osc_a64`, + codegen `osc_cg`, loader `osc_native`, bootstrap runtime `osc_rt`, CLI + `oscc_main.c`), the II.11 model in `src/compiler/model/`, tests in + `tests/compiler/` (OSC-0 III.8 names `tests/osc/`; this slice keeps its tests + next to its sources under `tests/compiler/`). +- Encoder. `src/aarch64_encoder.c` (used by `omega_program_realize`, M5/M6/M9/M14) + masks register fields silently (`rm & 0x1f`), which is exactly what OSC-0 III.6 + says must be hardened. Changing it would change the inputs of the existing + gates, so it is left untouched and OSC-1 uses its own validating encoder + `osc_a64.c` with a decoder mirror. The existing M6/M9/M14 gates were run + before and after this work and are unchanged. +- `make test-compiler` (host, single core, about 70 s): OSC-0B model sweep + (10^6 sequences), back end differential test, compiler golden / negative / + model-agreement test, cross-process determinism; the three test binaries also + run under ASan/UBSan. `make compiler-receipt` writes the content-addressed + receipt `evidence/OSC-1/receipts/osc1-compiler-.json`; + `make osc0b-model-receipt` writes the OSC-0B exit receipt + `evidence/OSC-1/receipts/osc0b-model-.json`. +- The reference interpreter is a second implementation of section 5 (signed + arithmetic computed exactly in 128 bits and range-checked), not a copy of the + codegen's flag logic. It is a differential oracle; agreement between two + implementations is evidence, not proof. diff --git a/tests/compiler/osc1_receipt.sh b/tests/compiler/osc1_receipt.sh new file mode 100644 index 000000000..d6da289ff --- /dev/null +++ b/tests/compiler/osc1_receipt.sh @@ -0,0 +1,114 @@ +#!/bin/sh +# OSC-1 compiler slice receipt (docs/osc/OSC-1-DESIGN.md). +# OSC-1 slice; not a general Omega compiler; no self-hosting. +# 1. refuses a dirty tree (any tracked or untracked change): receipts record an exact commit +# 2. runs `make test-compiler` into a temporary OUT_DIR (model sweep, back end, +# compiler golden/negative/model agreement, determinism; plain + ASan/UBSan) +# 3. compiles every golden program with oscc and records its IR and machine-code digests +# 4. checks that the existing Omega core sources (src/omega_*, src/aarch64_*, +# src/language/, tools/omegatool.c, Makefile) are unchanged against the merge +# base with origin/main, so the M6/M9/M14 gates cannot have changed; if +# PHYSICS_DIR points at the pinned physics checkout it also runs those gates +# 5. writes a content-addressed receipt evidence/OSC-1/receipts/osc1-compiler-.json +# Never overwrites existing evidence. Timing is not recorded. +set -eu +ROOT=$(cd "$(dirname "$0")/../.." && pwd -P) +cd "$ROOT" +EVD=evidence/OSC-1/receipts +die() { echo "osc1-receipt: REFUSED: $*" >&2; exit 2; } + +[ -z "$(git status --porcelain --untracked-files=all)" ] || die "dirty tree; commit first (receipts record an exact commit)" +COMMIT=$(git rev-parse HEAD) +BASE=$(git merge-base HEAD origin/main) || die "no merge base with origin/main" + +T=$(mktemp -d) +trap 'rm -rf "$T"' EXIT +O="$T/build/compiler" +nice make --no-print-directory OUT_DIR="$T/build" PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-compiler \ + >"$T/make.log" 2>&1 || { tail -30 "$T/make.log"; die "make test-compiler failed"; } +grep -q '^test-compiler: PASS' "$T/make.log" || die "no test-compiler PASS line" + +MSUM=$(grep '^OSC0B_MODEL_SEED=' "$O/model.out" | tail -1) +mf() { echo "$MSUM" | sed -n "s/.*$1=\([0-9a-fx]*\).*/\1/p"; } +BCOUNTS=$(grep '^units=' "$O/backend.out" | tail -1) +BCHECKS=$(grep '^checks=' "$O/backend.out" | tail -1 | sed 's/ time=.*//') +CLINE=$(grep '^golden=' "$O/compiler.out" | tail -1 | sed 's/ time=.*//') +DLINE=$(grep '^programs=' "$O/determinism.out" | tail -1) +tc() { grep "^ $1 " "$O/compiler.out" | awk '{print $2}'; } +for v in "$MSUM" "$BCOUNTS" "$BCHECKS" "$CLINE" "$DLINE"; do [ -n "$v" ] || die "cannot parse test output"; done +for k in OVERFLOW DIV0 BOUNDS LOOP_BOUND CAST OOM SHIFT; do + n=$(tc $k); [ -n "$n" ] && [ "$n" -gt 0 ] || die "trap $k not observed in golden corpus" +done + +# golden corpus digests (oscc, one process per program) +: >"$T/corpus.txt" +for f in tests/compiler/progs/*.osc; do + out=$("$O/oscc" "$f") || die "oscc refused golden program $f" + ir=$(echo "$out" | sed -n 's/^ir_sha256=//p'); code=$(echo "$out" | sed -n 's/^code_sha256=//p') + printf '%s %s %s %s\n' "$f" "$(sha256sum "$f" | cut -d' ' -f1)" "$ir" "$code" >>"$T/corpus.txt" +done +CORPUS_SHA=$(sha256sum "$T/corpus.txt" | cut -d' ' -f1) +NPROG=$(wc -l <"$T/corpus.txt" | tr -d ' ') +NNEG=$(ls tests/compiler/neg/*.osc | wc -l | tr -d ' ') + +CORE="src/omega_*.c src/omega_*.h src/aarch64_* src/language tools/omegatool.c Makefile" +# shellcheck disable=SC2086 +if git diff --quiet "$BASE" HEAD -- $CORE; then CORE_UNCHANGED=true; else die "existing Omega core sources changed vs $BASE"; fi + +GATES='"NOT_RUN (PHYSICS_DIR not set; core sources unchanged vs merge base)"' +if [ -n "${PHYSICS_DIR:-}" ] && [ -d "$PHYSICS_DIR" ]; then + G="" + for m in m6 m9 m14; do + nice make --no-print-directory OUT_DIR="$T/gates" PHYSICS_DIR="$PHYSICS_DIR" "test-$m" >"$T/$m.log" 2>&1 \ + || { tail -20 "$T/$m.log"; die "test-$m failed"; } + tot=$(grep 'TOTAL GATES' "$T/$m.log" | head -1 | sed 's/.*TOTAL GATES: \([0-9]*\) | PASSED: \([0-9]*\) | FAILED: \([0-9]*\).*/{"total": \1, "passed": \2, "failed": \3}/') + G="$G\"$m\": $tot, " + done + GATES="{${G%, }}" +fi + +R="$T/receipt.json" +{ + printf '{\n' + printf ' "schema": "omega.osc1.compiler.receipt.v1",\n' + printf ' "verdict": "PASS",\n' + printf ' "statement": "OSC-1 slice; not a general Omega compiler; no self-hosting",\n' + printf ' "subset": "integer scalars u8 u16 u32 u64 (wrap) and i8 i16 i32 i64 (checked, trap on overflow), bool; let / let mut; arithmetic, bitwise, shift, compare, logical (short-circuit), checked as-casts; if/else; while with static bound N (trap past N) and for over literal ranges; calls to earlier functions in the unit (no recursion, <= 6 params); unique allocation own [T; N] (N <= 64), moves, shared and mutable borrows with lexical lifetimes, bounds-checked indexing, deterministic destruction at scope end; requires/ensures recorded as text, not checked",\n' + printf ' "pipeline": "surface text -> lexer/parser -> typed AST -> name/type + ownership/borrow analysis -> typed IR (canonical encoding + sha256) -> AArch64 via src/compiler/osc_a64 (validating encoder, decoder mirror)",\n' + printf ' "repo_commit": "%s",\n' "$COMMIT" + printf ' "base_commit": "%s",\n' "$BASE" + printf ' "tree_clean": true,\n' + printf ' "host_arch": "%s",\n' "$(uname -m)" + printf ' "c_compiler": "%s",\n' "$(${CC:-cc} --version 2>/dev/null | head -1 | sed 's/"/\\"/g')" + printf ' "osc0b_model": {"seed": "0x%s", "sequences": %s, "steps": %s, "false_accepts": %s, "wrong_name": %s, "false_rejects": %s, "result": "OSC0B_MODEL_PASS"},\n' \ + "$(mf OSC0B_MODEL_SEED)" "$(mf SEQUENCES)" "$(mf STEPS)" "$(mf FALSE_ACCEPTS)" "$(mf WRONG_NAME)" "$(mf FALSE_REJECTS)" + printf ' "backend": "%s; %s; native == interpreter on every run",\n' "$BCOUNTS" "$BCHECKS" + printf ' "compiler": "%s",\n' "$CLINE" + printf ' "golden_trap_coverage": {"none": %s, "overflow": %s, "div0": %s, "bounds": %s, "loop_bound": %s, "cast": %s, "oom": %s, "shift": %s, "runtime": %s},\n' \ + "$(tc none)" "$(tc OVERFLOW)" "$(tc DIV0)" "$(tc BOUNDS)" "$(tc LOOP_BOUND)" "$(tc CAST)" "$(tc OOM)" "$(tc SHIFT)" "$(tc RUNTIME)" + printf ' "determinism": "%s (oscc in separate processes, byte-identical IR digest and machine code)",\n' "$DLINE" + printf ' "sanitizers": "all three test binaries also pass under -fsanitize=address,undefined -fno-sanitize-recover=all (model sweep at 10^5)",\n' + printf ' "golden_programs": %s,\n' "$NPROG" + printf ' "negative_programs": %s,\n' "$NNEG" + printf ' "golden_corpus_sha256": "%s",\n' "$CORPUS_SHA" + printf ' "golden_corpus": [\n' + n=0 + while read -r f src ir code; do + n=$((n + 1)); sep=,; [ "$n" = "$NPROG" ] && sep= + printf ' {"program": "%s", "source_sha256": "%s", "ir_sha256": "%s", "code_sha256": "%s"}%s\n' "$f" "$src" "$ir" "$code" "$sep" + done <"$T/corpus.txt" + printf ' ],\n' + printf ' "omega_core_sources_unchanged_vs_base": %s,\n' "$CORE_UNCHANGED" + printf ' "m6_m9_m14_gates": %s,\n' "$GATES" + printf ' "self_host": "no: the OSC-1 compiler cannot compile any part of itself (docs/osc/OSC-1-SELF-HOST-STATEMENT.md)",\n' + printf ' "not_covered": "contract enforcement (OSC-2), effects/capabilities, structs, strings, generations, arenas, unsafe physical, FFI, Flow IR optimisation, self-hosting (OSC-14); not a general Omega compiler",\n' + printf ' "timing_measured": false\n' + printf '}\n' +} >"$R" + +mkdir -p "$EVD" +RSHA=$(sha256sum "$R" | cut -d' ' -f1) +OUT="$EVD/osc1-compiler-$RSHA.json" +[ -e "$OUT" ] && { echo "osc1-receipt: identical receipt already present: $OUT"; exit 0; } +cp "$R" "$OUT" +echo "osc1-receipt: PASS receipt=$OUT" From 6283a67a341f2988a9f011c3e7ee4cbe4e93f0b7 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Thu, 1 Oct 2026 03:05:06 -0500 Subject: [PATCH 06/10] OSC-1 receipt: gate legs use a relative OUT_DIR; keep gate logs for comparison Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Opus 5.5 --- tests/compiler/osc1_receipt.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/compiler/osc1_receipt.sh b/tests/compiler/osc1_receipt.sh index d6da289ff..88eaed393 100644 --- a/tests/compiler/osc1_receipt.sh +++ b/tests/compiler/osc1_receipt.sh @@ -58,10 +58,12 @@ if git diff --quiet "$BASE" HEAD -- $CORE; then CORE_UNCHANGED=true; else die "e GATES='"NOT_RUN (PHYSICS_DIR not set; core sources unchanged vs merge base)"' if [ -n "${PHYSICS_DIR:-}" ] && [ -d "$PHYSICS_DIR" ]; then G="" + rm -rf build/osc1-receipt-gates; mkdir -p build/osc1-receipt-gates # gate targets need a relative OUT_DIR (./$(OUT_DIR)/omegatool); build/ is ignored for m in m6 m9 m14; do - nice make --no-print-directory OUT_DIR="$T/gates" PHYSICS_DIR="$PHYSICS_DIR" "test-$m" >"$T/$m.log" 2>&1 \ + nice make --no-print-directory OUT_DIR=build/osc1-receipt-gates PHYSICS_DIR="$PHYSICS_DIR" "test-$m" >"$T/$m.log" 2>&1 \ || { tail -20 "$T/$m.log"; die "test-$m failed"; } tot=$(grep 'TOTAL GATES' "$T/$m.log" | head -1 | sed 's/.*TOTAL GATES: \([0-9]*\) | PASSED: \([0-9]*\) | FAILED: \([0-9]*\).*/{"total": \1, "passed": \2, "failed": \3}/') + sed -n "/omegatool --run/,\$p" "$T/$m.log" >build/osc1-receipt-gates/$m.gate.log G="$G\"$m\": $tot, " done GATES="{${G%, }}" From feafe32713cb7aedb60d305af5ab86dfda0bd373 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Thu, 1 Oct 2026 03:08:26 -0500 Subject: [PATCH 07/10] OSC-0B: executable memory model receipt (II.11 exit gate) Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Opus 5.5 --- ...fe7f5e6df1724a609201f5b4f72efc60e14c4.json | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 evidence/OSC-1/receipts/osc0b-model-55a044e75da3f820e941446713efe7f5e6df1724a609201f5b4f72efc60e14c4.json diff --git a/evidence/OSC-1/receipts/osc0b-model-55a044e75da3f820e941446713efe7f5e6df1724a609201f5b4f72efc60e14c4.json b/evidence/OSC-1/receipts/osc0b-model-55a044e75da3f820e941446713efe7f5e6df1724a609201f5b4f72efc60e14c4.json new file mode 100644 index 000000000..fdeff7c3c --- /dev/null +++ b/evidence/OSC-1/receipts/osc0b-model-55a044e75da3f820e941446713efe7f5e6df1724a609201f5b4f72efc60e14c4.json @@ -0,0 +1,43 @@ +{ + "schema": "omega.osc0b.model.receipt.v1", + "verdict": "PASS", + "gate": "OSC-0B exit: II.11 model rejects every named invalid transition across >= 10^6 seeded random sequences, zero false accepts", + "repo_commit": "6283a67a341f2988a9f011c3e7ee4cbe4e93f0b7", + "tree_clean": true, + "host_arch": "aarch64", + "compiler": "cc (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0", + "seed": "0x05c0b5eed0010001", + "sequences": 1000000, + "valid_sequences": 249448, + "steps": 21905422, + "false_accepts": 0, + "wrong_name": 0, + "false_rejects": 0, + "sweep_digest": "7acef55477b7d971", + "unit_cases": 68, + "unit_failed": 0, + "classes": { + "use-after-move": {"injected": 58076, "rejected_correct": 58076, "rejected_wrong_name": 0, "accepted": 0}, + "use-after-release": {"injected": 57680, "rejected_correct": 57680, "rejected_wrong_name": 0, "accepted": 0}, + "double-release": {"injected": 57515, "rejected_correct": 57515, "rejected_wrong_name": 0, "accepted": 0}, + "stale-generation": {"injected": 57696, "rejected_correct": 57696, "rejected_wrong_name": 0, "accepted": 0}, + "generation-wrap": {"injected": 57733, "rejected_correct": 57733, "rejected_wrong_name": 0, "accepted": 0}, + "mutable-alias": {"injected": 57882, "rejected_correct": 57882, "rejected_wrong_name": 0, "accepted": 0}, + "borrow-outlives-owner": {"injected": 58008, "rejected_correct": 58008, "rejected_wrong_name": 0, "accepted": 0}, + "arena-escape": {"injected": 57668, "rejected_correct": 57668, "rejected_wrong_name": 0, "accepted": 0}, + "reclaim-without-quiesced": {"injected": 57777, "rejected_correct": 57777, "rejected_wrong_name": 0, "accepted": 0}, + "read-before-observe": {"injected": 57728, "rejected_correct": 57728, "rejected_wrong_name": 0, "accepted": 0}, + "publish-without-release": {"injected": 57767, "rejected_correct": 57767, "rejected_wrong_name": 0, "accepted": 0}, + "forged-rights": {"injected": 57264, "rejected_correct": 57264, "rejected_wrong_name": 0, "accepted": 0}, + "live-handle-durable": {"injected": 57758, "rejected_correct": 57758, "rejected_wrong_name": 0, "accepted": 0} + }, + "sanitizer_run": {"flags": "-fsanitize=address,undefined -fno-sanitize-recover=all", "sequences": 1000000, "result": "OSC0B_MODEL_PASS", "digest_matches_plain": true}, + "sources_sha256": { + "src/compiler/model/osc_model.h": "8c1225c64d3e2999234b6d8cdd91a24ca625ddee689ede8a7b1fef5feacb0006", + "src/compiler/model/osc_model.c": "fe0330e6e2e8f658df81a2c9e6d38f4227f121f764634b4be772d02c8ffa3319", + "src/compiler/model/osc_model_gen.h": "239ef9bed262222ae1b430eac5cf12c1b886430371c06817ebad3f500187e556", + "src/compiler/model/osc_model_gen.c": "87cabaa2a03e1998b94acc88b58410b7d567a6d4dbf0efb930d3e70e3e25f0f0", + "tests/compiler/test_osc_model.c": "805dc24d290283c4d43de388b934e7a5dd23cf7f24c7c6a46bdc169c2f496937" + }, + "timing_measured": false +} From 300dd5553452e500f1f04b0fc446b6dd78815d43 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Thu, 1 Oct 2026 03:09:56 -0500 Subject: [PATCH 08/10] OSC-1: compiler slice receipt (M6/M9/M14 10/10 each, byte-identical gate output) Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Opus 5.5 --- ...0e087d494c5f894c0de86d2e3ccf0e0abef7f.json | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 evidence/OSC-1/receipts/osc1-compiler-c3bafdabb8cbdf6b4c70511a01b0e087d494c5f894c0de86d2e3ccf0e0abef7f.json diff --git a/evidence/OSC-1/receipts/osc1-compiler-c3bafdabb8cbdf6b4c70511a01b0e087d494c5f894c0de86d2e3ccf0e0abef7f.json b/evidence/OSC-1/receipts/osc1-compiler-c3bafdabb8cbdf6b4c70511a01b0e087d494c5f894c0de86d2e3ccf0e0abef7f.json new file mode 100644 index 000000000..5f17df282 --- /dev/null +++ b/evidence/OSC-1/receipts/osc1-compiler-c3bafdabb8cbdf6b4c70511a01b0e087d494c5f894c0de86d2e3ccf0e0abef7f.json @@ -0,0 +1,52 @@ +{ + "schema": "omega.osc1.compiler.receipt.v1", + "verdict": "PASS", + "statement": "OSC-1 slice; not a general Omega compiler; no self-hosting", + "subset": "integer scalars u8 u16 u32 u64 (wrap) and i8 i16 i32 i64 (checked, trap on overflow), bool; let / let mut; arithmetic, bitwise, shift, compare, logical (short-circuit), checked as-casts; if/else; while with static bound N (trap past N) and for over literal ranges; calls to earlier functions in the unit (no recursion, <= 6 params); unique allocation own [T; N] (N <= 64), moves, shared and mutable borrows with lexical lifetimes, bounds-checked indexing, deterministic destruction at scope end; requires/ensures recorded as text, not checked", + "pipeline": "surface text -> lexer/parser -> typed AST -> name/type + ownership/borrow analysis -> typed IR (canonical encoding + sha256) -> AArch64 via src/compiler/osc_a64 (validating encoder, decoder mirror)", + "repo_commit": "feafe32713cb7aedb60d305af5ab86dfda0bd373", + "base_commit": "0580ef874d7ec23a15386c82cc420752ce1ef00c", + "tree_clean": true, + "host_arch": "aarch64", + "c_compiler": "cc (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0", + "osc0b_model": {"seed": "0x05c0b5eed0010001", "sequences": 1000000, "steps": 21905422, "false_accepts": 0, "wrong_name": 0, "false_rejects": 0, "result": "OSC0B_MODEL_PASS"}, + "backend": "units=15 funcs_fuzzed=361 diff_runs=722000 words_roundtrip=12964 enc_random_ok=45779 enc_random_refused=126221 dec_random_words=76497 validator_neg=40; checks=798962 failed=0; native == interpreter on every run", + "compiler": "golden=24/24 funcs=89 entries=62 expect_runs=48 diff_runs=62000 trace_replays=54 rt_replays=49408 rt_events=191868 neg=34/34 neg_traced=12 checks=180162 failed=0", + "golden_trap_coverage": {"none": 49408, "overflow": 3075, "div0": 23, "bounds": 2725, "loop_bound": 2100, "cast": 1499, "oom": 365, "shift": 2805, "runtime": 0}, + "determinism": "programs=24 identical=24 (oscc in separate processes, byte-identical IR digest and machine code)", + "sanitizers": "all three test binaries also pass under -fsanitize=address,undefined -fno-sanitize-recover=all (model sweep at 10^5)", + "golden_programs": 24, + "negative_programs": 34, + "golden_corpus_sha256": "cf11c49293599cc926214650546db507f478bbfd20fcd7ae4f77928dfd4a33b5", + "golden_corpus": [ + {"program": "tests/compiler/progs/arrays.osc", "source_sha256": "0d41e301111e2c132ceba7d7272eb42ae0d1b1cb0341c4f76d3fec2ce38a6ee8", "ir_sha256": "3c3b6e50085dd82cde7ec97d2feb580d38b714f8cb4f60db35b9a4f36530df0d", "code_sha256": "e6b45cce88509c39fa0503302691906d79e4189de57244a9bc1036ba15c91ac5"}, + {"program": "tests/compiler/progs/bitrev.osc", "source_sha256": "7a831a9f47434a76b65bdf837fecaf96f4a85d2c31c4682b280301b8aa588d1c", "ir_sha256": "e3aa5e5e5c58fbc686025370e8c87eceb5c4805b2a9d21d55bfbf7bfdba6cc36", "code_sha256": "94674978c5ca8c96ccc0fed847668ab4b73c0dd1f3f7527a613b26cd307c2362"}, + {"program": "tests/compiler/progs/bounds.osc", "source_sha256": "0519478f54c98ca06f3414ff9ac5dc4193ed5b2b43a7a89b2333ef3bb54b3094", "ir_sha256": "7e7bb041550f9a5a4445c0e028650f6e0cf9afcea61819a95e29b92eca13d966", "code_sha256": "07bb15370990980cd1b27be4ee87612133a58463e305e067870b6668ebc9a2d9"}, + {"program": "tests/compiler/progs/calls.osc", "source_sha256": "add5b82ec5ea73b322e9b1620220f9ff73ba9f76aeff031e0654980e2f36bcbc", "ir_sha256": "9d50bea67d3928a457201dfe35541b912b9acfbdaf97e901e7ea2e0f3185524d", "code_sha256": "a6434af2275da292a0a573b355cab439bfb26f85be6b0b0dcdc709edc66d7a94"}, + {"program": "tests/compiler/progs/casts.osc", "source_sha256": "a5093b32ee0d204d20920e5fd8f8c39c8e10b92c89aabb41fb703e7e28637fb3", "ir_sha256": "cc35e86f43ba0ebe29ea6906c0af5e01fa30964c75b0a69b05370c4100ae80b3", "code_sha256": "fdff78f367ea211da5e5058ffe715ea7fb14a1bee2727e69aefd9fda2b27bece"}, + {"program": "tests/compiler/progs/collatz.osc", "source_sha256": "912412fa1ffd990786a055d2b43a35f9fd629fa59299b1181463f3b314cd741f", "ir_sha256": "fdf94380724fa0994a074cbed2cf789c3ed4dfeb14450e648b9144ada4e57edd", "code_sha256": "9b06e959179f262f45ef72015ee1001a026262754804c107b640813131e014bf"}, + {"program": "tests/compiler/progs/factorial.osc", "source_sha256": "3e410e9214a30628b199f7bfe8f99d7e9f439e73af2d279719fa7b523bc74e21", "ir_sha256": "cc36ae8edf9a203d4f82bd1b351b92f2df818427d26239ae8c6542e175674700", "code_sha256": "a3fc5f8c4a5ae8ce6381a0db02a03e391df791a0ce2d6f778face3a30532ecd3"}, + {"program": "tests/compiler/progs/fib.osc", "source_sha256": "9490114a0c756edab0ee7af37252b5883cc7c11b69e54ba5481530b2dcb8e03c", "ir_sha256": "bfe54f4d1502277153becb83faa0fd2975496a1875837fa8e8aa72431aa0ad00", "code_sha256": "d2e25ea89ebd59e49e29303696b7b2bff4ff39d45f62bd5566db609830d153a8"}, + {"program": "tests/compiler/progs/gcd.osc", "source_sha256": "0fad11202f1f6ce6e845b266f24df86cbc0e6160a4772c043a15b60fa54a720f", "ir_sha256": "5d649066a565d7e7ab680ea6b2827306701714da7b23755836814da7cccfa328", "code_sha256": "eb4cbe78da3176853323b2d11b970444c51fb61a33dbc770ec355cc10b94d45d"}, + {"program": "tests/compiler/progs/ifchain.osc", "source_sha256": "89fd46fc610516121dbd38cca232a98abccb55abf1593409ca575ab7e293699e", "ir_sha256": "2323f2753d8e2eb269d65db1b8e9a6006b0e09ed98e0f3f74268143cf870342d", "code_sha256": "f7c3aa9e0ae96c5d1a1c0fbcb44b7504843aac8ed5035b2400d50819cc999e03"}, + {"program": "tests/compiler/progs/isort.osc", "source_sha256": "7dceeaf139addf172152b8861602d02d654e5d2f9fab451d2c38d823ddd1b7db", "ir_sha256": "fe5d0090baeb54d9afd33a9745b7a60136e513aaca0c03f5275d5efab4de3091", "code_sha256": "b99188f630088cd1c48b4e57d48431982eb3671c50fbe5ea42e17db680baf100"}, + {"program": "tests/compiler/progs/loopbound.osc", "source_sha256": "71def740b4af102745e954e5d06582cf28b5e90e633a254a3f248bd1ed8c10c3", "ir_sha256": "d5994fccb2c93ba53d8e3a73222aa54f28f2159509f992167c8e77e779734db2", "code_sha256": "e8b5a7ca1240adbcfc66c6e1e117b01ad692c4faed32381742e0ba9a7313bd83"}, + {"program": "tests/compiler/progs/minmax.osc", "source_sha256": "95c17e1cb5ffc836ef2bcf16ab39246b5c0bbb8acb1c05a6e08b838a12b60b7e", "ir_sha256": "a5ee50c4f631cfda3282c6a6a42842f20986ae4129fa4e22656ea836c8a01543", "code_sha256": "387756318095cc219eec337923bf12440927b254cac189872b17ea617f17ae41"}, + {"program": "tests/compiler/progs/nested.osc", "source_sha256": "8e9aaf037c142ea43dcc4e9013013688eb19f03f24a9e8511058623ced32dc35", "ir_sha256": "94e13f928a06a8d2ddff59030bb412cfcb5e4888570f9b7fc44786c135415c04", "code_sha256": "0eb5b788611a907d360730c08b78c6b0cfbf3a454323b42808f77f8aed300e71"}, + {"program": "tests/compiler/progs/oom.osc", "source_sha256": "1d82ff5262c21e4760b2404dc8fc649863a35ac4a164e4ae6684adcd7cecfc7e", "ir_sha256": "6ce4fcbb5b507668183dd67678a93dad7fe11d7b3f02c2466815712fb300116c", "code_sha256": "5c788e2eef2be25b04013f7bd8378d715756293c36f9509c14e9d5d465e5552a"}, + {"program": "tests/compiler/progs/ops.osc", "source_sha256": "2f68f1cf7d7d4569c90d79e4afc2bbdb9cf1bc2fc39cc8f8e23555c90cdd0223", "ir_sha256": "9742eb592d1cfcd72c622d2ab28fe1dd1fa921f14cd3418662f303be851e1162", "code_sha256": "0c038096a7f33e702937c2979eba15d6fc5a25dd66ba12c5b746df8529e7a959"}, + {"program": "tests/compiler/progs/popcount.osc", "source_sha256": "eab7407d3cfc923d15f52e04e00d96a9e7331b0e2496552b8258e7f88bc65236", "ir_sha256": "15aa9536feb7cbbe9cd03efcf2517321964bb479c0331f45610225c64af186ac", "code_sha256": "04510e1bf63889d5dd0bb7b85eeffb7b016ad87a65a7e0e2209df082f1a9d1db"}, + {"program": "tests/compiler/progs/prefix.osc", "source_sha256": "a4852da0953c8e11e5a9e51d00be81a6cc9e1f9e938cbd9d186f34ccb53cc524", "ir_sha256": "6feaa9af48e493a02a3de461aeae3b88b1c813c9011a462537e88c661704ee63", "code_sha256": "f4c78d8644d86ce7f1edd36ebd6958d5250a34dedde3435587e34dfb2d474362"}, + {"program": "tests/compiler/progs/reborrow.osc", "source_sha256": "caf5e895fcd0660d6ca7c6360228901cb4eee5a7afe128b59334aec904e63feb", "ir_sha256": "34086f590aeaec09669b9656cfca7db57beffb67a59d7e1ba22548336de146b2", "code_sha256": "a6a0a251ed5ddcbc431e38ed73602ee9202fd2d601bd7085ae70ccb5974daf62"}, + {"program": "tests/compiler/progs/scopes.osc", "source_sha256": "9904f63cb89734f2411f04b098640cb0ebe8069a49ae7b1a40c728d434770070", "ir_sha256": "81e996a3c8c6515d57375609aba9ae7c6c5822626b1a8da9cd0943b70db4a1ed", "code_sha256": "e3faba53225b4f3a9398b5d39f6a224b24df08cf9b6a67ca5652a439f0717127"}, + {"program": "tests/compiler/progs/shifts.osc", "source_sha256": "dd33980fb0f3b8d61477b6c197508e3c46d894c0ebc0f99244c01b5e86ee8780", "ir_sha256": "7d2e542f2241ccfacbd6a812c1671733dda94410ede4e3847b43c0955a6f69b3", "code_sha256": "c07f4547cac6e250b1c76021f0955fd530844fcc593a33192592ee0f917ecf59"}, + {"program": "tests/compiler/progs/shortcircuit.osc", "source_sha256": "c3f272b3f6b6d27c9cde9887197e73dd622ea30ff802fb87c250a5e2f704e1d0", "ir_sha256": "863365c4653fb44aac42316b1cde491107ad739d58b7af5b4b55e3a2774c5d41", "code_sha256": "bbd44412068130fdf65d66f718f74c6e0e7e36ee19282f19e5c2f3bbcf66ba2e"}, + {"program": "tests/compiler/progs/sixparams.osc", "source_sha256": "535fead297b7c4b7946c25b0b1f716634b4342701c3ff486dbd8189ed8bc3770", "ir_sha256": "176dee2ab6b66ff28dc04f095964c51f59dcda5518a9696a95a9c588dd78083e", "code_sha256": "c1e8cf802ef21c2b08b08dd266303c715e64ab7323cb5267fe2492de1e54cee8"}, + {"program": "tests/compiler/progs/types.osc", "source_sha256": "ca4d49a4aca05b04e9935dd7cc560a023c4e4cffa36ff84c7755883a90c2b0d5", "ir_sha256": "f623556285814fbd02241fe4f24025bf93811581655beab6073e8d867b42b3a5", "code_sha256": "45c042eeb15cebf30615b7ad341b58a41bd805d83a08c358304b4284785eee35"} + ], + "omega_core_sources_unchanged_vs_base": true, + "m6_m9_m14_gates": {"m6": {"total": 10, "passed": 10, "failed": 0}, "m9": {"total": 10, "passed": 10, "failed": 0}, "m14": {"total": 10, "passed": 10, "failed": 0}}, + "self_host": "no: the OSC-1 compiler cannot compile any part of itself (docs/osc/OSC-1-SELF-HOST-STATEMENT.md)", + "not_covered": "contract enforcement (OSC-2), effects/capabilities, structs, strings, generations, arenas, unsafe physical, FFI, Flow IR optimisation, self-hosting (OSC-14); not a general Omega compiler", + "timing_measured": false +} From 26bbe0717af4c18e8b6cbeb4669076e0ed5e4c16 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Thu, 1 Oct 2026 03:23:43 -0500 Subject: [PATCH 09/10] OSC-1 codegen: local guard that a CALL target is already emitted (Codex review P1) The IR validator already refuses calls to later functions and self-calls before codegen runs (tested in test_osc_backend 'call to later function', 'call to itself'), so forward BL targets could not occur on validated units. The guard makes the invariant local to the emitter. Generated machine code for the golden corpus is byte-identical. Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Opus 5.5 --- src/compiler/osc_cg.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/compiler/osc_cg.c b/src/compiler/osc_cg.c index 9ed4dd415..8688d8985 100644 --- a/src/compiler/osc_cg.c +++ b/src/compiler/osc_cg.c @@ -381,6 +381,10 @@ static void gen_func(Cg *g, const OscUnit *u, int fi) { } break; case OSC_I_CALL: + /* Direct BL needs the callee already emitted. osc_ir_validate refuses + * calls to later functions (and self), so this cannot trigger on a + * validated unit; kept so the invariant is local to the emitter. */ + if (in->callee < 0 || in->callee >= fi) { cg_fail(g, "CALL to function %d not emitted before function %d", in->callee, fi); return; } for (int k = 0; k < in->nargs; k++) ld(g, k, in->args[k]); load_rt(g, 7); E(g, osc_a64_br(OSC_A64_BL, ((int64_t)g->entry_word[in->callee] - (int64_t)here(g)) * 4)); From 0270855a49ab748741473f0844108671954d2792 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Thu, 1 Oct 2026 03:25:16 -0500 Subject: [PATCH 10/10] OSC-1: receipt for the reviewed head (earlier receipt kept) Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Opus 5.5 --- ...d46e7b2d0fae441d2264c0b03f50c21adb383.json | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 evidence/OSC-1/receipts/osc1-compiler-8fdc926784a348acaf640d24a66d46e7b2d0fae441d2264c0b03f50c21adb383.json diff --git a/evidence/OSC-1/receipts/osc1-compiler-8fdc926784a348acaf640d24a66d46e7b2d0fae441d2264c0b03f50c21adb383.json b/evidence/OSC-1/receipts/osc1-compiler-8fdc926784a348acaf640d24a66d46e7b2d0fae441d2264c0b03f50c21adb383.json new file mode 100644 index 000000000..8e3a6c0dd --- /dev/null +++ b/evidence/OSC-1/receipts/osc1-compiler-8fdc926784a348acaf640d24a66d46e7b2d0fae441d2264c0b03f50c21adb383.json @@ -0,0 +1,52 @@ +{ + "schema": "omega.osc1.compiler.receipt.v1", + "verdict": "PASS", + "statement": "OSC-1 slice; not a general Omega compiler; no self-hosting", + "subset": "integer scalars u8 u16 u32 u64 (wrap) and i8 i16 i32 i64 (checked, trap on overflow), bool; let / let mut; arithmetic, bitwise, shift, compare, logical (short-circuit), checked as-casts; if/else; while with static bound N (trap past N) and for over literal ranges; calls to earlier functions in the unit (no recursion, <= 6 params); unique allocation own [T; N] (N <= 64), moves, shared and mutable borrows with lexical lifetimes, bounds-checked indexing, deterministic destruction at scope end; requires/ensures recorded as text, not checked", + "pipeline": "surface text -> lexer/parser -> typed AST -> name/type + ownership/borrow analysis -> typed IR (canonical encoding + sha256) -> AArch64 via src/compiler/osc_a64 (validating encoder, decoder mirror)", + "repo_commit": "26bbe0717af4c18e8b6cbeb4669076e0ed5e4c16", + "base_commit": "0580ef874d7ec23a15386c82cc420752ce1ef00c", + "tree_clean": true, + "host_arch": "aarch64", + "c_compiler": "cc (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0", + "osc0b_model": {"seed": "0x05c0b5eed0010001", "sequences": 1000000, "steps": 21905422, "false_accepts": 0, "wrong_name": 0, "false_rejects": 0, "result": "OSC0B_MODEL_PASS"}, + "backend": "units=15 funcs_fuzzed=361 diff_runs=722000 words_roundtrip=12964 enc_random_ok=45779 enc_random_refused=126221 dec_random_words=76497 validator_neg=40; checks=798962 failed=0; native == interpreter on every run", + "compiler": "golden=24/24 funcs=89 entries=62 expect_runs=48 diff_runs=62000 trace_replays=54 rt_replays=49408 rt_events=191868 neg=34/34 neg_traced=12 checks=180162 failed=0", + "golden_trap_coverage": {"none": 49408, "overflow": 3075, "div0": 23, "bounds": 2725, "loop_bound": 2100, "cast": 1499, "oom": 365, "shift": 2805, "runtime": 0}, + "determinism": "programs=24 identical=24 (oscc in separate processes, byte-identical IR digest and machine code)", + "sanitizers": "all three test binaries also pass under -fsanitize=address,undefined -fno-sanitize-recover=all (model sweep at 10^5)", + "golden_programs": 24, + "negative_programs": 34, + "golden_corpus_sha256": "cf11c49293599cc926214650546db507f478bbfd20fcd7ae4f77928dfd4a33b5", + "golden_corpus": [ + {"program": "tests/compiler/progs/arrays.osc", "source_sha256": "0d41e301111e2c132ceba7d7272eb42ae0d1b1cb0341c4f76d3fec2ce38a6ee8", "ir_sha256": "3c3b6e50085dd82cde7ec97d2feb580d38b714f8cb4f60db35b9a4f36530df0d", "code_sha256": "e6b45cce88509c39fa0503302691906d79e4189de57244a9bc1036ba15c91ac5"}, + {"program": "tests/compiler/progs/bitrev.osc", "source_sha256": "7a831a9f47434a76b65bdf837fecaf96f4a85d2c31c4682b280301b8aa588d1c", "ir_sha256": "e3aa5e5e5c58fbc686025370e8c87eceb5c4805b2a9d21d55bfbf7bfdba6cc36", "code_sha256": "94674978c5ca8c96ccc0fed847668ab4b73c0dd1f3f7527a613b26cd307c2362"}, + {"program": "tests/compiler/progs/bounds.osc", "source_sha256": "0519478f54c98ca06f3414ff9ac5dc4193ed5b2b43a7a89b2333ef3bb54b3094", "ir_sha256": "7e7bb041550f9a5a4445c0e028650f6e0cf9afcea61819a95e29b92eca13d966", "code_sha256": "07bb15370990980cd1b27be4ee87612133a58463e305e067870b6668ebc9a2d9"}, + {"program": "tests/compiler/progs/calls.osc", "source_sha256": "add5b82ec5ea73b322e9b1620220f9ff73ba9f76aeff031e0654980e2f36bcbc", "ir_sha256": "9d50bea67d3928a457201dfe35541b912b9acfbdaf97e901e7ea2e0f3185524d", "code_sha256": "a6434af2275da292a0a573b355cab439bfb26f85be6b0b0dcdc709edc66d7a94"}, + {"program": "tests/compiler/progs/casts.osc", "source_sha256": "a5093b32ee0d204d20920e5fd8f8c39c8e10b92c89aabb41fb703e7e28637fb3", "ir_sha256": "cc35e86f43ba0ebe29ea6906c0af5e01fa30964c75b0a69b05370c4100ae80b3", "code_sha256": "fdff78f367ea211da5e5058ffe715ea7fb14a1bee2727e69aefd9fda2b27bece"}, + {"program": "tests/compiler/progs/collatz.osc", "source_sha256": "912412fa1ffd990786a055d2b43a35f9fd629fa59299b1181463f3b314cd741f", "ir_sha256": "fdf94380724fa0994a074cbed2cf789c3ed4dfeb14450e648b9144ada4e57edd", "code_sha256": "9b06e959179f262f45ef72015ee1001a026262754804c107b640813131e014bf"}, + {"program": "tests/compiler/progs/factorial.osc", "source_sha256": "3e410e9214a30628b199f7bfe8f99d7e9f439e73af2d279719fa7b523bc74e21", "ir_sha256": "cc36ae8edf9a203d4f82bd1b351b92f2df818427d26239ae8c6542e175674700", "code_sha256": "a3fc5f8c4a5ae8ce6381a0db02a03e391df791a0ce2d6f778face3a30532ecd3"}, + {"program": "tests/compiler/progs/fib.osc", "source_sha256": "9490114a0c756edab0ee7af37252b5883cc7c11b69e54ba5481530b2dcb8e03c", "ir_sha256": "bfe54f4d1502277153becb83faa0fd2975496a1875837fa8e8aa72431aa0ad00", "code_sha256": "d2e25ea89ebd59e49e29303696b7b2bff4ff39d45f62bd5566db609830d153a8"}, + {"program": "tests/compiler/progs/gcd.osc", "source_sha256": "0fad11202f1f6ce6e845b266f24df86cbc0e6160a4772c043a15b60fa54a720f", "ir_sha256": "5d649066a565d7e7ab680ea6b2827306701714da7b23755836814da7cccfa328", "code_sha256": "eb4cbe78da3176853323b2d11b970444c51fb61a33dbc770ec355cc10b94d45d"}, + {"program": "tests/compiler/progs/ifchain.osc", "source_sha256": "89fd46fc610516121dbd38cca232a98abccb55abf1593409ca575ab7e293699e", "ir_sha256": "2323f2753d8e2eb269d65db1b8e9a6006b0e09ed98e0f3f74268143cf870342d", "code_sha256": "f7c3aa9e0ae96c5d1a1c0fbcb44b7504843aac8ed5035b2400d50819cc999e03"}, + {"program": "tests/compiler/progs/isort.osc", "source_sha256": "7dceeaf139addf172152b8861602d02d654e5d2f9fab451d2c38d823ddd1b7db", "ir_sha256": "fe5d0090baeb54d9afd33a9745b7a60136e513aaca0c03f5275d5efab4de3091", "code_sha256": "b99188f630088cd1c48b4e57d48431982eb3671c50fbe5ea42e17db680baf100"}, + {"program": "tests/compiler/progs/loopbound.osc", "source_sha256": "71def740b4af102745e954e5d06582cf28b5e90e633a254a3f248bd1ed8c10c3", "ir_sha256": "d5994fccb2c93ba53d8e3a73222aa54f28f2159509f992167c8e77e779734db2", "code_sha256": "e8b5a7ca1240adbcfc66c6e1e117b01ad692c4faed32381742e0ba9a7313bd83"}, + {"program": "tests/compiler/progs/minmax.osc", "source_sha256": "95c17e1cb5ffc836ef2bcf16ab39246b5c0bbb8acb1c05a6e08b838a12b60b7e", "ir_sha256": "a5ee50c4f631cfda3282c6a6a42842f20986ae4129fa4e22656ea836c8a01543", "code_sha256": "387756318095cc219eec337923bf12440927b254cac189872b17ea617f17ae41"}, + {"program": "tests/compiler/progs/nested.osc", "source_sha256": "8e9aaf037c142ea43dcc4e9013013688eb19f03f24a9e8511058623ced32dc35", "ir_sha256": "94e13f928a06a8d2ddff59030bb412cfcb5e4888570f9b7fc44786c135415c04", "code_sha256": "0eb5b788611a907d360730c08b78c6b0cfbf3a454323b42808f77f8aed300e71"}, + {"program": "tests/compiler/progs/oom.osc", "source_sha256": "1d82ff5262c21e4760b2404dc8fc649863a35ac4a164e4ae6684adcd7cecfc7e", "ir_sha256": "6ce4fcbb5b507668183dd67678a93dad7fe11d7b3f02c2466815712fb300116c", "code_sha256": "5c788e2eef2be25b04013f7bd8378d715756293c36f9509c14e9d5d465e5552a"}, + {"program": "tests/compiler/progs/ops.osc", "source_sha256": "2f68f1cf7d7d4569c90d79e4afc2bbdb9cf1bc2fc39cc8f8e23555c90cdd0223", "ir_sha256": "9742eb592d1cfcd72c622d2ab28fe1dd1fa921f14cd3418662f303be851e1162", "code_sha256": "0c038096a7f33e702937c2979eba15d6fc5a25dd66ba12c5b746df8529e7a959"}, + {"program": "tests/compiler/progs/popcount.osc", "source_sha256": "eab7407d3cfc923d15f52e04e00d96a9e7331b0e2496552b8258e7f88bc65236", "ir_sha256": "15aa9536feb7cbbe9cd03efcf2517321964bb479c0331f45610225c64af186ac", "code_sha256": "04510e1bf63889d5dd0bb7b85eeffb7b016ad87a65a7e0e2209df082f1a9d1db"}, + {"program": "tests/compiler/progs/prefix.osc", "source_sha256": "a4852da0953c8e11e5a9e51d00be81a6cc9e1f9e938cbd9d186f34ccb53cc524", "ir_sha256": "6feaa9af48e493a02a3de461aeae3b88b1c813c9011a462537e88c661704ee63", "code_sha256": "f4c78d8644d86ce7f1edd36ebd6958d5250a34dedde3435587e34dfb2d474362"}, + {"program": "tests/compiler/progs/reborrow.osc", "source_sha256": "caf5e895fcd0660d6ca7c6360228901cb4eee5a7afe128b59334aec904e63feb", "ir_sha256": "34086f590aeaec09669b9656cfca7db57beffb67a59d7e1ba22548336de146b2", "code_sha256": "a6a0a251ed5ddcbc431e38ed73602ee9202fd2d601bd7085ae70ccb5974daf62"}, + {"program": "tests/compiler/progs/scopes.osc", "source_sha256": "9904f63cb89734f2411f04b098640cb0ebe8069a49ae7b1a40c728d434770070", "ir_sha256": "81e996a3c8c6515d57375609aba9ae7c6c5822626b1a8da9cd0943b70db4a1ed", "code_sha256": "e3faba53225b4f3a9398b5d39f6a224b24df08cf9b6a67ca5652a439f0717127"}, + {"program": "tests/compiler/progs/shifts.osc", "source_sha256": "dd33980fb0f3b8d61477b6c197508e3c46d894c0ebc0f99244c01b5e86ee8780", "ir_sha256": "7d2e542f2241ccfacbd6a812c1671733dda94410ede4e3847b43c0955a6f69b3", "code_sha256": "c07f4547cac6e250b1c76021f0955fd530844fcc593a33192592ee0f917ecf59"}, + {"program": "tests/compiler/progs/shortcircuit.osc", "source_sha256": "c3f272b3f6b6d27c9cde9887197e73dd622ea30ff802fb87c250a5e2f704e1d0", "ir_sha256": "863365c4653fb44aac42316b1cde491107ad739d58b7af5b4b55e3a2774c5d41", "code_sha256": "bbd44412068130fdf65d66f718f74c6e0e7e36ee19282f19e5c2f3bbcf66ba2e"}, + {"program": "tests/compiler/progs/sixparams.osc", "source_sha256": "535fead297b7c4b7946c25b0b1f716634b4342701c3ff486dbd8189ed8bc3770", "ir_sha256": "176dee2ab6b66ff28dc04f095964c51f59dcda5518a9696a95a9c588dd78083e", "code_sha256": "c1e8cf802ef21c2b08b08dd266303c715e64ab7323cb5267fe2492de1e54cee8"}, + {"program": "tests/compiler/progs/types.osc", "source_sha256": "ca4d49a4aca05b04e9935dd7cc560a023c4e4cffa36ff84c7755883a90c2b0d5", "ir_sha256": "f623556285814fbd02241fe4f24025bf93811581655beab6073e8d867b42b3a5", "code_sha256": "45c042eeb15cebf30615b7ad341b58a41bd805d83a08c358304b4284785eee35"} + ], + "omega_core_sources_unchanged_vs_base": true, + "m6_m9_m14_gates": {"m6": {"total": 10, "passed": 10, "failed": 0}, "m9": {"total": 10, "passed": 10, "failed": 0}, "m14": {"total": 10, "passed": 10, "failed": 0}}, + "self_host": "no: the OSC-1 compiler cannot compile any part of itself (docs/osc/OSC-1-SELF-HOST-STATEMENT.md)", + "not_covered": "contract enforcement (OSC-2), effects/capabilities, structs, strings, generations, arenas, unsafe physical, FFI, Flow IR optimisation, self-hosting (OSC-14); not a general Omega compiler", + "timing_measured": false +}