Repository navigation
fix(codegen): start the wasm heap after the last data segment (#830) - #835
Merged
Merged
Conversation
|
Review these changes at https://app.gitnotebooks.com/hyperpolymath/affinescript/pull/835 |
hyperpolymath
added a commit
that referenced
this pull request
Dec 1, 2026
…direct types (#838) (#840) Closes #838 Found by the #829 thread; reproduced independently on `main` `ee211d3`. This is split off from #835, which fixes the heap and literal layout, so each PR stays reviewable. ## The holes **1. Silent wrong value.** ```affine fn helper(s: String) -> Int { 7 } fn call(helper: fn(String) -> Int) -> Int { helper("x") } fn main() -> () { println(int_to_string(call(|s| 9))); } ``` The interpreter and Bun-ESM print `9`. Core wasm printed **`7`**: the call went to the top-level `helper`, and the argument was silently ignored. The same happens with a let-bound closure. Cause: the generic `ExprApp` arm of `gen_expr` (`lib/codegen.ml`) consulted `func_indices` before `ctx.locals`. The `ExprVar` value paths already looked up locals first. **2. Invalid wasm (found while fixing 1).** `fn call(f: fn(String) -> Int) -> Int { f("x") }`, followed by `call(|s| 9)`, failed with `CompileError: WebAssembly.Module doesn't validate`. Cause: the three `CallIndirect` sites looked up the signature in the type section but never added it. If the signature was absent, they returned the next free index, and a later, different type took that slot. On `main`, this breaks any higher-order function compiled before a function with its closure signature exists. ## The fix - **Call resolution:** the call arm and `expr_val_type`'s `ExprApp` case now check locals first, so a local shadows a same-named top-level function. A name that is not a local resolves as before. - **Type interning:** a shared `intern_type` helper adds a missing signature, and all three `CallIndirect` sites now use it. This complements #824, which only stopped a parameter from pulling in a module import. It is consistent with #824: a parameter is never a reference to a top-level or imported function. ## Tests (`test/test_wasm_call_resolution.ml`, run under Bun's WASI; SKIP without `bun`) | Test | `main` `ee211d3` | This PR | |---|---|---| | `test_wasm_param_shadows_fn` | **FAIL**: got `7` | pass: `9` | | `test_wasm_let_shadows_fn` | **FAIL**: got `7` | pass: `9` | | `test_wasm_unshadowed_fn_still_direct` (direct call plus closure, `16`) | **FAIL**: invalid wasm (bug 2) | pass | | `test_wasm_call_indirect_type_interned` (every `call_indirect` type index is in the section, and the program runs) | **FAIL** | pass | ## Gates (local, this branch) ``` just check → exit 0 (test_main: 666 tests; soundness ledger: all 5 properties hold) 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) ``` The new `SOUNDNESS.adoc` row for #838 is `fixed`. The stamp is set to `ee211d3` / 2026-12-01, and the anchors are resealed. ## Coordination - **#835:** adds ledger rows at the same place in `docs/SOUNDNESS.adoc`. It also changes `tools/soundness-anchors.sha256` and `test/test_main.ml`. Whichever PR lands second needs a rebase and a reseal. I own both and will do it. - **#829:** sets the same stamp. ## Not in this PR - #839: a named function passed as a value (`call(nine)`) is refused at compile time with `UnboundVariable`. That fails loudly, and the fix is a feature (named functions as null-environment closures). - #836: a user function named like an intrinsic is silently replaced by the intrinsic. It is pinned in #835. Each of its 20 interceptions needs checking first. --- - **Commit signature:** signed with the session key. The owner re-signs before merge. - **Constraints:** no licence or SPDX edits, and no TypeScript or JS. --- _Generated by [Claude Code](https://claude.ai/code)_ Co-authored-by: Claude <noreply@anthropic.com>
hyperpolymath
force-pushed
the
claude/wasm-heap-literals
branch
from
December 1, 2026 16:51
c131d9c to
7f1f965
Compare
hyperpolymath
marked this pull request as ready for review
December 1, 2026 17:30
hyperpolymath
added a commit
that referenced
this pull request
Dec 1, 2026
…) (#841) Closes #836 ## The bug On core wasm, the intrinsic arms of `gen_expr`'s `ExprApp` dispatch (`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. ```affine fn string_sub(s: String, a: Int, b: Int) -> Int { 7 } pub fn main() -> () { println(int_to_string(string_sub("x", 0, 1))); } ``` | Backend | `main` `4248912` | this PR | |---|---|---| | interp | 7 | 7 | | Bun-ESM | 7 | 7 | | core wasm | **1024** (a heap pointer) | 7 | ## The fix - A new `user_fns` set in the codegen context holds the names the program *defines*: a `fn` with a body or a `const`, in this module or imported. An `extern fn` is not in it. - `user_binds ctx name` is true for a name in that set or a local. `intrinsic_callee ctx callee` returns the callee's ident only when the program does not bind it. - All 26 arms now match on `intrinsic_callee`, not on the raw callee. An arm added later gets the guard without asking for it. - The WASI import pre-scan skips a name the program defines. Without this, a user `fn net_accept` left an unused `sock_accept` import that Bun's WASI cannot satisfy. - `Typecheck.elab_poly_builtin` rewrites `show` on Int and `slice` on a String into intrinsic calls. Those calls are now named `__builtin:int_to_string` and `__builtin:string_slice`, which no program can write. Otherwise, once a user `int_to_string` wins, `show(5)` would call it. `user_binds` has the name and signature of the helper in #829, with a stricter body (#829 tests membership of `func_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 through `intrinsic_callee`. ## Classification of the name-matched arms A definition with a body wins in both classes. The classes differ in what an `extern fn` of the same name means: for class (b) the arm *is* the lowering of that declaration, so a guard on `func_indices` would break it. | Class | Names | wasm on `4248912` with a user fn returning 7 | |---|---|---| | (a) pure intrinsic | `print` | invalid module (loud) | | (a) | `println` (0 and 1 argument) | prints the argument; user fn not called | | (a) | `string_length`, `len` | 3 | | (a) | `string_char_code_at`, `char_to_int` | 97 | | (a) | `string_from_char_code`, `string_slice`, `string_sub`, `to_lowercase`, `to_uppercase`, `trim`, `float_to_string` | 1024 | | (a) | `string_find` | 1 | | (a) | `int_to_string` (user fn returns `"seven"`) | 1 | | (b) WASI lowering | `clock_now_ms` | 6 | | (b) | `net_shutdown`, `net_send` | 52 | | (b) | `file_open` | -44 | | (b) | `file_fd_write` | writes `d`, prints 0 | | (b) | `file_read`, `net_recv` | 1042 | | (b) | `file_close` | prints nothing | | (b) | `net_accept` | fails to instantiate (loud) | | (b) | `env_count`, `arg_count` | 186, 1 | | (b) | `env_at`, `arg_at` | 12221, 1136 | | internal | `__show_unsupported:<T>` | not writable in source | The interpreter returns 7 for every row. Bun-ESM prints 7 for every row except a user `print` or `println`, which it refuses at compile time (#801). With this PR core wasm gives 7 (`seven`) on every row. `print`, `println`, `int_to_string` and `string_length` are also declared `extern fn` in `stdlib/effects.affine`, so the extern rule matters for them too. ## Tests `test/test_intrinsic_shadow.ml`, 95 cases: - every name on the interpreter, Bun-ESM and core wasm (29 cases each); - a check that reads the arms out of `lib/codegen.ml` and fails if an arm has no case; - class (b): each of the 13 WASI names still lowers to its import; an `extern fn` in scope keeps the lowering and its `env` import is not called; the lowerings run under Bun's WASI; - `show` / `slice` are not captured by a user `int_to_string` / `string_slice`; - a local and an imported definition win. ``` [OK] 0 every name-matched arm has a case.... [OK] 1 user `print` wins (interp).... ... [OK] 59 user `print` wins (wasm).... [OK] 60 user `println/0` wins (wasm).... ... [OK] 87 user `arg_at` wins (wasm).... [OK] 88 no WASI import for a user-defined name.... [OK] 89 class (b): WASI names still lower.... [OK] 90 class (b): an extern in scope keeps the lowering.... [OK] 91 class (b): the lowerings run (bun).... [OK] 92 show/slice are not captured by user fns (bun).... [OK] 93 a local shadows an intrinsic (bun).... [OK] 94 an imported definition wins.... Test Successful in 0.505s. 95 tests run. ``` ### Mutation checks | Mutation | Failing tests | |---|---| | `lib/codegen.ml` and `lib/typecheck.ml` as on `4248912` | 34: all 29 wasm cases, the arm-coverage check, unused WASI import, `show`/`slice`, local, imported | | `intrinsic_callee` ignores `user_binds` | 29 (three wasm cases pass by accident, see below) | | `user_binds` tests `func_indices` (the blanket guard) | "an extern in scope keeps the lowering" | | elaboration emits the plain names again | `show`/`slice`, arm-coverage | | imported definitions not recorded | "an imported definition wins" | | WASI pre-scan ignores user definitions | "no WASI import for a user-defined name", `net_accept` on wasm | Under the second mutation alone, `net_shutdown` and `file_close` still pass: with no WASI import the arm falls back to function index 1, which happens to be the user's function. `string_slice` passes because the plain name is no longer an arm. All three fail under the first mutation. ### Gates | Gate | Result | |---|---| | `dune runtest --force` | pass (767 tests in the main suite) | | `just check` | pass. The `lint` step printed "ocamlformat not installed; skipping format check", so formatting was not checked here | | `tools/run_codegen_wasm_tests.sh` | pass (48 harnesses) | | `tools/run_codegen_deno_tests.sh` | pass (42 harnesses) | | `tools/run_codegen_bun_tests.sh` | pass (8 harnesses) | `docs/SOUNDNESS.adoc` gains a `fixed` row for #836, the stamp advances to `4248912`, and the manifest is resealed. ## Interaction with open PRs - #835 adds an xfail pin for #836. Once both are merged that pin reports `XPASS`; its row should then be dropped in favour of the row here. - #829: see the note on `user_binds` above. `test/dune` and `docs/SOUNDNESS.adoc` will conflict trivially. ## Found, not fixed here 1. `print("hi")` on core wasm emits an invalid module. The arm lowers `print` as an integer print, but its type is `String -> Unit`. Loud. 2. With an in-file `extern fn clock_now_ms(c: Int) -> Int;` the call is lowered to WASI, but the unused `env.clock_now_ms` import is still emitted, so a WASI-only host cannot instantiate the module. Same on `4248912`. Loud. 3. The interpreter does not bind the WASI builtins (`file_fd_write`, `clock_now_ms`, ...): they type-check and then fail with "Unbound variable" at run time. Loud. 4. `is_string_concat_operand` in `lib/codegen.ml` still recognises String-returning builtins by spelling and has no context, so a user `fn trim` that returns an array is treated as a String operand of `++`. It is a rejection heuristic, so the effect is a loud refusal. 5. `tools/run_codegen_bun_tests.sh` leaves an untracked `tests/codegen-bun/deno-removed.json` behind. --- _Generated by [Claude Code](https://claude.ai/code)_ Co-authored-by: Claude <noreply@anthropic.com>
hyperpolymath
enabled auto-merge (squash)
December 1, 2026 18:35
The core-wasm heap-pointer global was initialised to a fixed 1024 while string literals were laid out from a fixed 2048, so any program that bump-allocated more than ~1 KiB overwrote its own literals: #829's 60-concatenation repro printed 21 lines, then `label_number_22abe`, then trapped out of bounds. The interpreter printed all 60. Fix at source in lib/codegen.ml ("Linear-memory layout"): - literals start at static_data_base (= scratch_end = 1024); - after code generation, memory_layout_of_datas computes data_end from the emitted segments, and the heap global is set to align8(max(scratch_end, data_end)); the memory's initial page count covers it; - check_memory_layout refuses (compile-time error) any module whose heap base is below the end of static data, whose segments overlap or dip into the scratch region, or whose memory does not hold the static data. There is no memory.grow path; heap exhaustion stays a loud OOB trap. Tests: test/test_wasm_heap_layout.ml (layout check, static layout of compiled programs, and under Bun's WASI: the #829 repro, literals intact after ~40 KiB of allocation, exhaustion traps loudly). Three fail on the old layout; the gate alone refuses the old layout at compile time. Docs: docs/WASM-MEMORY-LAYOUT.adoc (invariant), SOUNDNESS.adoc row #830 (stamp ee211d3, resealed), audit of the other #829 divergences in docs/reports/AUDIT-2026-12-01-backend-divergences.adoc (follow-ups Closes #830 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01J4QvDjPsKtu8zU9b32Cv1P
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
… and #839 (fn as value) to the divergence audit 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
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01J4QvDjPsKtu8zU9b32Cv1P
hyperpolymath
force-pushed
the
claude/wasm-heap-literals
branch
from
December 1, 2026 18:37
7f1f965 to
2f46ef0
Compare
hyperpolymath
disabled auto-merge
December 1, 2026 19:00
hyperpolymath
enabled auto-merge (squash)
December 1, 2026 19:17
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.



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.mainmakes 60 calls ofprintln("label_number_N" ++ " ok"). Compiled withaffinescript compile repro.affine -o repro.wasmand run withbun run repro.wasm:affinescript evalprints 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 fromstatic_data_base = 1024, then the heap fromheap_base = align8(max(1024, data_end)).generate_modulecallsmemory_layout_of_datasafter code generation, so every literal has already been laid out. It sets the heap global toheap_baseand sizes the memory to cover it (max 1 (ceil(heap_base / 64 KiB))pages).check_memory_layoutrefuses the module with a compile-time error if: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.growpath. 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_bridgeandtea_routerhave no data segments. WasmGC uses no linear memory for strings.Wasm_dtoaand 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 ofdune runtest)The last three run under Bun's WASI. They SKIP without
bun, as in CI's coverage job.test_wasm_heap_base_below_data_end_refused: the check refuses heap 1024 with a literal at 2048, overlapping segments, and a segment in scratchtest_wasm_heap_after_literals_static: the heap global equalsheap_base, no mutable global starts inside static data, and memory covers datatest_wasm_heap_repro_runs: the #829 repro prints all 60 linestest_wasm_heap_literals_intact_after_alloc: about 40 KiB of allocation, then every literal is reprintedtest_wasm_heap_exhaustion_traps: past one page, it traps loudly and only the pre-loop literal is printedFor 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)
#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 ownfixedrow 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.adocrow (#830,fixed), anchored to the suite and the five named tests. After #840 and #841 merged, I rebased onto0cf73b2and advanced the stamp to0cf73b2/ 2026-12-01, themaincommit I verified against. I resealedtools/soundness-anchors.sha256, which now has 30 anchors. On the rebased branch,just checkexits 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 newermaincommit 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 onmainee211d3. Only #830 is implemented here.len("🦜")is 4 / 4 / 2;string_char_code_at("🦜",0)is 240 / 240 / 55358Utf8Offsettype (the dependable, type-led option). Changes semantics: owner decision..jscompiles; thenReferenceError: int_to_string is not definedError. Share the Bun lowering table.evalfails on self-recursion andlet mutUnbound variable: g;Expected mutable reference. Also new: forward and mutual references are refused as type errors, becauseevalfoldscheck_declwithoutcheck_program's forward pass.printlnprints quotes.evalusescheck_program; a two-phase recursive top-level environment;let mutbinds aVMutcellstring_sub) is silently replaced by the intrinsic1024onmain); interp and Bun print7intrinsic_calleelen) on Bun-ESMReferenceError: len is not defined; wasm refuses at compile time7, interp and Bun9call_indirecttypes. Fixed by #840 (merged), with 4 run tests that fail firstUnboundVariable "nine"; interp and Bun print9The 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.cjsis 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 tomain(a rebuild differs by more than the layout), so the rebuild should be its own reviewed change.Notes
https://claude.ai/code/session_01J4QvDjPsKtu8zU9b32Cv1P
Generated by Claude Code