Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions docs/SOUNDNESS.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
// Freshness stamp — a real main-ancestor commit (survives squash-merge); advance
// it (and --reseal) in any change that touches a soundness path. See "Keeping
// this honest" and tools/check-soundness-ledger.sh (property 4).
:ground-truth-sha: 70379fe
:ground-truth-date: 2026-11-19
:ground-truth-sha: ee211d3
:ground-truth-date: 2026-12-01
:stamp-verified-by: tools/check-soundness-ledger.sh
:toc: macro
:toclevels: 2
Expand Down Expand Up @@ -238,6 +238,20 @@ this reason until impl methods get distinct names.
| `loud-fail`
| `test_801_impl_methods_refused` (the AOT smoke pins `traits.affine`'s refusal
in `expected_refusals`).

| #838
| On core wasm a local (parameter, let-bound closure) shadows a top-level
function of the same name, as on the interpreter and Bun-ESM. The generic call
arm of `gen_expr` used to consult `func_indices` before `ctx.locals`, so
`fn call(helper: fn(String) -> Int) { helper("x") }` silently called the
top-level `helper` (wasm printed 7; interp and Bun print 9). Fixed alongside:
the three `CallIndirect` sites now intern their signature (`intern_type`)
instead of looking it up without adding it, which made a higher-order
function compiled before its closure signature existed emit invalid wasm.
| `fixed`
| `test/test_wasm_call_resolution.ml` (`test_wasm_param_shadows_fn`,
`test_wasm_let_shadows_fn`, `test_wasm_unshadowed_fn_still_direct`,
`test_wasm_call_indirect_type_interned` — all four fail on `ee211d3`)
|===

== Still open — read before claiming "sound"
Expand Down
62 changes: 31 additions & 31 deletions lib/codegen.ml
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,19 @@ let rec gen_pattern_bind (ctx : context) (pat : pattern) : (context * instr list
let (ctx', idx) = alloc_local ctx "__pat_bind" in
Ok (ctx', [LocalSet idx])

(** Index of [ft] in the module's type section, adding it if absent.
A [call_indirect] needs its signature in the type section; looking it up
without adding it returned the *next free* index when the signature had
not been seen yet (the caller compiled before any function of that type),
and a later, different type then took that slot — invalid wasm. *)
let intern_type (ctx : context) (ft : func_type) : (context * int) =
let rec find i = function
| [] -> ({ ctx with types = ctx.types @ [ft] }, List.length ctx.types)
| t :: _ when t = ft -> (ctx, i)
| _ :: rest -> find (i + 1) rest
in
find 0 ctx.types

(** Ensure heap pointer global is initialized.
Returns (context, heap_global_idx). *)
let ensure_heap_ptr (ctx : context) : (context * int) =
Expand Down Expand Up @@ -501,6 +514,8 @@ let rec expr_val_type (ctx : context) (e : expr) : value_type =
| Some k when k < 0 && -(k + 1) < List.length ctx.globals ->
(List.nth ctx.globals (-(k + 1))).g_type
| _ -> I32))
| ExprApp (ExprVar id, _) when List.mem_assoc id.name ctx.locals ->
I32 (* a local closure shadows a same-named top-level fn *)
| ExprApp (ExprVar id, _) ->
(match List.assoc_opt id.name ctx.fn_ret_types with Some t -> t | None -> I32)
| ExprIf r -> expr_val_type ctx r.ei_then
Expand Down Expand Up @@ -2049,8 +2064,17 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result =
(* Generate code for function expression *)
begin match func_expr with
| ExprVar id ->
(* Check if it's a named function or a variable holding a lambda *)
begin match List.assoc_opt id.name ctx_after_args.func_indices with
(* Check if it's a named function or a variable holding a lambda.
A local (parameter, let, pattern binder) shadows a top-level
function of the same name, as it does on the interpreter and
Bun-ESM: look in [ctx.locals] first. Matching [func_indices]
first made `fn call(helper: fn(String) -> Int) { helper("x") }`
call the top-level `helper`, silently ignoring the argument. *)
let fn_index =
if List.mem_assoc id.name ctx_after_args.locals then None
else List.assoc_opt id.name ctx_after_args.func_indices
in
begin match fn_index with
| Some func_idx when func_idx < 0 ->
(* #561: a negative index is a top-level const (global
sentinel), not a function. Calling a function-valued const
Expand Down Expand Up @@ -2093,15 +2117,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result =
let call_type = { ft_params = param_types; ft_results = result_type } in

(* Find or add this type *)
let type_idx =
(* OCaml 4.14 compat: List.find_index is 5.1+. Inline equivalent. *)
let rec find_idx i = function
| [] -> List.length ctx_temp2.types
| t :: _ when t = call_type -> i
| _ :: rest -> find_idx (i + 1) rest
in
find_idx 0 ctx_temp2.types
in
let (ctx_temp2, type_idx) = intern_type ctx_temp2 call_type in

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

(* Find matching type index *)
let type_idx =
(* OCaml 4.14 compat: List.find_index is 5.1+. Inline equivalent. *)
let rec find_idx i = function
| [] -> List.length ctx_with_lambda.types
| t :: _ when t = call_type -> i
| _ :: rest -> find_idx (i + 1) rest
in
find_idx 0 ctx_with_lambda.types
in
(* Find or add the matching type *)
let (ctx_with_lambda, type_idx) = intern_type ctx_with_lambda call_type in

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

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

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

Ok (ctx_final, all_arg_code @ func_code @ [CallIndirect type_idx])
end
Expand Down
1 change: 1 addition & 0 deletions test/test_main.ml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ let () =
("Bun integer block scope", Test_int_scope_bun.tests);
("Same cube: faces compile alike (#601)", Test_same_cube.tests);
("float_to_string format (#643)", Test_float_format.tests);
("Wasm call resolution", Test_wasm_call_resolution.tests);
("ESM runtime pruning", Test_runtime_prune.tests);
("Stdlib algebraic laws (batch 1)", Test_stdlib_laws.tests);
("Solo CESK (VM M1, ADR-0025)", Test_solo_cesk.tests);
Expand Down
126 changes: 126 additions & 0 deletions test/test_wasm_call_resolution.ml
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
(* SPDX-License-Identifier: MPL-2.0 *)
(* SPDX-FileCopyrightText: 2026 hyperpolymath *)

(** Core-wasm call resolution: a local shadows a top-level function, and a
closure call always names a signature present in the type section.

Two holes, both found by the #829 thread on `main` `ee211d3`:

- silent: the generic [ExprApp] arm of [Codegen.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 `fn helper` instead of the argument (wasm printed
7; the interpreter and Bun-ESM print 9);
- loud: the three [CallIndirect] sites looked a signature up in the type
section without adding it, so a higher-order function compiled before
any function of its closure signature got the next free index, which a
later, different type then took — the module failed validation.

The run tests use Bun's WASI and SKIP where `bun` is not installed. *)

open Affinescript

let compile src =
let prog = Parse_driver.parse_string ~file:"<wasm_call_resolution>" src in
let loader = Module_loader.create (Module_loader.default_config ()) in
match Resolve.resolve_program_with_loader prog loader with
| Error (e, _) -> Alcotest.failf "resolve: %s" (Resolve.show_resolve_error e)
| Ok (rctx, itc) ->
match Typecheck.check_program ~import_types:itc.Typecheck.name_types
rctx.symbols prog with
| Error e -> Alcotest.failf "typecheck: %s" (Typecheck.format_type_error e)
| Ok _ ->
let prog = Opt.fold_constants_program
(Typecheck.elaborate_string_concat prog) in
match Codegen.generate_module ~loader prog with
| Ok m -> m
| Error e -> Alcotest.failf "codegen: %s" (Codegen.show_codegen_error e)

let bun_available () = Sys.command "bun --version > /dev/null 2>&1" = 0

let run_wasm (m : Wasm.wasm_module) : string list * Unix.process_status =
let file = Filename.temp_file "wasm_call_resolution" ".wasm" in
Wasm_encode.write_module_to_file file m;
let ic = Unix.open_process_in ("bun run " ^ Filename.quote file ^ " 2>&1") in
let rec read acc =
match input_line ic with
| l -> read (l :: acc)
| exception End_of_file -> List.rev acc
in
let lines = read [] in
let st = Unix.close_process_in ic in
(try Sys.remove file with Sys_error _ -> ());
(lines, st)

let expect_output what src expected =
if not (bun_available ()) then
Printf.printf "SKIP %s: bun not installed\n%!" what
else begin
let lines, st = run_wasm (compile src) in
Alcotest.(check (list string)) what expected lines;
Alcotest.(check bool) (what ^ ": exit 0") true (st = Unix.WEXITED 0)
end

(* Every closure call names a signature that is in the type section. *)
let call_indirect_types_present (m : Wasm.wasm_module) =
let ntypes = List.length m.types in
let rec ok = function
| Wasm.CallIndirect t -> t < ntypes
| Wasm.Block (_, b) | Wasm.Loop (_, b) -> List.for_all ok b
| Wasm.If (_, a, b) -> List.for_all ok a && List.for_all ok b
| _ -> true
in
List.for_all (fun (f : Wasm.func) -> List.for_all ok f.f_body) m.funcs

(* The #829 reproduction: a parameter shadows a top-level fn. *)
let param_shadow_src = {|fn helper(s: String) -> Int { 7 }
fn call(helper: fn(String) -> Int) -> Int { helper("x") }
fn main() -> () { println(int_to_string(call(|s| 9))); }
|}

let test_wasm_param_shadows_fn () =
expect_output "a parameter shadows a same-named fn" param_shadow_src [ "9" ]

(* A let-bound closure shadows a top-level fn too. *)
let let_shadow_src = {|fn helper(s: String) -> Int { 7 }
fn main() -> () {
let helper = |s: String| 9;
println(int_to_string(helper("x")));
}
|}

let test_wasm_let_shadows_fn () =
expect_output "a let-bound closure shadows a same-named fn" let_shadow_src [ "9" ]

(* Without shadowing, the top-level fn is still called directly. *)
let no_shadow_src = {|fn helper(s: String) -> Int { 7 }
fn call(f: fn(String) -> Int) -> Int { helper("x") + f("x") }
fn main() -> () { println(int_to_string(call(|s| 9))); }
|}

let test_wasm_unshadowed_fn_still_direct () =
expect_output "an unshadowed fn is still called" no_shadow_src [ "16" ]

(* A higher-order fn compiled before any function of its closure signature:
was invalid wasm (call_indirect named a type not yet in the section). *)
let hof_first_src = {|fn call(f: fn(String) -> Int) -> Int { f("x") }
fn main() -> () { println(int_to_string(call(|s| 9))); }
|}

let test_wasm_call_indirect_type_interned () =
List.iter (fun (what, src) ->
Alcotest.(check bool) (what ^ ": every call_indirect type is in the type section")
true (call_indirect_types_present (compile src)))
[ ("param shadow", param_shadow_src); ("hof first", hof_first_src) ];
expect_output "higher-order fn declared before its lambda" hof_first_src [ "9" ]

let tests = [
Alcotest.test_case "parameter shadows a same-named fn (bun)" `Quick
test_wasm_param_shadows_fn;
Alcotest.test_case "let-bound closure shadows a same-named fn (bun)" `Quick
test_wasm_let_shadows_fn;
Alcotest.test_case "unshadowed fn still called directly (bun)" `Quick
test_wasm_unshadowed_fn_still_direct;
Alcotest.test_case "call_indirect signature is interned" `Quick
test_wasm_call_indirect_type_interned;
]
5 changes: 5 additions & 0 deletions tools/soundness-anchors.sha256
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,23 @@
# test's function-body hash; SUITE = whole-file hash.
09f299eaf7e9a0d912db441f346438e31ea7157f6f730ab1b6d78ef6d22a76a1 test:test_801_planted_collision_refused
0d3623cf36a67860106d64bb32d30633978bb426d4ddd77ecc2bf6e48e1b7263 fixture:test/e2e/fixtures/borrow_callee_returned_borrow_uam.affine
2bbd1b989fd0097530eede3e5230258e0e1092271a23ff7dff20cca65c0e612e suite:test/test_wasm_call_resolution.ml
2dfe36a21983a7dfb7ffa1157f7ddec9865a531a92682976b8fd677e4825e78d test:test_801_impl_methods_refused
546939eaa3c64c82edd23da0a3ba7f74bcf7378cfe1e426132dd1a9f8fd46050 test:test_801_transitive_public_and_const
5b84a4f71aa65f9aa9383e31c0cb624291c4f9d0de7cca4a0ea6a76fe85aea35 fixture:test/e2e/fixtures/handle_resume_nontail.affine
68f0f4ad2462f146b87f491b7456aff9a56b77397344d22c62f4f4ff5ca6e3ae fixture:test/e2e/fixtures/assume_rejected.affine
6dc672457b5dc5840e58a5d5014d192c459d038ab57f9b09fa3234a1e3df985c test:test_wasm_unshadowed_fn_still_direct
7f416f186a15511ec5c64d2b96bfffbdf9e7c8c0879951d56c80e46129e2ea48 test:test_stub_backend_return_fenced
80541ee00580b4dccee4657cbd31d11a1ddaa18cc49813b48f686c9509f314dc suite:test/test_borrow_polonius.ml
832d4c8b64176706535334a5dbbb16345f42b75ac9b1a93f0a5dc371d84b5a0d test:test_801_same_name_in_two_modules
874a5531cd8bc402adf4b66277b21b15d921efe06a7128ea6583bcd6e55781ba test:test_resume_nontail_xfail
ac1da10c3206605304f11e869f6aa07acba57f6f8248bb2dfacca19984f86c31 test:test_coherence_duplicate_rejected
ad1e66df361641660125a84fb4694785357d542b0a7856de8f28e4d81f8635b5 test:test_wasm_let_shadows_fn
b76c7824a9b1570d66752359a28d75ebdfaedb5de5ad68c343a0a2c26ad4221c fixture:test/e2e/fixtures/async_sync_fallback.affine
c743b86cfc50512e5867ddd792b4b4273b5bfb6f40205b4a07019031d7e7b102 fixture:test/e2e/fixtures/handle_resume_multishot.affine
ce709dcd36043d1b546b568cae277a83b843d1621275d830d72efef2e9a6a87c test:test_parse_assume_rejected
d35167312f3aa763ad337570e3791e67f1caa799ca686162831d3a4d6ad82f41 test:test_wasm_call_indirect_type_interned
e0f594e54026d859726491722d5736238a8c3758df754c3a40ee213e2d71f5d1 fixture:test/e2e/fixtures/handle_return_arm.affine
eb830b47bda480cebad2da80ac30285ab97801df1a754344121f4fa3f0034b9b test:test_wasm_param_shadows_fn
f39454a40f4abcb7583226907d5bc34972de528c0e87164361a04cf289f9308d fixture:test/e2e/fixtures/stub_backend_return_dropped.affine
f5db1006f77d16af2ef176629a9b06440582d667ac7e3cc12011af153b077e97 test:test_coherence_generic_subsumption_rejected
Loading