Skip to content

Commit c2a5493

Browse files
fix(codegen): a local shadows a same-named fn on wasm; intern call_indirect 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>
1 parent ee211d3 commit c2a5493

5 files changed

Lines changed: 179 additions & 33 deletions

File tree

‎docs/SOUNDNESS.adoc‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
// Freshness stamp — a real main-ancestor commit (survives squash-merge); advance
55
// it (and --reseal) in any change that touches a soundness path. See "Keeping
66
// this honest" and tools/check-soundness-ledger.sh (property 4).
7-
:ground-truth-sha: 70379fe
8-
:ground-truth-date: 2026-11-19
7+
:ground-truth-sha: ee211d3
8+
:ground-truth-date: 2026-12-01
99
:stamp-verified-by: tools/check-soundness-ledger.sh
1010
:toc: macro
1111
:toclevels: 2
@@ -238,6 +238,20 @@ this reason until impl methods get distinct names.
238238
| `loud-fail`
239239
| `test_801_impl_methods_refused` (the AOT smoke pins `traits.affine`'s refusal
240240
in `expected_refusals`).
241+
242+
| #838
243+
| On core wasm a local (parameter, let-bound closure) shadows a top-level
244+
function of the same name, as on the interpreter and Bun-ESM. The generic call
245+
arm of `gen_expr` used to consult `func_indices` before `ctx.locals`, so
246+
`fn call(helper: fn(String) -> Int) { helper("x") }` silently called the
247+
top-level `helper` (wasm printed 7; interp and Bun print 9). Fixed alongside:
248+
the three `CallIndirect` sites now intern their signature (`intern_type`)
249+
instead of looking it up without adding it, which made a higher-order
250+
function compiled before its closure signature existed emit invalid wasm.
251+
| `fixed`
252+
| `test/test_wasm_call_resolution.ml` (`test_wasm_param_shadows_fn`,
253+
`test_wasm_let_shadows_fn`, `test_wasm_unshadowed_fn_still_direct`,
254+
`test_wasm_call_indirect_type_interned` — all four fail on `ee211d3`)
241255
|===
242256

243257
== Still open — read before claiming "sound"

‎lib/codegen.ml‎

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,19 @@ let rec gen_pattern_bind (ctx : context) (pat : pattern) : (context * instr list
369369
let (ctx', idx) = alloc_local ctx "__pat_bind" in
370370
Ok (ctx', [LocalSet idx])
371371

372+
(** Index of [ft] in the module's type section, adding it if absent.
373+
A [call_indirect] needs its signature in the type section; looking it up
374+
without adding it returned the *next free* index when the signature had
375+
not been seen yet (the caller compiled before any function of that type),
376+
and a later, different type then took that slot — invalid wasm. *)
377+
let intern_type (ctx : context) (ft : func_type) : (context * int) =
378+
let rec find i = function
379+
| [] -> ({ ctx with types = ctx.types @ [ft] }, List.length ctx.types)
380+
| t :: _ when t = ft -> (ctx, i)
381+
| _ :: rest -> find (i + 1) rest
382+
in
383+
find 0 ctx.types
384+
372385
(** Ensure heap pointer global is initialized.
373386
Returns (context, heap_global_idx). *)
374387
let ensure_heap_ptr (ctx : context) : (context * int) =
@@ -501,6 +514,8 @@ let rec expr_val_type (ctx : context) (e : expr) : value_type =
501514
| Some k when k < 0 && -(k + 1) < List.length ctx.globals ->
502515
(List.nth ctx.globals (-(k + 1))).g_type
503516
| _ -> I32))
517+
| ExprApp (ExprVar id, _) when List.mem_assoc id.name ctx.locals ->
518+
I32 (* a local closure shadows a same-named top-level fn *)
504519
| ExprApp (ExprVar id, _) ->
505520
(match List.assoc_opt id.name ctx.fn_ret_types with Some t -> t | None -> I32)
506521
| ExprIf r -> expr_val_type ctx r.ei_then
@@ -2049,8 +2064,17 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result =
20492064
(* Generate code for function expression *)
20502065
begin match func_expr with
20512066
| ExprVar id ->
2052-
(* Check if it's a named function or a variable holding a lambda *)
2053-
begin match List.assoc_opt id.name ctx_after_args.func_indices with
2067+
(* Check if it's a named function or a variable holding a lambda.
2068+
A local (parameter, let, pattern binder) shadows a top-level
2069+
function of the same name, as it does on the interpreter and
2070+
Bun-ESM: look in [ctx.locals] first. Matching [func_indices]
2071+
first made `fn call(helper: fn(String) -> Int) { helper("x") }`
2072+
call the top-level `helper`, silently ignoring the argument. *)
2073+
let fn_index =
2074+
if List.mem_assoc id.name ctx_after_args.locals then None
2075+
else List.assoc_opt id.name ctx_after_args.func_indices
2076+
in
2077+
begin match fn_index with
20542078
| Some func_idx when func_idx < 0 ->
20552079
(* #561: a negative index is a top-level const (global
20562080
sentinel), not a function. Calling a function-valued const
@@ -2093,15 +2117,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result =
20932117
let call_type = { ft_params = param_types; ft_results = result_type } in
20942118

20952119
(* Find or add this type *)
2096-
let type_idx =
2097-
(* OCaml 4.14 compat: List.find_index is 5.1+. Inline equivalent. *)
2098-
let rec find_idx i = function
2099-
| [] -> List.length ctx_temp2.types
2100-
| t :: _ when t = call_type -> i
2101-
| _ :: rest -> find_idx (i + 1) rest
2102-
in
2103-
find_idx 0 ctx_temp2.types
2104-
in
2120+
let (ctx_temp2, type_idx) = intern_type ctx_temp2 call_type in
21052121

21062122
(* Call: push env, push user args, push func_id, call indirect *)
21072123
let call_instrs = [
@@ -2125,16 +2141,8 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result =
21252141
let result_type = [I32] in
21262142
let call_type = { ft_params = param_types; ft_results = result_type } in
21272143

2128-
(* Find matching type index *)
2129-
let type_idx =
2130-
(* OCaml 4.14 compat: List.find_index is 5.1+. Inline equivalent. *)
2131-
let rec find_idx i = function
2132-
| [] -> List.length ctx_with_lambda.types
2133-
| t :: _ when t = call_type -> i
2134-
| _ :: rest -> find_idx (i + 1) rest
2135-
in
2136-
find_idx 0 ctx_with_lambda.types
2137-
in
2144+
(* Find or add the matching type *)
2145+
let (ctx_with_lambda, type_idx) = intern_type ctx_with_lambda call_type in
21382146

21392147
Ok (ctx_with_lambda, all_arg_code @ lambda_code @ [CallIndirect type_idx])
21402148

@@ -2194,16 +2202,8 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result =
21942202
let result_type = [I32] in
21952203
let call_type = { ft_params = param_types; ft_results = result_type } in
21962204

2197-
(* Find matching type index *)
2198-
let type_idx =
2199-
(* OCaml 4.14 compat: List.find_index is 5.1+. Inline equivalent. *)
2200-
let rec find_idx i = function
2201-
| [] -> List.length ctx_final.types
2202-
| t :: _ when t = call_type -> i
2203-
| _ :: rest -> find_idx (i + 1) rest
2204-
in
2205-
find_idx 0 ctx_final.types
2206-
in
2205+
(* Find or add the matching type *)
2206+
let (ctx_final, type_idx) = intern_type ctx_final call_type in
22072207

22082208
Ok (ctx_final, all_arg_code @ func_code @ [CallIndirect type_idx])
22092209
end

‎test/test_main.ml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ let () =
3737
("Bun integer block scope", Test_int_scope_bun.tests);
3838
("Same cube: faces compile alike (#601)", Test_same_cube.tests);
3939
("float_to_string format (#643)", Test_float_format.tests);
40+
("Wasm call resolution", Test_wasm_call_resolution.tests);
4041
("ESM runtime pruning", Test_runtime_prune.tests);
4142
("Stdlib algebraic laws (batch 1)", Test_stdlib_laws.tests);
4243
("Solo CESK (VM M1, ADR-0025)", Test_solo_cesk.tests);

‎test/test_wasm_call_resolution.ml‎

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
(* SPDX-License-Identifier: MPL-2.0 *)
2+
(* SPDX-FileCopyrightText: 2026 hyperpolymath *)
3+
4+
(** Core-wasm call resolution: a local shadows a top-level function, and a
5+
closure call always names a signature present in the type section.
6+
7+
Two holes, both found by the #829 thread on `main` `ee211d3`:
8+
9+
- silent: the generic [ExprApp] arm of [Codegen.gen_expr] looked up
10+
[func_indices] before [ctx.locals], so in
11+
`fn call(helper: fn(String) -> Int) -> Int { helper("x") }` the call
12+
went to a top-level `fn helper` instead of the argument (wasm printed
13+
7; the interpreter and Bun-ESM print 9);
14+
- loud: the three [CallIndirect] sites looked a signature up in the type
15+
section without adding it, so a higher-order function compiled before
16+
any function of its closure signature got the next free index, which a
17+
later, different type then took — the module failed validation.
18+
19+
The run tests use Bun's WASI and SKIP where `bun` is not installed. *)
20+
21+
open Affinescript
22+
23+
let compile src =
24+
let prog = Parse_driver.parse_string ~file:"<wasm_call_resolution>" src in
25+
let loader = Module_loader.create (Module_loader.default_config ()) in
26+
match Resolve.resolve_program_with_loader prog loader with
27+
| Error (e, _) -> Alcotest.failf "resolve: %s" (Resolve.show_resolve_error e)
28+
| Ok (rctx, itc) ->
29+
match Typecheck.check_program ~import_types:itc.Typecheck.name_types
30+
rctx.symbols prog with
31+
| Error e -> Alcotest.failf "typecheck: %s" (Typecheck.format_type_error e)
32+
| Ok _ ->
33+
let prog = Opt.fold_constants_program
34+
(Typecheck.elaborate_string_concat prog) in
35+
match Codegen.generate_module ~loader prog with
36+
| Ok m -> m
37+
| Error e -> Alcotest.failf "codegen: %s" (Codegen.show_codegen_error e)
38+
39+
let bun_available () = Sys.command "bun --version > /dev/null 2>&1" = 0
40+
41+
let run_wasm (m : Wasm.wasm_module) : string list * Unix.process_status =
42+
let file = Filename.temp_file "wasm_call_resolution" ".wasm" in
43+
Wasm_encode.write_module_to_file file m;
44+
let ic = Unix.open_process_in ("bun run " ^ Filename.quote file ^ " 2>&1") in
45+
let rec read acc =
46+
match input_line ic with
47+
| l -> read (l :: acc)
48+
| exception End_of_file -> List.rev acc
49+
in
50+
let lines = read [] in
51+
let st = Unix.close_process_in ic in
52+
(try Sys.remove file with Sys_error _ -> ());
53+
(lines, st)
54+
55+
let expect_output what src expected =
56+
if not (bun_available ()) then
57+
Printf.printf "SKIP %s: bun not installed\n%!" what
58+
else begin
59+
let lines, st = run_wasm (compile src) in
60+
Alcotest.(check (list string)) what expected lines;
61+
Alcotest.(check bool) (what ^ ": exit 0") true (st = Unix.WEXITED 0)
62+
end
63+
64+
(* Every closure call names a signature that is in the type section. *)
65+
let call_indirect_types_present (m : Wasm.wasm_module) =
66+
let ntypes = List.length m.types in
67+
let rec ok = function
68+
| Wasm.CallIndirect t -> t < ntypes
69+
| Wasm.Block (_, b) | Wasm.Loop (_, b) -> List.for_all ok b
70+
| Wasm.If (_, a, b) -> List.for_all ok a && List.for_all ok b
71+
| _ -> true
72+
in
73+
List.for_all (fun (f : Wasm.func) -> List.for_all ok f.f_body) m.funcs
74+
75+
(* The #829 reproduction: a parameter shadows a top-level fn. *)
76+
let param_shadow_src = {|fn helper(s: String) -> Int { 7 }
77+
fn call(helper: fn(String) -> Int) -> Int { helper("x") }
78+
fn main() -> () { println(int_to_string(call(|s| 9))); }
79+
|}
80+
81+
let test_wasm_param_shadows_fn () =
82+
expect_output "a parameter shadows a same-named fn" param_shadow_src [ "9" ]
83+
84+
(* A let-bound closure shadows a top-level fn too. *)
85+
let let_shadow_src = {|fn helper(s: String) -> Int { 7 }
86+
fn main() -> () {
87+
let helper = |s: String| 9;
88+
println(int_to_string(helper("x")));
89+
}
90+
|}
91+
92+
let test_wasm_let_shadows_fn () =
93+
expect_output "a let-bound closure shadows a same-named fn" let_shadow_src [ "9" ]
94+
95+
(* Without shadowing, the top-level fn is still called directly. *)
96+
let no_shadow_src = {|fn helper(s: String) -> Int { 7 }
97+
fn call(f: fn(String) -> Int) -> Int { helper("x") + f("x") }
98+
fn main() -> () { println(int_to_string(call(|s| 9))); }
99+
|}
100+
101+
let test_wasm_unshadowed_fn_still_direct () =
102+
expect_output "an unshadowed fn is still called" no_shadow_src [ "16" ]
103+
104+
(* A higher-order fn compiled before any function of its closure signature:
105+
was invalid wasm (call_indirect named a type not yet in the section). *)
106+
let hof_first_src = {|fn call(f: fn(String) -> Int) -> Int { f("x") }
107+
fn main() -> () { println(int_to_string(call(|s| 9))); }
108+
|}
109+
110+
let test_wasm_call_indirect_type_interned () =
111+
List.iter (fun (what, src) ->
112+
Alcotest.(check bool) (what ^ ": every call_indirect type is in the type section")
113+
true (call_indirect_types_present (compile src)))
114+
[ ("param shadow", param_shadow_src); ("hof first", hof_first_src) ];
115+
expect_output "higher-order fn declared before its lambda" hof_first_src [ "9" ]
116+
117+
let tests = [
118+
Alcotest.test_case "parameter shadows a same-named fn (bun)" `Quick
119+
test_wasm_param_shadows_fn;
120+
Alcotest.test_case "let-bound closure shadows a same-named fn (bun)" `Quick
121+
test_wasm_let_shadows_fn;
122+
Alcotest.test_case "unshadowed fn still called directly (bun)" `Quick
123+
test_wasm_unshadowed_fn_still_direct;
124+
Alcotest.test_case "call_indirect signature is interned" `Quick
125+
test_wasm_call_indirect_type_interned;
126+
]

‎tools/soundness-anchors.sha256‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,23 @@
55
# test's function-body hash; SUITE = whole-file hash.
66
09f299eaf7e9a0d912db441f346438e31ea7157f6f730ab1b6d78ef6d22a76a1 test:test_801_planted_collision_refused
77
0d3623cf36a67860106d64bb32d30633978bb426d4ddd77ecc2bf6e48e1b7263 fixture:test/e2e/fixtures/borrow_callee_returned_borrow_uam.affine
8+
2bbd1b989fd0097530eede3e5230258e0e1092271a23ff7dff20cca65c0e612e suite:test/test_wasm_call_resolution.ml
89
2dfe36a21983a7dfb7ffa1157f7ddec9865a531a92682976b8fd677e4825e78d test:test_801_impl_methods_refused
910
546939eaa3c64c82edd23da0a3ba7f74bcf7378cfe1e426132dd1a9f8fd46050 test:test_801_transitive_public_and_const
1011
5b84a4f71aa65f9aa9383e31c0cb624291c4f9d0de7cca4a0ea6a76fe85aea35 fixture:test/e2e/fixtures/handle_resume_nontail.affine
1112
68f0f4ad2462f146b87f491b7456aff9a56b77397344d22c62f4f4ff5ca6e3ae fixture:test/e2e/fixtures/assume_rejected.affine
13+
6dc672457b5dc5840e58a5d5014d192c459d038ab57f9b09fa3234a1e3df985c test:test_wasm_unshadowed_fn_still_direct
1214
7f416f186a15511ec5c64d2b96bfffbdf9e7c8c0879951d56c80e46129e2ea48 test:test_stub_backend_return_fenced
1315
80541ee00580b4dccee4657cbd31d11a1ddaa18cc49813b48f686c9509f314dc suite:test/test_borrow_polonius.ml
1416
832d4c8b64176706535334a5dbbb16345f42b75ac9b1a93f0a5dc371d84b5a0d test:test_801_same_name_in_two_modules
1517
874a5531cd8bc402adf4b66277b21b15d921efe06a7128ea6583bcd6e55781ba test:test_resume_nontail_xfail
1618
ac1da10c3206605304f11e869f6aa07acba57f6f8248bb2dfacca19984f86c31 test:test_coherence_duplicate_rejected
19+
ad1e66df361641660125a84fb4694785357d542b0a7856de8f28e4d81f8635b5 test:test_wasm_let_shadows_fn
1720
b76c7824a9b1570d66752359a28d75ebdfaedb5de5ad68c343a0a2c26ad4221c fixture:test/e2e/fixtures/async_sync_fallback.affine
1821
c743b86cfc50512e5867ddd792b4b4273b5bfb6f40205b4a07019031d7e7b102 fixture:test/e2e/fixtures/handle_resume_multishot.affine
1922
ce709dcd36043d1b546b568cae277a83b843d1621275d830d72efef2e9a6a87c test:test_parse_assume_rejected
23+
d35167312f3aa763ad337570e3791e67f1caa799ca686162831d3a4d6ad82f41 test:test_wasm_call_indirect_type_interned
2024
e0f594e54026d859726491722d5736238a8c3758df754c3a40ee213e2d71f5d1 fixture:test/e2e/fixtures/handle_return_arm.affine
25+
eb830b47bda480cebad2da80ac30285ab97801df1a754344121f4fa3f0034b9b test:test_wasm_param_shadows_fn
2126
f39454a40f4abcb7583226907d5bc34972de528c0e87164361a04cf289f9308d fixture:test/e2e/fixtures/stub_backend_return_dropped.affine
2227
f5db1006f77d16af2ef176629a9b06440582d667ac7e3cc12011af153b077e97 test:test_coherence_generic_subsumption_rejected

0 commit comments

Comments
 (0)