diff --git a/docs/osc/OSC-1-DESIGN.md b/docs/osc/OSC-1-DESIGN.md index fe33a4c57..9be6cf84d 100644 --- a/docs/osc/OSC-1-DESIGN.md +++ b/docs/osc/OSC-1-DESIGN.md @@ -26,7 +26,7 @@ and control-flow core needed to write programs that exercise it: - 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** +- `requires` / `ensures` clauses parsed and recorded as text, **not checked** (superseded by OSC-2 item 1: `docs/osc/OSC-2-DESIGN.md` section 1) (OSC-0 decision 3, III.6). Enforcement is OSC-2 and mandatory before any production C migrates. diff --git a/docs/osc/OSC-2-DESIGN.md b/docs/osc/OSC-2-DESIGN.md new file mode 100644 index 000000000..35d9acce2 --- /dev/null +++ b/docs/osc/OSC-2-DESIGN.md @@ -0,0 +1,118 @@ +# OSC-2: the second compiler slice (design, normative) + +OSC-2 slice; not a general Omega compiler; no self-hosting. + +OSC-2 extends the OSC-1 slice (`docs/osc/OSC-1-DESIGN.md`) item by item. Everything +OSC-1 states stays in force unless a section below changes it. Each item ships with +its own golden programs, named negatives, fuzz coverage and a receipt +(`make osc2-receipt ITEM=`, schema `omega.osc2.compiler.receipt.v1`, written to +`evidence/OSC-2/receipts/osc2--.json`). + +## 1. Contracts + +### 1.1 Subset statement + +OSC-1 parsed `requires` / `ensures` and recorded them as text only. OSC-2 item 1 makes +them enforced contracts: + +- a clause is a pure `bool` expression of the OSC-1 expression grammar; +- a clause that constant folding decides false is refused at compile time; +- every other clause is checked at run time, by a check lowered into the IR, so + native code and the reference interpreter run the same check and report the same trap; +- there is no symbolic proof: anything constant folding cannot decide is left to the + run-time check. + +Functions without clauses compile to byte-identical IR and machine code compared with +OSC-1 (checked for every program in `tests/compiler/progs/` that existed before OSC-2). + +### 1.2 Grammar change + +``` +fn_decl = "fn" ident "(" [ params ] ")" [ "->" type ] + [ "requires" expr ] [ "ensures" expr ] block ; +``` + +`clause = { token }` from OSC-1 section 2 is replaced by `expr`. The clause must be +followed by `ensures` (after `requires`) or by the function's `{`. An empty clause is a +SYNTAX error. The source text is still recorded in `OscFunc.requires_text` / +`ensures_text` (it is part of the canonical IR encoding, unchanged from OSC-1), rebuilt +from the clause tokens with the OSC-1 spacing rule. Longer than 255 bytes is CAPACITY. + +### 1.3 Names a clause may use + +| clause | may use | +|-----------|---------| +| `requires` | parameters; element reads `p[i]` through any array parameter (`own`, `&`, `&mut`) | +| `ensures` | parameters; `result` (the return value) in a non-void function; element reads only through shared `&` parameters | + +- Contracts are pure. A call inside a clause is refused: CONTRACT_INVALID, transition + `call in contract`, object = callee. (This rules out side effects and keeps the + evaluation order of a contract trivially the same in both engines.) +- `result` in `requires`: CONTRACT_INVALID, object `result`, transition `result in requires`. +- `result` in the `ensures` of a void function: CONTRACT_INVALID, object `result`, + transition `result in void function`. +- An element read in `ensures` through an `own` or `&mut` parameter: CONTRACT_INVALID, + object = the array, transition `array read in ensures`. (The body may have changed or + moved that array; a shared borrow cannot change while the call runs.) +- `result` is a name only inside an `ensures` clause. A parameter named `result` in a + function that has an `ensures` clause is REDEFINED_NAME (transition + `parameter named result with ensures`). +- Any other name is UNDEFINED_NAME (locals of the body are not in scope). +- A clause that is not `bool` is TYPE_MISMATCH with object `requires` / `ensures`. All + other OSC-1 expression rules (AMBIGUOUS_WIDTH, static OVERFLOW folding, ...) apply + unchanged. +- Parameters are immutable, so `ensures` sees the values the function was called with. +- An element read in `requires` is traced as a read at function entry (ownership trace). + +### 1.4 Static enforcement (constant folding only) + +The checker evaluates clauses with the same arithmetic as the interpreter (wrap for +unsigned, checked for signed). A sub-expression that would trap, an element read and a +call are "unknown". `&&` and `||` are decided left to right, so `false && x` is false and +`true || x` is true. Three refusals, all CONTRACT_VIOLATION with `origin_line` = the line +of the clause and `other` = the clause text: + +| transition | line | object | when | +|------------|------|--------|------| +| `requires is constant false` / `ensures is constant false` | clause | function | the clause folds to false on its own | +| `requires false at call` | call | callee | the arguments of a call fold to constants that make the callee's `requires` fold to false | +| `ensures false at return` | `return` | function | a `return` with a constant value makes `ensures` fold to false | + +### 1.5 Run-time checks + +- `requires` is checked once, on the callee side, at function entry, before the first + statement. False: TRAP REQUIRES (code 9). +- `ensures` is checked at every `return` (and at the fall-off end of a void function) + after the return value is computed and before the releases of the scopes being left. + False: TRAP ENSURES (code 10). +- A contract trap ends the run like every OSC-1 trap: no destructors run; owners that were + live stay live in the pool log. +- A clause obeys the checked semantics: signed overflow inside a clause traps OVERFLOW, + a dynamic out-of-range element index traps BOUNDS, and so on, before the contract's own + verdict. +- Lowering: `v = clause; CBR v ok bad; bad: TRAP code; BR ok; ok: ...`. The interpreter + executes the same instructions, so both engines report the identical trap. + +Trap codes 9 and 10 are appended to the OSC-1 list; existing codes are never renumbered. +`OSC_TRAP_MAX` = 10. The back end emits a trap stub only for codes a unit uses, so units +without contracts produce the same bytes as OSC-1. + +### 1.6 Elision + +- A clause that folds to true on its own gets no run-time check at all. +- A `return` whose constant value makes `ensures` fold to true gets no check at that return. + +### 1.7 Evidence + +- Golden programs: `tests/compiler/progs/contracts_basic.osc`, `contracts_requires.osc`, + `contracts_ensures.osc` (passing calls, TRAP REQUIRES, TRAP ENSURES, OVERFLOW and + BOUNDS inside a clause, void `ensures`, elided clauses), each with hand-computed + `expect-run` lines checked in both engines. +- Negatives in `tests/compiler/neg/`: `cv_requires_false_at_call`, `cv_constant_false_clause`, + `cv_ensures_static`, `cv_ensures_constant_false`, `ci_result_in_requires`, + `ci_result_in_void`, `ci_call_in_contract`, `ci_array_read_ensures`, + `tm_non_bool_clause`, `undefined_in_clause`. +- Contract fuzz (`test_osc_compiler`): generated units whose functions carry random + `requires` / `ensures`; each unit compiles or is refused with CONTRACT_VIOLATION only; + compiled units run native vs interpreter with 0 mismatches and must hit both + TRAP REQUIRES and TRAP ENSURES. diff --git a/evidence/OSC-2/receipts/osc2-contracts-dea8a5499f6ac150198a7cc5473b0e25f623887a74d10ccaa0ca6c85b51a0500.json b/evidence/OSC-2/receipts/osc2-contracts-dea8a5499f6ac150198a7cc5473b0e25f623887a74d10ccaa0ca6c85b51a0500.json new file mode 100644 index 000000000..8271b06f8 --- /dev/null +++ b/evidence/OSC-2/receipts/osc2-contracts-dea8a5499f6ac150198a7cc5473b0e25f623887a74d10ccaa0ca6c85b51a0500.json @@ -0,0 +1,58 @@ +{ + "schema": "omega.osc2.compiler.receipt.v1", + "verdict": "PASS", + "item": "contracts", + "statement": "OSC-2 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; OSC-2 item 1: requires/ensures are pure bool expressions over parameters (and result in ensures; element reads through parameters, ensures only via shared borrows; no calls), refused statically when constant folding decides them false (CONTRACT_VIOLATION), otherwise checked at run time (TRAP REQUIRES = 9 at entry, TRAP ENSURES = 10 at each return before releases; statically true clauses elided)", + "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": "1c7e3a6415887972c59ffa7a332c803e6b78ea74", + "base_commit": "4c8ca18c2e8fa5c56c4f235fc8ba306c6fc22a54", + "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=13006 enc_random_ok=45779 enc_random_refused=126221 dec_random_words=76497 validator_neg=40; checks=798964 failed=0; native == interpreter on every run", + "compiler": "golden=27/27 funcs=105 entries=75 expect_runs=73 diff_runs=86136 trace_replays=65 rt_replays=58537 rt_events=195062 neg=46/46 neg_traced=12 checks=238889 failed=0", + "golden_trap_coverage": {"none": 58537, "overflow": 3089, "div0": 23, "bounds": 3625, "loop_bound": 2100, "cast": 1499, "oom": 365, "shift": 2805, "runtime": 0, "requires": 1307, "ensures": 1650}, + "contract_fuzz": "contract fuzz: units=200 compiled=174 static_refused=26 runs=11136 ok=882 requires=5435 ensures=4384 overflow=435 other_traps=0 mismatches=0; native == interpreter on every run", + "contract_fuzz_asan": "contract fuzz: units=200 compiled=174 static_refused=26 runs=11136 ok=882 requires=5435 ensures=4384 overflow=435 other_traps=0 mismatches=0", + "determinism": "programs=27 identical=27 (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": 27, + "negative_programs": 46, + "golden_corpus_sha256": "a4a06ed4500711c2507ed1d77783d8eb1dbd641ac1ddc581b96d21b390c11405", + "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/contracts_basic.osc", "source_sha256": "8a1370cec47deb9671ef6e4a55a66a94b97d3f34754fa7c64ae741853134bb99", "ir_sha256": "94f2e0f6c9c8c15630725d5105007a7ecdb26212c898219b4d99be340d027ede", "code_sha256": "b7d9a360486ca56847ee83a0dc7731026305a20a9dfd250d2d6bc3197b74a0fc"}, + {"program": "tests/compiler/progs/contracts_ensures.osc", "source_sha256": "4bade10adc6078e9a8cb77b12fd529f0cb733bcf24629018a95402528a0bc3f0", "ir_sha256": "c2a7c5cca6ffd933c90d89d20e0b8dcb5c56fbf831fd9b882ad729de1efefa9f", "code_sha256": "de5746dd6d6c22049987e7bd5bdde6a238fe24785e4c654a852e383a0e657f6a"}, + {"program": "tests/compiler/progs/contracts_requires.osc", "source_sha256": "83f5842fba1f7f027cb655fcff243f1650761afedecb1cd168992a08b7924224", "ir_sha256": "16bc4b6267ee1d4a75cc60d35514baf10cc3f326b3a3e47222ca271587c9dac3", "code_sha256": "599922ff8eff90977309cf593da6cac4f951eb182bdf8a8b156c36ca6c7917ff"}, + {"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-2 compiler slice cannot compile any part of itself (docs/osc/OSC-1-SELF-HOST-STATEMENT.md)", + "not_covered": "contracts beyond constant folding (no symbolic proof), effects/capabilities, structs, strings, generations, arenas, unsafe physical, FFI, Flow IR optimisation, self-hosting (OSC-14); not a general Omega compiler", + "timing_measured": false +} diff --git a/mk/compiler.mk b/mk/compiler.mk index 79dfdc458..b47faf451 100644 --- a/mk/compiler.mk +++ b/mk/compiler.mk @@ -8,9 +8,10 @@ # 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) +# osc2-receipt ITEM= (default contracts): receipt under evidence/OSC-2/receipts (clean tree only) ifndef COMPILER_MK COMPILER_MK := 1 -.PHONY: test-compiler oscc compiler-receipt osc0b-model-receipt +.PHONY: test-compiler oscc compiler-receipt osc0b-model-receipt osc2-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 @@ -68,11 +69,16 @@ test-compiler: $(OSC_DIR)/test_osc_model $(OSC_DIR)/test_osc_model_asan \ @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)" + @grep "^contract fuzz:" $(OSC_DIR)/compiler.out + @echo "test-compiler: PASS (OSC-1 slice + OSC-2 contracts; OSC-2 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 + +osc2-receipt: ITEM ?= contracts +osc2-receipt: + sh tests/compiler/osc2_receipt.sh $(ITEM) endif diff --git a/src/compiler/osc_cg.c b/src/compiler/osc_cg.c index 8688d8985..327d9de4e 100644 --- a/src/compiler/osc_cg.c +++ b/src/compiler/osc_cg.c @@ -37,8 +37,8 @@ typedef struct { 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]; + int64_t trapl[OSC_TRAP_MAX + 1]; + int trap_used[OSC_TRAP_MAX + 1]; Fix *fx; size_t nfx, capfx; uint32_t frame; @@ -321,7 +321,7 @@ static void gen_func(Cg *g, const OscUnit *u, int fi) { 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; } + for (int c = 0; c <= OSC_TRAP_MAX; c++) { g->trapl[c] = -1; g->trap_used[c] = 0; } /* prologue */ E(g, osc_a64_pair(OSC_A64_STP_PRE, 29, 30, SP, -16)); @@ -408,7 +408,7 @@ static void gen_func(Cg *g, const OscUnit *u, int fi) { } } /* trap stubs, in code order */ - for (int c = 1; c <= OSC_TRAP_RUNTIME; c++) { + for (int c = 1; c <= OSC_TRAP_MAX; c++) { if (!g->trap_used[c]) continue; g->trapl[c] = (int64_t)here(g); trap_seq(g, c); diff --git a/src/compiler/osc_check.c b/src/compiler/osc_check.c index 10b807ee4..3e9994e75 100644 --- a/src/compiler/osc_check.c +++ b/src/compiler/osc_check.c @@ -66,6 +66,7 @@ typedef struct { int loop_depth; int term; /* current path has returned */ char sobj[64]; /* statement object (diagnostics) */ + int contract; /* 0 body; 1 checking a requires clause; 2 an ensures clause (OSC-2) */ } C; #define NODE(i) (&c->ast->nodes[(i)]) @@ -568,6 +569,159 @@ static int fold(C *c, int i, OscScalar t, i128 *out) return 0; } + +/* ------------------------------------------------------------ contracts (OSC-2) */ +/* Static evaluation of a checked contract clause (docs/osc/OSC-2-DESIGN.md + * section 1.4). Constant folding only: a leaf is known if it is a literal / + * folded constant, a `true` / `false`, or a name whose value the caller + * supplies (call-site literal arguments, a constant return value). Operators + * follow section 5 of OSC-1 exactly; any operation that would trap at run time + * (overflow, divide by zero, shift range, cast range) makes the result + * unknown, as do array reads and calls. `&&` / `||` are decided left to + * right: the right operand is consulted only when the left one is known. */ +typedef struct { + int nk; /* symbols 0..nk-1 may be known (parameters) */ + uint64_t v[OSC_MAX_PARAMS]; + uint8_t k[OSC_MAX_PARAMS]; + int res_sym; /* `result` symbol, or -1 */ + uint8_t res_known; + uint64_t res_val; +} CEnv; + +static uint64_t ccanon(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 int sfits(unsigned w, i128 r) { return r >= -((i128)1 << (w - 1)) && r <= ((i128)1 << (w - 1)) - 1; } + +/* 1 known (*out canonical for the node's type), 0 unknown */ +static int ceval(C *c, int i, const CEnv *env, uint64_t *out) +{ + const OscNode *n = NODE(i); + if (n->is_const) { *out = n->cval; return 1; } + uint64_t a, b; + switch (n->kind) { + case ON_BOOL: *out = n->ival ? 1 : 0; return 1; + case ON_NAME: + if (n->sym >= 0 && n->sym < env->nk && env->k[n->sym]) { *out = env->v[n->sym]; return 1; } + if (n->sym >= 0 && n->sym == env->res_sym && env->res_known) { *out = env->res_val; return 1; } + return 0; + case ON_UN: { + if (!ceval(c, n->a, env, &a)) return 0; + OscScalar t = n->ty.s; + if (n->op == OT_BANG) { *out = a ^ 1; return 1; } + if (n->op == OT_TILDE) { *out = ccanon(t, ~a); return 1; } + if (osc_scalar_signed(t)) { + i128 r = -(i128)(int64_t)a; + if (!sfits(osc_scalar_width(t), r)) return 0; + *out = (uint64_t)(int64_t)r; + return 1; + } + *out = ccanon(t, 0 - a); + return 1; + } + case ON_CAST: { + if (!ceval(c, n->a, env, &a)) return 0; + OscScalar from = NODE(n->a)->ty.s, to = n->ty.s; + i128 v = osc_scalar_signed(from) ? (i128)(int64_t)a : (i128)a; + unsigned w = osc_scalar_width(to); + i128 lo = osc_scalar_signed(to) ? -((i128)1 << (w - 1)) : 0; + i128 hi = osc_scalar_signed(to) ? ((i128)1 << (w - 1)) - 1 : (((i128)1 << w) - 1); + if (v < lo || v > hi) return 0; + *out = (uint64_t)v; + return 1; + } + case ON_BIN: { + int op = n->op; + if (op == OT_ANDAND || op == OT_OROR) { + if (!ceval(c, n->a, env, &a)) return 0; + if (op == OT_ANDAND && !a) { *out = 0; return 1; } + if (op == OT_OROR && a) { *out = 1; return 1; } + if (!ceval(c, n->b, env, &b)) return 0; + *out = b; + return 1; + } + if (!ceval(c, n->a, env, &a) || !ceval(c, n->b, env, &b)) return 0; + if (is_cmpop(op)) { + OscScalar T = (OscScalar)n->flag; + int lt = osc_scalar_signed(T) ? (int64_t)a < (int64_t)b : a < b, eq = a == b; + switch (op) { + case OT_EQ: *out = eq; break; + case OT_NE: *out = !eq; break; + case OT_LT: *out = lt; break; + case OT_LE: *out = lt || eq; break; + case OT_GT: *out = !lt && !eq; break; + default: *out = !lt; break; + } + return 1; + } + OscScalar t = n->ty.s, tb = NODE(n->b)->ty.s; + unsigned w = osc_scalar_width(t); + int 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, r; + switch (op) { + case OT_PLUS: if (!s) { *out = ccanon(t, a + b); return 1; } r = A + B; break; + case OT_MINUS: if (!s) { *out = ccanon(t, a - b); return 1; } r = A - B; break; + case OT_STAR: if (!s) { *out = ccanon(t, a * b); return 1; } r = A * B; break; + case OT_SLASH: + if (b == 0) return 0; + if (!s) { *out = a / b; return 1; } + r = A / B; + break; + case OT_PERCENT: + if (b == 0) return 0; + *out = s ? (uint64_t)(int64_t)(A % B) : a % b; + return 1; + case OT_AMP: *out = a & b; return 1; + case OT_PIPE: *out = a | b; return 1; + case OT_CARET: *out = a ^ b; return 1; + case OT_SHL: case OT_SHR: + if (B < 0 || B >= (i128)w) return 0; + if (op == OT_SHR) { *out = s ? (uint64_t)((int64_t)a >> (unsigned)B) : a >> (unsigned)B; return 1; } + if (!s) { *out = ccanon(t, a << (unsigned)B); return 1; } + r = A * ((i128)1 << (unsigned)B); + break; + default: return 0; + } + if (!sfits(w, r)) return 0; + *out = (uint64_t)(int64_t)r; + return 1; + } + default: + return 0; /* ON_INDEX (memory), ON_CALL (refused in clauses anyway) */ + } +} + +/* name check inside a clause: `result` is reserved there */ +static int contract_name(C *c, const OscNode *n) +{ + if (!c->contract) return 0; + char name[64]; + osc_node_name(c->ast, n, name, sizeof name); + if (strcmp(name, "result") != 0) return 0; + char fname[64]; + osc_node_name(c->ast, NODE(c->fnode), fname, sizeof fname); + if (c->contract == 1) { + osc_diag_set(c->d, OSC_DIAG_CONTRACT_INVALID, n->line, n->col, "result", NODE(c->fnode)->line, fname, + "result in requires", "'result' (the return value) is not available in a requires clause"); + return -1; + } + if (c->fret.s == OSC_T_VOID) { + osc_diag_set(c->d, OSC_DIAG_CONTRACT_INVALID, n->line, n->col, "result", NODE(c->fnode)->line, fname, + "result in void function", "'%s' returns nothing, so its ensures clause has no 'result'", fname); + return -1; + } + 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); @@ -640,6 +794,7 @@ static int chk(C *c, int i, OscScalar want) t = OSC_T_BOOL; break; case ON_NAME: { + if (contract_name(c, n)) return -1; int s = resolve(c, n); if (s < 0) return -1; n->sym = s; @@ -652,9 +807,17 @@ static int chk(C *c, int i, OscScalar want) break; } case ON_INDEX: { + if (contract_name(c, n)) return -1; int s = resolve(c, n); if (s < 0) return -1; n->sym = s; + if (c->contract == 2 && c->sym[s].kind != SK_SCALAR && !(c->sym[s].kind == SK_BORROW && c->sym[s].ty.ref == OSC_REF_SHARED)) { + osc_diag_set(c->d, OSC_DIAG_CONTRACT_INVALID, n->line, n->col, c->sym[s].name, c->sym[s].line, NULL, + "array read in ensures", + "an ensures clause may read elements only through a shared '&' parameter ('%s' is not one)", + c->sym[s].name); + return -1; + } 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); @@ -665,6 +828,13 @@ static int chk(C *c, int i, OscScalar want) break; } case ON_CALL: { + if (c->contract) { + char cn[64]; + osc_node_name(c->ast, n, cn, sizeof cn); + osc_diag_set(c->d, OSC_DIAG_CONTRACT_INVALID, n->line, n->col, cn, 0, c->contract == 1 ? "requires" : "ensures", + "call in contract", "a contract clause may not call a function ('%s')", cn); + return -1; + } int r = chk_call(c, i, want, 0); if (r < 0) return -1; t = (OscScalar)r; @@ -806,6 +976,112 @@ static int find_fn(C *c, const char *name, int *after) static int same_arr(const OscType *a, const OscType *b) { return a->elem == b->elem && a->len == b->len; } +/* OSC-2: check fn fi's requires / ensures clauses (after its parameters are + * declared, before its body). See docs/osc/OSC-2-DESIGN.md section 1. */ +static int chk_contracts(C *c, int fi) +{ + OscAst *a = c->ast; + char fname[64]; + osc_node_name(a, NODE(c->fnode), fname, sizeof fname); + CEnv none; + memset(&none, 0, sizeof none); + none.res_sym = -1; + uint64_t v; + if (a->reqn[fi] >= 0) { + int r = a->reqn[fi]; + c->contract = 1; + snprintf(c->sobj, sizeof c->sobj, "requires"); + /* element reads in a requires clause are uses at function entry (traced) */ + if (chk(c, r, OSC_T_BOOL) < 0) return -1; + c->contract = 0; + if (ceval(c, r, &none, &v)) { + if (!v) { + osc_diag_set(c->d, OSC_DIAG_CONTRACT_VIOLATION, NODE(r)->line, NODE(r)->col, fname, NODE(r)->line, + a->req[fi], "requires is constant false", + "the requires clause of '%s' is false for every call", fname); + return -1; + } + a->req_elide[fi] = 1; + } + } + if (a->ensn[fi] >= 0) { + int e = a->ensn[fi]; + OscTrace *tr = c->tr; + if (push_scope(c, NODE(e)->line)) return -1; + if (lookup(c, "result") >= 0) { /* any fn with ensures: `result` is reserved there */ + int p = lookup(c, "result"); + osc_diag_set(c->d, OSC_DIAG_REDEFINED_NAME, NODE(e)->line, NODE(e)->col, "result", c->sym[p].line, + fname, "parameter named result with ensures", + "'result' names the return value in an ensures clause; parameter 'result' of '%s' " + "collides with it", fname); + return -1; + } + if (c->fret.s != OSC_T_VOID) { + /* the `result` pseudo binding, visible only inside the clause */ + if (c->nsym >= OSC_CHECK_MAX_SYMS) return cap_fail(c, NODE(e)->line, "symbol capacity"); + int s = c->nsym++; + Sym *y = &c->sym[s]; + memset(y, 0, sizeof *y); + snprintf(y->name, sizeof y->name, "result"); + y->line = NODE(e)->line; + y->kind = SK_SCALAR; + y->ty = c->fret; + y->obj = y->bor = -1; + c->vis[c->nvis++] = s; + a->res_sym[fi] = s; + } + c->contract = 2; + snprintf(c->sobj, sizeof c->sobj, "ensures"); + /* ensures reads happen at each return; only shared-borrow parameters may + * be read, which no body operation can invalidate, so they are not traced */ + c->tr = NULL; + int rc = chk(c, e, OSC_T_BOOL); + c->tr = tr; + c->contract = 0; + if (rc < 0) return -1; + pop_scope(c); + if (ceval(c, e, &none, &v)) { + if (!v) { + osc_diag_set(c->d, OSC_DIAG_CONTRACT_VIOLATION, NODE(e)->line, NODE(e)->col, fname, NODE(e)->line, + a->ens[fi], "ensures is constant false", + "the ensures clause of '%s' is false for every return", fname); + return -1; + } + a->ens_elide[fi] = 1; + } + } + snprintf(c->sobj, sizeof c->sobj, "%s", fname); + return 0; +} + +/* OSC-2: refuse a call whose literal / constant arguments make the callee's + * requires clause fold to false. */ +static int chk_call_requires(C *c, int i, int g, const int *args, int na) +{ + OscAst *a = c->ast; + if (a->reqn[g] < 0 || a->req_elide[g]) return 0; + const OscNode *n = NODE(i); + const OscNode *f = NODE(a->fns[g]); + CEnv env, none; + memset(&env, 0, sizeof env); + memset(&none, 0, sizeof none); + env.res_sym = none.res_sym = -1; + env.nk = na; + int k = 0; + for (int p = f->a; p >= 0 && k < na; p = NODE(p)->next, k++) + if (NODE(p)->ty.s != OSC_T_REF && ceval(c, args[k], &none, &env.v[k])) env.k[k] = 1; + uint64_t v; + if (ceval(c, a->reqn[g], &env, &v) && !v) { + char name[64]; + osc_node_name(a, n, name, sizeof name); + osc_diag_set(c->d, OSC_DIAG_CONTRACT_VIOLATION, n->line, n->col, name, NODE(a->reqn[g])->line, a->req[g], + "requires false at call", "these constant arguments make the requires clause of '%s' false", + name); + return -1; + } + return 0; +} + static int chk_call(C *c, int i, OscScalar want, int as_stmt) { OscNode *n = NODE(i); @@ -871,6 +1147,7 @@ static int chk_call(C *c, int i, OscScalar want, int as_stmt) if (b < 0) return -1; cb[ncb++] = b; } + if (chk_call_requires(c, i, g, args, na)) return -1; 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) { @@ -1011,6 +1288,35 @@ out: return rc; } +/* OSC-2: `return E;` with E constant: fold the ensures clause with `result` = E. + * False -> static postcondition violation; true -> no check at this return + * (ON_RETURN flag = 1). */ +static int chk_return_ensures(C *c, OscNode *n) +{ + OscAst *a = c->ast; + int fi = c->fi; + if (a->ensn[fi] < 0 || a->ens_elide[fi] || a->res_sym[fi] < 0) return 0; + CEnv env; + memset(&env, 0, sizeof env); + env.res_sym = -1; + uint64_t rv, v; + if (!ceval(c, n->a, &env, &rv)) return 0; + env.res_sym = a->res_sym[fi]; + env.res_known = 1; + env.res_val = rv; + if (!ceval(c, a->ensn[fi], &env, &v)) return 0; + if (!v) { + char fname[64]; + osc_node_name(a, NODE(c->fnode), fname, sizeof fname); + osc_diag_set(c->d, OSC_DIAG_CONTRACT_VIOLATION, n->line, n->col, fname, NODE(a->ensn[fi])->line, a->ens[fi], + "ensures false at return", "this constant return value makes the ensures clause of '%s' false", + fname); + return -1; + } + n->flag = 1; + return 0; +} + static int chk_stmt(C *c, int i) { OscNode *n = NODE(i); @@ -1173,6 +1479,7 @@ static int chk_stmt(C *c, int i) return -1; } if (chk(c, n->a, c->fret.s) < 0) return -1; + if (chk_return_ensures(c, n)) return -1; } scope_exit_events(c, c->depth, n->line, n); c->term = 1; @@ -1254,6 +1561,7 @@ static int chk_fn(C *c, int fi) c->bor[b].sym = s; } } + if (chk_contracts(c, fi)) return -1; if (chk_block(c, fn->b, 1)) return -1; if (!c->term) { if (fn->ty.s != OSC_T_VOID) { diff --git a/src/compiler/osc_diag.c b/src/compiler/osc_diag.c index 6db868de0..4df5ba1a0 100644 --- a/src/compiler/osc_diag.c +++ b/src/compiler/osc_diag.c @@ -12,7 +12,7 @@ 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"}; + "READ_ONLY_BORROW", "CONTRACT_INVALID", "CONTRACT_VIOLATION"}; const char *osc_diag_kind_name(int kind) { diff --git a/src/compiler/osc_diag.h b/src/compiler/osc_diag.h index cdd5d239c..f74d917d4 100644 --- a/src/compiler/osc_diag.h +++ b/src/compiler/osc_diag.h @@ -27,6 +27,9 @@ typedef enum { OSC_DIAG_STATIC_OUT_OF_BOUNDS, OSC_DIAG_IMMUTABLE_ASSIGN, OSC_DIAG_READ_ONLY_BORROW, + /* appended for OSC-2 contracts (docs/osc/OSC-2-DESIGN.md section 1) */ + OSC_DIAG_CONTRACT_INVALID, /* ill-formed clause: result in requires / void fn, call, own read */ + OSC_DIAG_CONTRACT_VIOLATION, /* clause decided false at compile time (constant folding) */ OSC_DIAG__COUNT } OscDiagKind; @@ -40,7 +43,7 @@ typedef struct { char message[160]; /* human-readable summary */ } OscDiag; -/* "SYNTAX", ..., "READ_ONLY_BORROW"; "NONE" for 0; "?" out of range. */ +/* "SYNTAX", ..., "CONTRACT_VIOLATION"; "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); diff --git a/src/compiler/osc_ir.c b/src/compiler/osc_ir.c index 60fef0997..eb5248979 100644 --- a/src/compiler/osc_ir.c +++ b/src/compiler/osc_ir.c @@ -193,7 +193,7 @@ static int validate_insn(const OscUnit *u, int fi, const OscFunc *f, uint32_t ii break; } case OSC_I_TRAP: - NEED(in->imm >= OSC_TRAP_OVERFLOW && in->imm <= OSC_TRAP_RUNTIME, "TRAP bad code", fi, ii); + NEED(in->imm >= OSC_TRAP_OVERFLOW && in->imm <= OSC_TRAP_MAX, "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); diff --git a/src/compiler/osc_ir.h b/src/compiler/osc_ir.h index 27ba49497..ce006ac78 100644 --- a/src/compiler/osc_ir.h +++ b/src/compiler/osc_ir.h @@ -35,7 +35,7 @@ #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) */ +#define OSC_CLAUSE_MAX 256 /* requires/ensures source text (recorded; enforced by the front end, OSC-2) */ /* ---- types ------------------------------------------------------------ */ typedef enum { @@ -116,10 +116,17 @@ typedef enum { 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 */ + OSC_TRAP_RUNTIME = 8, /* runtime invariant broken (double release, bad */ /* handle): must never happen for checked code */ + /* Appended for OSC-2 contracts (docs/osc/OSC-2-DESIGN.md section 1). + * Existing codes are never renumbered. */ + OSC_TRAP_REQUIRES = 9, /* a `requires` clause evaluated to false at entry */ + OSC_TRAP_ENSURES = 10 /* an `ensures` clause evaluated to false at return */ } OscTrap; +/* Highest trap code; arrays indexed by trap code have OSC_TRAP_MAX + 1 entries. */ +#define OSC_TRAP_MAX OSC_TRAP_ENSURES + typedef struct { uint8_t op; /* OscOp */ uint8_t sub; /* OscBinOp / OscUnOp / OscCmp */ @@ -148,7 +155,7 @@ typedef struct { 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 requires_text[OSC_CLAUSE_MAX]; /* source text; checks are lowered into the CFG (OSC-2) */ char ensures_text[OSC_CLAUSE_MAX]; } OscFunc; diff --git a/src/compiler/osc_lower.c b/src/compiler/osc_lower.c index 49b96e9e5..b6fc71ae4 100644 --- a/src/compiler/osc_lower.c +++ b/src/compiler/osc_lower.c @@ -22,6 +22,7 @@ typedef struct { int cur; /* current block or -1 (dead) */ int16_t vreg[OSC_CHECK_MAX_SYMS]; int failed; + int fi; /* function being lowered */ } L; #define NODE(i) (&l->ast->nodes[(i)]) @@ -229,6 +230,30 @@ static int expr(L *l, int i) } } +/* OSC-2 contract check: evaluate clause (bool) with the checked semantics; + * false -> TRAP code (docs/osc/OSC-2-DESIGN.md section 1.5). */ +static void contract_check(L *l, int clause, unsigned code) +{ + uint32_t line = NODE(clause)->line; + int c = expr(l, clause); + int ok = newblk(l, line), bad = newblk(l, line); + cbr(l, c, ok, bad, line); + l->cur = bad; + OscInsn *x = emit(l, OSC_I_TRAP, line); + x->imm = code; + br(l, ok, line); + l->cur = ok; +} + +/* ensures at a return whose value is in vreg v (-1 for void) */ +static void ensures_check(L *l, int v) +{ + const OscAst *a = l->ast; + if (a->ensn[l->fi] < 0 || a->ens_elide[l->fi]) return; + if (a->res_sym[l->fi] >= 0) l->vreg[a->res_sym[l->fi]] = (int16_t)v; + contract_check(l, a->ensn[l->fi], OSC_TRAP_ENSURES); +} + static void block(L *l, int i); static void stmt(L *l, int i) @@ -377,6 +402,7 @@ static void stmt(L *l, int i) case ON_RETURN: { int v = -1; if (n->a >= 0) v = expr(l, n->a); + if (!n->flag) ensures_check(l, v); /* flag: checker proved it true here */ releases(l, n); OscInsn *x = emit(l, OSC_I_RET, n->line); x->a = (int16_t)v; @@ -422,8 +448,15 @@ static int lower_fn(L *l, int fi) f->nparams++; } l->cur = newblk(l, fn->line); - block(l, fn->b); + l->fi = fi; + if (a->reqn[fi] >= 0 && !a->req_elide[fi]) contract_check(l, a->reqn[fi], OSC_TRAP_REQUIRES); + /* body block inlined (same emission as block()) so a void function's + * fall-off ensures check precedes the body scope's releases */ + const OscNode *body = NODE(fn->b); + for (int s = body->a; s >= 0 && l->cur >= 0; s = NODE(s)->next) stmt(l, s); if (l->cur >= 0) { + ensures_check(l, -1); + releases(l, body); releases(l, fn); OscInsn *x = emit(l, OSC_I_RET, (uint32_t)NODE(fn->b)->ival); x->a = -1; diff --git a/src/compiler/osc_parse.c b/src/compiler/osc_parse.c index 42b8e4429..b25465491 100644 --- a/src/compiler/osc_parse.c +++ b/src/compiler/osc_parse.c @@ -569,19 +569,24 @@ static int parse_block(P *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) +/* clause: one expression (OSC-2, docs/osc/OSC-2-DESIGN.md section 1). The + * source text is still recorded (token spellings joined by single spaces, + * none after '(' or before ')') and carried into the IR; the expression node + * is checked and lowered into runtime checks by the checker / lowerer. */ +static int parse_clause(P *p, char *out, const OscToken *kw, int32_t *node) { - size_t len = 0; - int depth = 0, prev = -1; + uint32_t start = p->pos; 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); + if (at(p, OT_LBRACE) || at(p, OT_ENSURES) || at(p, OT_EOF)) return syntax(p, "a contract expression"); + int e = parse_expr(p); + if (e < 0) return -1; + if (!at(p, OT_LBRACE) && !at(p, OT_ENSURES)) + return syntax(p, "'ensures' or a function body '{' after the contract expression"); + size_t len = 0; + int prev = -1; + for (uint32_t i = start; i < p->pos; i++) { + const OscToken *t = &p->ast->toks[i]; + int k = t->kind; 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, @@ -593,8 +598,8 @@ static int parse_clause(P *p, char *out, const OscToken *kw) len += t->len; out[len] = 0; prev = k; - adv(p); } + *node = e; return 0; } @@ -649,15 +654,17 @@ static int parse_fn(P *p) } uint32_t fi = a->nfns; a->req[fi][0] = a->ens[fi][0] = 0; + a->reqn[fi] = a->ensn[fi] = a->res_sym[fi] = -1; + a->req_elide[fi] = a->ens_elide[fi] = 0; if (at(p, OT_REQUIRES)) { const OscToken *kw = cur(p); adv(p); - if (parse_clause(p, a->req[fi], kw)) return -1; + if (parse_clause(p, a->req[fi], kw, &a->reqn[fi])) return -1; } if (at(p, OT_ENSURES)) { const OscToken *kw = cur(p); adv(p); - if (parse_clause(p, a->ens[fi], kw)) return -1; + if (parse_clause(p, a->ens[fi], kw, &a->ensn[fi])) return -1; } int b = parse_block(p); if (b < 0) return -1; diff --git a/src/compiler/osc_parse.h b/src/compiler/osc_parse.h index 3a6d5877f..d97424fcc 100644 --- a/src/compiler/osc_parse.h +++ b/src/compiler/osc_parse.h @@ -80,6 +80,16 @@ typedef struct { uint32_t nfns; char req[OSC_MAX_FUNCS][OSC_CLAUSE_MAX]; char ens[OSC_MAX_FUNCS][OSC_CLAUSE_MAX]; + /* OSC-2 contracts (docs/osc/OSC-2-DESIGN.md section 1). Parser: clause + * expression nodes (-1 = no clause). Checker: res_sym = symbol id of the + * `result` pseudo binding of a non-void function with an ensures clause + * (-1 otherwise); *_elide = 1 when the clause folds to true on its own and + * no runtime check is emitted. */ + int32_t reqn[OSC_MAX_FUNCS]; + int32_t ensn[OSC_MAX_FUNCS]; + int32_t res_sym[OSC_MAX_FUNCS]; + uint8_t req_elide[OSC_MAX_FUNCS]; + uint8_t ens_elide[OSC_MAX_FUNCS]; /* filled by the checker: symbol ids of owners to release, in emission order */ int16_t rel[OSC_AST_MAX_REL]; uint32_t nrel; diff --git a/src/compiler/osc_rt.c b/src/compiler/osc_rt.c index 87696d021..835706714 100644 --- a/src/compiler/osc_rt.c +++ b/src/compiler/osc_rt.c @@ -51,7 +51,7 @@ static void log_event(OscRt *rt, uint8_t kind, unsigned slot, uint16_t len, uint } void osc_rt_trap(OscRt *rt, uint64_t code) { - rt->trap_code = (code >= 1 && code <= OSC_TRAP_RUNTIME) ? (uint32_t)code : OSC_TRAP_RUNTIME; + rt->trap_code = (code >= 1 && code <= OSC_TRAP_MAX) ? (uint32_t)code : OSC_TRAP_RUNTIME; longjmp(rt->jb, 1); } diff --git a/tests/compiler/neg/ci_array_read_ensures.osc b/tests/compiler/neg/ci_array_read_ensures.osc new file mode 100644 index 000000000..87d1f6498 --- /dev/null +++ b/tests/compiler/neg/ci_array_read_ensures.osc @@ -0,0 +1,7 @@ +// expect: CONTRACT_INVALID object=a line=4 +// transition: array read in ensures +// ensures may read elements only through a shared & parameter +fn f(a: &mut [u8; 2]) -> u8 ensures a[0] == result { + a[0] = 3; + return 3; +} diff --git a/tests/compiler/neg/ci_call_in_contract.osc b/tests/compiler/neg/ci_call_in_contract.osc new file mode 100644 index 000000000..ad77c8b4a --- /dev/null +++ b/tests/compiler/neg/ci_call_in_contract.osc @@ -0,0 +1,9 @@ +// expect: CONTRACT_INVALID object=id line=7 +// transition: call in contract +// contracts are pure expressions: calls are refused (OSC-2 section 1) +fn id(x: u8) -> u8 { + return x; +} +fn f(x: u8) -> u8 requires id(x) > 0 { + return x; +} diff --git a/tests/compiler/neg/ci_result_in_requires.osc b/tests/compiler/neg/ci_result_in_requires.osc new file mode 100644 index 000000000..df14112d7 --- /dev/null +++ b/tests/compiler/neg/ci_result_in_requires.osc @@ -0,0 +1,6 @@ +// expect: CONTRACT_INVALID object=result line=4 +// transition: result in requires +// `result` names the return value; it only exists in ensures +fn f(x: u8) -> u8 requires result > 0 { + return x; +} diff --git a/tests/compiler/neg/ci_result_in_void.osc b/tests/compiler/neg/ci_result_in_void.osc new file mode 100644 index 000000000..a80f5a01b --- /dev/null +++ b/tests/compiler/neg/ci_result_in_void.osc @@ -0,0 +1,6 @@ +// expect: CONTRACT_INVALID object=result line=4 +// transition: result in void function +// a void function has no return value to name +fn f(x: u8) ensures result == x { + let y: u8 = x; +} diff --git a/tests/compiler/neg/cv_constant_false_clause.osc b/tests/compiler/neg/cv_constant_false_clause.osc new file mode 100644 index 000000000..f8c14fde5 --- /dev/null +++ b/tests/compiler/neg/cv_constant_false_clause.osc @@ -0,0 +1,6 @@ +// expect: CONTRACT_VIOLATION object=f line=4 +// transition: requires is constant false +// a clause that folds to false on its own can never hold +fn f(x: u8) -> u8 requires false && x > 0 { + return x; +} diff --git a/tests/compiler/neg/cv_ensures_constant_false.osc b/tests/compiler/neg/cv_ensures_constant_false.osc new file mode 100644 index 000000000..d3bf4a369 --- /dev/null +++ b/tests/compiler/neg/cv_ensures_constant_false.osc @@ -0,0 +1,5 @@ +// expect: CONTRACT_VIOLATION object=h line=3 +// transition: ensures is constant false +fn h(x: i32) -> i32 ensures !true { + return x; +} diff --git a/tests/compiler/neg/cv_ensures_static.osc b/tests/compiler/neg/cv_ensures_static.osc new file mode 100644 index 000000000..c4a616a52 --- /dev/null +++ b/tests/compiler/neg/cv_ensures_static.osc @@ -0,0 +1,7 @@ +// expect: CONTRACT_VIOLATION object=g line=6 +// transition: ensures false at return +// a constant return value that violates ensures is refused at the return +fn g(x: u8) -> u8 ensures result < 10 { + if x < 5 { return x; } + return 12; +} diff --git a/tests/compiler/neg/cv_requires_false_at_call.osc b/tests/compiler/neg/cv_requires_false_at_call.osc new file mode 100644 index 000000000..ebb7eda2e --- /dev/null +++ b/tests/compiler/neg/cv_requires_false_at_call.osc @@ -0,0 +1,10 @@ +// expect: CONTRACT_VIOLATION object=safe_sub line=9 +// transition: requires false at call +// constant arguments make the callee's requires false (line = the call; origin_line = the clause) +fn safe_sub(a: u32, b: u32) -> u32 requires a >= b { + return a - b; +} + +fn caller() -> u32 { + return safe_sub(3, 5); +} diff --git a/tests/compiler/neg/rd_result_param.osc b/tests/compiler/neg/rd_result_param.osc new file mode 100644 index 000000000..57a5a5606 --- /dev/null +++ b/tests/compiler/neg/rd_result_param.osc @@ -0,0 +1,6 @@ +// expect: REDEFINED_NAME object=result line=4 +// transition: parameter named result with ensures +// `result` is reserved in a function that has an ensures clause +fn f(result: u8) -> u8 ensures result >= 0 { + return result; +} diff --git a/tests/compiler/neg/rd_result_param_void.osc b/tests/compiler/neg/rd_result_param_void.osc new file mode 100644 index 000000000..e4388f2f5 --- /dev/null +++ b/tests/compiler/neg/rd_result_param_void.osc @@ -0,0 +1,6 @@ +// expect: REDEFINED_NAME object=result line=4 +// transition: parameter named result with ensures +// the reservation holds in a void function too (OSC-2-DESIGN 1.3) +fn f(result: u8) ensures result == 1 { + let y: u8 = result; +} diff --git a/tests/compiler/neg/tm_non_bool_clause.osc b/tests/compiler/neg/tm_non_bool_clause.osc new file mode 100644 index 000000000..223c571c1 --- /dev/null +++ b/tests/compiler/neg/tm_non_bool_clause.osc @@ -0,0 +1,7 @@ +// expect: TYPE_MISMATCH object=requires line=4 +// a clause must be a bool expression +fn f(x: u8) -> u8 + requires x + 1 +{ + return x; +} diff --git a/tests/compiler/neg/undefined_in_clause.osc b/tests/compiler/neg/undefined_in_clause.osc new file mode 100644 index 000000000..88a534e63 --- /dev/null +++ b/tests/compiler/neg/undefined_in_clause.osc @@ -0,0 +1,6 @@ +// expect: UNDEFINED_NAME object=y line=3 +// clauses see only the parameters (and result in ensures) +fn f(x: u8) -> u8 requires x > y { + let y: u8 = 1; + return x + y; +} diff --git a/tests/compiler/osc2_receipt.sh b/tests/compiler/osc2_receipt.sh new file mode 100755 index 000000000..087ede889 --- /dev/null +++ b/tests/compiler/osc2_receipt.sh @@ -0,0 +1,126 @@ +#!/bin/sh +# OSC-2 compiler slice receipt, one per item (docs/osc/OSC-2-DESIGN.md). +# OSC-2 slice; not a general Omega compiler; no self-hosting. +# Usage: tests/compiler/osc2_receipt.sh [ITEM] (ITEM default: contracts) +# 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, contract fuzz, 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-2/receipts/osc2--.json +# Never overwrites existing evidence (evidence/OSC-1 is never touched). Timing is not recorded. +set -eu +ITEM=${1:-${ITEM:-contracts}} +case "$ITEM" in contracts) ;; *) echo "osc2-receipt: REFUSED: unknown ITEM $ITEM (known: contracts)" >&2; exit 2 ;; esac +ROOT=$(cd "$(dirname "$0")/../.." && pwd -P) +cd "$ROOT" +EVD=evidence/OSC-2/receipts +die() { echo "osc2-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 +FLINE=$(grep "^contract fuzz:" "$O/compiler.out" | tail -1) +FLINE_ASAN=$(grep "^contract fuzz:" "$O/compiler_asan.out" | tail -1) +[ -n "$FLINE" ] && [ -n "$FLINE_ASAN" ] || die "no contract fuzz line" +for k in OVERFLOW DIV0 BOUNDS LOOP_BOUND CAST OOM SHIFT REQUIRES ENSURES; 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="" + rm -rf build/osc2-receipt-gates; mkdir -p build/osc2-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=build/osc2-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/osc2-receipt-gates/$m.gate.log + G="$G\"$m\": $tot, " + done + GATES="{${G%, }}" +fi + +R="$T/receipt.json" +{ + printf '{\n' + printf ' "schema": "omega.osc2.compiler.receipt.v1",\n' + printf ' "verdict": "PASS",\n' + printf ' "item": "%s",\n' "$ITEM" + printf '' + printf ' "statement": "OSC-2 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; OSC-2 item 1: requires/ensures are pure bool expressions over parameters (and result in ensures; element reads through parameters, ensures only via shared borrows; no calls), refused statically when constant folding decides them false (CONTRACT_VIOLATION), otherwise checked at run time (TRAP REQUIRES = 9 at entry, TRAP ENSURES = 10 at each return before releases; statically true clauses elided)",\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, "requires": %s, "ensures": %s},\n' \ + "$(tc none)" "$(tc OVERFLOW)" "$(tc DIV0)" "$(tc BOUNDS)" "$(tc LOOP_BOUND)" "$(tc CAST)" "$(tc OOM)" "$(tc SHIFT)" "$(tc RUNTIME)" "$(tc REQUIRES)" "$(tc ENSURES)" + printf ' "contract_fuzz": "%s; native == interpreter on every run",\n' "$FLINE" + printf ' "contract_fuzz_asan": "%s",\n' "$FLINE_ASAN" + 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-2 compiler slice cannot compile any part of itself (docs/osc/OSC-1-SELF-HOST-STATEMENT.md)",\n' + printf ' "not_covered": "contracts beyond constant folding (no symbolic proof), 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/osc2-$ITEM-$RSHA.json" +[ -e "$OUT" ] && { echo "osc2-receipt: identical receipt already present: $OUT"; exit 0; } +cp "$R" "$OUT" +echo "osc2-receipt: PASS receipt=$OUT" diff --git a/tests/compiler/progs/contracts_basic.osc b/tests/compiler/progs/contracts_basic.osc new file mode 100644 index 000000000..b8de17a2b --- /dev/null +++ b/tests/compiler/progs/contracts_basic.osc @@ -0,0 +1,35 @@ +// entry: safe_sub seven always use_safe_sub +// OSC-2 contracts that hold for every call in range: requires / ensures are +// enforced at run time; constant-true clauses and constant returns that +// satisfy ensures are elided (docs/osc/OSC-2-DESIGN.md section 1). +fn safe_sub(a: u32, b: u32) -> u32 + requires a >= b + ensures result <= a +{ + return a - b; +} + +// the first return folds `result == 7` to true: no check there +fn seven(x: u8) -> u8 ensures result == 7 || result == x { + if x > 3 { return 7; } + return x; +} + +// both clauses fold to true on their own: no runtime check at all +fn always(x: u8) -> u8 requires true || false ensures !false { + return x; +} + +// constant arguments that satisfy the callee's requires are accepted +fn use_safe_sub(x: u32) -> u32 { + let k: u32 = safe_sub(10, 3); + if x >= k { return safe_sub(x, k); } + return k; +} +// expect-run: safe_sub 7 5 -> 2 +// expect-run: safe_sub 5 5 -> 0 +// expect-run: seven 9 -> 7 +// expect-run: seven 2 -> 2 +// expect-run: always 200 -> 200 +// expect-run: use_safe_sub 3 -> 7 +// expect-run: use_safe_sub 10 -> 3 diff --git a/tests/compiler/progs/contracts_ensures.osc b/tests/compiler/progs/contracts_ensures.osc new file mode 100644 index 000000000..e520bc67d --- /dev/null +++ b/tests/compiler/progs/contracts_ensures.osc @@ -0,0 +1,39 @@ +// entry: half_up void_check pick sum_first +// OSC-2 ensures clauses that fail at run time: TRAP ENSURES after the return +// value is computed and before the scope releases (no destructors run). +// `half_up` is deliberately wrong for odd inputs. +fn half_up(x: u16) -> u16 ensures result * 2 >= x { + return x / 2; +} + +// void function: the check runs at the fall-off end, before `a` is released +fn void_check(n: i64) ensures n >= 0 { + let a: own [i64; 4] = alloc(n); + a[0] = 1; +} + +// checked at every return; the early return is wrong when x == 100 +fn pick(x: u8, y: u8) -> u8 ensures result != 100 { + if x == 100 { return x; } + if y > x { return y - x; } + return x - y; +} + +// ensures reads elements through a shared borrow parameter +fn first(a: &[u32; 3], k: u32) -> u32 ensures result == a[0] { + if k > 5 { return k; } + return a[0]; +} + +fn sum_first(k: u32) -> u32 { + let a: own [u32; 3] = alloc(4); + return first(&a, k); +} +// expect-run: half_up 7 -> trap=ENSURES +// expect-run: half_up 8 -> 4 +// expect-run: void_check -1 -> trap=ENSURES +// expect-run: void_check 3 -> 0 +// expect-run: pick 100 1 -> trap=ENSURES +// expect-run: pick 9 1 -> 8 +// expect-run: sum_first 6 -> trap=ENSURES +// expect-run: sum_first 5 -> 4 diff --git a/tests/compiler/progs/contracts_requires.osc b/tests/compiler/progs/contracts_requires.osc new file mode 100644 index 000000000..8cdfb7848 --- /dev/null +++ b/tests/compiler/progs/contracts_requires.osc @@ -0,0 +1,48 @@ +// entry: safe_sub abs8 inc use_arr give +// OSC-2 requires clauses that fail at run time: TRAP REQUIRES at entry of the +// callee, after which the run ends with no destructors (owners stay live in +// the pool log, as for every OSC-1 trap). The clause obeys the checked +// semantics: signed overflow inside it traps OVERFLOW, a dynamic index BOUNDS. +fn safe_sub(a: u32, b: u32) -> u32 requires a >= b { + return a - b; +} + +fn abs8(x: i8) -> i8 requires x != -128 ensures result >= 0 { + if x < 0 { return -x; } + return x; +} + +// `x + 1` itself overflows for x = i32 max: OVERFLOW, not REQUIRES +fn inc(x: i32) -> i32 requires x + 1 > x ensures result - 1 == x { + return x + 1; +} + +// element reads through a borrow parameter +fn first_pos(a: &[i32; 4]) -> i32 requires a[0] > 0 ensures result == a[0] { + return a[0]; +} + +fn use_arr(x: i32) -> i32 { + let a: own [i32; 4] = alloc(x); + return first_pos(&a); +} + +// element read through an own parameter, dynamic index (BOUNDS inside the clause) +fn take(a: own [u8; 2], i: u8) -> u8 requires a[i] == 7 { + return a[1]; +} + +fn give(i: u8) -> u8 { + let a: own [u8; 2] = alloc(7); + return take(a, i); +} +// expect-run: safe_sub 5 7 -> trap=REQUIRES +// expect-run: safe_sub 9 7 -> 2 +// expect-run: abs8 -128 -> trap=REQUIRES +// expect-run: abs8 -5 -> 5 +// expect-run: inc 2147483647 -> trap=OVERFLOW +// expect-run: inc 4 -> 5 +// expect-run: use_arr 0 -> trap=REQUIRES +// expect-run: use_arr 5 -> 5 +// expect-run: give 1 -> 7 +// expect-run: give 5 -> trap=BOUNDS diff --git a/tests/compiler/test_osc_backend.c b/tests/compiler/test_osc_backend.c index faa02f0a8..d76c214c8 100644 --- a/tests/compiler/test_osc_backend.c +++ b/tests/compiler/test_osc_backend.c @@ -29,7 +29,7 @@ #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_diff_runs, n_funcs_fuzzed, n_units, n_words, n_trap[OSC_TRAP_MAX + 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, ...) { @@ -231,7 +231,7 @@ static void unit_check(OscUnit *u, const char *uname) { osc_rt_same_outcome(rtI, rtN) ? "same" : "DIFFERENT"); else n_checks++; - if (tn >= 0 && tn <= OSC_TRAP_RUNTIME) n_trap[tn]++; + if (tn >= 0 && tn <= OSC_TRAP_MAX) n_trap[tn]++; } } osc_native_unmap(&nm); @@ -481,7 +481,7 @@ static void gen_arrays(void) { 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++) { + for (int code = 1; code <= OSC_TRAP_MAX; code++) { at(&b, nxt); int hit = blk(&b); nxt = blk(&b); @@ -893,7 +893,7 @@ static void test_validator(void) { 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("TRAP code out of range", { f0->insns[0] = I0(OSC_I_TRAP); f0->insns[0].imm = OSC_TRAP_MAX + 1; }); 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); }); @@ -964,7 +964,7 @@ int main(void) { 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); + for (int c = 1; c <= OSC_TRAP_MAX; 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); @@ -972,8 +972,8 @@ int main(void) { 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("traps: none=%lu overflow=%lu div0=%lu bounds=%lu loop_bound=%lu cast=%lu oom=%lu shift=%lu runtime=%lu requires=%lu ensures=%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], n_trap[9], n_trap[10]); printf("checks=%lu failed=%lu time=%.2fs\n", n_checks, n_fail, secs); free(rtI); free(rtN); diff --git a/tests/compiler/test_osc_compiler.c b/tests/compiler/test_osc_compiler.c index 09cc3780f..68ca502ef 100644 --- a/tests/compiler/test_osc_compiler.c +++ b/tests/compiler/test_osc_compiler.c @@ -24,6 +24,7 @@ * OSC-1 slice; not a general Omega compiler; no self-hosting. */ #include +#include #include #include #include @@ -37,7 +38,7 @@ #include "model/osc_model.h" static unsigned long checks, failures; -static unsigned long trap_seen[9]; +static unsigned long trap_seen[OSC_TRAP_MAX + 1]; static unsigned long diff_runs, rt_replays, trace_replays, rt_events_replayed; #define CHECK(cond, ...) \ @@ -246,7 +247,7 @@ static int replay_rt(const OscRt *rt, char *why, size_t n) /* ------------------------------------------------------------ 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 const char *trap_names[OSC_TRAP_MAX + 1] = {"none", "OVERFLOW", "DIV0", "BOUNDS", "LOOP_BOUND", "CAST", "OOM", "SHIFT", "RUNTIME", "REQUIRES", "ENSURES"}; static uint64_t parse_val(const char *s) { @@ -334,7 +335,7 @@ static void golden(const char *dir, const char *name, unsigned fuzz) 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}; + unsigned long pertrap[OSC_TRAP_MAX + 1] = {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); @@ -359,7 +360,7 @@ static void golden(const char *dir, const char *name, unsigned fuzz) } break; } - if (ti >= 0 && ti <= 8) { trap_seen[ti]++; pertrap[ti]++; } + if (ti >= 0 && ti <= OSC_TRAP_MAX) { 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, @@ -368,8 +369,8 @@ static void golden(const char *dir, const char *name, unsigned fuzz) 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]); + printf(" %-18s %-12s ok=%-5lu ovf=%-4lu div0=%-4lu bnd=%-4lu loop=%-4lu cast=%-4lu oom=%-4lu shift=%-4lu rq=%-4lu en=%-4lu\n", + name, tok, pertrap[0], pertrap[1], pertrap[2], pertrap[3], pertrap[4], pertrap[5], pertrap[6], pertrap[7], pertrap[9], pertrap[10]); } expect_runs(name, src, &nm, &c1); osc_native_unmap(&nm); @@ -494,6 +495,154 @@ static void negative(const char *dir, const char *name) free(src); } +/* ------------------------------------------------------------ OSC-2 contract fuzz */ +/* Generated units: 2..4 helper functions with random `requires` / `ensures` + * clauses over their parameters (and `result`), plus an entry that chains + * calls to them. Each unit either compiles, or is refused statically with + * CONTRACT_VIOLATION (a clause or call that folds false); any other refusal + * is a failure. Compiled units run in the interpreter and natively on random + * arguments: identical trap / value / pool outcome (0 mismatches), and both + * TRAP REQUIRES and TRAP ENSURES must be observed. */ +static unsigned long cf_mismatch, cf_units, cf_compiled, cf_static_refused, cf_runs, cf_trap[OSC_TRAP_MAX + 1]; + +static void cf_cat(char *b, size_t cap, const char *fmt, ...) __attribute__((format(printf, 3, 4))); +static void cf_cat(char *b, size_t cap, const char *fmt, ...) +{ + size_t l = strlen(b); + va_list ap; + va_start(ap, fmt); + vsnprintf(b + l, cap - l, fmt, ap); + va_end(ap); +} + +/* an atom of type T over the names in scope */ +static void cf_atom(char *o, size_t cap, int with_result) +{ + unsigned r = (unsigned)(sm() % (with_result ? 6 : 4)); + switch (r) { + case 0: snprintf(o, cap, "a"); break; + case 1: snprintf(o, cap, "b"); break; + case 2: snprintf(o, cap, "%u", (unsigned)(sm() % 60)); break; + case 3: snprintf(o, cap, "%s %s %u", sm() & 1 ? "a" : "b", sm() & 1 ? "+" : "-", (unsigned)(sm() % 5)); break; + default: snprintf(o, cap, "result"); break; + } +} + +static void cf_clause(char *o, size_t cap, int with_result) +{ + static const char *cmp[] = {"<", "<=", ">", ">=", "==", "!="}; + char x[48], y[48], x2[48], y2[48]; + do cf_atom(x, sizeof x, with_result); while (x[0] >= '0' && x[0] <= '9'); + if (with_result && strcmp(x, "result") && sm() % 2) snprintf(x, sizeof x, "result"); + cf_atom(y, sizeof y, 0); + unsigned shape = (unsigned)(sm() % 8); + if (shape < 4) { snprintf(o, cap, "%s %s %s", x, cmp[sm() % 6], y); return; } + do cf_atom(x2, sizeof x2, with_result); while (x2[0] >= '0' && x2[0] <= '9'); + cf_atom(y2, sizeof y2, 0); + if (shape < 6) + snprintf(o, cap, "%s %s %s %s %s %s %s", x, cmp[sm() % 6], y, shape == 4 ? "&&" : "||", x2, cmp[sm() % 6], y2); + else if (shape == 6) + snprintf(o, cap, "!(%s %s %s)", x, cmp[sm() % 6], y); + else + snprintf(o, cap, "%s", sm() % 3 ? "true" : "a >= a"); +} + +static void contract_fuzz(unsigned n) +{ + static const char *tys[] = {"u8", "u16", "u32", "i8", "i16", "i32", "i64"}; + static const OscScalar tsc[] = {OSC_T_U8, OSC_T_U16, OSC_T_U32, OSC_T_I8, OSC_T_I16, OSC_T_I32, OSC_T_I64}; + static const char *ops[] = {"+", "-", "*", "&", "|", "^"}; + static char src[8192]; + sm_state = 0x05C2C0DEull; + for (unsigned u = 0; u < n; u++) { + unsigned ti = (unsigned)(sm() % 7); + const char *T = tys[ti]; + unsigned nh = 2 + (unsigned)(sm() % 3); + src[0] = 0; + for (unsigned h = 0; h < nh; h++) { + char rq[200], en[200]; + cf_clause(rq, sizeof rq, 0); + cf_clause(en, sizeof en, 1); + cf_cat(src, sizeof src, "fn g%u(a: %s, b: %s) -> %s", h, T, T, T); + if (sm() % 5) cf_cat(src, sizeof src, " requires %s", rq); + if (sm() % 5) cf_cat(src, sizeof src, " ensures %s", en); + unsigned body = (unsigned)(sm() % 4); + if (body == 0) + cf_cat(src, sizeof src, " {\n return a %s b;\n}\n", ops[sm() % 6]); + else if (body == 1) + cf_cat(src, sizeof src, " {\n if a > b { return a - b; }\n return b %s a;\n}\n", ops[sm() % 6]); + else if (body == 2) /* a constant return: checked statically against ensures */ + cf_cat(src, sizeof src, " {\n if a == %u { return %u; }\n return b;\n}\n", + (unsigned)(sm() % 40), (unsigned)(sm() % 40)); + else + cf_cat(src, sizeof src, " {\n let t: %s = a %s %u;\n return t;\n}\n", T, ops[sm() % 3], + (unsigned)(sm() % 9)); + } + cf_cat(src, sizeof src, "fn entry(a: %s, b: %s) -> %s {\n let x0: %s = g0(a, b);\n", T, T, T, T); + for (unsigned h = 1; h < nh; h++) { + if (sm() % 6 == 0) /* literal arguments: decided at compile time when the clause folds */ + cf_cat(src, sizeof src, " let x%u: %s = g%u(%u, %u);\n", h, T, h, (unsigned)(sm() % 50), + (unsigned)(sm() % 50)); + else + cf_cat(src, sizeof src, " let x%u: %s = g%u(x%u, %s);\n", h, T, h, h - 1, sm() & 1 ? "a" : "b"); + } + cf_cat(src, sizeof src, " return x%u;\n}\n", nh - 1); + cf_units++; + + OscDiag d; + int rc = osc_compile(src, strlen(src), U1, &d, NULL); + if (rc) { + CHECK(d.kind == OSC_DIAG_CONTRACT_VIOLATION, "contract fuzz unit %u refused %s line %u object=%s: %s\n%s", u, + osc_diag_kind_name(d.kind), d.line, d.object, d.message, src); + cf_static_refused++; + continue; + } + cf_compiled++; + OscCode c; + char err[160]; + memset(&c, 0, sizeof c); + int cg = osc_cg_compile(U1, &c, err, sizeof err); + CHECK(cg == 0, "contract fuzz unit %u codegen refused: %s", u, err); + if (cg) continue; + OscNative nm; + int mr = osc_native_map(&nm, c.code, c.len); + CHECK(mr == 0, "contract fuzz unit %u native map failed (%d)", u, mr); + if (mr) { osc_cg_free(&c); continue; } + int fi = U1->nfuncs - 1; + void *entry = osc_native_at(&nm, c.entry[fi]); + for (unsigned it = 0; it < 64; it++) { + uint64_t args[OSC_MAX_PARAMS] = {0}, ri = 0, rn = 0; + args[0] = gen_arg(tsc[ti]); + args[1] = gen_arg(tsc[ti]); + osc_rt_reset(RI); + osc_rt_reset(RN); + int t1 = osc_interp_run_prevalidated(U1, fi, args, 2, RI, &ri); + int t2 = osc_rt_call_native(RN, entry, args, 2, &rn); + cf_runs++; + diff_runs++; + int same = t1 == t2 && t1 >= 0 && (t1 != 0 || ri == rn) && osc_rt_same_outcome(RI, RN); + CHECK(same, "contract fuzz unit %u args %llu %llu: interp trap %d ret %llu vs native trap %d ret %llu\n%s", u, + (unsigned long long)args[0], (unsigned long long)args[1], t1, (unsigned long long)ri, t2, + (unsigned long long)rn, src); + if (!same) { cf_mismatch++; break; } + if (t1 >= 0 && t1 <= OSC_TRAP_MAX) cf_trap[t1]++; + CHECK(t1 != OSC_TRAP_RUNTIME, "contract fuzz unit %u RUNTIME trap", u); + } + osc_native_unmap(&nm); + osc_cg_free(&c); + } + printf("contract fuzz: units=%lu compiled=%lu static_refused=%lu runs=%lu ok=%lu requires=%lu ensures=%lu " + "overflow=%lu other_traps=%lu mismatches=%lu\n", + cf_units, cf_compiled, cf_static_refused, cf_runs, cf_trap[0], cf_trap[OSC_TRAP_REQUIRES], + cf_trap[OSC_TRAP_ENSURES], cf_trap[OSC_TRAP_OVERFLOW], + cf_runs - cf_trap[0] - cf_trap[OSC_TRAP_REQUIRES] - cf_trap[OSC_TRAP_ENSURES] - cf_trap[OSC_TRAP_OVERFLOW] - cf_mismatch, cf_mismatch); + CHECK(cf_trap[OSC_TRAP_REQUIRES] > 0, "contract fuzz never hit TRAP REQUIRES"); + CHECK(cf_trap[OSC_TRAP_ENSURES] > 0, "contract fuzz never hit TRAP ENSURES"); + CHECK(cf_trap[0] > 0, "contract fuzz never returned normally"); + CHECK(cf_static_refused > 0, "contract fuzz never produced a static CONTRACT_VIOLATION"); + CHECK(cf_compiled > n / 2, "contract fuzz compiled only %lu of %u units", cf_compiled, n); +} + int main(int argc, char **argv) { unsigned fuzz = argc > 1 ? (unsigned)strtoul(argv[1], NULL, 10) : 1000; @@ -522,12 +671,14 @@ int main(int argc, char **argv) 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); + contract_fuzz(fuzz / 5 ? fuzz / 5 : 20); 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 = 0; k <= OSC_TRAP_MAX; 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(trap_seen[OSC_TRAP_REQUIRES] > 0 && trap_seen[OSC_TRAP_ENSURES] > 0, "golden fuzz never hit REQUIRES/ENSURES"); 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]); @@ -579,7 +730,7 @@ static void expect_runs(const char *name, const char *src, const OscNative *nm, uint64_t want = 0; if (strncmp(res, "trap=", 5) == 0) { want_trap = -1; - for (int k = 1; k <= 8; k++) + for (int k = 1; k <= OSC_TRAP_MAX; k++) if (strcmp(res + 5, trap_names[k]) == 0) want_trap = k; } else { want = canon(f->ret.s, parse_val(res));