diff --git a/.gitignore b/.gitignore index b89185b5..9924c052 100644 --- a/.gitignore +++ b/.gitignore @@ -104,6 +104,7 @@ bisect*.coverage # Issue #734: generated native Bun-ESM acceptance outputs. /tests/codegen-bun/*.bun.js /tests/codegen-bun/backend-conflict.json +/tests/codegen-bun/deno-removed.json # Local-only build workaround (see file header); never committed. /dune-workspace packages/affinescript-cli/deno.lock diff --git a/docs/SOUNDNESS.adoc b/docs/SOUNDNESS.adoc index 69cb0a4d..32644df0 100644 --- a/docs/SOUNDNESS.adoc +++ b/docs/SOUNDNESS.adoc @@ -229,6 +229,18 @@ backstop refuses a planted collision in the flattener and in both JS emitters); `tests/codegen-bun/same_name_modules` runs #801's reproduction under Bun. +| #827 +| Bun-ESM: a `let` that reads or shadows an enclosing name is emitted under +a fresh name. `const x = x + 1` in a nested block threw `ReferenceError`, and +a `let` rebinding a parameter was a `SyntaxError` that stopped the module +loading. A lambda parameter typed `fn(..) -> Int` is an Int callable, so +`len(s) / 2` truncates: a function declared `-> Int` returned `2.5`. +| `fixed` +| `test/test_let_rebind_bun.ml` (emitted JS) and `tests/codegen-bun/let_rebind` +(run under Bun): parameter, nested, +callable and mutable rebinds, destructuring, a lambda shadowing a renamed +binding, an Int-typed lambda parameter. + | #801 (impl methods) | Trait impl methods are emitted as free functions under their own names on Bun-ESM (trait dispatch is not lowered there), so `impl Eq for Int` and diff --git a/lib/codegen_deno.ml b/lib/codegen_deno.ml index 8d23be6c..024981e8 100644 --- a/lib/codegen_deno.ml +++ b/lib/codegen_deno.ml @@ -111,6 +111,13 @@ type codegen_ctx = { exit, an [Int] classification gained by an assignment to any other (enclosing) name is kept; see {!with_locals_scope}. *) block_decls : (string, unit) Hashtbl.t; + (* Source name -> emitted JS name, for a `let` binder emitted under a + fresh name (see {!let_renames}). Consulted by {!resolve_var}; scoped + like {!locals}. *) + renames : (string, string) Hashtbl.t; + (* Binder renames {!gen_pattern} applies to the pattern being declared + right now; empty otherwise. *) + pat_renames : (string, string) Hashtbl.t; (* True while emitting a synthesised `async` method body. The expression-position IIFE wrappers (block/try/match/let/return) must then be `async` and awaited, because they may contain an awaited @@ -146,6 +153,8 @@ let create_ctx host symbols = { locals = Hashtbl.create 16; int_callables = Hashtbl.create 8; block_decls = Hashtbl.create 8; + renames = Hashtbl.create 8; + pat_renames = Hashtbl.create 4; in_async = false; top_names = Hashtbl.create 128; public_ctors = Hashtbl.create 32; @@ -1455,7 +1464,10 @@ let claim_runtime ctx (js : string) : unit = let resolve_var ctx (name : string) : string = match ctx.self_name with | Some s when s = name -> "this" - | _ -> mangle name + | _ -> + (match Hashtbl.find_opt ctx.renames name with + | Some js -> js + | None -> mangle name) (* ============================================================================ Integer-operand inference for division (issue #478) @@ -1628,6 +1640,46 @@ let track_int_binding ctx (name : string) (value : expr) : unit = if expr_is_int ctx value then Hashtbl.replace ctx.int_vars name () else Hashtbl.remove ctx.int_vars name +(* Fresh temporaries and binder names (`$`-suffixed, so never a source + identifier) for `let` lowering. *) +let let_tmp_counter = ref 0 + +(* Does [js] contain [ident] as an identifier token (not a property after + `.`)? Over-approximates: a string literal or an object key also counts, + which only costs an unneeded rename. *) +let mentions_ident (js : string) (ident : string) : bool = + let n = String.length js and m = String.length ident in + let is_id c = + (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') + || c = '_' || c = '$' + in + let rec go i = + if i + m > n then false + else if String.sub js i m = ident + && (i = 0 || (not (is_id js.[i - 1]) && js.[i - 1] <> '.')) + && (i + m = n || not (is_id js.[i + m])) + then true + else go (i + 1) + in + m > 0 && go 0 + +(* The binders of a `let` that must be emitted under a fresh name. A JS + `const x` is in its temporal dead zone for its whole block, so + `const x = x + 1` throws when the initializer reads the outer `x`; + and `function f(x) { const x = ... }` is a SyntaxError. So a binder is + renamed when its initializer mentions the name, or when it shadows a + name already bound in this function. `$` cannot occur in a source + identifier, so a fresh name cannot collide with one. *) +let let_renames ctx (binders : string list) (init_js : string) : + (string * string) list = + List.filter_map + (fun n -> + if Hashtbl.mem ctx.locals n || mentions_ident init_js (mangle n) then begin + incr let_tmp_counter; + Some (n, Printf.sprintf "%s$%d" (mangle n) !let_tmp_counter) + end else None) + binders + (* Reset [int_vars] / [int_array_vars] for a new function body and seed them from [Int]- and [Array]-typed params. Returns [ctx] with the fresh tables installed. *) @@ -1648,7 +1700,7 @@ 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; - block_decls = Hashtbl.create 8 } + block_decls = Hashtbl.create 8; renames = Hashtbl.create 8 } (* Run [f] with [names] bound as locals, then restore the previous bindings, so a scoped binder (let body, lambda, match arm, loop) cannot shadow an @@ -1658,21 +1710,30 @@ let with_locals : 'a. codegen_ctx -> string list -> (unit -> 'a) -> 'a = let mem t n = Hashtbl.mem t n in let had = List.map - (fun n -> (n, mem ctx.locals n, mem ctx.int_vars n, mem ctx.int_callables n)) + (fun n -> + (n, mem ctx.locals n, mem ctx.int_vars n, mem ctx.int_callables n, + Hashtbl.find_opt ctx.renames n)) names in (* A binder of no declared callable type shadows any [Int]-returning callable of the same name. *) List.iter - (fun n -> Hashtbl.replace ctx.locals n (); Hashtbl.remove ctx.int_callables n) + (fun n -> + Hashtbl.replace ctx.locals n (); + Hashtbl.remove ctx.int_callables n; + (* The binder is emitted under its own name. *) + Hashtbl.remove ctx.renames n) names; let set t n b = if b then Hashtbl.replace t n () else Hashtbl.remove t n in (* Restore every table the binders could change: an [Int] recorded for a binder inside [f] must not reach a same-named outer binding. *) let restore () = List.iter - (fun (n, l, i, c) -> - set ctx.locals n l; set ctx.int_vars n i; set ctx.int_callables n c) + (fun (n, l, i, c, r) -> + set ctx.locals n l; set ctx.int_vars n i; set ctx.int_callables n c; + match r with + | Some js -> Hashtbl.replace ctx.renames n js + | None -> Hashtbl.remove ctx.renames n) had in match f () with @@ -1691,6 +1752,7 @@ let with_locals_scope : 'a. codegen_ctx -> (unit -> 'a) -> 'a = fun ctx f -> let saved_ints = Hashtbl.copy ctx.int_vars in let saved_callables = Hashtbl.copy ctx.int_callables in let saved_decls = Hashtbl.copy ctx.block_decls in + let saved_renames = Hashtbl.copy ctx.renames in Hashtbl.reset ctx.block_decls; let refill t src = Hashtbl.reset t; Hashtbl.iter (Hashtbl.replace t) src in let restore () = @@ -1705,7 +1767,8 @@ let with_locals_scope : 'a. codegen_ctx -> (unit -> 'a) -> 'a = fun ctx f -> refill ctx.int_vars saved_ints; List.iter (fun n -> Hashtbl.replace ctx.int_vars n ()) gained; refill ctx.int_callables saved_callables; - refill ctx.block_decls saved_decls + refill ctx.block_decls saved_decls; + refill ctx.renames saved_renames in match f () with | v -> restore (); v @@ -1719,9 +1782,6 @@ let with_locals_scope : 'a. codegen_ctx -> (unit -> 'a) -> 'a = fun ctx f -> call whose head is a known [extern fn] lowers via {!deno_builtins}. ============================================================================ *) -(* Fresh temporaries for `let` initializers lowered to statements. *) -let let_tmp_counter = ref 0 - (* Initializer shapes {!gen_assign_tail} can lower to statements. *) let rec lowers_to_statements = function | ExprSpan (e, _) -> lowers_to_statements e @@ -1836,8 +1896,10 @@ let rec gen_expr ctx (expr : expr) : string = "(" ^ gen_expr ctx ei_cond ^ " ? " ^ gen_expr ctx ei_then ^ " : " ^ else_str ^ ")" | ExprLet { el_pat; el_value; el_body; el_mut; el_quantity = _; el_ty = _ } -> - let pat_str = gen_pattern ctx el_pat in let val_str = gen_expr ctx el_value in + let binders = pattern_binders el_pat in + let renames = let_renames ctx binders val_str in + let pat_str = gen_let_pattern ctx renames el_pat in let kw = if el_mut then "let" else "const" in (* `let x = v in body` is lexically scoped, so track [x]'s int-ness only for [body] and restore afterward — a leaked binding could @@ -1856,7 +1918,9 @@ let rec gen_expr ctx (expr : expr) : string = | None -> fun () -> () in let b = - with_locals ctx (pattern_binders el_pat) (fun () -> gen_expr ctx body) + with_locals ctx binders (fun () -> + List.iter (fun (n, r) -> Hashtbl.replace ctx.renames n r) renames; + gen_expr ctx body) in restore (); kw ^ " " ^ pat_str ^ " = " ^ val_str ^ "; return " ^ b ^ ";" @@ -1904,6 +1968,16 @@ let rec gen_expr ctx (expr : expr) : string = let lctx = { ctx with in_async = false } in let names = List.map (fun (p : param) -> p.p_name.name) elam_params in with_locals lctx names (fun () -> + (* Typed parameters are classified by their own types, as in + {!enter_fn_scope}; an untyped or non-Int one shadows an outer + Int of the same name. *) + List.iter + (fun (p : param) -> + let n = p.p_name.name in + if type_head_is_int p.p_ty then Hashtbl.replace lctx.int_vars n () + else Hashtbl.remove lctx.int_vars n; + if type_returns_int p.p_ty then Hashtbl.replace lctx.int_callables n ()) + elam_params; with_locals_scope lctx (fun () -> if lowers_to_statements elam_body && expr_contains_return elam_body then (* A `return` in the body returns from the lambda: emit a block @@ -1956,21 +2030,38 @@ and gen_literal (lit : literal) : string = | LitChar (c, _) -> Js_codegen.js_string_lit (String.make 1 c) | LitUnit _ -> "Unit" +and pattern_binder_js ctx (name : string) : string = + match Hashtbl.find_opt ctx.pat_renames name with + | Some js -> js + | None -> mangle name + +(* The JS for a `let` pattern whose binders [renames] are declared under + fresh names. *) +and gen_let_pattern ctx (renames : (string * string) list) (pat : pattern) = + List.iter (fun (n, js) -> Hashtbl.replace ctx.pat_renames n js) renames; + let js = gen_pattern ctx pat in + Hashtbl.reset ctx.pat_renames; + js + and gen_pattern ctx (pat : pattern) : string = match pat with | PatWildcard _ -> "_" - | PatVar name -> mangle name.name + | PatVar name -> pattern_binder_js ctx name.name | PatLit _ -> "_" | PatTuple pats -> "[" ^ String.concat ", " (List.map (gen_pattern ctx) pats) ^ "]" | PatRecord (fields, _) -> let strs = List.map (fun (n, sub) -> match sub with - | None -> mangle n.name + | None -> + (* A punned field binds the field's own name. *) + (match Hashtbl.find_opt ctx.pat_renames n.name with + | Some js -> mangle n.name ^ ": " ^ js + | None -> mangle n.name) | Some sub -> mangle n.name ^ ": " ^ gen_pattern ctx sub ) fields in "{ " ^ String.concat ", " strs ^ " }" - | PatAs (id, _) -> mangle id.name + | PatAs (id, _) -> pattern_binder_js ctx id.name | PatCon (id, _) -> mangle id.name | PatOr (p, _) -> gen_pattern ctx p @@ -2346,6 +2437,7 @@ and gen_stmt ctx (stmt : stmt) : string = gen_expr ctx sl_value ^ ";" | StmtLet { sl_pat; sl_value; sl_mut; sl_quantity = _; sl_ty } -> let kw = if sl_mut then "let" else "const" in + let binders = pattern_binders sl_pat in let js = if lowers_to_statements sl_value && expr_contains_return sl_value then begin (* `let x = match e { A(v) => v, B(err) => return f(err) };` @@ -2356,12 +2448,18 @@ and gen_stmt ctx (stmt : stmt) : string = `return` is a real function return. *) incr let_tmp_counter; let tmp = Printf.sprintf "$let_tmp_%d" !let_tmp_counter in - "let " ^ tmp ^ "; " ^ gen_assign_tail ctx tmp sl_value ^ " " - ^ kw ^ " " ^ gen_pattern ctx sl_pat ^ " = " ^ tmp ^ ";" - end else - kw ^ " " ^ gen_pattern ctx sl_pat ^ " = " - ^ gen_expr ctx sl_value ^ ";" + let init = "let " ^ tmp ^ "; " ^ gen_assign_tail ctx tmp sl_value in + let renames = let_renames ctx binders init in + let pat = gen_let_pattern ctx renames sl_pat in + (init ^ " " ^ kw ^ " " ^ pat ^ " = " ^ tmp ^ ";", renames) + end else begin + let init = gen_expr ctx sl_value in + let renames = let_renames ctx binders init in + let pat = gen_let_pattern ctx renames sl_pat in + (kw ^ " " ^ pat ^ " = " ^ init ^ ";", renames) + end in + let js, renames = js in (* Track an [Int]-bound name for the rest of this block (#478). {!with_locals_scope} restores the enclosing binding on exit. *) (match pat_var_name sl_pat with @@ -2369,9 +2467,11 @@ and gen_stmt ctx (stmt : stmt) : string = | None -> ()); (* Bound after its initializer is emitted: `let len = len(s);` still calls the intrinsic. Lasts to the end of the enclosing scope. *) - let binders = pattern_binders sl_pat in List.iter (fun n -> + (match List.assoc_opt n renames with + | Some r -> Hashtbl.replace ctx.renames n r + | None -> Hashtbl.remove ctx.renames n); Hashtbl.replace ctx.locals n (); Hashtbl.replace ctx.block_decls n (); Hashtbl.remove ctx.int_callables n) diff --git a/test/test_let_rebind_bun.ml b/test/test_let_rebind_bun.ml new file mode 100644 index 00000000..fa7b5893 --- /dev/null +++ b/test/test_let_rebind_bun.ml @@ -0,0 +1,65 @@ +(* SPDX-License-Identifier: MPL-2.0 *) +(** Bun-ESM: a [let] that reads or shadows an enclosing name (#827). + + A JS [const x] is in its temporal dead zone for its whole block, so + [const x = (x + 1)] threw [ReferenceError], and a [let] rebinding a + parameter emitted [function p(x) { const x = ... }], a [SyntaxError] + that stopped the module loading. The binder is now emitted under a + fresh [x$N]. These tests check the emitted JS; the run-time behaviour + is checked by [tests/codegen-bun/let_rebind]. *) + +open Affinescript + +let emit src = + let prog = Parse_driver.parse_string ~file:"" src in + let loader = Module_loader.create (Module_loader.default_config ()) in + let ctx = match Resolve.resolve_program_with_loader prog loader with + | Ok (ctx, _) -> ctx + | Error (e, _) -> Alcotest.fail (Resolve.show_resolve_error e) + in + match Codegen_deno.codegen_bun prog ctx.symbols with + | Error e -> Alcotest.fail e + | Ok js -> js + +let count needle js = Test_int_div_js.count_occurrences ~needle js + +let absent what needle js = + Alcotest.(check int) what 0 (count needle js) + +let present what needle js = + if count needle js = 0 then Alcotest.failf "%s: %S not in output" what needle + +let tests = [ + Alcotest.test_case "let rebinding a parameter is renamed" `Quick (fun () -> + let js = emit {|pub fn p(x: Int) -> Int { let x = x + 1; x * 10 }|} in + absent "no second declaration of the parameter" "const x =" js; + present "the rebinding is fresh" "const x$" js); + Alcotest.test_case "nested let reading the outer name is renamed" `Quick (fun () -> + let js = emit {|pub fn f(n: Int) -> Int { + let x = n; + let y = { let x = x + 1; x }; + y + x + }|} in + absent "no const reading itself" "const x = (x + 1)" js; + present "the inner binding is fresh" "const x$" js); + Alcotest.test_case "a fresh name is used by later references" `Quick (fun () -> + let js = emit {|pub fn m(x: Int) -> Int { let mut x = x; x = x + 5; x }|} in + absent "no second declaration" "let x =" js; + present "assignment targets the fresh name" "= (x$" js); + Alcotest.test_case "an unshadowed let keeps its name" `Quick (fun () -> + let js = emit {|pub fn g(n: Int) -> Int { let total = n + 1; total }|} in + present "plain binding" "const total = (n + 1)" js; + absent "no rename" "total$" js); + Alcotest.test_case "Int-returning lambda parameter truncates" `Quick (fun () -> + let js = emit {|pub fn f(s: String) -> Int { + let g = fn(len: String -> Int) => len(s) / 2; + g(fn(t: String) => 5) + }|} in + Alcotest.(check int) "len(s) / 2 truncates" 1 (count "Math.trunc(" js)); + Alcotest.test_case "Float lambda parameter shadows an outer Int" `Quick (fun () -> + let js = emit {|pub fn f(x: Int, y: Int) -> Float { + let g = fn(x: Float, y: Float) => x / y; + g(5.0, 2.0) + }|} in + Alcotest.(check int) "x / y does not truncate" 0 (count "Math.trunc(" js)); +] diff --git a/test/test_main.ml b/test/test_main.ml index 57a3f78b..5248be15 100644 --- a/test/test_main.ml +++ b/test/test_main.ml @@ -34,6 +34,7 @@ let () = ("Record update + imported types", Test_records_and_imports.tests); ("Module mut (#548)", Test_module_mut.tests); ("Int-div on JS-text backend (#478)", Test_int_div_js.tests); + ("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); ("Same cube: faces compile alike (#601)", Test_same_cube.tests); diff --git a/tests/codegen-bun/let_rebind.affine b/tests/codegen-bun/let_rebind.affine new file mode 100644 index 00000000..2363fa43 --- /dev/null +++ b/tests/codegen-bun/let_rebind.affine @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: MPL-2.0 +// Regression: a `let` that reads or shadows a name bound in an enclosing +// scope. JS `const x` is in its temporal dead zone for its whole block, so +// `const x = x + 1` threw ReferenceError, and `function f(x) { const x = .. }` +// was a SyntaxError that stopped the module loading. The binder is now +// emitted under a fresh name. Also: a lambda parameter typed `-> Int` is an +// Int callable, so its result divides as an Int. + +pub fn param_rebind(x: Int) -> Int { + let x = x + 1; + x * 10 +} +pub fn nested(n: Int) -> Int { + let x = n; + let y = { let x = x + 1; x }; + y + x +} +pub fn outer_fn(s: String) -> Int { + let len = fn(t: String) => 40; + let r = { let len = len(s); len + 2 }; + r +} +pub fn lambda_int(s: String) -> Int { + let f = fn(len: String -> Int) => len(s) / 2; + f(fn(t: String) => 5) +} +pub fn mut_rebind(x: Int) -> Int { + let mut x = x; + x = x + 5; + x +} + +// Destructuring rebinds through the same renaming. +pub fn tuple_rebind(x: Int) -> Int { + let (x, y) = (x + 1, x + 2); + x * 100 + y +} + +// A lambda parameter shadowing a renamed outer binding is the parameter. +pub fn lambda_shadows_renamed(x: Int) -> Int { + let x = x + 1; + let g = fn(x: Int) => x * 3; + g(10) + x +} diff --git a/tests/codegen-bun/let_rebind.harness.mjs b/tests/codegen-bun/let_rebind.harness.mjs new file mode 100644 index 00000000..a2e5633a --- /dev/null +++ b/tests/codegen-bun/let_rebind.harness.mjs @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MPL-2.0 +import * as subject from "./let_rebind.bun.js"; + +const expect = (label, got, want) => { + if (got !== want) throw new Error(`${label}: got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`); +}; +expect("let rebinds a parameter", subject.param_rebind(1), 20); +expect("nested let reads the outer binding", subject.nested(1), 3); +expect("nested let reads an outer callable of its own name", subject.outer_fn("ab"), 42); +expect("Int-returning lambda parameter divides as Int", subject.lambda_int("x"), 2); +expect("mutable rebind of a parameter", subject.mut_rebind(1), 6); +expect("destructuring rebind", subject.tuple_rebind(1), 203); +expect("lambda parameter shadows a renamed binding", subject.lambda_shadows_renamed(1), 32); +console.log("let_rebind: ok"); diff --git a/tools/soundness-anchors.sha256 b/tools/soundness-anchors.sha256 index 20d9be29..58f6020c 100644 --- a/tools/soundness-anchors.sha256 +++ b/tools/soundness-anchors.sha256 @@ -20,6 +20,7 @@ ac1da10c3206605304f11e869f6aa07acba57f6f8248bb2dfacca19984f86c31 test:test_coherence_duplicate_rejected ad1e66df361641660125a84fb4694785357d542b0a7856de8f28e4d81f8635b5 test:test_wasm_let_shadows_fn b76c7824a9b1570d66752359a28d75ebdfaedb5de5ad68c343a0a2c26ad4221c fixture:test/e2e/fixtures/async_sync_fallback.affine +bae092bc1fbac56c14a8d4448170e2f52b52fd4a93c687569738166b36586f97 suite:test/test_let_rebind_bun.ml c743b86cfc50512e5867ddd792b4b4273b5bfb6f40205b4a07019031d7e7b102 fixture:test/e2e/fixtures/handle_resume_multishot.affine ce709dcd36043d1b546b568cae277a83b843d1621275d830d72efef2e9a6a87c test:test_parse_assume_rejected d35167312f3aa763ad337570e3791e67f1caa799ca686162831d3a4d6ad82f41 test:test_wasm_call_indirect_type_interned