diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc index 1ed0e807..75cd0e3c 100644 --- a/CHANGELOG.adoc +++ b/CHANGELOG.adoc @@ -137,6 +137,13 @@ pure-extern semantics (Closes #332) (#338) ==== Fixed +* WASM: a write to a `mut` parameter now reaches the caller. Each `mut` +parameter is copied out to a write-back global on every return path, and the +caller stores it into the argument variable; before, the caller kept its old +value. Arguments that cannot be written back (a field, element or +dereference), `&mut` expressions, and `mut` parameters on imported functions +or closures fail with a named error. Bun-ESM fails loudly on `&mut` and on a +call to a function that reassigns a `mut` parameter (Closes #848) * Lexer: token spans start at the token, not at the token before it. The start was read before whitespace and comments were skipped, so every parse error, hover and goto-definition position was one token early (a parse diff --git a/docs/SOUNDNESS.adoc b/docs/SOUNDNESS.adoc index e8e4c10a..a560f277 100644 --- a/docs/SOUNDNESS.adoc +++ b/docs/SOUNDNESS.adoc @@ -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: 220d6f1 -:ground-truth-date: 2026-12-01 +:ground-truth-sha: 28d949f +:ground-truth-date: 2026-12-05 :stamp-verified-by: tools/check-soundness-ledger.sh :toc: macro :toclevels: 2 @@ -292,6 +292,22 @@ 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) +| #848 +| A write to a `mut` parameter reaches the caller, or the program is refused by +name; it is never silently lost. Core wasm lowered the parameter as a copy, so +`fn set(mut m: Int) { m = 100 }` left the caller's `x` at 5 (interp: 100). +Core wasm now writes through: each `mut` parameter has a write-back global that +the callee stores on every return path and the direct caller copies into the +argument variable. A field, element or dereference argument, an imported or +closure `mut` parameter, and any `&mut` expression fail loud +(`UnsupportedFeature`). Bun-ESM cannot write a JS parameter back, so a program +that calls a function reassigning a `mut` parameter, or uses `&mut`, fails loud; +only defining one, as `stdlib/option.affine`'s `take` does, still compiles. +Other text backends are not yet covered (ADR-028's every-backend gate). +| `fixed` (core wasm); `loud-fail` (Bun-ESM) +| `test/test_mut_param_848.ml`; `tests/codegen/mut_param_writeback.affine` +(+ `test_mut_param_writeback.mjs`: `early()` is 5 on `28d949f`, 100 now) + | #830 | Core-wasm heap allocations can no longer overwrite string literals. The heap-pointer global used to start at a fixed 1024 while literals were laid diff --git a/lib/codegen.ml b/lib/codegen.ml index 4fdb16cb..1e6ad32c 100644 --- a/lib/codegen.ml +++ b/lib/codegen.ml @@ -96,6 +96,14 @@ type context = { `mut`). The global is declared zero-initialised and mutable, and a start function runs each init in declaration order at instantiation. Most recent first. *) + mut_outs : (string * (int * int) list) list; + (** #848: a function with `mut` parameters (a mutable borrow of the + caller's place) -> [(parameter position, global index)]. The callee + stores each such parameter's final value in its global at every exit, + and a direct caller copies it back into the place it passed. *) + mut_param_imports : string list; + (** #848: imported functions with a `mut` parameter. Their write-back + global lives in the other module, so a call cannot copy it back. *) } (** Code generation error *) @@ -337,6 +345,8 @@ let create_context () : context = { ownership_annots = []; wasi_func_indices = []; global_inits = []; + mut_outs = []; + mut_param_imports = []; } (** Extract ownership kind from a parameter declaration. @@ -1153,7 +1163,19 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = | ExprUnary (op, operand) -> begin match op with - | OpRef | OpMutRef -> + | OpMutRef -> + (* #848: `&mut e` was lowered like `&e`, as a fresh heap cell holding + a copy of the value, so a write through the reference + (`*r = v`) never reached the original place and the program + silently kept the old value. There is no write-through lowering + yet, and ADR-028 recommends withdrawing reference expressions for + v1, so refuse it by name, as #555 does for handlers. *) + Error (UnsupportedFeature + "`&mut` reference expressions are not supported on the core-WASM \ + backend: a write through the reference would not reach the \ + borrowed place (#848). Use a `mut` parameter instead \ + (`fn f(mut x: T)`), or run with `--interp` / `-i`.") + | OpRef -> (* Take reference: &expr / &mut expr — same pointer representation; exclusivity is a static borrow property (CORE-01 pt2 / #177). *) (* Allocate heap memory, store the value, return pointer *) @@ -1269,6 +1291,16 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = interpreter (-i) or the Julia backend (-julia).") else Ok () in + (* #848: a closure is called indirectly, so a write to a `mut` + parameter could not be copied back to the caller's place. *) + let* () = + if List.exists (fun (p : param) -> p.p_ownership = Some Mut) lam.elam_params + then Error (UnsupportedFeature + "a closure with a `mut` parameter is not supported on the core-WASM \ + backend: it is called indirectly, so its write to the argument \ + would not reach the caller (#848). Use a named `fn`.") + else Ok () + in let lambda_id = ctx.next_lambda_id in @@ -2426,10 +2458,64 @@ let rec gen_expr (ctx : context) (expr : expr) : (context * instr list) result = (Printf.sprintf "calling the top-level constant `%s` is not \ supported on the core-WASM backend; declare it \ as a `fn` instead (#561)" id.name)) + | Some _ when List.mem id.name ctx_after_args.mut_param_imports -> + Error (UnsupportedFeature + (Printf.sprintf + "`%s` is imported from another module and has a `mut` \ + parameter; on the core-WASM backend its write to the \ + caller's argument cannot be copied back across the module \ + boundary (#848). Define it in this module, or run with \ + `--interp` / `-i`." id.name)) | Some func_idx -> (* Direct function call *) let call_instr = Call func_idx in - Ok (ctx_after_args, all_arg_code @ [call_instr]) + (* #848: copy each `mut` argument's final value back from the + callee's write-back global into the place the caller passed. + [global.get]/[local.set] are stack-neutral, so the call's + result stays on top. *) + let* writeback = + match List.assoc_opt id.name ctx_after_args.mut_outs with + | None -> Ok [] + | Some outs -> + List.fold_left (fun acc (pos, gidx) -> + let* code = acc in + match List.nth_opt args pos with + | Some (ExprVar v) -> + begin match lookup_local ctx_after_args v.name with + | Ok lidx -> Ok (code @ [GlobalGet gidx; LocalSet lidx]) + | Error _ -> + begin match List.assoc_opt v.name ctx_after_args.func_indices with + | Some k when k < 0 + && (List.nth ctx_after_args.globals (-(k + 1))).g_mutable + && not (List.exists (fun (g, _, _, m) -> + g = -(k + 1) && not m) + ctx_after_args.global_inits) -> + Ok (code @ [GlobalGet gidx; GlobalSet (-(k + 1))]) + | _ -> + Error (UnsupportedFeature + (Printf.sprintf + "argument %d of `%s` is a `mut` parameter, but \ + `%s` is not a mutable variable this function \ + can write back to (#848)" (pos + 1) id.name v.name)) + end + end + | Some (ExprField _ | ExprIndex _ | ExprTupleIndex _ + | ExprUnary (OpDeref, _)) -> + Error (UnsupportedFeature + (Printf.sprintf + "argument %d of `%s` is a `mut` parameter; on the \ + core-WASM backend only a variable can be passed \ + there, not a field, element or dereference: the \ + callee's write would not reach it (#848). Bind it to \ + a `let mut` first and assign it back." + (pos + 1) id.name)) + | _ -> + (* A temporary (literal, call, arithmetic): nothing in the + caller can observe the write. *) + Ok code + ) (Ok []) outs + in + Ok (ctx_after_args, all_arg_code @ [call_instr] @ writeback) | None -> (* Check if it's a local variable (could be a closure) *) begin match lookup_local ctx_after_args id.name with @@ -4067,6 +4153,27 @@ let gen_function (ctx : context) (fd : fn_decl) : (context * func) result = | None -> gen_expr_laid ctx_with_params ctx_with_params.ret_layout body_expr in + (* #848: a `mut` parameter is a mutable borrow of the caller's place. The + body works on the parameter's local; at every exit (each `return` and + the fall-through end) store its final value in the parameter's + write-back global, which a direct caller copies back after the call. + [local.get]/[global.set] are stack-neutral, so the result being + returned is untouched. *) + let body_code = + match List.assoc_opt fd.fd_name.name ctx.mut_outs with + | None | Some [] -> body_code + | Some outs -> + let wb = List.concat_map (fun (pos, gidx) -> [LocalGet pos; GlobalSet gidx]) outs in + let rec add_wb = function + | Return -> wb @ [Return] + | Block (bt, b) -> [Block (bt, List.concat_map add_wb b)] + | Loop (bt, b) -> [Loop (bt, List.concat_map add_wb b)] + | If (bt, t, e) -> [If (bt, List.concat_map add_wb t, List.concat_map add_wb e)] + | i -> [i] + in + List.concat_map add_wb body_code @ wb + in + (* Compute additional locals (beyond parameters) *) let local_count = ctx_final.next_local - param_count in (* Float wall: declare each non-param local with its tracked value type @@ -4455,6 +4562,9 @@ let gen_imports ?(used : (string, unit) Hashtbl.t option) 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); + mut_param_imports = + (if List.exists (fun (p : param) -> p.p_ownership = Some Mut) fd.fd_params + then local_name :: ctx.mut_param_imports else ctx.mut_param_imports); (* The alias carries the result type, so `let r = M.f()` declares r f64 when f returns Float. *) fn_ret_types = (local_name, @@ -4762,9 +4872,27 @@ let generate_module ?loader (prog : program) : wasm_module result = (td_name.name, List.mapi (fun i rf -> (rf.rf_name.name, i * 4)) rfs) :: c.struct_layouts } | TopFn fd -> - { c with fn_param_structs = + let c = { c with fn_param_structs = (fd.fd_name.name, List.map (fun p -> struct_name_of_ty p.p_ty) fd.fd_params) - :: c.fn_param_structs } + :: c.fn_param_structs } in + (* #848: one write-back global per `mut` parameter of a defined + function, registered up front so a call that precedes the callee's + declaration still copies the value back. *) + if fd.fd_body = FnExtern then c + else + let (c, outs) = List.fold_left (fun (c, outs) (pos, (p : param)) -> + if p.p_ownership <> Some Mut then (c, outs) + else + let vt = match type_to_wasm p.p_ty with Ok t -> t | Error _ -> I32 in + let init = match vt with + | F64 -> [F64Const 0.0] | F32 -> [F32Const 0.0] + | I64 -> [I64Const 0L] | _ -> [I32Const 0l] in + let gidx = List.length c.globals in + ({ c with globals = c.globals @ [{ g_type = vt; g_mutable = true; g_init = init }] }, + outs @ [(pos, gidx)]) + ) (c, []) (List.mapi (fun i p -> (i, p)) fd.fd_params) in + if outs = [] then c + else { c with mut_outs = (fd.fd_name.name, outs) :: c.mut_outs } | _ -> c) ctx_with_imports prog.prog_decls in (* Host imports must occupy the low function indices before any defined diff --git a/lib/codegen_deno.ml b/lib/codegen_deno.ml index cac8adb4..83e1335a 100644 --- a/lib/codegen_deno.ml +++ b/lib/codegen_deno.ml @@ -95,6 +95,16 @@ type codegen_ctx = { integer operand, so divisions over them truncate (#478). Reset per function alongside {!int_vars}. *) int_array_vars : (string, unit) Hashtbl.t; + (* The current function and its `mut`-mode parameters (#848). A JS + parameter is a copy, so a callee that reassigns one loses the write the + caller is owed. {!gen_stmt} records such callees in [mut_reassigners]; + {!gen_expr} records every called name in [called]. A callee that is in + both fails {!generate} loudly. Defining such a function stays legal + (stdlib/option.affine's [take] is one); only calling it is fenced. *) + cur_fn : string; + mut_params : string list; + mut_reassigners : (string, string) Hashtbl.t; + called : (string, unit) Hashtbl.t; (* Value names bound locally at the current emission point: parameters, `let`, `for`, lambda and match-arm binders. A local shadows a host intrinsic of the same name, so `fn f(get: ...) { get(x) }` calls the @@ -150,6 +160,10 @@ let create_ctx host symbols = { ctors = Hashtbl.create 32; int_vars = Hashtbl.create 16; int_array_vars = Hashtbl.create 16; + cur_fn = ""; + mut_params = []; + mut_reassigners = Hashtbl.create 8; + called = Hashtbl.create 64; locals = Hashtbl.create 16; int_callables = Hashtbl.create 8; block_decls = Hashtbl.create 8; @@ -1763,6 +1777,11 @@ let enter_fn_scope ctx (params : param list) : codegen_ctx = if type_returns_int p.p_ty then Hashtbl.replace int_callables p.p_name.name ()) params; { ctx with int_vars = tbl; int_array_vars = arr_tbl; locals; int_callables; + mut_params = + List.filter_map + (fun (p : param) -> + if p.p_ownership = Some Mut then Some p.p_name.name else None) + params; block_decls = Hashtbl.create 8; renames = Hashtbl.create 8 } (* Run [f] with [names] bound as locals, then restore the previous bindings, @@ -1919,6 +1938,9 @@ let rec gen_expr ctx (expr : expr) : string = | _ -> resolve_var ctx id.name) | ExprVar name -> resolve_var ctx name.name | ExprApp (func, args) -> + (match unspan func with + | ExprVar id -> Hashtbl.replace ctx.called id.name () + | _ -> ()); (match func with | ExprVar id when Hashtbl.mem ctx.assoc id.name && args <> [] -> (* Receiver-first associated call -> method call. *) @@ -1993,6 +2015,12 @@ let rec gen_expr ctx (expr : expr) : string = | OpNot -> "(!" ^ gen_expr ctx e ^ ")" | OpBitNot -> "(~" ^ gen_expr ctx e ^ ")" | OpRef -> "({ get: () => " ^ gen_expr ctx e ^ ", set: (_) => {} })" + | OpMutRef -> + failwith + "`&mut` reference expressions are not supported on the Bun-ESM \ + backend: a write through the reference would not reach the borrowed \ + place (#848). Use a `mut` parameter on WebAssembly, or run with \ + `--interp` / `-i`." | OpDeref -> "(" ^ gen_expr ctx e ^ ".get())") | ExprIf { ei_cond; ei_then; ei_else } -> let else_str = match ei_else with @@ -2589,6 +2617,12 @@ and gen_stmt ctx (stmt : stmt) : string = js | StmtExpr e -> gen_stmt_expr ctx e | StmtAssign (lhs, op, rhs) -> + (match unspan lhs with + | ExprVar id + when List.mem id.name ctx.mut_params + && not (Hashtbl.mem ctx.mut_reassigners ctx.cur_fn) -> + Hashtbl.replace ctx.mut_reassigners ctx.cur_fn id.name + | _ -> ()); (* #478: `x /= y` over integers must truncate, like `x = x / y`. *) let div_int = op = AssignDiv && expr_is_int ctx lhs && expr_is_int ctx rhs in @@ -2697,7 +2731,8 @@ let gen_function ctx (fd : fn_decl) : unit = else async_kw ^ "function" in emit_line ctx (Printf.sprintf "%s %s(%s) {" kw name (String.concat ", " params)); - let body_ctx = enter_fn_scope (increase_indent ctx) fd.fd_params in + let body_ctx = + { (enter_fn_scope (increase_indent ctx) fd.fd_params) with cur_fn = fd.fd_name.name } in let body_ctx = if is_async then { body_ctx with in_async = true } else body_ctx in gen_body body_ctx fd.fd_body; @@ -2766,7 +2801,9 @@ let gen_method ctx ~(recv_name : string) ~(js_name : string) emit_line ctx_m (Printf.sprintf "async %s(%s) {" (mangle js_name) (String.concat ", " params)); - gen_body (enter_fn_scope (increase_indent ctx_m) fd.fd_params) fd.fd_body; + gen_body + { (enter_fn_scope (increase_indent ctx_m) fd.fd_params) with cur_fn = fd.fd_name.name } + fd.fd_body; emit_line ctx_m "}"; emit ctx_m "" @@ -2777,7 +2814,8 @@ let gen_constructor ctx (fd : fn_decl) : unit = List.map (fun (p : param) -> mangle p.p_name.name) fd.fd_params in emit_line ctx (Printf.sprintf "constructor(%s) {" (String.concat ", " params)); - let body_ctx = enter_fn_scope (increase_indent ctx) fd.fd_params in + let body_ctx = + { (enter_fn_scope (increase_indent ctx) fd.fd_params) with cur_fn = fd.fd_name.name } in let rec assign_record e = match e with | ExprSpan (inner, _) -> assign_record inner @@ -3163,6 +3201,19 @@ let generate (host : host_profile) (program : program) (symbols : Symbol.t) : st | TopFn fd -> fd.fd_name.name = "main" | _ -> false) program.prog_decls in if has_main then emit_line ctx "await main();"; + (* #848: a call to a function that reassigns a `mut` parameter would + silently lose the write on return; refuse the program by name. *) + Hashtbl.iter + (fun fn param -> + if Hashtbl.mem ctx.called fn then + failwith + (Printf.sprintf + "`%s` assigns to its `mut` parameter `%s`, and the program calls it; \ + the Bun-ESM backend cannot write that back to the caller (a JS \ + parameter is a copy), so the write would be lost (#848). Compile \ + to WebAssembly (`.wasm`), or run with `--interp` / `-i`." + fn param)) + ctx.mut_reassigners; let all = Buffer.contents ctx.output in let header = String.sub all 0 runtime_at in let body = String.sub all runtime_at (String.length all - runtime_at) in diff --git a/test/test_main.ml b/test/test_main.ml index 3d171f99..d0e48521 100644 --- a/test/test_main.ml +++ b/test/test_main.ml @@ -41,6 +41,7 @@ let () = ("Bun-ESM let rebinding (#827)", Test_let_rebind_bun.tests); ("Deno builtins ↔ stdlib decls consistency", Test_deno_builtins_consistency.tests); ("Bun integer block scope", Test_int_scope_bun.tests); + ("mut parameter write-through or loud failure (#848)", Test_mut_param_848.tests); ("Unicode strings / UTF-8 octets, cross-backend", Test_unicode_octets.tests); ("Same cube: faces compile alike (#601)", Test_same_cube.tests); ("float_to_string format (#643)", Test_float_format.tests); diff --git a/test/test_mut_param_848.ml b/test/test_mut_param_848.ml new file mode 100644 index 00000000..a6b9e019 --- /dev/null +++ b/test/test_mut_param_848.ml @@ -0,0 +1,93 @@ +(* SPDX-License-Identifier: MPL-2.0 *) +(* SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) *) + +(** #848: a write through a [mut] parameter must reach the caller, or the + backend must refuse the program by name (ADR-028's gate). It must never + compile and quietly lose the write. + + Core-WASM writes through: the callee copies each [mut] parameter out to a + write-back global on every return, and the caller stores it back into the + argument variable. tests/codegen/mut_param_writeback.affine checks the + values at runtime. This file pins the shapes that fail loudly: + - on WASM, an [&mut] expression and a non-variable [mut] argument; + - on Bun-ESM, an [&mut] expression and any reassignment of a [mut] + parameter. *) + +open Affinescript + +let frontend src = + let prog = Parse_driver.parse_string ~file:"<848>" 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 (ctx, _) -> + (match Typecheck.check_program ctx.symbols prog with + | Error e -> Alcotest.failf "typecheck: %s" (Typecheck.format_type_error e) + | Ok _ -> (prog, ctx)) + +let wasm src = + let prog, _ = frontend src in + match Codegen.generate_module (Opt.fold_constants_program prog) with + | Ok _ -> Ok () + | Error e -> Error (Codegen.show_codegen_error e) + +let bun src = + let prog, ctx = frontend src in + match Codegen_deno.codegen_bun prog ctx.symbols with + | Ok js -> Ok js + | Error e -> Error e + +let contains hay needle = + let n = String.length needle and h = String.length hay in + let rec go i = i + n <= h && (String.sub hay i n = needle || go (i + 1)) in + go 0 + +let expect_named what needle = function + | Ok _ -> Alcotest.failf "%s: compiled, but the write would be lost" what + | Error msg when contains msg needle && contains msg "#848" -> () + | Error msg -> Alcotest.failf "%s: expected a #848 error naming %S, got: %s" what needle msg + +let set_src = + "fn set(mut m: Int) -> Int { m = 100; return 0; }\n\ + pub fn main() -> Int { let mut x = 5; let _z = set(x); x }\n" + +let mut_ref_src = + "pub fn main() -> Int { let mut x = 5; let r = &mut x; *r = 100; x }\n" + +let tests = [ + Alcotest.test_case "wasm: mut param write-through compiles" `Quick (fun () -> + match wasm set_src with + | Ok () -> () + | Error e -> Alcotest.failf "should compile: %s" e); + Alcotest.test_case "wasm: &mut expression is a named error" `Quick (fun () -> + expect_named "&mut on wasm" "&mut" (wasm mut_ref_src)); + Alcotest.test_case "wasm: a tuple element as a mut argument is a named error" `Quick + (fun () -> + expect_named "element argument" "only a variable" + (wasm + "fn set(mut m: Int) -> Int { m = 1; 0 }\n\ + pub fn main() -> Int { let t = (5, 6); let _z = set(t.0); 0 }\n")); + Alcotest.test_case "bun: reassigning a mut param is a named error" `Quick (fun () -> + expect_named "mut param on bun" "`mut` parameter `m`" (bun set_src)); + Alcotest.test_case "bun: compound assignment to a mut param is a named error" `Quick + (fun () -> + expect_named "m += on bun" "`mut` parameter `m`" + (bun "fn bump(mut m: Int) -> Int { m += 1; m }\n\ + pub fn main() -> Int { let mut x = 5; bump(x) }\n")); + (* stdlib/option.affine defines `take(mut opt)`; a program that never + calls such a function must still compile, or the whole module would be + unusable on Bun. *) + Alcotest.test_case "bun: defining an uncalled mut-reassigning fn compiles" `Quick + (fun () -> + match bun "fn set(mut m: Int) -> Int { m = 100; 0 }\n\ + pub fn main() -> Int { 7 }\n" with + | Ok _ -> () + | Error e -> Alcotest.failf "nothing is lost until it is called: %s" e); + Alcotest.test_case "bun: &mut expression is a named error" `Quick (fun () -> + expect_named "&mut on bun" "&mut" (bun mut_ref_src)); + Alcotest.test_case "bun: a mut param that is only read still compiles" `Quick (fun () -> + match bun "fn peek(mut m: Int) -> Int { m + 1 }\n\ + pub fn main() -> Int { let mut x = 5; peek(x) }\n" with + | Ok _ -> () + | Error e -> Alcotest.failf "a read-only mut param loses nothing: %s" e); +] diff --git a/tests/codegen/mut_param_writeback.affine b/tests/codegen/mut_param_writeback.affine new file mode 100644 index 00000000..46455aca --- /dev/null +++ b/tests/codegen/mut_param_writeback.affine @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MPL-2.0 +// #848: on core-WASM a write to a `mut` parameter reaches the caller's +// variable, on every return path. test_mut_param_writeback.mjs checks +// each export. + +fn set_to(mut m: Int, v: Int) -> Int { + m = v; + return 0; +} + +// A write before an explicit `return`. +pub fn early() -> Int { + let mut x = 5; + let _z = set_to(x, 100); + x +} + +fn bump(mut m: Int) -> Int { + m = m + 1; + m +} + +pub fn twice() -> Int { + let mut x = 5; + let y = bump(x); + let _w = bump(x); + x * 100 + y +} + +// The write must come back on the early `return` as well as at the end. +fn clamp(mut m: Int) -> Int { + if m > 10 { + m = 10; + return 1; + } + m = m * 2; + 0 +} + +pub fn clamp_high() -> Int { + let mut x = 50; + let r = clamp(x); + x * 10 + r +} + +pub fn clamp_low() -> Int { + let mut x = 3; + let r = clamp(x); + x * 10 + r +} + +fn halve(mut f: Float) -> Int { + f = f / 2.0; + 0 +} + +pub fn float_param() -> Float { + let mut g = 9.0; + let _z = halve(g); + g +} + +// Two `mut` params, each written back to its own argument. +fn swap(mut a: Int, mut b: Int) -> Int { + let t = a; + a = b; + b = t; + 0 +} + +pub fn swapped() -> Int { + let mut p = 1; + let mut q = 2; + let _z = swap(p, q); + p * 10 + q +} + +// An rvalue argument has nowhere to write back to; it must still run. +pub fn rvalue_arg() -> Int { + bump(41) +} diff --git a/tests/codegen/test_mut_param_writeback.mjs b/tests/codegen/test_mut_param_writeback.mjs new file mode 100644 index 00000000..43858cbf --- /dev/null +++ b/tests/codegen/test_mut_param_writeback.mjs @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: MPL-2.0 +// +// #848: a write to a `mut` parameter must reach the caller's variable on +// core-WASM. Before the fix every caller saw its old value (early() was 5). +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; + +const mod = await WebAssembly.compile( + await readFile('./tests/codegen/mut_param_writeback.wasm')); +const imports = {}; +for (const i of WebAssembly.Module.imports(mod)) { + if (i.kind !== 'function') continue; + imports[i.module] ??= {}; + imports[i.module][i.name] = () => 0; +} +const { exports: e } = await WebAssembly.instantiate(mod, imports); + +const want = { + early: 100, // write, then explicit `return` + twice: 706, // x: 5 -> 6 -> 7; y = 6 + clamp_high: 101, // write-back on the early `return` path + clamp_low: 60, // write-back at the fall-through end + float_param: 4.5, // an f64 write-back global + swapped: 21, // two `mut` params, each to its own argument + rvalue_arg: 42, // an rvalue argument: nothing to write back +}; +for (const [name, value] of Object.entries(want)) { + const got = e[name](); + assert.equal(got, value, `mut_param_writeback: ${name}()=${got}, want ${value}`); +} +console.log('test_mut_param_writeback.mjs OK'); diff --git a/tools/soundness-anchors.sha256 b/tools/soundness-anchors.sha256 index 8d9a6543..61926f70 100644 --- a/tools/soundness-anchors.sha256 +++ b/tools/soundness-anchors.sha256 @@ -10,6 +10,7 @@ 2bbd1b989fd0097530eede3e5230258e0e1092271a23ff7dff20cca65c0e612e suite:test/test_wasm_call_resolution.ml 2dfe36a21983a7dfb7ffa1157f7ddec9865a531a92682976b8fd677e4825e78d test:test_801_impl_methods_refused 45eb0f3aa5f643afbd003248998dd5a046688418647b491e0f2d4bb55fcbd0f2 test:test_wasm_heap_exhaustion_traps +49031b601e4e9f165b9539ce59be7aefe4917fb2317841c2678b5cfc0a2f23d6 suite:test/test_mut_param_848.ml 546939eaa3c64c82edd23da0a3ba7f74bcf7378cfe1e426132dd1a9f8fd46050 test:test_801_transitive_public_and_const 5b84a4f71aa65f9aa9383e31c0cb624291c4f9d0de7cca4a0ea6a76fe85aea35 fixture:test/e2e/fixtures/handle_resume_nontail.affine 61a824a9bbd1243c27aab2687e7ef0da1afdfd208cd26187908797f16adad163 test:test_wasm_heap_repro_runs