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
7 changes: 7 additions & 0 deletions CHANGELOG.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 18 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: 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
Expand Down Expand Up @@ -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
Expand Down
136 changes: 132 additions & 4 deletions lib/codegen.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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 *)
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 *)
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
57 changes: 54 additions & 3 deletions lib/codegen_deno.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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. *)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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 ""

Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions test/test_main.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading
Loading