Repository navigation
fix(codegen): a user fn named like an intrinsic is called on wasm (#836) - #841
Conversation
The intrinsic arms of gen_expr's ExprApp dispatch matched the callee by
spelling, before asking whether the program binds that name. On core wasm
`fn string_sub(s: String, a: Int, b: Int) -> Int { 7 }` was never called:
the intrinsic ran and the program printed a heap pointer (1024) where the
interpreter and Bun-ESM print 7.
All 26 arms now dispatch on `intrinsic_callee`, which is empty for a name
the program binds: a fn with a body or a const (here or imported), or a
local. A name that is only declared (`extern fn`) keeps its lowering, so
the WASI lowerings are unchanged; that is why the guard is a set of
user-defined names and not membership of func_indices.
The WASI import pre-scan skips a name the program defines, so no unused
import is emitted. The calls elaboration makes for `show` on Int and
`slice` on a String are renamed `__builtin:...`, which no program can
write, so a user int_to_string / string_slice does not capture them.
test/test_intrinsic_shadow.ml covers every name on the interpreter,
Bun-ESM and core wasm. docs/SOUNDNESS.adoc gains the #836 row and the
ground-truth stamp advances to 4248912.
Closes #836
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J4QvDfoRYrnr6w2SMcxvze
|
Review these changes at https://app.gitnotebooks.com/hyperpolymath/affinescript/pull/841 |
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 58 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
|
Codex Review Summary: ❌ FailedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
…dispatch #841 (#836) routes every name-matched wasm intrinsic arm through `intrinsic_callee`, using a stricter `user_binds` (user-defined fns and consts, not externs). This branch's three Unicode arms carried their own `user_binds` guard. Resolution: - lib/codegen.ml: drop this branch's `user_binds` and keep main's; the three Unicode arms now match `Some id, _` like every other arm, with no per-arm guard. - test/test_intrinsic_shadow.ml: add shadowing cases for utf8_byte_length, code_points and string_from_code_points. Fix the arm-coverage gate's name regex to allow digits: `[a-z_]+` could not see `utf8_byte_length`, so a digit-bearing intrinsic would have escaped the coverage check. - test/dune: keep both main's `(file ../lib/codegen.ml)` and this branch's `../bin/main.exe` dependency. - docs/UNICODE-STRINGS.adoc: the wasm-shadowing finding is now "fixed by #841". - docs/SOUNDNESS.adoc: stamp to 0cf73b2 (main incl. #841), verified on the merged tree: dune runtest --force 811 + 32 + 3 pass; codegen corpora 48 + 42 + 8 pass; all 5 guards OK. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01J4QvDfgDTxx9Bumfa2XXcQ
…adow change 40167ad changed test/test_intrinsic_shadow.ml, the anchor of #841's ledger row, deliberately: it added shadowing cases for the three Unicode primitives and let the arm-coverage regex accept digits. The ledger gate (property 3) correctly flagged the digest drift. This reseals that one anchor per "Keeping this honest". 40167ad was pushed before this reseal, so it fails property 3 on its own; this commit restores the gate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01J4QvDfgDTxx9Bumfa2XXcQ
Both were reported by the #829 thread after the first version of the audit. #836 (a user fn named like an intrinsic is replaced on wasm) has since been fixed on main by #841, so no pin is added here; #837 (an intrinsic used as a value on Bun-ESM) is a loud divergence, tracked by its issue. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01J4QvDjPsKtu8zU9b32Cv1P
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01J4QvDjPsKtu8zU9b32Cv1P
…835) Closes #830 ## The hole On `main` (`ee211d3`), the core-wasm heap-pointer global started at a fixed 1024, while string literals were laid out from a fixed 2048. Any program that bump-allocates more than about 1 KiB overwrites its own literals. Found by #829. **Reproduction on `main`.** `main` makes 60 calls of `println("label_number_N" ++ " ok")`. Compiled with `affinescript compile repro.affine -o repro.wasm` and run with `bun run repro.wasm`: ``` label_number_1 ok … label_number_21 ok label_number_22abe RuntimeError: Out of bounds memory access (evaluating 'instance') exit=1 ``` `affinescript eval` prints all 60 lines. This was silent corruption: the wrong line is printed before anything traps. **With this PR**, the same program prints all 60 lines, exits 0, and its stdout matches the interpreter's output line for line (after removing the interpreter's quotes; see #833). ## The fix (`lib/codegen.ml`, "Linear-memory layout") - **Layout:** scratch `[0, 1024)`, then static data from `static_data_base = 1024`, then the heap from `heap_base = align8(max(1024, data_end))`. - `generate_module` calls `memory_layout_of_datas` after code generation, so every literal has already been laid out. It sets the heap global to `heap_base` and sizes the memory to cover it (`max 1 (ceil(heap_base / 64 KiB))` pages). - `check_memory_layout` refuses the module with a compile-time error if: - the heap base is below the end of static data; - two segments overlap; - a segment lies in the scratch region; - the memory does not hold the static data. I checked that this gate alone catches the old layout. With the old layout restored and the gate kept, the compiler refuses the repro: `internal error (wasm memory layout): heap base 1024 is below the end of static data 3186; allocations would overwrite literals`. - **Memory growth:** there is no `memory.grow` path. If a program allocates past the module's pages, it gets an out-of-bounds trap, not a write into the literal region. A test pins this behaviour. - **Other wasm emitters:** I checked them and they are not affected. `tea_bridge`, `tea_cs_bridge` and `tea_router` have no data segments. WasmGC uses no linear memory for strings. `Wasm_dtoa` and the clock use the heap global. - **Docs:** the invariant is written up in `docs/WASM-MEMORY-LAYOUT.adoc`. ## Tests (`test/test_wasm_heap_layout.ml`, part of `dune runtest`) The last three run under Bun's WASI. They SKIP without `bun`, as in CI's coverage job. | Test | Old layout | Fix | |---|---|---| | `test_wasm_heap_base_below_data_end_refused`: the check refuses heap 1024 with a literal at 2048, overlapping segments, and a segment in scratch | n/a: the check is new. Its assertion *is* the old layout. | pass | | `test_wasm_heap_after_literals_static`: the heap global equals `heap_base`, no mutable global starts inside static data, and memory covers data | **FAIL** | pass | | `test_wasm_heap_repro_runs`: the #829 repro prints all 60 lines | **FAIL** | pass | | `test_wasm_heap_literals_intact_after_alloc`: about 40 KiB of allocation, then every literal is reprinted | **FAIL** | pass | | `test_wasm_heap_exhaustion_traps`: past one page, it traps loudly and only the pre-loop literal is printed | pass (characterisation) | pass | For the "old layout" column, I restored literals at 2048 and the heap at 1024 and removed the check, then ran the suite. The result was `3 failures! … 5 tests run`. ## Gates (run locally on this branch) ``` just check → exit 0 test_main: Test Successful, 667 tests run (incl. 5 new) res-to-affine walker: 32 tests run OK: soundness ledger — all 5 properties hold (anchors exist + back-links + content-bound + stamp-fresh + pins live) OK: doc-truthing / DEED gates / capability anchors / no extension.ts tools/run_codegen_wasm_tests.sh → All codegen WASM tests passed (48 JS harnesses) tools/run_codegen_deno_tests.sh → All codegen Bun-ESM (legacy codegen-deno corpus) tests passed (42 harnesses) tools/run_codegen_bun_tests.sh → All native Bun-ESM tests passed (8 harnesses) ``` **#836.** An earlier version of this PR pinned #836 as `open (tracked)` with an xfail test. #841 has since fixed #836 on main and added its own `fixed` row and tests, so the rebase dropped the pin and fixture. The audit marks #836 as fixed by #841. **Soundness ledger.** I added a new `docs/SOUNDNESS.adoc` row (`#830`, `fixed`), anchored to the suite and the five named tests. After #840 and #841 merged, I rebased onto `0cf73b2` and advanced the stamp to `0cf73b2` / 2026-12-01, the `main` commit I verified against. I resealed `tools/soundness-anchors.sha256`, which now has 30 anchors. On the rebased branch, `just check` exits 0 with 772 tests and the ledger reports all 5 properties; the wasm (48), Bun-ESM legacy (42) and native Bun (8) runners all pass. ## Coordination with #829 (stamp collision) #829 advances the stamp to the same `ee211d3` / 2026-12-01. I did a test merge of the two branches. It is textually clean, and the build and tests pass. However, **ledger property 4 fails on the merged tree**: #829's soundness-path edits come after the last stamp advance, and the merge leaves the stamp line unchanged. Whichever PR lands second must re-advance `:ground-truth-sha:` to the newer `main` commit it was verified against. If #829 lands first, I will rebase this branch and re-stamp. ## Audit of the other #829 divergences The full audit is in `docs/reports/AUDIT-2026-12-01-backend-divergences.adoc`. I reproduced every finding on `main` `ee211d3`. Only #830 is implemented here. | Finding | Evidence | Class | Recommended fix (most elegant and correct) | Tracking | |---|---|---|---|---| | String indices are octets on interp and wasm, UTF-16 units on Bun-ESM | `len("🦜")` is 4 / 4 / 2; `string_char_code_at("🦜",0)` is 240 / 240 / 55358 | Silent divergence, not type unsoundness | Octet offsets everywhere, failing loudly off a character boundary. Pair with an opaque `Utf8Offset` type (the dependable, type-led option). **Changes semantics: owner decision.** | #831 | | Plain-JS backend has no string builtins | `.js` compiles; then `ReferenceError: int_to_string is not defined` | Loud, but at run time instead of compile time | A closed-world check at codegen: each backend declares which builtins it lowers, and any other free identifier is a codegen `Error`. Share the Bun lowering table. | #832 | | `eval` fails on self-recursion and `let mut` | `Unbound variable: g`; `Expected mutable reference`. Also new: forward and mutual references are refused as *type* errors, because `eval` folds `check_decl` without `check_program`'s forward pass. `println` prints quotes. | Loud divergence of the reference interpreter. No silent wrong value found. | `eval` uses `check_program`; a two-phase recursive top-level environment; `let mut` binds a `VMut` cell | #833 | | **Added later:** a user fn named like a wasm-intercepted intrinsic (e.g. `string_sub`) is silently replaced by the intrinsic | Wasm prints a heap pointer (`1024` on `main`); interp and Bun print `7` | **Soundness hole (silent wrong value)** | **Fixed by #841 (merged)**: all 26 arms go through `intrinsic_callee` | #836 | | **Added later:** an intrinsic used as a value (`len`) on Bun-ESM | `ReferenceError: len is not defined`; wasm refuses at compile time | Loud, at the wrong phase | Eta-expand intrinsics in value position in a shared pass | #837 | | **Added later:** a local or parameter does not shadow a same-named top-level fn on wasm | wasm `7`, interp and Bun `9` | **Soundness hole (silent wrong value)** | Look up locals first, and intern `call_indirect` types. **Fixed by #840 (merged)**, with 4 run tests that fail first | #838 | | **Added later:** a named fn passed as a value | wasm refuses it with `UnboundVariable "nine"`; interp and Bun print `9` | Loud (compile time) | Lower it to a closure with a null environment and a trampoline | #839 | The audit also notes a proof route. The layout invariant is a small frame lemma (no allocation store aliases a data segment) that could sit beside K-1 in `formal/`. **It is not claimed here: the fix is tested, not proved.** ## Beyond this repo #834 tracks rebuilding core-wasm artefacts that were built before this fix. In this repo, **`editors/vscode/out/extension.cjs` is affected**: its embedded module has the heap at 1024 and literals at 2048–2761. I did not regenerate it here, because the committed file is already stale relative to `main` (a rebuild differs by more than the layout), so the rebuild should be its own reviewed change. ## Notes - **Signatures.** The commit is signed with the session key. The owner re-signs before merge. - **Licences.** No licence or SPDX edits. The new files carry the repo's usual headers. - **Languages.** No TypeScript and no new JavaScript. The tests are OCaml and drive Bun's built-in WASI. https://claude.ai/code/session_01J4QvDjPsKtu8zU9b32Cv1P --- _Generated by [Claude Code](https://claude.ai/code)_ --------- Co-authored-by: Claude <noreply@anthropic.com>



Closes #836
The bug
On core wasm, the intrinsic arms of
gen_expr'sExprAppdispatch (lib/codegen.ml) matched the callee by spelling, before asking whether the program binds that name. A user function named like an intrinsic was compiled but never called.main4248912The fix
user_fnsset in the codegen context holds the names the program defines: afnwith a body or aconst, in this module or imported. Anextern fnis not in it.user_binds ctx nameis true for a name in that set or a local.intrinsic_callee ctx calleereturns the callee's ident only when the program does not bind it.intrinsic_callee, not on the raw callee. An arm added later gets the guard without asking for it.fn net_acceptleft an unusedsock_acceptimport that Bun's WASI cannot satisfy.Typecheck.elab_poly_builtinrewritesshowon Int andsliceon a String into intrinsic calls. Those calls are now named__builtin:int_to_stringand__builtin:string_slice, which no program can write. Otherwise, once a userint_to_stringwins,show(5)would call it.user_bindshas the name and signature of the helper in #829, with a stricter body (#829 tests membership offunc_indices, which also holds externs). Whichever lands second keeps this definition; #829's three guards then work unchanged, and become redundant because its arms go throughintrinsic_callee.Classification of the name-matched arms
A definition with a body wins in both classes. The classes differ in what an
extern fnof the same name means: for class (b) the arm is the lowering of that declaration, so a guard onfunc_indiceswould break it.4248912with a user fn returning 7printprintln(0 and 1 argument)string_length,lenstring_char_code_at,char_to_intstring_from_char_code,string_slice,string_sub,to_lowercase,to_uppercase,trim,float_to_stringstring_findint_to_string(user fn returns"seven")clock_now_msnet_shutdown,net_sendfile_openfile_fd_writed, prints 0file_read,net_recvfile_closenet_acceptenv_count,arg_countenv_at,arg_at__show_unsupported:<T>The interpreter returns 7 for every row. Bun-ESM prints 7 for every row except a user
printorprintln, which it refuses at compile time (#801). With this PR core wasm gives 7 (seven) on every row.print,println,int_to_stringandstring_lengthare also declaredextern fninstdlib/effects.affine, so the extern rule matters for them too.Tests
test/test_intrinsic_shadow.ml, 95 cases:lib/codegen.mland fails if an arm has no case;extern fnin scope keeps the lowering and itsenvimport is not called; the lowerings run under Bun's WASI;show/sliceare not captured by a userint_to_string/string_slice;Mutation checks
lib/codegen.mlandlib/typecheck.mlas on4248912show/slice, local, importedintrinsic_calleeignoresuser_bindsuser_bindstestsfunc_indices(the blanket guard)show/slice, arm-coveragenet_accepton wasmUnder the second mutation alone,
net_shutdownandfile_closestill pass: with no WASI import the arm falls back to function index 1, which happens to be the user's function.string_slicepasses because the plain name is no longer an arm. All three fail under the first mutation.Gates
dune runtest --forcejust checklintstep printed "ocamlformat not installed; skipping format check", so formatting was not checked heretools/run_codegen_wasm_tests.shtools/run_codegen_deno_tests.shtools/run_codegen_bun_tests.shdocs/SOUNDNESS.adocgains afixedrow for #836, the stamp advances to4248912, and the manifest is resealed.Interaction with open PRs
XPASS; its row should then be dropped in favour of the row here.user_bindsabove.test/duneanddocs/SOUNDNESS.adocwill conflict trivially.Found, not fixed here
print("hi")on core wasm emits an invalid module. The arm lowersprintas an integer print, but its type isString -> Unit. Loud.extern fn clock_now_ms(c: Int) -> Int;the call is lowered to WASI, but the unusedenv.clock_now_msimport is still emitted, so a WASI-only host cannot instantiate the module. Same on4248912. Loud.file_fd_write,clock_now_ms, ...): they type-check and then fail with "Unbound variable" at run time. Loud.is_string_concat_operandinlib/codegen.mlstill recognises String-returning builtins by spelling and has no context, so a userfn trimthat returns an array is treated as a String operand of++. It is a rejection heuristic, so the effect is a loud refusal.tools/run_codegen_bun_tests.shleaves an untrackedtests/codegen-bun/deno-removed.jsonbehind.Generated by Claude Code