From 98a4dff8e1fc43e6eaeb3b7fe307a9eed36c4e78 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 18:11:56 +0000 Subject: [PATCH] fix(codegen): a user fn named like an intrinsic is called on wasm (#836) 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 Claude-Session: https://claude.ai/code/session_01J4QvDfoRYrnr6w2SMcxvze --- docs/SOUNDNESS.adoc | 20 +- lib/codegen.ml | 114 ++++++--- lib/typecheck.ml | 12 +- test/dune | 1 + test/test_intrinsic_shadow.ml | 445 +++++++++++++++++++++++++++++++++ test/test_main.ml | 1 + tools/soundness-anchors.sha256 | 1 + 7 files changed, 558 insertions(+), 36 deletions(-) create mode 100644 test/test_intrinsic_shadow.ml diff --git a/docs/SOUNDNESS.adoc b/docs/SOUNDNESS.adoc index 22050505..69cb0a4d 100644 --- a/docs/SOUNDNESS.adoc +++ b/docs/SOUNDNESS.adoc @@ -4,7 +4,7 @@ // 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: ee211d3 +:ground-truth-sha: 4248912 :ground-truth-date: 2026-12-01 :stamp-verified-by: tools/check-soundness-ledger.sh :toc: macro @@ -261,6 +261,24 @@ function compiled before its closure signature existed emit invalid wasm. | `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`) + +| #836 +| On core wasm a function the program defines is called even when it is named +like a compiler intrinsic, as on the interpreter and Bun-ESM. The intrinsic +arms of `gen_expr`'s call dispatch matched the callee by spelling, so +`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). All 26 arms +(28 names) 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. The calls that elaboration makes for `show` on +Int and `slice` on a String are now named `__builtin:…`, which no program can +write, so a user `int_to_string` / `string_slice` does not capture them. +| `fixed` +| `test/test_intrinsic_shadow.ml` (each name on the interpreter, Bun-ESM and +core wasm; every wasm case fails on `4248912`. Also: an `extern fn` in scope +keeps the lowering; the lowerings still run; `show`/`slice` are not captured; +a local and an imported definition win) |=== == Still open — read before claiming "sound" diff --git a/lib/codegen.ml b/lib/codegen.ml index a45b23e4..c2931a62 100644 --- a/lib/codegen.ml +++ b/lib/codegen.ml @@ -40,6 +40,12 @@ type context = { (** Top-level functions, externs and effect operations declared to return Unit. A block whose tail is a call to one emits the same code as the statement form `f(..);` (#601); see [expr_is_unit]. *) + user_fns : string list; + (** #836: top-level names the program itself *defines*: a [TopFn] with a + body or a [TopConst], here or imported from another module. An + `extern fn` (a declaration without a body) is deliberately absent: + several intrinsic arms of [gen_expr] are the lowering of such a + declaration. See [user_binds]. *) loop_depth : int; (** current loop nesting depth *) func_indices : (string * int) list; (** Top-level name environment shared by functions and constants. @@ -191,6 +197,7 @@ let create_context () : context = { local_types = []; fn_ret_types = []; unit_fns = []; + user_fns = []; loop_depth = 0; func_indices = []; lambda_funcs = []; @@ -315,6 +322,36 @@ let unit_fn_names (prog : program) : string list = | _ -> []) prog.prog_decls +(** #836: names this module defines with a body ([TopFn] other than + `extern fn`) or as a constant. Imported definitions are added by + [gen_imports]. *) +let user_fn_names (prog : program) : string list = + List.filter_map + (function + | TopFn fd when fd.fd_body <> FnExtern -> Some fd.fd_name.name + | TopConst tc -> Some tc.tc_name.name + | _ -> None) + prog.prog_decls + +(** #836: does the program itself define [name] — as a function with a body + or a constant (here or imported), or as a local? The intrinsic arms of + [gen_expr]'s [ExprApp] dispatch match a callee by spelling; a callee for + which this holds is the program's own and takes the ordinary call + instead, as it does on the interpreter and Bun-ESM. A name that is only + *declared* (`extern fn`, an effect operation) is not user-bound, so the + WASI lowerings of the stdlib externs keep working. *) +let user_binds (ctx : context) (name : string) : bool = + List.mem name ctx.user_fns || List.mem_assoc name ctx.locals + +(** #836: the callee of a call, if it may be lowered as a compiler + intrinsic: a bare name the program does not itself bind. Every + name-matched intrinsic arm dispatches on this, never on the raw callee, + so an arm added later cannot reintroduce the hijack. *) +let intrinsic_callee (ctx : context) (func_expr : expr) : ident option = + match func_expr with + | ExprVar id when not (user_binds ctx id.name) -> Some id + | _ -> None + (** Is [e] provably Unit-valued? Conservative: a [false] keeps the tail value as emitted. A call whose callee name is a local (a closure) is not the top-level declaration of that name. *) @@ -452,7 +489,9 @@ let rec is_string_concat_operand (e : expr) : bool = (* String-returning builtins (Int/Char-returning ones are excluded). *) List.mem id.name [ "int_to_string"; "float_to_string"; "to_lowercase"; "to_uppercase"; - "trim"; "string_sub"; "string_slice"; "string_from_char_code"; "show" ] + "trim"; "string_sub"; "string_slice"; "string_from_char_code"; "show"; + (* #836: the names Typecheck.elab_poly_builtin gives `slice`/`show`. *) + "__builtin:string_slice"; "__builtin:int_to_string" ] | ExprBinary (a, OpConcat, b) -> is_string_concat_operand a || is_string_concat_operand b | _ -> false @@ -1207,9 +1246,11 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = Ok (ctx_final3, closure_code) | ExprApp (func_expr, args) -> - (* Check for built-in WASI functions first *) - begin match func_expr with - | ExprVar id when id.name = "print" && List.length args = 1 -> + (* Check for built-in WASI functions first. The intrinsic arms match on + [intrinsic_callee], which is [None] for a name the program defines + itself (#836). *) + begin match intrinsic_callee ctx func_expr, func_expr with + | Some id, _ when id.name = "print" && List.length args = 1 -> (* print(x) - print integer without newline *) let* (ctx_with_arg, arg_code) = gen_expr ctx (List.hd args) in @@ -1228,7 +1269,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = Ok (ctx_with_heap, print_code) - | ExprVar id when id.name = "println" && List.length args = 0 -> + | Some id, _ when id.name = "println" && List.length args = 0 -> (* println() - print newline *) let (ctx_with_temp, temp_local) = alloc_local ctx "__println_temp" in (* Ensure heap pointer is initialized *) @@ -1237,7 +1278,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = let println_code = Wasi_runtime.gen_println heap_idx fd_write_idx temp_local in Ok (ctx_with_heap, println_code) - | ExprVar id when id.name = "println" && List.length args = 1 -> + | Some id, _ when id.name = "println" && List.length args = 1 -> (* println(s) - print string and newline *) let* (ctx_with_arg, arg_code) = gen_expr ctx (List.hd args) in let (ctx_with_ptr, str_ptr) = alloc_local ctx_with_arg "__println_str_ptr" in @@ -1253,7 +1294,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (ctx_with_heap, print_code) - | ExprVar id when id.name = "clock_now_ms" && List.length args = 1 -> + | Some id, _ when id.name = "clock_now_ms" && List.length args = 1 -> (* ADR-015 S4a (#180): clock_now_ms(clock_id) -> Int ms. Lowers to a `wasi_snapshot_preview1.clock_time_get` call; the import is added on-demand at module assembly (S4b refactor), and the @@ -1277,7 +1318,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (ctx_with_heap, code) - | ExprVar id when id.name = "net_shutdown" && List.length args = 2 -> + | Some id, _ when id.name = "net_shutdown" && List.length args = 2 -> (* ADR-015 S6b (#180): net_shutdown(fd, how) -> Int errno. Lowers to a `wasi_snapshot_preview1.sock_shutdown` import (on-demand, via the same Effect_sites pre-scan as the S4 @@ -1292,7 +1333,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = let code = fd_code @ how_code @ [Call sock_func_idx] in Ok (ctx_how, code) - | ExprVar id when id.name = "file_open" && List.length args = 2 -> + | Some id, _ when id.name = "file_open" && List.length args = 2 -> (* ADR-015 S5 (#485): file_open(path, oflags) -> Int fd. Lowers to wasi_snapshot_preview1.path_open against dirfd 3 (first --dir preopen). Failure returns -errno. *) @@ -1316,7 +1357,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (ctx_h, code) - | ExprVar id when id.name = "file_fd_write" && List.length args = 2 -> + | Some id, _ when id.name = "file_fd_write" && List.length args = 2 -> (* ADR-015 S5 (#485): file_fd_write(fd, data) -> Int errno. Reuses the always-present fd_write import with a caller fd. *) let* (ctx_fd, fd_code) = gen_expr ctx (List.nth args 0) in @@ -1337,7 +1378,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (ctx_h, code) - | ExprVar id when id.name = "file_read" && List.length args = 2 -> + | Some id, _ when id.name = "file_read" && List.length args = 2 -> (* ADR-015 S5 (#485): file_read(fd, max_len) -> String. *) let* (ctx_fd, fd_code) = gen_expr ctx (List.nth args 0) in let* (ctx_n, n_code) = gen_expr ctx_fd (List.nth args 1) in @@ -1363,7 +1404,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (ctx_h, code) - | ExprVar id when id.name = "file_close" && List.length args = 1 -> + | Some id, _ when id.name = "file_close" && List.length args = 1 -> (* ADR-015 S5 (#485): file_close(fd) -> Int errno. *) let* (ctx_fd, fd_code) = gen_expr ctx (List.hd args) in let fd_close_idx = @@ -1373,7 +1414,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = let code = fd_code @ Wasi_runtime.gen_file_close fd_close_idx in Ok (ctx_fd, code) - | ExprVar id when id.name = "net_recv" && List.length args = 2 -> + | Some id, _ when id.name = "net_recv" && List.length args = 2 -> (* #487: net_recv(fd, max_len) -> String. *) let* (ctx_fd, fd_code) = gen_expr ctx (List.nth args 0) in let* (ctx_n, n_code) = gen_expr ctx_fd (List.nth args 1) in @@ -1399,7 +1440,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (ctx_h, code) - | ExprVar id when id.name = "net_send" && List.length args = 2 -> + | Some id, _ when id.name = "net_send" && List.length args = 2 -> (* #487: net_send(fd, data) -> Int errno. *) let* (ctx_fd, fd_code) = gen_expr ctx (List.nth args 0) in let* (ctx_s, str_code) = gen_expr ctx_fd (List.nth args 1) in @@ -1419,7 +1460,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (ctx_h, code) - | ExprVar id when id.name = "net_accept" && List.length args = 1 -> + | Some id, _ when id.name = "net_accept" && List.length args = 1 -> (* #487: net_accept(fd) -> Int new_fd (or -errno). *) let* (ctx_fd, fd_code) = gen_expr ctx (List.hd args) in let (ctx1, fd_local) = alloc_local ctx_fd "__net_accept_fd" in @@ -1437,7 +1478,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (ctx_h, code) - | ExprVar id when (id.name = "env_count" || id.name = "arg_count") + | Some id, _ when (id.name = "env_count" || id.name = "arg_count") && List.length args = 1 -> (* ADR-015 S4b (#180): env_count(u: Unit) / arg_count(u: Unit) — i32 count returns. Lower to the matching @@ -1465,7 +1506,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (ctx_with_heap, code) - | ExprVar id when (id.name = "string_length" || id.name = "len") + | Some id, _ when (id.name = "string_length" || id.name = "len") && List.length args = 1 -> (* STDLIB-04e (#332) wasm-backend lowering. AS string layout is `[len: i32][bytes...]` at the pointer the arg evaluates to — @@ -1486,7 +1527,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = let* (ctx_with_arg, arg_code) = gen_expr ctx (List.hd args) in Ok (ctx_with_arg, arg_code @ [I32Load (2, 0)]) - | ExprVar id when id.name = "string_char_code_at" + | Some id, _ when id.name = "string_char_code_at" && List.length args = 2 -> (* PHASE-F string-wall slice 1 (proposals/MIGRATION-PLAN.adoc §"The two walls"). String indexing on the read-side @@ -1518,7 +1559,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (ctx4, code) - | ExprVar id when id.name = "char_to_int" + | Some id, _ when id.name = "char_to_int" && List.length args = 1 -> (* PHASE-F string-wall slice 1. `char_to_int` is identity on the wasm value lattice: a Char is already an i32 byte code (cf. the @@ -1530,7 +1571,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = let* (ctx_with_arg, arg_code) = gen_expr ctx (List.hd args) in Ok (ctx_with_arg, arg_code) - | ExprVar id when id.name = "string_from_char_code" + | Some id, _ when id.name = "string_from_char_code" && List.length args = 1 -> (* PHASE-F string-wall slice 2: the write-side of the `[len: i32 LE][utf8 bytes...]` ABI. `string_from_char_code(n)` @@ -1560,7 +1601,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (ctx_v, code) - | ExprVar id when id.name = "string_slice" + | Some id, _ when id.name = "__builtin:string_slice" && List.length args = 3 -> (* #560: `slice(s, lo, hi)` on a String, after Typecheck.elaborate_string_concat picked the String case of the @@ -1620,7 +1661,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (c10, code) - | ExprVar id when String.length id.name > 19 + | Some id, _ when String.length id.name > 19 && String.sub id.name 0 19 = "__show_unsupported:" -> (* #560: `show` on a type whose rendering the backends do not agree on (the interpreter quotes Strings and Chars and prints Float 3.0 @@ -1633,7 +1674,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = the type's own to-string function, e.g. float_to_string. (#560)" tname)) - | ExprVar id when id.name = "string_sub" + | Some id, _ when id.name = "string_sub" && List.length args = 3 -> (* PHASE-F string-wall slice 3: the runtime-length copy op. `string_sub(s, start, length)` returns the substring of `length` @@ -1699,7 +1740,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (c11, code) - | ExprVar id when (id.name = "to_lowercase" || id.name = "to_uppercase") + | Some id, _ when (id.name = "to_lowercase" || id.name = "to_uppercase") && List.length args = 1 -> (* PHASE-F string-wall slice 4: ASCII case-folding — a copy-with- transform over the runtime-length idiom established in slice 3 @@ -1759,7 +1800,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (c7, code) - | ExprVar id when id.name = "trim" + | Some id, _ when id.name = "trim" && List.length args = 1 -> (* PHASE-F string-wall slice 5: `trim` — scan-for-bounds then copy, over the slice-3 runtime-length idiom. Matches the interp oracle @@ -1825,7 +1866,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (c9, code) - | ExprVar id when id.name = "string_find" + | Some id, _ when id.name = "string_find" && List.length args = 2 -> (* PHASE-F string-wall slice 6: substring search (read-side, no allocation). `string_find(haystack, needle)` returns the index of @@ -1890,7 +1931,8 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (c10, code) - | ExprVar id when id.name = "int_to_string" + | Some id, _ when (id.name = "int_to_string" + || id.name = "__builtin:int_to_string") && List.length args = 1 -> (* PHASE-F string-wall slice 7: decimal rendering. `int_to_string(n)` produces the base-10 text of an i32 — matching the interp oracle @@ -1963,7 +2005,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (c10, code) - | ExprVar id when id.name = "float_to_string" + | Some id, _ when id.name = "float_to_string" && List.length args = 1 -> (* #643: shortest round-trip rendering, the same text as Bun's `String(x)` and the interpreter. The printer is emitted once per @@ -1973,7 +2015,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = let (ctx2, _heap_idx) = ensure_heap_ptr ctx1 in Ok (ctx2, x_code @ [Call Wasm_dtoa.call_sentinel]) - | ExprVar id when (id.name = "env_at" || id.name = "arg_at") + | Some id, _ when (id.name = "env_at" || id.name = "arg_at") && List.length args = 1 -> (* ADR-015 S5 (#180): env_at(i) / arg_at(i) — fetch the i-th entry from the WASI environ/argv vector and return as a @@ -2016,7 +2058,7 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = in Ok (ctx_with_heap, code) - | ExprVar id when List.mem_assoc id.name ctx.variant_tags -> + | _, ExprVar id when List.mem_assoc id.name ctx.variant_tags -> (* Enum constructor called as a function: Circle(5), Rect({x:1,y:2}), etc. Layout: [tag: i32][field1: i32][field2: i32]... Reuses the same heap-boxing approach as ExprVariant with args. *) @@ -4108,6 +4150,10 @@ let gen_imports ?(used : (string, unit) Hashtbl.t option) types = types_after; imports = ctx.imports @ [import]; func_indices = (local_name, import_func_idx) :: ctx.func_indices; + (* #836: an imported function with a body is the program's own; + an imported `extern fn` stays an intrinsic's declaration. *) + user_fns = (if fd.fd_body <> FnExtern + then local_name :: ctx.user_fns else ctx.user_fns); (* The alias carries the result type, so `let r = M.f()` declares r f64 when f returns Float. *) fn_ret_types = (local_name, @@ -4152,6 +4198,7 @@ let gen_imports ?(used : (string, unit) Hashtbl.t option) Ok { ctx' with globals = ctx'.globals @ [global]; func_indices = (local_name, -(global_idx + 1)) :: ctx'.func_indices; + user_fns = local_name :: ctx'.user_fns; } in let expand_import imp : (string list * string * string option) list = @@ -4307,7 +4354,9 @@ let generate_module ?loader (prog : program) : wasm_module result = | Some l -> l | None -> Module_loader.create (Module_loader.default_config ()) in - let ctx = { (create_context ()) with unit_fns = unit_fn_names prog } in + let user_fns = user_fn_names prog in + let ctx = { (create_context ()) with unit_fns = unit_fn_names prog; + user_fns } in (* Add WASI fd_write import at index 0 *) let (fd_write_import, fd_write_type) = Wasi_runtime.create_fd_write_import () in @@ -4332,6 +4381,9 @@ let generate_module ?loader (prog : program) : wasm_module result = | ExprApp (ExprVar id, _) -> id.name = builtin | _ -> false) false prog + (* #836: a program that defines [builtin] itself calls its own function, + so the WASI import would be unused. *) + && not (List.mem builtin user_fns) in let optional_wasi = (* (guest_builtin_name, wasi_import_name, factory) — canonical order. diff --git a/lib/typecheck.ml b/lib/typecheck.ml index 4c32140d..5b12cf28 100644 --- a/lib/typecheck.ml +++ b/lib/typecheck.ml @@ -848,8 +848,10 @@ let reset_float_heap_sites () : unit = float_heap_sites := [] the instantiated function type at that call. After checking, the first parameter of that type is the argument's type, so {!elaborate_string_concat} can pick a monomorphic lowering: - `slice` on a String becomes `string_slice`; `show` on Int becomes - `int_to_string`, on Bool an if over two literals. Same physical-identity + `slice` on a String becomes `__builtin:string_slice`; `show` on Int + becomes `__builtin:int_to_string` (names no program can write, so its own + `string_slice` / `int_to_string` cannot capture them, #836); on Bool an if + over two literals. Same physical-identity discipline as {!string_concat_sites}. *) let poly_builtin_sites : (expr * ty) list ref = ref [] @@ -1787,8 +1789,10 @@ let elab_poly_builtin (id : ident) (fty : ty) (args : expr list) : expr = let arg_ty = match repr fty with TArrow (a, _, _, _) -> Some (repr a) | _ -> None in let call name = ExprApp (ExprVar { id with name }, args) in match id.name, arg_ty, args with - | "slice", Some (TCon "String"), _ -> call "string_slice" - | "show", Some (TCon "Int"), _ -> call "int_to_string" + (* #836: `__builtin:` names cannot be written in source, so a program's + own `string_slice` / `int_to_string` never captures these calls. *) + | "slice", Some (TCon "String"), _ -> call "__builtin:string_slice" + | "show", Some (TCon "Int"), _ -> call "__builtin:int_to_string" | "show", Some (TCon "Bool"), [b] -> ExprIf { ei_cond = b; ei_then = ExprLit (LitString ("true", id.span)); diff --git a/test/dune b/test/dune index 4c5bb097..f29d22e7 100644 --- a/test/dune +++ b/test/dune @@ -6,4 +6,5 @@ (source_tree e2e) (source_tree ../examples) (source_tree ../stdlib) + (file ../lib/codegen.ml) (file ../lib/codegen_deno.ml))) diff --git a/test/test_intrinsic_shadow.ml b/test/test_intrinsic_shadow.ml new file mode 100644 index 00000000..a2c73075 --- /dev/null +++ b/test/test_intrinsic_shadow.ml @@ -0,0 +1,445 @@ +(* SPDX-License-Identifier: MPL-2.0 *) +(* SPDX-FileCopyrightText: 2026 hyperpolymath *) + +(** #836: a function the program defines is called, even when it is named + like a compiler intrinsic. + + The intrinsic arms of [Codegen.gen_expr]'s [ExprApp] dispatch matched the + callee by spelling, before asking whether the program binds that name. On + core wasm `fn string_sub(..) -> Int { 7 }` was therefore never called: + the intrinsic ran and the program printed a heap pointer (1024) where the + interpreter and Bun-ESM print 7. A silent wrong value. + + Every name-matched arm is covered here, in two classes: + + - (a) pure language intrinsics (string and conversion primitives, print); + - (b) WASI lowerings (clock, env/args, files, sockets). + + In both classes a definition *with a body* wins. A name that is only + *declared* (`extern fn`) keeps its lowering: that is what the class-(b) + arms are for, and why the guard is not "is the name in [func_indices]". + + The expected value is the one the program's own function returns, checked + on each backend separately (not one backend against another): + + interp Interp.eval_program, then apply `probe` + bun-esm Codegen_deno.codegen_bun, then `bun` + wasm Codegen.generate_module, then `bun run` (Bun's WASI) + + The interpreter always runs. The two Bun-hosted backends SKIP loudly where + `bun` is not installed. No hand-written JS: the hosts run compiler output. *) + +open Affinescript + +let frontend ?loader src = + let prog = Parse_driver.parse_string ~file:"" src in + let loader = match loader with + | Some l -> l + | None -> 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 _ -> (prog, rctx, loader) + +let compile_wasm ?loader src : Wasm.wasm_module = + let (prog, _, loader) = frontend ?loader src in + 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 "wasm codegen: %s" (Codegen.show_codegen_error e) + +let compile_bun src : (string, string) result = + let (prog, rctx, _) = frontend src in + Codegen_deno.codegen_bun prog rctx.symbols + +let bun_available = lazy (Sys.command "bun --version > /dev/null 2>&1" = 0) + +let skip backend what = + Printf.printf "SKIP [%s] %s: bun not installed\n%!" backend what + +(* Run [cmd file], returning its combined output lines and exit status. *) +let run_file ~suffix ~write cmd : string list * Unix.process_status = + let file = Filename.temp_file "intrinsic_shadow" suffix in + write file; + let ic = Unix.open_process_in (cmd ^ " " ^ 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 run_wasm (m : Wasm.wasm_module) = + run_file ~suffix:".wasm" "bun run" + ~write:(fun f -> Wasm_encode.write_module_to_file f m) + +let run_bun (js : string) = + run_file ~suffix:".bun.js" "bun" + ~write:(fun f -> let oc = open_out_bin f in output_string oc js; close_out oc) + +let interp_probe src : string = + let (prog, _, _) = frontend src in + match Interp.eval_program prog with + | Error e -> Alcotest.failf "interp: %s" (Value.show_eval_error e) + | Ok env -> + match Value.lookup_env "probe" env with + | Error _ -> Alcotest.fail "interp: no `probe`" + | Ok f -> + match Interp.apply_function f [] with + | Ok (Value.VInt n) -> string_of_int n + | Ok (Value.VString s) -> s + | Ok _ -> Alcotest.fail "interp: `probe` returned neither Int nor String" + | Error e -> Alcotest.failf "interp: %s" (Value.show_eval_error e) + +(* ---- the shadowing cases ---------------------------------------------- *) + +type cls = Pure | Wasi + +(* How `main` reports `probe()`. [Println_int] is the ordinary route; a case + that shadows `println` or `print` itself reports through `file_fd_write` + (core wasm only: the interpreter does not bind it, and Bun-ESM refuses a + user `print`/`println` loudly, #801). *) +type report = Println_int | Println_str | Fd_write_int + +type case = { + cls : cls; + name : string; (* the intrinsic's spelling *) + label : string; + decl : string; (* the program's own definition of [name] *) + call : string; (* a call of it, as an expression *) + ret : string; (* `probe`'s return type *) + expect : string; (* what the program's own function returns *) + report : report; + bun_refuses : bool; (* Bun-ESM refuses the program at compile time (#801) *) +} + +let int_case ?(report = Println_int) ?(bun_refuses = false) ?label cls name + params args = + { cls; name; label = Option.value label ~default:name; + decl = Printf.sprintf "fn %s(%s) -> Int { 7 }" name params; + call = Printf.sprintf "%s(%s)" name args; + ret = "Int"; expect = "7"; report; bun_refuses } + +let cases = [ + (* (a) pure language intrinsics *) + int_case Pure "print" "x: Int" "1" ~report:Fd_write_int ~bun_refuses:true; + int_case Pure "println" "" "" ~label:"println/0" + ~report:Fd_write_int ~bun_refuses:true; + int_case Pure "println" "s: String" {|"hijacked"|} ~label:"println/1" + ~report:Fd_write_int ~bun_refuses:true; + int_case Pure "string_length" "s: String" {|"abc"|}; + int_case Pure "len" "s: String" {|"abc"|}; + int_case Pure "string_char_code_at" "s: String, i: Int" {|"abc", 0|}; + int_case Pure "char_to_int" "c: Char" "'a'"; + int_case Pure "string_from_char_code" "n: Int" "65"; + int_case Pure "string_slice" "s: String, a: Int, b: Int" {|"abc", 0, 1|}; + int_case Pure "string_sub" "s: String, a: Int, b: Int" {|"abc", 0, 1|}; + int_case Pure "to_lowercase" "s: String" {|"ABC"|}; + int_case Pure "to_uppercase" "s: String" {|"abc"|}; + int_case Pure "trim" "s: String" {|" a "|}; + int_case Pure "string_find" "a: String, b: String" {|"abc", "b"|}; + { cls = Pure; name = "int_to_string"; label = "int_to_string"; + decl = {|fn int_to_string(n: Int) -> String { "seven" }|}; + call = "int_to_string(1)"; ret = "String"; expect = "seven"; + report = Println_str; bun_refuses = false }; + int_case Pure "float_to_string" "x: Float" "1.5"; + (* (b) WASI lowerings *) + int_case Wasi "clock_now_ms" "c: Int" "1"; + int_case Wasi "net_shutdown" "a: Int, b: Int" "1, 2"; + int_case Wasi "file_open" "a: String, b: Int" {|"p", 2|}; + int_case Wasi "file_fd_write" "a: Int, b: String" {|1, "d"|}; + int_case Wasi "file_read" "a: Int, b: Int" "1, 2"; + int_case Wasi "file_close" "a: Int" "1"; + int_case Wasi "net_recv" "a: Int, b: Int" "1, 2"; + int_case Wasi "net_send" "a: Int, b: String" {|1, "d"|}; + int_case Wasi "net_accept" "a: Int" "1"; + int_case Wasi "env_count" "a: Int" "1"; + int_case Wasi "arg_count" "a: Int" "1"; + int_case Wasi "env_at" "i: Int" "0"; + int_case Wasi "arg_at" "i: Int" "0"; +] + +let program (c : case) : string = + let report = match c.report with + | Println_int -> "println(int_to_string(probe()));" + | Println_str -> "println(probe());" + | Fd_write_int -> "file_fd_write(1, int_to_string(probe()));" + in + Printf.sprintf "%s\npub fn probe() -> %s { %s }\npub fn main() -> () { %s }\n" + c.decl c.ret c.call report + +(* Every name the wasm dispatch matches by spelling has a case here. The list + is read out of lib/codegen.ml's own arms, so an arm added without a case + fails this test. `__`-prefixed names cannot be written in source. *) +let intrinsic_arm_names () : string list = + let path = + List.find Sys.file_exists + [ "../lib/codegen.ml"; "lib/codegen.ml"; "../../lib/codegen.ml" ] in + let ic = open_in_bin path in + let src = really_input_string ic (in_channel_length ic) in + close_in ic; + let arm = Str.regexp {|^ | Some id, _ when|} in + let nm = Str.regexp {|id\.name = "\([a-z_]+\)"|} in + let rec arms pos acc = + match Str.search_forward arm src pos with + | exception Not_found -> List.rev acc + | start -> + let stop = Str.search_forward (Str.regexp_string "->") src start in + let head = String.sub src start (stop - start) in + let rec names p acc = + match Str.search_forward nm head p with + | exception Not_found -> acc + | _ -> names (Str.match_end ()) (Str.matched_group 1 head :: acc) + in + arms stop (names 0 acc) + in + List.sort_uniq compare (arms 0 []) + +let test_every_arm_has_a_case () = + let arms = intrinsic_arm_names () in + Alcotest.(check bool) "the arms were found" true (List.length arms >= 27); + let covered = List.sort_uniq compare (List.map (fun c -> c.name) cases) in + (* `string_slice` is no longer an arm (only `__builtin:string_slice` is), + but keeps its case: a program may define that name. *) + Alcotest.(check (list string)) "every name-matched arm has a shadowing case" + arms (List.filter (fun n -> n <> "string_slice") covered) + +let test_interp (c : case) () = + Alcotest.(check string) (c.label ^ " on the interpreter") c.expect + (interp_probe (program c)) + +let test_bun (c : case) () = + match compile_bun (program c) with + | Error e when c.bun_refuses -> + Alcotest.(check bool) (c.label ^ ": Bun-ESM refuses loudly (#801)") true + (Test_int_div_js.count_occurrences ~needle:"#801" e > 0) + | Error e -> Alcotest.failf "%s: Bun-ESM codegen: %s" c.label e + | Ok _ when c.bun_refuses -> + Alcotest.failf "%s: Bun-ESM now compiles a user `%s`; run it here and \ + expect %s" c.label c.name c.expect + | Ok js -> + if not (Lazy.force bun_available) then skip "bun-esm" c.label + else begin + let lines, st = run_bun js in + Alcotest.(check (list string)) (c.label ^ " on Bun-ESM") [ c.expect ] lines; + Alcotest.(check bool) (c.label ^ ": exit 0") true (st = Unix.WEXITED 0) + end + +let test_wasm (c : case) () = + let m = compile_wasm (program c) in + if not (Lazy.force bun_available) then skip "wasm" c.label + else begin + let lines, st = run_wasm m in + Alcotest.(check (list string)) (c.label ^ " on core wasm") [ c.expect ] lines; + Alcotest.(check bool) (c.label ^ ": exit 0") true (st = Unix.WEXITED 0) + end + +(* ---- wasm structure helpers ------------------------------------------- *) + +let func_imports (m : Wasm.wasm_module) : (string * string) list = + List.filter_map (fun (i : Wasm.import) -> + match i.i_desc with + | Wasm.ImportFunc _ -> Some (i.i_module, i.i_name) + | _ -> None) m.imports + +let import_index m key : int option = + let rec go k = function + | [] -> None + | x :: _ when x = key -> Some k + | _ :: r -> go (k + 1) r + in + go 0 (func_imports m) + +let calls (m : Wasm.wasm_module) (idx : int) : bool = + let rec has = function + | Wasm.Call k -> k = idx + | Wasm.Block (_, b) | Wasm.Loop (_, b) -> List.exists has b + | Wasm.If (_, a, b) -> List.exists has a || List.exists has b + | _ -> false + in + List.exists (fun (f : Wasm.func) -> List.exists has f.f_body) m.funcs + +(* A program that defines a WASI-lowered name does not import the WASI + function it would otherwise have lowered to. *) +let test_wasm_no_unused_wasi_import () = + let m = compile_wasm + "fn clock_now_ms(c: Int) -> Int { 7 }\n\ + pub fn main() -> Int { clock_now_ms(1) }\n" in + Alcotest.(check bool) "no clock_time_get import" true + (import_index m ("wasi_snapshot_preview1", "clock_time_get") = None) + +(* ---- class (b): the lowerings still work ------------------------------- *) + +(* With no declaration in scope each WASI name still lowers to its import. *) +let test_wasi_lowering_kept () = + List.iter (fun (call, wasi) -> + let m = compile_wasm + (Printf.sprintf "pub fn main() -> () { let r = %s; }\n" call) in + match import_index m ("wasi_snapshot_preview1", wasi) with + | None -> Alcotest.failf "%s: no %s import" call wasi + | Some idx -> + Alcotest.(check bool) (call ^ " calls " ^ wasi) true (calls m idx)) + [ ("clock_now_ms(1)", "clock_time_get"); + ("net_shutdown(3, 2)", "sock_shutdown"); + ({|file_open("p", 0)|}, "path_open"); + ({|file_fd_write(1, "d")|}, "fd_write"); + ("file_read(3, 8)", "fd_read"); + ("file_close(3)", "fd_close"); + ("net_recv(3, 8)", "sock_recv"); + ({|net_send(3, "d")|}, "sock_send"); + ("net_accept(3)", "sock_accept"); + ("env_count(())", "environ_sizes_get"); + ("arg_count(())", "args_sizes_get"); + ("env_at(0)", "environ_get"); + ("arg_at(0)", "args_get") ] + +(* An `extern fn` of the name in scope is a declaration, not a definition: + the call keeps its lowering and never goes to the `env` import. This is + the case a guard on [func_indices] would break. *) +let test_extern_keeps_lowering () = + List.iter (fun (name, decl, call, wasi) -> + let m = compile_wasm + (Printf.sprintf "%s\npub fn main() -> () { let r = %s; }\n" decl call) in + (match import_index m ("env", name) with + | None -> Alcotest.failf "%s: the extern's own import is missing" name + | Some idx -> + Alcotest.(check bool) (name ^ ": the extern's `env` import is not called") + false (calls m idx)); + match wasi with + | None -> () + | Some w -> + (match import_index m ("wasi_snapshot_preview1", w) with + | None -> Alcotest.failf "%s: no %s import" name w + | Some idx -> + Alcotest.(check bool) (name ^ " still calls " ^ w) true (calls m idx))) + [ ("clock_now_ms", "extern fn clock_now_ms(c: Int) -> Int;", + "clock_now_ms(1)", Some "clock_time_get"); + ("file_close", "extern fn file_close(fd: Int) -> Int;", + "file_close(3)", Some "fd_close"); + ("net_accept", "extern fn net_accept(fd: Int) -> Int;", + "net_accept(3)", Some "sock_accept"); + ("arg_at", "extern fn arg_at(i: Int) -> String;", + "arg_at(0)", Some "args_get"); + (* declared `extern fn` in stdlib/effects.affine *) + ("string_length", "extern fn string_length(s: String) -> Int;", + {|string_length("abcd")|}, None); + ("int_to_string", "extern fn int_to_string(n: Int) -> String;", + "int_to_string(4)", None) ] + +(* The lowerings run: Bun's WASI serves the clock, argv, environ and stdout. *) +let test_wasi_lowering_runs () = + let src = {|pub fn main() -> () { + if clock_now_ms(1) >= 0 { println("clock"); } else { println("FAIL clock"); } + if arg_count(()) >= 0 { println("args"); } else { println("FAIL args"); } + if env_count(()) >= 0 { println("env"); } else { println("FAIL env"); } + if file_fd_write(1, "fd_write") == 0 { println(""); } else { println("FAIL fd_write"); } + println(int_to_string(string_length(trim(" abcd ")))); +} +|} in + let m = compile_wasm src in + if not (Lazy.force bun_available) then skip "wasm" "WASI lowerings run" + else begin + let lines, st = run_wasm m in + Alcotest.(check (list string)) "unshadowed intrinsics still lower" + [ "clock"; "args"; "env"; "fd_write"; "4" ] lines; + Alcotest.(check bool) "exit 0" true (st = Unix.WEXITED 0) + end + +(* ---- neighbours of the fix --------------------------------------------- *) + +(* `show` on Int and `slice` on a String are elaborated to intrinsic calls. + A program's own `int_to_string` / `string_slice` must not capture them. *) +let hygiene_src = {|fn int_to_string(n: Int) -> String { "seven" } +fn string_slice(s: String, a: Int, b: Int) -> String { "mine" } +pub fn main() -> () { + println(show(5)); + println(slice("hello", 1, 3)); + println(int_to_string(5)); + println(string_slice("hello", 1, 3)); +} +|} + +let test_elaborated_calls_not_captured () = + let m = compile_wasm hygiene_src in + if not (Lazy.force bun_available) then skip "wasm" "show/slice hygiene" + else begin + let lines, st = run_wasm m in + Alcotest.(check (list string)) "show/slice keep their meaning" + [ "5"; "el"; "seven"; "mine" ] lines; + Alcotest.(check bool) "exit 0" true (st = Unix.WEXITED 0) + end + +(* A local (let-bound closure, parameter) named like an intrinsic is called. *) +let local_src = {|fn call(trim: fn(String) -> Int) -> Int { trim(" a ") } +pub fn main() -> () { + let string_sub = |s: String, a: Int, b: Int| 9; + println(int_to_string(string_sub("x", 0, 1))); + println(int_to_string(call(|s| 8))); +} +|} + +let test_local_shadows_intrinsic () = + let m = compile_wasm local_src in + if not (Lazy.force bun_available) then skip "wasm" "local shadows intrinsic" + else begin + let lines, st = run_wasm m in + Alcotest.(check (list string)) "a local named like an intrinsic is called" + [ "9"; "8" ] lines; + Alcotest.(check bool) "exit 0" true (st = Unix.WEXITED 0) + end + +(* A function with a body imported from another module is the program's own + too: the call goes to the module import, not to the intrinsic. *) +let test_imported_definition_wins () = + let dir = Filename.concat (Filename.get_temp_dir_name ()) + (Printf.sprintf "as_intrinsic_shadow_%d" (Unix.getpid ())) in + (try Unix.mkdir dir 0o755 with Unix.Unix_error (Unix.EEXIST, _, _) -> ()); + let file = Filename.concat dir "ShadowLib.affine" in + let oc = open_out file in + output_string oc "module ShadowLib;\npub fn trim(s: String) -> Int { 7 }\n"; + close_out oc; + let cfg = Module_loader.default_config () in + let loader = Module_loader.create + { cfg with search_paths = dir :: cfg.search_paths } in + let m = compile_wasm ~loader + "use ShadowLib::{trim};\npub fn main() -> Int { trim(\" a \") }\n" in + (try Sys.remove file; Unix.rmdir dir with Sys_error _ | Unix.Unix_error _ -> ()); + match import_index m ("ShadowLib", "trim") with + | None -> Alcotest.fail "no ShadowLib.trim import" + | Some idx -> + Alcotest.(check bool) "main calls the imported trim" true (calls m idx) + +let tests = + let per backend f = + List.map (fun c -> + Alcotest.test_case (Printf.sprintf "user `%s` wins (%s)" c.label backend) + `Quick (f c)) + cases + in + [ Alcotest.test_case "every name-matched arm has a case" `Quick + test_every_arm_has_a_case ] + @ per "interp" test_interp + @ per "bun-esm" test_bun + @ per "wasm" test_wasm + @ [ + Alcotest.test_case "no WASI import for a user-defined name" `Quick + test_wasm_no_unused_wasi_import; + Alcotest.test_case "class (b): WASI names still lower" `Quick + test_wasi_lowering_kept; + Alcotest.test_case "class (b): an extern in scope keeps the lowering" `Quick + test_extern_keeps_lowering; + Alcotest.test_case "class (b): the lowerings run (bun)" `Quick + test_wasi_lowering_runs; + Alcotest.test_case "show/slice are not captured by user fns (bun)" `Quick + test_elaborated_calls_not_captured; + Alcotest.test_case "a local shadows an intrinsic (bun)" `Quick + test_local_shadows_intrinsic; + Alcotest.test_case "an imported definition wins" `Quick + test_imported_definition_wins; + ] diff --git a/test/test_main.ml b/test/test_main.ml index b4890b12..57a3f78b 100644 --- a/test/test_main.ml +++ b/test/test_main.ml @@ -39,6 +39,7 @@ let () = ("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); + ("User fn named like an intrinsic (#836)", Test_intrinsic_shadow.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); diff --git a/tools/soundness-anchors.sha256 b/tools/soundness-anchors.sha256 index 9146785c..20d9be29 100644 --- a/tools/soundness-anchors.sha256 +++ b/tools/soundness-anchors.sha256 @@ -7,6 +7,7 @@ 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 +3b74c20f201d0d53c2fbab5582a681d3dfc3cf978a0aea676ecc6400087452d9 suite:test/test_intrinsic_shadow.ml 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