interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / docs / osc / OSC-2-DESIGN.md

545 lines · 31146 bytes Raw Blame History Rendered
1# OSC-2: the second compiler slice (design, normative)
2
3OSC-2 slice; not a general Omega compiler; no self-hosting.
4
5Status note 2026-10-01: OSC-2 items 1 to 4 are merged (omega#148 `0abdb08` contracts, #149 `845dce4` structs, #150 `c773622` arenas, #151 `7e713e3` writer range checks). Status is IMPLEMENTED / NOT QUALIFIED (host receipts only). Shortfalls against the ADR and audit III.7 are listed in the addendum of `docs/osc/OSC-1-SELF-HOST-STATEMENT.md`.
6
7OSC-2 extends the OSC-1 slice (`docs/osc/OSC-1-DESIGN.md`) item by item. Everything
8OSC-1 states stays in force unless a section below changes it. Each item ships with
9its own golden programs, named negatives, fuzz coverage and a receipt
10(`make osc2-receipt ITEM=<name>`, schema `omega.osc2.compiler.receipt.v1`, written to
11`evidence/OSC-2/receipts/osc2-<item>-<sha256>.json`).
12
13## 1. Contracts
14
15### 1.1 Subset statement
16
17OSC-1 parsed `requires` / `ensures` and recorded them as text only. OSC-2 item 1 makes
18them enforced contracts:
19
20- a clause is a pure `bool` expression of the OSC-1 expression grammar;
21- a clause that constant folding decides false is refused at compile time;
22- every other clause is checked at run time, by a check lowered into the IR, so
23 native code and the reference interpreter run the same check and report the same trap;
24- there is no symbolic proof: anything constant folding cannot decide is left to the
25 run-time check.
26
27Functions without clauses compile to byte-identical IR and machine code compared with
28OSC-1 (checked for every program in `tests/compiler/progs/` that existed before OSC-2).
29
30### 1.2 Grammar change
31
32```
33fn_decl = "fn" ident "(" [ params ] ")" [ "->" type ]
34 [ "requires" expr ] [ "ensures" expr ] block ;
35```
36
37`clause = { token }` from OSC-1 section 2 is replaced by `expr`. The clause must be
38followed by `ensures` (after `requires`) or by the function's `{`. An empty clause is a
39SYNTAX error. The source text is still recorded in `OscFunc.requires_text` /
40`ensures_text` (it is part of the canonical IR encoding, unchanged from OSC-1), rebuilt
41from the clause tokens with the OSC-1 spacing rule. Longer than 255 bytes is CAPACITY.
42
43### 1.3 Names a clause may use
44
45| clause | may use |
46|-----------|---------|
47| `requires` | parameters; element reads `p[i]` through any array parameter (`own`, `&`, `&mut`) |
48| `ensures` | parameters; `result` (the return value) in a non-void function; element reads only through shared `&` parameters |
49
50- Contracts are pure. A call inside a clause is refused: CONTRACT_INVALID, transition
51 `call in contract`, object = callee. (This rules out side effects and keeps the
52 evaluation order of a contract trivially the same in both engines.)
53- `result` in `requires`: CONTRACT_INVALID, object `result`, transition `result in requires`.
54- `result` in the `ensures` of a void function: CONTRACT_INVALID, object `result`,
55 transition `result in void function`.
56- An element read in `ensures` through an `own` or `&mut` parameter: CONTRACT_INVALID,
57 object = the array, transition `array read in ensures`. (The body may have changed or
58 moved that array; a shared borrow cannot change while the call runs.)
59- `result` is a name only inside an `ensures` clause. A parameter named `result` in a
60 function that has an `ensures` clause is REDEFINED_NAME (transition
61 `parameter named result with ensures`).
62- Any other name is UNDEFINED_NAME (locals of the body are not in scope).
63- A clause that is not `bool` is TYPE_MISMATCH with object `requires` / `ensures`. All
64 other OSC-1 expression rules (AMBIGUOUS_WIDTH, static OVERFLOW folding, ...) apply
65 unchanged.
66- Parameters are immutable, so `ensures` sees the values the function was called with.
67- An element read in `requires` is traced as a read at function entry (ownership trace).
68
69### 1.4 Static enforcement (constant folding only)
70
71The checker evaluates clauses with the same arithmetic as the interpreter (wrap for
72unsigned, checked for signed). A sub-expression that would trap, an element read and a
73call are "unknown". `&&` and `||` are decided left to right, so `false && x` is false and
74`true || x` is true. Three refusals, all CONTRACT_VIOLATION with `origin_line` = the line
75of the clause and `other` = the clause text:
76
77| transition | line | object | when |
78|------------|------|--------|------|
79| `requires is constant false` / `ensures is constant false` | clause | function | the clause folds to false on its own |
80| `requires false at call` | call | callee | the arguments of a call fold to constants that make the callee's `requires` fold to false |
81| `ensures false at return` | `return` | function | a `return` with a constant value makes `ensures` fold to false |
82
83### 1.5 Run-time checks
84
85- `requires` is checked once, on the callee side, at function entry, before the first
86 statement. False: TRAP REQUIRES (code 9).
87- `ensures` is checked at every `return` (and at the fall-off end of a void function)
88 after the return value is computed and before the releases of the scopes being left.
89 False: TRAP ENSURES (code 10).
90- A contract trap ends the run like every OSC-1 trap: no destructors run; owners that were
91 live stay live in the pool log.
92- A clause obeys the checked semantics: signed overflow inside a clause traps OVERFLOW,
93 a dynamic out-of-range element index traps BOUNDS, and so on, before the contract's own
94 verdict.
95- Lowering: `v = clause; CBR v ok bad; bad: TRAP code; BR ok; ok: ...`. The interpreter
96 executes the same instructions, so both engines report the identical trap.
97
98Trap codes 9 and 10 are appended to the OSC-1 list; existing codes are never renumbered.
99`OSC_TRAP_MAX` = 10. The back end emits a trap stub only for codes a unit uses, so units
100without contracts produce the same bytes as OSC-1.
101
102### 1.6 Elision
103
104- A clause that folds to true on its own gets no run-time check at all.
105- A `return` whose constant value makes `ensures` fold to true gets no check at that return.
106
107### 1.7 Evidence
108
109- Golden programs: `tests/compiler/progs/contracts_basic.osc`, `contracts_requires.osc`,
110 `contracts_ensures.osc` (passing calls, TRAP REQUIRES, TRAP ENSURES, OVERFLOW and
111 BOUNDS inside a clause, void `ensures`, elided clauses), each with hand-computed
112 `expect-run` lines checked in both engines.
113- Negatives in `tests/compiler/neg/`: `cv_requires_false_at_call`, `cv_constant_false_clause`,
114 `cv_ensures_static`, `cv_ensures_constant_false`, `ci_result_in_requires`,
115 `ci_result_in_void`, `ci_call_in_contract`, `ci_array_read_ensures`,
116 `tm_non_bool_clause`, `undefined_in_clause`.
117- Contract fuzz (`test_osc_compiler`): generated units whose functions carry random
118 `requires` / `ensures`; each unit compiles or is refused with CONTRACT_VIOLATION only;
119 compiled units run native vs interpreter with 0 mismatches and must hit both
120 TRAP REQUIRES and TRAP ENSURES.
121
122## 2. Structs
123
124### 2.1 Subset statement
125
126OSC-2 item 2 adds fixed-layout structs to the OSC-1 subset. A struct is a named group of
127fields that lives in one pool allocation and is handled exactly like an owned array: it is
128created by its owner, moved, borrowed with `&` / `&mut`, and released at scope end. A struct
129is never a value: there is no struct copy, compare, or return. OSC-2 slice; not a general
130Omega compiler; no self-hosting.
131
132### 2.2 Grammar
133
134```
135unit := (struct | fn)*
136struct := "struct" NAME "{" field ("," field)* "}"
137field := NAME ":" ftype
138ftype := scalar | "[" scalar ";" INT "]" scalar = integer type or bool
139type := ... | "own" NAME | "&" NAME | "&mut" NAME (NAME = a declared struct)
140let := ... | "let" NAME ":" "own" NAME "=" NAME "{" init ("," init)* "}" ";"
141init := NAME ":" expr (scalar field)
142 | NAME ":" "[" expr ";" INT "]" (array field, INT = its length)
143expr := ... | NAME "." NAME | NAME "." NAME "[" expr "]"
144stmt := ... | NAME "." NAME "=" expr ";" | NAME "." NAME "[" expr "]" "=" expr ";"
145```
146
147- `struct` declarations sit at unit level, before any function that names them.
148 `struct` is now a keyword and `.` a token.
149- A struct literal appears only as the initialiser of `let x: own S = S { ... }`.
150 Fields may be listed in any order. The values are evaluated in source order.
151- A local, parameter, or binding of struct type is always `own S`, `&S`, or `&mut S`.
152
153### 2.3 Layout (fixed, part of the IR digest)
154
155- Every field takes whole 8-byte cells, in declaration order. A scalar takes 1 cell and
156 `[T; N]` takes N cells. Field offsets are prefix sums, with no padding and no reordering.
157 Example: `struct L { a: u8, b: [i16; 3], c: bool, d: [u64; 2], e: i64 }` has offsets
158 0 1 4 5 7 and uses 8 cells. `test_osc_compiler` asserts this.
159- A struct owner is one pool allocation of `ncells` cells. This uses the same `alloc` /
160 `release` events and the same 64-slot pool as arrays.
161- IR: `OscUnit.structs[]` records each struct's name, fields (name, scalar type, array length,
162 offset) and cell count. `osc_ir_validate` re-checks the prefix sums. A struct reference
163 type is `OSC_T_REF` with `sid` = struct index + 1. Two new instructions are added,
164 `FLOAD dst, a, idx|-1, field` and `FSTORE a, idx|-1, value, field`. FSTORE needs an own or
165 `&mut` reference.
166- Encoding: a unit with no structs encodes exactly as in OSC-1 (version byte 1), so every
167 existing program keeps byte-identical IR and machine code. A unit with structs uses version
168 byte 2 and adds the struct table (names, field types, lengths, offsets, cell counts), so
169 the digest binds the layout. Reordering two fields changes the digest.
170
171### 2.4 Semantics
172
173- **Creation.** `let s: own S = S { f: e, ... }` allocates one object and stores every
174 field. An array field `[e; N]` fills all N elements with `e`.
175- **Field access.** `s.f` reads and `s.f = v` writes. For an array field, `s.f[i]` reads and
176 `s.f[i] = v` writes, with the same bounds checks as arrays: a constant index outside
177 0..N-1 is STATIC_OUT_OF_BOUNDS, and a dynamic one traps with TRAP BOUNDS (3) in both the
178 interpreter and native code. A field is used at its declared type. Arithmetic follows the
179 OSC-1 rules (wrap for unsigned types, overflow trap for signed types).
180- **Ownership (OSC-0B, as for arrays).**
181 - `let t: own S = s;` and passing `s` to an `own S` parameter are moves. Any later use of
182 `s` is USE_AFTER_MOVE.
183 - `&s` and `&mut s` follow the same lexical borrow rules as arrays: no `&mut` together with
184 any other live borrow (MUTABLE_ALIAS), no write through `&` (READ_ONLY_BORROW), and no
185 borrow outliving its owner (BORROW_OUTLIVES_OWNER).
186 - Struct borrows produce the same model trace events, which are replayed against the
187 OSC-0B model.
188- **Destruction.** Owners are released at scope end in reverse declaration order, structs
189 and arrays alike. A moved-from owner is not released again.
190 `tests/compiler/progs/structs_dtor.osc` asserts the event sequence alloc 1 2 3,
191 release 3 2, alloc 4, release 4 1 in both engines.
192- **Functions.** A struct passes as `own S`, `&S`, or `&mut S`. Returning a struct (any
193 `-> S`, `-> own S`, `-> &S`) is refused as UNSUPPORTED, transition `struct return type`.
194 Bare `S` as a parameter or local type is UNSUPPORTED (`struct by value`).
195- **Contracts.**
196 - `requires` may read fields (and array-field elements) through any struct parameter.
197 - `ensures` may read them only through a shared `&S` parameter; otherwise the clause is
198 CONTRACT_INVALID (`struct field read in ensures`). This is the same rule as array
199 element reads (section 1.3): an `own` or `&mut` parameter may have changed by the time
200 of the return.
201
202### 2.5 Diagnostics
203
204New kinds (appended; existing kinds unchanged):
205
206| Kind | Transition | Cause |
207|---|---|---|
208| UNKNOWN_FIELD | `access unknown field` / `initialise unknown field` | `s.z` or `S { z: .. }` with no field `z` |
209| DUPLICATE_FIELD | `field initialised twice` / `field declared twice` | a field given twice in a literal or declaration |
210| MISSING_FIELD | `field not initialised` | a literal omits a field |
211| UNDEFINED_TYPE | `undefined struct type` | a type name that is not a declared struct |
212| RECURSIVE_STRUCT | `struct field of its own type` | a field whose type names the struct itself |
213
214Existing kinds used by structs:
215
216- **TYPE_MISMATCH:**
217 - a field given a value of the wrong type
218 - a literal of another struct
219 - an array field set without `[e; N]`, or with the wrong N
220 - indexing a struct, or `.f` on an array
221 - indexing a scalar field, or using an array field without an index
222 - a struct used as a scalar
223 - a struct passed or moved where another struct type is needed
224- **UNSUPPORTED:**
225 - `empty struct`
226 - `struct-typed field`
227 - `owner or borrow field`
228 - `struct by value`
229 - `struct return type`
230 - `alloc of a struct`
231- **CAPACITY:** `struct capacity`, `field capacity`, `struct size`.
232- **REDEFINED_NAME:** `struct declared twice`.
233- **STATIC_OUT_OF_BOUNDS** on `s.f[k]`.
234- **CONTRACT_INVALID:** `struct field read in ensures`.
235
236### 2.6 Limits
237
238- At most 16 structs per unit.
239- Each struct has 1 to 16 fields and at most 64 cells.
240- An array field is `[T; N]` of any integer type or bool, N >= 1.
241- Fields cannot be structs, owners, or borrows.
242- Struct literals appear only in `let own` initialisers.
243
244### 2.7 Evidence
245
246- Golden programs:
247 - `structs_fields.osc`: layout use, field read/write, array fields, TRAP BOUNDS.
248 - `structs_owner.osc`: moves, own / `&` / `&mut` parameters, borrow bindings.
249 - `structs_contracts.osc`: TRAP REQUIRES and TRAP ENSURES on fields.
250 - `structs_dtor.osc`: destruction order.
251- Negatives in `tests/compiler/neg/st_*.osc` (36), each asserting kind, object, line, and
252 transition. They include:
253 - unknown field
254 - duplicate field init
255 - missing field init
256 - field type mismatch
257 - write through shared borrow
258 - use after move
259 - mutable alias
260 - borrow outlives owner
261 - recursive struct
262 - undefined struct type
263- `test_osc_compiler` adds:
264 - the layout assertion, with the digest binding the layout and struct-free units still
265 using version 1;
266 - the destruction-order event check;
267 - **struct fuzz:** generated units with random field types, literals, field writes,
268 moves, and `&` / `&mut` / own calls with `requires` on fields. Every unit compiles,
269 and native and interpreter outcomes are identical (`struct fuzz: ... mismatches=0`) in
270 the plain and ASan/UBSan runs. The fuzz must hit TRAP BOUNDS and TRAP REQUIRES.
271
272## 3. Arenas
273
274### 3.1 Subset statement
275
276OSC-2 item 3 wires the OSC-0B region rules (model events REGION_OPEN, ALLOC with a region,
277REGION_DESTROY) into the compiler. An arena is a bounded block of cells. Objects allocated
278in it are never released one by one: the whole arena is destroyed when its block ends.
279OSC-2 slice; not a general Omega compiler; no self-hosting.
280
281### 3.2 Grammar
282
283```
284stmt := ... | "arena" NAME "bound" INT block (INT = K, 1..64 cells)
285let := ... | "let" NAME ":" "own" "[" scalar ";" INT "]" "in" NAME "=" "alloc" "(" expr ")" ";"
286 | "let" NAME ":" "own" NAME "in" NAME "=" NAME "{" init ("," init)* "}" ";"
287```
288
289- `arena` is now a keyword. `in` (already a keyword for `for`) also names the arena of an
290 allocation.
291- The arena name is visible only inside its block, so allocating from an arena outside its
292 block is impossible: the name is undefined there (UNDEFINED_NAME).
293- An arena name is not a value. Any other use of it is TYPE_MISMATCH (`arena used as a
294 value`). It cannot be passed to a function or returned.
295
296### 3.3 Semantics
297
298- **Capacity.** K counts 8-byte cells. `[T; N]` uses N cells and a struct uses its cell
299 count (section 2.3). An allocation is *definite* when it is in the arena's own
300 straight-line code: same loop depth and same branch depth as the `arena` statement
301 (nested arena blocks count as straight-line code). The checker adds up definite
302 allocations; going over K is refused (ARENA_CAPACITY). Every other allocation (inside a
303 `while` / `for` body or an `if` / `else` branch) is checked at run time: past K the run
304 traps with TRAP ARENA_FULL (11) in both the interpreter and native code.
305- **Runtime.** An arena takes one slot of the 64-slot pool (the lowest free one, like any
306 allocation; no free slot is TRAP OOM) and bump-allocates its objects inside that slot's
307 cells. Cells are filled with the initial value at allocation and zeroed at destroy.
308- **Destruction order (deterministic).** At the end of an arena block (normal end, or a
309 `return` from inside it):
310 1. the unique owners declared inside the block are released, in reverse declaration
311 order (OSC-1 rule);
312 2. then the arena is destroyed: one REGION_DESTROY frees all its objects at once.
313 Nested arenas: the inner block ends first, so the inner arena is destroyed before the
314 outer one. A `return` destroys every enclosing arena, innermost first, interleaved with
315 the releases of each scope. `tests/compiler/progs/arena_dtor.osc` asserts the exact event
316 sequence (alloc 1, open 2, arena alloc 3, open 4, arena alloc 5, alloc 6, release 6,
317 destroy 4, alloc 7, release 7, destroy 2, release 1) in both engines.
318- **Borrows.** `&x` and `&mut x` of an arena object follow the OSC-1 lexical rules
319 (MUTABLE_ALIAS, READ_ONLY_BORROW, `&` / `&mut` parameters). A borrow of an arena object
320 may not outlive the arena: assigning it to a borrow binding declared outside the arena
321 block, or returning it, is ARENA_ESCAPE. The model rejects the same situation (a
322 REGION_DESTROY while a borrow of one of its objects is live) as `arena-escape`.
323- **Moves (slice restriction).** Every move that involves an arena object is refused with
324 ARENA_MOVE: `let y: own .. = x;` with `x` in an arena (`move out of arena`), passing `x`
325 to an `own` parameter (`move into own parameter`), and `let x: own .. in r = y;`
326 (`move into arena`). The OSC-0B model allows a move inside a region (the new owner
327 inherits the region); this slice is stricter than the model and refuses all of them.
328- **Model trace.** The checker trace gains REGION_OPEN (at `arena`), ALLOC with the region
329 id (for `in r`) and REGION_DESTROY (at block end), with per-function region ids 1..16.
330 Arena objects get no RELEASE event. Golden and fuzz traces replay through the model with
331 ACCEPT; an ARENA_ESCAPE refusal ends its trace in the refused REGION_DESTROY, which the
332 model rejects with `arena-escape` (model-agreement test).
333- **Runtime event log.** `osc_rt` logs REGION_OPEN (slot, K, region serial), ARENA_ALLOC
334 (slot, length, object serial) and REGION_DESTROY next to ALLOC / RELEASE. Interpreter and
335 native code produce identical logs (checked on every differential run). Releasing an arena
336 slot with RELEASE is a runtime invariant violation (TRAP RUNTIME, never seen for checked
337 code).
338- **IR.** Three instructions are added. `AOPEN dst, K` puts a u64 arena handle in `dst`.
339 `AALLOC dst, init, h` allocates `dst` (an own reference or struct) from handle `h`.
340 `ADESTROY h` destroys the arena. The validator enforces a handle discipline: a handle
341 register is defined once, by AOPEN only, is never a parameter, and is used only as the
342 handle operand of AALLOC / ADESTROY. Native code calls the runtime through three new
343 OscRt entry points at offsets 24, 32 and 40 (`arena_open`, `arena_alloc`,
344 `arena_destroy`).
345- **Encoding.** A unit with no arena instruction encodes exactly as before (version byte 1
346 without structs, 2 with structs), so every existing program keeps byte-identical IR and
347 machine code (checked: all 31 earlier golden programs and all 82 earlier negatives give
348 the same oscc output as origin/main). A unit with arena instructions uses version byte 3,
349 always writes the struct table, and encodes the new instructions.
350
351### 3.4 Diagnostics
352
353New kinds (appended; existing kinds unchanged):
354
355| Kind | Transition | Cause |
356|---|---|---|
357| ARENA_ESCAPE | `outer borrow assigned a borrow of an arena object` / `borrow of an arena object returned` / `borrow live at arena end` | a borrow of an arena object outlives the arena |
358| ARENA_MOVE | `move out of arena` / `move into own parameter` / `move into arena` | any move of an arena object (slice restriction) |
359| ARENA_CAPACITY | `arena bound outside 1..64` / `arena capacity exceeded` | K not in 1..64; definite allocations over K |
360
361`borrow live at arena end` is a defence in depth: with lexical borrows the two other
362ARENA_ESCAPE checks catch every escape first, so no test reaches it.
363
364Existing kinds used by arenas:
365
366- **UNDEFINED_NAME:** `allocate in undefined arena` (unknown name, or an arena used after
367 its block).
368- **TYPE_MISMATCH:** `in a non-arena` (`in x` where `x` is not an arena), `arena used as a
369 value`.
370- **REDEFINED_NAME:** an arena name that shadows a visible name (no shadowing, OSC-1 rule).
371
372New trap: TRAP ARENA_FULL = 11 (`OSC_TRAP_ARENA_FULL`, now `OSC_TRAP_MAX`).
373
374### 3.5 Limits
375
376- K is 1..64 cells (one pool slot). An arena uses one of the 64 pool slots while open.
377- The static model trace holds 16 arenas per function (the model's region capacity). A function
378 with more still compiles, but its trace is marked overflow and is not replayed (same rule
379 as the 64-object and 64-borrow limits).
380- Objects are never moved into, out of, or between arenas.
381- Arena objects cannot be released early; there is no per-object free.
382- Arena names are not values: no arena parameters, returns, or arenas outliving their block.
383
384### 3.6 Evidence
385
386- Golden programs:
387 - `arena_basic.osc`: basic allocation, `return` from inside an arena, unique owners mixed
388 with arena objects.
389 - `arena_nested.osc`: nested arenas, allocation into the outer arena from the inner
390 block, sibling arenas reusing a slot.
391 - `arena_structs.osc`: struct literals in an arena.
392 - `arena_borrows.osc`: `&` / `&mut` borrows and parameters on arena objects.
393 - `arena_full.osc`: allocations in a loop and in a branch, TRAP ARENA_FULL.
394 - `arena_dtor.osc`: destruction order (event sequence above).
395- Negatives in `tests/compiler/neg/ar_*.osc` (14), each asserting kind, object, line, and
396 transition: escape through an outer borrow, escape by return, move out, move into, move
397 into an own parameter, static capacity, bound 0, bound 65, undefined arena, `in` a
398 non-arena, arena shadowing, allocation after the block, arena object used after the
399 block, arena used as a value. The two ARENA_ESCAPE negatives also pass the
400 model-agreement check (`ARENA_ESCAPE` maps to the model's `arena-escape`).
401- `test_osc_backend` adds the arena validator cases (bad bound, handle type, double
402 definition, allocation or destroy from a non-handle, handle used as a value or redefined).
403- `test_osc_compiler` adds:
404 - the arena destruction-order event check (`arena destruction order: ...`);
405 - **arena fuzz:** generated units with nested arenas of random bound, array and struct
406 allocations into any visible arena, unique owners, borrows passed to `&` / `&mut`
407 parameters, and allocations in loops and branches. Every unit compiles, native and
408 interpreter outcomes are identical (`arena fuzz: ... mismatches=0`) in the plain and
409 ASan/UBSan runs, and the fuzz must hit TRAP ARENA_FULL;
410 - **runtime model replay:** the runtime event log of every native run in the test
411 (golden fuzz, expect-run lines, contract, struct and arena fuzz, destruction-order
412 tests) is replayed through the OSC-0B model. A run that returns replays fully; a run
413 that traps replays the prefix logged before the trap. Object and region ids are
414 windowed when a run exceeds 64 objects or 16 regions (a new window re-opens the open
415 regions and re-allocates the live objects). The line
416 `runtime model replay: runs=.. events=.. accepted=.. rejected=0` must report
417 `rejected=0`. **This checks the runs that were executed. It is not a proof that every
418 program's runtime behaviour satisfies the model.**
419- `make osc2-receipt ITEM=arenas` records the arena fuzz lines, the destruction order, the
420 runtime model replay lines (plain and ASan) and the ARENA_FULL run count.
421
422## 4. Legacy AArch64 writer
423
424### 4.1 Statement
425
426`src/aarch64_encoder.c` is the instruction writer used by the existing Omega code
427(`omega_program_realize`, the matvec emitters, `omega_self_host`, `omega_exec`, the
428polyglot encoder, `rx_omega`, the M5/M6/M9/M14 gates). Up to OSC-1 it trimmed fields
429silently (`rm & 0x1f`, `imm19 & 0x7FFFF`, `(uoff >> scale) & 0xFFF`, `simm9 & 0x1FF`,
430`(shift / 16) & 3`, ...), which OSC-0 III.6 says must be hardened (OSC-1-DESIGN.md
431section 9 left it untouched). OSC-2 item 4 takes option A (fix, not retire):
432
433- every emitter checks every field against its exact architectural range before it
434 encodes anything;
435- an in-range call produces the same word as before: the encoding formulas are
436 unchanged and their masks are now no-ops;
437- an out-of-range field is refused, never trimmed (4.3);
438- the set of files that use the writer is frozen (4.4). New code uses the validating
439 encoder `src/compiler/osc_a64.c`.
440
441Option B (keep trimming for a caller that relies on it) was not needed: an audit of all
442280 call sites found no caller that passes an out-of-range field. Every constant is in
443range; computed values are either range-checked by the caller first
444(`src/polyglot/omx_encoder.c`, its `resolve()` branch fix-ups), already cast to the
445parameter type by the caller (`omega_self_host.c` instruction counts), or registers
446X0..X17/XZR. The M6/M9/M14 gates and the host suites in 4.5 run through the strict writer
447and pass unchanged.
448
449### 4.2 Ranges (normative)
450
451| Emitter | Field | Accepted |
452|---|---|---|
453| all | `rd` `rn` `rm` `rt` | 0..31 (31 is XZR or SP, as the instruction defines) |
454| all with `sf` | `sf` | C `bool` (0 or 1 by type) |
455| `movz` `movk` | `imm16` | 0..65535 (`uint16_t`) |
456| `movz` `movk` | `shift` | 0, 16, 32, 48 when `sf` = 1; 0, 16 when `sf` = 0 |
457| `b` | `imm26` (words) | -2^25 .. 2^25 - 1 |
458| `b_cond` | `cond` | 0..15 |
459| `b_cond` `cbz` `cbnz` | `imm19` (words) | -2^18 .. 2^18 - 1 |
460| `adr` | `imm21` (bytes) | -2^20 .. 2^20 - 1 |
461| `ldr_uoff` `str_uoff` | `uoff` (bytes) | multiple of 8 (`sf` = 1) or 4 (`sf` = 0), `uoff / size` <= 4095 |
462| `ldrb_uoff` `strb_uoff` | `uoff` (bytes) | 0..4095 |
463| `ldr_post` `str_post` `ldr_x_post` `str_x_post` | `simm9` | -256..255 |
464| `subs_imm` | `imm12` | 0..4095 |
465
466`ret` has no fields. The "buffer full" result (-1, nothing written) is unchanged.
467
468### 4.3 Refusal path
469
470A refused call writes nothing and does not advance `*pos`. It prints exactly one line on
471stderr,
472
473```
474A64_LEGACY_FIELD_OUT_OF_RANGE <emitter> <field>=<value>
475```
476
477(`<emitter>` is the C function name, e.g. `aarch64_emit_cbz`; `<field>` is the parameter
478name; `<value>` is the received value in signed decimal), and then calls `abort()`
479(SIGABRT). Abort is deliberate and deterministic: several existing callers ignore the
480emitter's `int` result (for example the matvec emitters), and this item may not change
481callers, so a soft error would silently drop an instruction and produce wrong code. A
482refusal is a bug in the caller.
483
484### 4.4 No new callers
485
486`tests/compiler/legacy_a64_allowlist.txt` lists the 17 C files that include
487`aarch64_encoder.h` or name an `aarch64_emit_*` function (14 callers, the writer itself
488and its header, this item's test, and `seed/check/a64check.c`, a reference check that uses
489the writer only as an oracle for the seed's hand-written words and makes no program with it).
490`tests/compiler/legacy_a64_callers.sh` scans every
491tracked and untracked (not ignored) `*.c` / `*.h` file and requires the set to equal the
492list:
493
494- `A64_LEGACY_NEW_CALLER <file>`: a file not on the list uses the writer;
495- `A64_LEGACY_ALLOWLIST_STALE <file>`: a listed file no longer uses it (drop the line;
496 the list may only shrink).
497
498`--selftest` first proves both refusals fire on a synthetic tree (a new includer, a new
499direct caller, a stale line). It runs in `make test-compiler`. The CI `compiler` job
500guard now also triggers on `src/aarch64_*` changes.
501
502### 4.5 Evidence
503
504- `tests/compiler/test_legacy_a64.c` (in `make test-compiler`, plain and ASan/UBSan):
505 - **differential:** the pre-OSC-2 formulas are kept in the test as the oracle
506 (`old_*`). For all 25 emitters, in-range fields give the oracle's word. The field
507 space is covered exhaustively for the register-register forms, `mov_reg`,
508 `movz`/`movk` (all registers, immediates and shifts), `b_cond` (all conditions and
509 offsets), `ldr`/`str` unsigned offset, `ldrb`/`strb`, the post-index forms and
510 `subs_imm`; `b`, `cbz`, `cbnz` and `adr` use 400 000 seeded random samples each with
511 every range edge (about 71 million words in all). Each word also decodes through
512 `src/aarch64_decoder.c` to the same operation and to every field that decoder reports
513 (`sf`, registers, `imm16`/`hw`, condition, raw branch field). The decoder does not
514 report load/store or `subs` immediates or the ADR offset, so the test checks the
515 `imm12` field of `ldr`/`str` and the reassembled ADR offset from the word directly.
516 Line: `legacy a64 differential: emitters=25 mode=full words=.. decoded=.. mismatches=0`.
517 The ASan leg runs `quick` (strided samples, same edges).
518 - **refusal:** 90 cases, every field of every emitter that has one, just outside its
519 range and at extremes (for example `rd=32`, `shift=17`, `shift=32` with `sf` = 0,
520 `imm26=2^25`, `cond=16`, misaligned `uoff`, `simm9=-257`). Each runs in a child
521 process with output buffer and position in shared memory; the child must die by
522 SIGABRT with exactly the line of 4.3 on stderr and must not touch buffer or position
523 (core dumps disabled in the child). Line:
524 `legacy a64 refusal: cases=90 named_abort_and_no_write=90`.
525 - mutation check (done once, not in the suite): removing the `simm9` check, or changing
526 one bit of the `mul_reg` formula, makes the test fail.
527- M6/M9/M14 gate output (from `omegatool --run` on) is byte-identical to the baseline
528 taken before this item.
529- Host suites that link the writer were run on one core and pass (list and results in
530 the item report); suites that need the GB10, the resident seat or the quiet flag were
531 not run.
532- `make osc2-receipt ITEM=encoder` records the differential, ASan and refusal lines, the
533 caller check line and, with `PHYSICS_DIR` set, the M6/M9/M14 gates.
534
535### 4.6 Not covered
536
537- Instructions are checked field by field; the writer still does not know whether a
538 register choice is legal for a particular form beyond 0..31 (for example it does not
539 refuse SP where an instruction reads XZR). Callers keep that responsibility; the OSC-1
540 encoder `osc_a64.c` is the one that checks SP vs XZR.
541- `src/aarch64_decoder.c` is unchanged: it still decodes only the subset above and keeps
542 no load/store or `subs` immediate.
543- The allowlist check scans C files only; it does not stop a caller written in another
544 language or one that declares the functions itself under another spelling.
545- Refusal ends the process; there is no recoverable error API for the legacy writer.