Skip to content

fix(codegen): a local shadows a same-named fn on wasm; intern call_indirect types (#838) - #840

Merged
hyperpolymath merged 1 commit into
mainfrom
claude/wasm-local-shadows-fn
Dec 1, 2026
Merged

hyperpolymath merged 1 commit into
mainfrom
claude/wasm-local-shadows-fn

Conversation

@hyperpolymath

Copy link
Copy Markdown
Owner

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.

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

Not in this PR


  • 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

…direct types (#838)

Found by the #829 thread on main ee211d3.

1. Silent wrong value. The generic ExprApp arm of gen_expr looked up
   func_indices before ctx.locals, so in
     fn call(helper: fn(String) -> Int) -> Int { helper("x") }
   the call went to a top-level `helper` and ignored the argument (wasm
   printed 7; the interpreter and Bun-ESM print 9). The arm, and
   expr_val_type's ExprApp case, now look up locals first, matching the
   ExprVar paths. This complements #824, which only stopped a parameter
   pulling in a module import.

2. Invalid wasm. The three CallIndirect sites looked a signature up in the
   type section without adding it, so a higher-order fn compiled before
   any function of its closure signature got the next free index, which a
   later type then took ("WebAssembly.Module doesn't validate"). A shared
   intern_type helper now adds the signature when it is missing.

Tests: test/test_wasm_call_resolution.ml (param shadow, let-bound shadow,
unshadowed fn still called, call_indirect types interned; run under
Bun's WASI). All four fail on ee211d3 and pass here. SOUNDNESS.adoc row
#838 (fixed), stamp ee211d3, resealed.

Closes #838

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J4QvDjPsKtu8zU9b32Cv1P
@gitnotebooks

gitnotebooks Bot commented Dec 1, 2026

Copy link
Copy Markdown

@coderabbitai

coderabbitai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You'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 30 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: fc697588-4827-4ee9-83e3-d7f115b46ec0
Commits

Reviewing files that changed from the base of the PR and between ee211d3 and 65d6bd0.

Files selected for processing: 5

  • docs/SOUNDNESS.adoc
  • lib/codegen.ml
  • test/test_main.ml
  • test/test_wasm_call_resolution.ml
  • tools/soundness-anchors.sha256
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

Share

hyperpolymath pushed a commit that referenced this pull request Dec 1, 2026
… 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
@sonarqubecloud

sonarqubecloud Bot commented Dec 1, 2026

Copy link
Copy Markdown

@hyperpolymath
hyperpolymath marked this pull request as ready for review December 1, 2026 16:39
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-12-01T16:39:35.656284Z
We couldn’t complete this review. Comment @codex review to try again.
65d6bd0 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@hyperpolymath
hyperpolymath enabled auto-merge (squash) December 1, 2026 16:39
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@hyperpolymath
hyperpolymath merged commit c2a5493 into main Dec 1, 2026
24 of 26 checks passed
@hyperpolymath
hyperpolymath deleted the claude/wasm-local-shadows-fn branch December 1, 2026 16:50
hyperpolymath pushed a commit that referenced this pull request Dec 1, 2026
… 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
hyperpolymath pushed a commit that referenced this pull request Dec 1, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J4QvDjPsKtu8zU9b32Cv1P
hyperpolymath pushed a commit that referenced this pull request Dec 1, 2026
The merge of main (809c42d) brought in #840, which itself set the stamp
to ee211d3, so relative to the new base this branch changed soundness
paths without changing the stamp line, and property 4 (as scoped in
f2ef469) correctly failed.

Re-verified this branch merged with main at c2a5493: dune runtest
--force 701 + 32 + 3 tests pass; codegen corpora 48 wasm + 42 legacy
Bun-ESM + 8 native Bun harnesses pass; the cross-backend Unicode and
shadowing suites pass on all four backends; all 5 guards OK. #840 also
fixes the wasm parameter-shadowing case raised in review (it now prints
9, matching interp and Bun-ESM).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J4QvDfgDTxx9Bumfa2XXcQ
hyperpolymath pushed a commit that referenced this pull request Dec 1, 2026
… 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
hyperpolymath pushed a commit that referenced this pull request Dec 1, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01J4QvDjPsKtu8zU9b32Cv1P
hyperpolymath added a commit that referenced this pull request Dec 1, 2026
…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>
hyperpolymath added a commit that referenced this pull request Dec 1, 2026
…iew (#829)

## For the DEED printer thread (metadatastician/standards)

Switch to these names. They mean the same thing on every backend:

| Name | Kind | Meaning |
|---|---|---|
| `utf8_byte_length(s: String) -> Int` | intrinsic | octets of the UTF-8
encoding of `s` |
| `code_points(s: String) -> [Int]` | intrinsic | the Unicode scalar
values of `s` |
| `string_from_code_points(cps: [Int]) -> String` | intrinsic | inverse
of `code_points` |
| `utf8_width(cp: Int) -> Int` | `use utf8::{…}` | 1/2/3/4 octets for
one scalar value |
| `code_point_count(s: String) -> Int` | `use utf8::{…}` | number of
scalar values |
| `code_point_slice(s, start, end) -> String` | `use utf8::{…}` |
`[start, end)` in code points, clamped; never splits a character |
| `code_points_within_octets(s, max_octets) -> Int` | `use utf8::{…}` |
how many leading code points fit in `max_octets`; Bun-ESM only (the
interpreter can't run self-recursion, see Findings) |

Do **not** use `len`, `string_get`, `string_sub`, `string_length`,
`char_at` or `substring` to count octets. On Bun-ESM they count UTF-16
code units.

## What and why

Ground truth is recorded in `docs/UNICODE-STRINGS.adoc`. It was measured
by compiling and running probes on `main` `ee211d3`:

| Operation | interp | Bun ESM | plain JS | core wasm |
|---|---|---|---|---|
| `len` of `a`/`é`/`漢`/`🦜` | 1/2/3/4 (octets) | 1/1/1/2 (UTF-16 units) |
`ReferenceError` | 1/2/3/4 |
| `string_get("🦜",0)` → `char_to_int` | 240 | 55358 (lone surrogate) |
`ReferenceError` | refused at compile time |
| `string_char_code_at("🦜",0/1)` | 240/159 | 55358/56732 |
`ReferenceError` | 240/159 |
| `string_sub("🦜x",0,1)` | ill-formed octet | lone surrogate |
`ReferenceError` | ill-formed octet |
| char literal `'é'` | lexer rejects it on every backend (`Char` is one
octet) | | | |

Deno-ESM is retired (`--deno-esm` is refused), so the Bun-ESM column
covers it.

This PR is **additive**: `len`, `string_get` and `string_sub` keep their
current meaning. The three intrinsics are lowered on the interpreter,
Bun-ESM, plain JS and core wasm.

Each is defined only on well-formed input and fails loudly otherwise: a
run-time error on the interpreter, a JS throw, or a wasm trap.
Ill-formed input means a string cut by `string_sub`, a lone surrogate,
overlong or truncated UTF-8, or a non-scalar `Int`. None of them ever
substitutes U+FFFD.

## Assumptions a later proof can rely on (tested, not proved)

1. A well-formed `String` denotes a sequence of Unicode scalar values.
2. `string_from_code_points ∘ code_points = id` on well-formed strings,
and `code_points ∘ string_from_code_points = id` on arrays of scalar
values.
3. `utf8_byte_length(s) = Σ utf8_width(cp)` over `code_points(s)`, using
RFC 3629 shortest-form widths.
4. On Bun, writing a well-formed string as UTF-8 emits exactly
`utf8_byte_length(s)` octets.
5. There is no Unicode normalisation.
6. Integers are exact: wasm i32 and JS Number.
7. The trusted base is OCaml's `String.get_utf_8_uchar`/`Uchar`, JS
`charCodeAt`/`fromCodePoint`, and the wasm decode and encode loops in
`lib/codegen.ml`.

## Tests

`test/test_unicode_octets.ml` is part of `dune runtest`. It runs
fixtures through the real CLI on interp, Bun-ESM, plain JS (node) and
core wasm (`bun run`, Bun's WASI). No hand-written JS is involved. Each
backend is checked against RFC 3629 / Unicode values, not against
another backend.

The suite was mutation-checked:
- a wrong 2-octet width in the Bun helper fails the Bun-ESM checks;
- a missing surrogate check in the wasm encoder fails the wasm
loud-failure check.

```
just check                         → exit 0
  test_main: Test Successful, 691 tests run (incl. 28 new Unicode cases)
  res-to-affine walker: Test Successful, 32 tests run
  OK: no extension.ts / doc-truthing / DEED gates / soundness ledger (5 properties) / capability anchors
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)
```

Notes on the test run:
- `lint` is a no-op: the repo has no `.ocamlformat`, so ocamlformat
disables itself. That predates this PR.
- In CI's coverage job (no Bun), the Bun and wasm cases print `SKIP` and
the interp cases still run. The `build` job has Bun and Node and runs
all four backends.


## Soundness-ledger stamp and gate fix (owner decision: "thread bumps +
fixes check")

This PR touches `lib/{interp,codegen,codegen_deno,typecheck}.ml`, which
are ledger soundness paths.

- `66a314e` advances `:ground-truth-sha:` to `ee211d3` and
`:ground-truth-date:` to `2026-12-01`. That is current `main`, verified
together with this branch's changes.
- `34f5ecc` and `f2ef469` fix ledger **property 4**, in their own
commits.
- `b70e9df` advances the stamp again, to `c2a5493`. The owner merged
`main` into this branch (`809c42d`), bringing in #840, which had itself
set the stamp to `ee211d3`, so property 4 correctly required a fresh
bump against the new base. I re-verified on the merged head: `dune
runtest --force` 701 + 32 + 3 tests pass; the codegen corpora (48 + 42 +
8 harnesses) pass; all 5 guards pass.

**The bug.** Property 4 diffed the tree against the stamp commit `S` and
passed if that diff showed a stamp-line change. The commit that sets the
stamp to `S` always comes after `S`, so the diff always contained one,
and the property passed for every later change. At least ten unbumped
soundness-path PRs merged after #802 that way.

**The new rule (`f2ef469`).** Property 4 judges *the change*:
`merge-base(HEAD, origin/main)` to the working tree, which is what gets
squash-merged. If that change touches a soundness path, it must also
change `:ground-truth-sha:`. Without `origin/main`, the fallback is a
history rule: nothing on a soundness path may change after the last
commit that changed the stamp line. That rule is merge-aware, so a bump
made in a merge commit is found.

I first used the history rule as the primary check (`34f5ecc`). It could
never pass a PR that re-verifies against an unchanged `main`, because
re-stamping to the same SHA changes no line, and it turned every PR red
while `main` was stale. `f2ef469` replaces it.

Planted cases, run in an isolated clone:

| Case | Old | New (with `origin/main`, as in CI) | New (fallback) |
|---|---|---|---|
| A pristine `main` | pass | pass | FAIL (stale `main`) |
| B unbumped soundness edit | pass | **FAIL** | **FAIL** |
| C edit + bump in one change | pass | pass | pass |
| D bump, then a later edit in the same branch | pass | pass (same
change) | FAIL |
| E edit commit, then bump commit | pass | pass | pass |
| F bump made in a merge commit | pass | pass | pass |
| G merge of an unbumped soundness change | pass | **FAIL** | **FAIL** |
| H unrelated docs-only change | pass | pass | FAIL (stale `main`) |

**Effect on other open PRs.** None, unless the PR touches a soundness
path; then it must advance the stamp in that PR. A stale `main` no
longer turns unrelated PRs red. The existing "main moved a soundness
path under this branch; rebase" check is unchanged.

## Review follow-ups (CodeRabbit)

- **User definitions now shadow the three intrinsics on every backend
(`4f5eb58`).**
- Core wasm used to emit the intrinsic anyway and print a heap pointer;
its three arms are now guarded by `user_binds`.
- The plain-JS backend refused such declarations, a regression from this
PR. Its helpers are now internal `__as_*` names, bound to the source
names only when the program doesn't declare them.
- The JS int-division classifier no longer treats a declared fn named
like an Int intrinsic as returning Int.
- New tests cover all four backends plus two int-division cases. Each
was mutation-checked: it fails with its fix reverted.
- **The `stdlib/utf8.affine` header** now says
`code_points_within_octets` runs on Bun-ESM only.
- **Not changed here: using an intrinsic as a value on Bun-ESM** (for
example `let f = code_points; f(s)`). It emits a bare name for every
intrinsic, `len` included, and that predates this PR. Direct calls work
on all four backends, and on plain JS the three new names now also work
as values.
- **Fixed on `main` by #840: a wasm parameter now shadows a same-named
top-level fn.** I reported this case with a repro in review, and it now
prints 9 on the merged head, matching interp and Bun-ESM.
- **Also not changed: shadowing for the older wasm intrinsics.** A user
`string_sub` still prints a heap pointer on wasm, on `main` today. Some
of those arms deliberately intercept stdlib externs, so it needs its own
audit; it is recorded in `docs/UNICODE-STRINGS.adoc`.

Fresh results on `f2ef469`'s code:
- `dune runtest --force`: 697 + 32 + 3 tests pass;
- the 3 codegen corpora: 48 + 42 + 8 harnesses pass;
- all 5 guards: OK.

## Owner decision still open

- **Commit signatures.** The commits are signed by the session's own
Claude key. You planned to re-sign them before merge.

## Findings (all reproduce on `main` without this PR; only 8 is fixed
here)

1. **The string builtins disagree between backends** (the table above).
This is a semantic divergence in the #560 class, not type unsoundness.
Proposed separate fix:
   - make string indices octet offsets everywhere (the Rust model);
- make `string_sub`/`string_get` fail loudly off a character boundary;
   - point code that needs characters at this API.
2. **Core-wasm heap overwrites string literals.** This is the most
serious finding. The heap starts at a fixed `1024`, but literals are
laid out from `2048`. Any program that allocates more than about 1 KiB
corrupts its own literals. Repro: 60 × `println("label_number_N" ++ "
ok")` compiled to wasm prints 21 lines, then `label_number_22abe`, then
traps with `Out of bounds memory access`. The interpreter prints all 60.
Proposed fix: start the heap at `align(next_string_offset, 8)`. The new
suite keeps its success path allocation-free so it tests the primitives,
not this.
3. **`affinescript eval` can't run a self-recursive top-level fn.**
`TopFn` builds the closure with `cl_env = env` before binding its own
name. `fn g(x) { … g(x - 1) … }` fails with `Unbound variable: g`; Bun
gives the right answer.
4. **`affinescript eval` rejects all mutable locals.** `let mut k = 0;
while k < 3 { k = k + 1; }` fails with `Type mismatch: Expected mutable
reference`.
5. **`string::char_at` fails under `eval`** with `Unbound variable:
Some`. The root cause is not established.
6. **The plain-JS backend lowers no string builtins** (`len`,
`int_to_string`, …). Each is a run-time `ReferenceError`, not a
compile-time refusal.
7. **Interp `println` prints a String as an escaped OCaml literal**,
quotes included.
8. **Soundness-ledger property 4** could not detect a missing stamp
bump. This one *is* fixed here, in `34f5ecc` and `f2ef469`, by owner
decision (see above).

## Coordination

The new Bun-ESM entries sit in the shared `deno_builtins`
string-primitive block next to `string_sub`, plus helpers next to
`__as_strFind`. The `bun_builtins` table is untouched, so this should
not collide with the typed-Bun-host-I/O thread.

https://claude.ai/code/session_01J4QvDfgDTxx9Bumfa2XXcQ


---
_Generated by [Claude Code](https://claude.ai/code)_

---------

Signed-off-by: Jonathan D.A. Jewell <6759885+hyperpolymath@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

wasm: a local/parameter does not shadow a same-named top-level fn (silent wrong value); closure call types not interned (invalid wasm)

2 participants