Skip to content

Commit 5c288b1

Browse files
committed
Merge branch 'main' into claude/js-backend-builtin-refusal-832
Conflict in test/test_main.ml: both sides added a suite to the list (#832 here, #827 on main). Both kept. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01J4QvDhJog6g9kprphCAadr
2 parents f043b95 + 84eca60 commit 5c288b1

8 files changed

Lines changed: 259 additions & 21 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ bisect*.coverage
104104
# Issue #734: generated native Bun-ESM acceptance outputs.
105105
/tests/codegen-bun/*.bun.js
106106
/tests/codegen-bun/backend-conflict.json
107+
/tests/codegen-bun/deno-removed.json
107108
# Local-only build workaround (see file header); never committed.
108109
/dune-workspace
109110
packages/affinescript-cli/deno.lock

‎docs/SOUNDNESS.adoc‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,18 @@ backstop refuses a planted collision in the flattener and in both JS
229229
emitters); `tests/codegen-bun/same_name_modules` runs #801's reproduction
230230
under Bun.
231231

232+
| #827
233+
| Bun-ESM: a `let` that reads or shadows an enclosing name is emitted under
234+
a fresh name. `const x = x + 1` in a nested block threw `ReferenceError`, and
235+
a `let` rebinding a parameter was a `SyntaxError` that stopped the module
236+
loading. A lambda parameter typed `fn(..) -> Int` is an Int callable, so
237+
`len(s) / 2` truncates: a function declared `-> Int` returned `2.5`.
238+
| `fixed`
239+
| `test/test_let_rebind_bun.ml` (emitted JS) and `tests/codegen-bun/let_rebind`
240+
(run under Bun): parameter, nested,
241+
callable and mutable rebinds, destructuring, a lambda shadowing a renamed
242+
binding, an Int-typed lambda parameter.
243+
232244
| #801 (impl methods)
233245
| Trait impl methods are emitted as free functions under their own names on
234246
Bun-ESM (trait dispatch is not lowered there), so `impl Eq for Int` and

‎lib/codegen_deno.ml‎

Lines changed: 121 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,13 @@ type codegen_ctx = {
111111
exit, an [Int] classification gained by an assignment to any other
112112
(enclosing) name is kept; see {!with_locals_scope}. *)
113113
block_decls : (string, unit) Hashtbl.t;
114+
(* Source name -> emitted JS name, for a `let` binder emitted under a
115+
fresh name (see {!let_renames}). Consulted by {!resolve_var}; scoped
116+
like {!locals}. *)
117+
renames : (string, string) Hashtbl.t;
118+
(* Binder renames {!gen_pattern} applies to the pattern being declared
119+
right now; empty otherwise. *)
120+
pat_renames : (string, string) Hashtbl.t;
114121
(* True while emitting a synthesised `async` method body. The
115122
expression-position IIFE wrappers (block/try/match/let/return) must
116123
then be `async` and awaited, because they may contain an awaited
@@ -146,6 +153,8 @@ let create_ctx host symbols = {
146153
locals = Hashtbl.create 16;
147154
int_callables = Hashtbl.create 8;
148155
block_decls = Hashtbl.create 8;
156+
renames = Hashtbl.create 8;
157+
pat_renames = Hashtbl.create 4;
149158
in_async = false;
150159
top_names = Hashtbl.create 128;
151160
public_ctors = Hashtbl.create 32;
@@ -1455,7 +1464,10 @@ let claim_runtime ctx (js : string) : unit =
14551464
let resolve_var ctx (name : string) : string =
14561465
match ctx.self_name with
14571466
| Some s when s = name -> "this"
1458-
| _ -> mangle name
1467+
| _ ->
1468+
(match Hashtbl.find_opt ctx.renames name with
1469+
| Some js -> js
1470+
| None -> mangle name)
14591471

14601472
(* ============================================================================
14611473
Integer-operand inference for division (issue #478)
@@ -1628,6 +1640,46 @@ let track_int_binding ctx (name : string) (value : expr) : unit =
16281640
if expr_is_int ctx value then Hashtbl.replace ctx.int_vars name ()
16291641
else Hashtbl.remove ctx.int_vars name
16301642

1643+
(* Fresh temporaries and binder names (`$`-suffixed, so never a source
1644+
identifier) for `let` lowering. *)
1645+
let let_tmp_counter = ref 0
1646+
1647+
(* Does [js] contain [ident] as an identifier token (not a property after
1648+
`.`)? Over-approximates: a string literal or an object key also counts,
1649+
which only costs an unneeded rename. *)
1650+
let mentions_ident (js : string) (ident : string) : bool =
1651+
let n = String.length js and m = String.length ident in
1652+
let is_id c =
1653+
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
1654+
|| c = '_' || c = '$'
1655+
in
1656+
let rec go i =
1657+
if i + m > n then false
1658+
else if String.sub js i m = ident
1659+
&& (i = 0 || (not (is_id js.[i - 1]) && js.[i - 1] <> '.'))
1660+
&& (i + m = n || not (is_id js.[i + m]))
1661+
then true
1662+
else go (i + 1)
1663+
in
1664+
m > 0 && go 0
1665+
1666+
(* The binders of a `let` that must be emitted under a fresh name. A JS
1667+
`const x` is in its temporal dead zone for its whole block, so
1668+
`const x = x + 1` throws when the initializer reads the outer `x`;
1669+
and `function f(x) { const x = ... }` is a SyntaxError. So a binder is
1670+
renamed when its initializer mentions the name, or when it shadows a
1671+
name already bound in this function. `$` cannot occur in a source
1672+
identifier, so a fresh name cannot collide with one. *)
1673+
let let_renames ctx (binders : string list) (init_js : string) :
1674+
(string * string) list =
1675+
List.filter_map
1676+
(fun n ->
1677+
if Hashtbl.mem ctx.locals n || mentions_ident init_js (mangle n) then begin
1678+
incr let_tmp_counter;
1679+
Some (n, Printf.sprintf "%s$%d" (mangle n) !let_tmp_counter)
1680+
end else None)
1681+
binders
1682+
16311683
(* Reset [int_vars] / [int_array_vars] for a new function body and seed
16321684
them from [Int]- and [Array<Int>]-typed params. Returns [ctx] with the
16331685
fresh tables installed. *)
@@ -1648,7 +1700,7 @@ let enter_fn_scope ctx (params : param list) : codegen_ctx =
16481700
if type_returns_int p.p_ty then Hashtbl.replace int_callables p.p_name.name ())
16491701
params;
16501702
{ ctx with int_vars = tbl; int_array_vars = arr_tbl; locals; int_callables;
1651-
block_decls = Hashtbl.create 8 }
1703+
block_decls = Hashtbl.create 8; renames = Hashtbl.create 8 }
16521704

16531705
(* Run [f] with [names] bound as locals, then restore the previous bindings,
16541706
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 =
16581710
let mem t n = Hashtbl.mem t n in
16591711
let had =
16601712
List.map
1661-
(fun n -> (n, mem ctx.locals n, mem ctx.int_vars n, mem ctx.int_callables n))
1713+
(fun n ->
1714+
(n, mem ctx.locals n, mem ctx.int_vars n, mem ctx.int_callables n,
1715+
Hashtbl.find_opt ctx.renames n))
16621716
names
16631717
in
16641718
(* A binder of no declared callable type shadows any [Int]-returning
16651719
callable of the same name. *)
16661720
List.iter
1667-
(fun n -> Hashtbl.replace ctx.locals n (); Hashtbl.remove ctx.int_callables n)
1721+
(fun n ->
1722+
Hashtbl.replace ctx.locals n ();
1723+
Hashtbl.remove ctx.int_callables n;
1724+
(* The binder is emitted under its own name. *)
1725+
Hashtbl.remove ctx.renames n)
16681726
names;
16691727
let set t n b = if b then Hashtbl.replace t n () else Hashtbl.remove t n in
16701728
(* Restore every table the binders could change: an [Int] recorded for a
16711729
binder inside [f] must not reach a same-named outer binding. *)
16721730
let restore () =
16731731
List.iter
1674-
(fun (n, l, i, c) ->
1675-
set ctx.locals n l; set ctx.int_vars n i; set ctx.int_callables n c)
1732+
(fun (n, l, i, c, r) ->
1733+
set ctx.locals n l; set ctx.int_vars n i; set ctx.int_callables n c;
1734+
match r with
1735+
| Some js -> Hashtbl.replace ctx.renames n js
1736+
| None -> Hashtbl.remove ctx.renames n)
16761737
had
16771738
in
16781739
match f () with
@@ -1691,6 +1752,7 @@ let with_locals_scope : 'a. codegen_ctx -> (unit -> 'a) -> 'a = fun ctx f ->
16911752
let saved_ints = Hashtbl.copy ctx.int_vars in
16921753
let saved_callables = Hashtbl.copy ctx.int_callables in
16931754
let saved_decls = Hashtbl.copy ctx.block_decls in
1755+
let saved_renames = Hashtbl.copy ctx.renames in
16941756
Hashtbl.reset ctx.block_decls;
16951757
let refill t src = Hashtbl.reset t; Hashtbl.iter (Hashtbl.replace t) src in
16961758
let restore () =
@@ -1705,7 +1767,8 @@ let with_locals_scope : 'a. codegen_ctx -> (unit -> 'a) -> 'a = fun ctx f ->
17051767
refill ctx.int_vars saved_ints;
17061768
List.iter (fun n -> Hashtbl.replace ctx.int_vars n ()) gained;
17071769
refill ctx.int_callables saved_callables;
1708-
refill ctx.block_decls saved_decls
1770+
refill ctx.block_decls saved_decls;
1771+
refill ctx.renames saved_renames
17091772
in
17101773
match f () with
17111774
| v -> restore (); v
@@ -1719,9 +1782,6 @@ let with_locals_scope : 'a. codegen_ctx -> (unit -> 'a) -> 'a = fun ctx f ->
17191782
call whose head is a known [extern fn] lowers via {!deno_builtins}.
17201783
============================================================================ *)
17211784

1722-
(* Fresh temporaries for `let` initializers lowered to statements. *)
1723-
let let_tmp_counter = ref 0
1724-
17251785
(* Initializer shapes {!gen_assign_tail} can lower to statements. *)
17261786
let rec lowers_to_statements = function
17271787
| ExprSpan (e, _) -> lowers_to_statements e
@@ -1836,8 +1896,10 @@ let rec gen_expr ctx (expr : expr) : string =
18361896
"(" ^ gen_expr ctx ei_cond ^ " ? " ^ gen_expr ctx ei_then ^ " : "
18371897
^ else_str ^ ")"
18381898
| ExprLet { el_pat; el_value; el_body; el_mut; el_quantity = _; el_ty = _ } ->
1839-
let pat_str = gen_pattern ctx el_pat in
18401899
let val_str = gen_expr ctx el_value in
1900+
let binders = pattern_binders el_pat in
1901+
let renames = let_renames ctx binders val_str in
1902+
let pat_str = gen_let_pattern ctx renames el_pat in
18411903
let kw = if el_mut then "let" else "const" in
18421904
(* `let x = v in body` is lexically scoped, so track [x]'s int-ness
18431905
only for [body] and restore afterward — a leaked binding could
@@ -1856,7 +1918,9 @@ let rec gen_expr ctx (expr : expr) : string =
18561918
| None -> fun () -> ()
18571919
in
18581920
let b =
1859-
with_locals ctx (pattern_binders el_pat) (fun () -> gen_expr ctx body)
1921+
with_locals ctx binders (fun () ->
1922+
List.iter (fun (n, r) -> Hashtbl.replace ctx.renames n r) renames;
1923+
gen_expr ctx body)
18601924
in
18611925
restore ();
18621926
kw ^ " " ^ pat_str ^ " = " ^ val_str ^ "; return " ^ b ^ ";"
@@ -1904,6 +1968,16 @@ let rec gen_expr ctx (expr : expr) : string =
19041968
let lctx = { ctx with in_async = false } in
19051969
let names = List.map (fun (p : param) -> p.p_name.name) elam_params in
19061970
with_locals lctx names (fun () ->
1971+
(* Typed parameters are classified by their own types, as in
1972+
{!enter_fn_scope}; an untyped or non-Int one shadows an outer
1973+
Int of the same name. *)
1974+
List.iter
1975+
(fun (p : param) ->
1976+
let n = p.p_name.name in
1977+
if type_head_is_int p.p_ty then Hashtbl.replace lctx.int_vars n ()
1978+
else Hashtbl.remove lctx.int_vars n;
1979+
if type_returns_int p.p_ty then Hashtbl.replace lctx.int_callables n ())
1980+
elam_params;
19071981
with_locals_scope lctx (fun () ->
19081982
if lowers_to_statements elam_body && expr_contains_return elam_body then
19091983
(* A `return` in the body returns from the lambda: emit a block
@@ -1956,21 +2030,38 @@ and gen_literal (lit : literal) : string =
19562030
| LitChar (c, _) -> Js_codegen.js_string_lit (String.make 1 c)
19572031
| LitUnit _ -> "Unit"
19582032

2033+
and pattern_binder_js ctx (name : string) : string =
2034+
match Hashtbl.find_opt ctx.pat_renames name with
2035+
| Some js -> js
2036+
| None -> mangle name
2037+
2038+
(* The JS for a `let` pattern whose binders [renames] are declared under
2039+
fresh names. *)
2040+
and gen_let_pattern ctx (renames : (string * string) list) (pat : pattern) =
2041+
List.iter (fun (n, js) -> Hashtbl.replace ctx.pat_renames n js) renames;
2042+
let js = gen_pattern ctx pat in
2043+
Hashtbl.reset ctx.pat_renames;
2044+
js
2045+
19592046
and gen_pattern ctx (pat : pattern) : string =
19602047
match pat with
19612048
| PatWildcard _ -> "_"
1962-
| PatVar name -> mangle name.name
2049+
| PatVar name -> pattern_binder_js ctx name.name
19632050
| PatLit _ -> "_"
19642051
| PatTuple pats ->
19652052
"[" ^ String.concat ", " (List.map (gen_pattern ctx) pats) ^ "]"
19662053
| PatRecord (fields, _) ->
19672054
let strs = List.map (fun (n, sub) ->
19682055
match sub with
1969-
| None -> mangle n.name
2056+
| None ->
2057+
(* A punned field binds the field's own name. *)
2058+
(match Hashtbl.find_opt ctx.pat_renames n.name with
2059+
| Some js -> mangle n.name ^ ": " ^ js
2060+
| None -> mangle n.name)
19702061
| Some sub -> mangle n.name ^ ": " ^ gen_pattern ctx sub
19712062
) fields in
19722063
"{ " ^ String.concat ", " strs ^ " }"
1973-
| PatAs (id, _) -> mangle id.name
2064+
| PatAs (id, _) -> pattern_binder_js ctx id.name
19742065
| PatCon (id, _) -> mangle id.name
19752066
| PatOr (p, _) -> gen_pattern ctx p
19762067

@@ -2346,6 +2437,7 @@ and gen_stmt ctx (stmt : stmt) : string =
23462437
gen_expr ctx sl_value ^ ";"
23472438
| StmtLet { sl_pat; sl_value; sl_mut; sl_quantity = _; sl_ty } ->
23482439
let kw = if sl_mut then "let" else "const" in
2440+
let binders = pattern_binders sl_pat in
23492441
let js =
23502442
if lowers_to_statements sl_value && expr_contains_return sl_value then begin
23512443
(* `let x = match e { A(v) => v, B(err) => return f(err) };`
@@ -2356,22 +2448,30 @@ and gen_stmt ctx (stmt : stmt) : string =
23562448
`return` is a real function return. *)
23572449
incr let_tmp_counter;
23582450
let tmp = Printf.sprintf "$let_tmp_%d" !let_tmp_counter in
2359-
"let " ^ tmp ^ "; " ^ gen_assign_tail ctx tmp sl_value ^ " "
2360-
^ kw ^ " " ^ gen_pattern ctx sl_pat ^ " = " ^ tmp ^ ";"
2361-
end else
2362-
kw ^ " " ^ gen_pattern ctx sl_pat ^ " = "
2363-
^ gen_expr ctx sl_value ^ ";"
2451+
let init = "let " ^ tmp ^ "; " ^ gen_assign_tail ctx tmp sl_value in
2452+
let renames = let_renames ctx binders init in
2453+
let pat = gen_let_pattern ctx renames sl_pat in
2454+
(init ^ " " ^ kw ^ " " ^ pat ^ " = " ^ tmp ^ ";", renames)
2455+
end else begin
2456+
let init = gen_expr ctx sl_value in
2457+
let renames = let_renames ctx binders init in
2458+
let pat = gen_let_pattern ctx renames sl_pat in
2459+
(kw ^ " " ^ pat ^ " = " ^ init ^ ";", renames)
2460+
end
23642461
in
2462+
let js, renames = js in
23652463
(* Track an [Int]-bound name for the rest of this block (#478).
23662464
{!with_locals_scope} restores the enclosing binding on exit. *)
23672465
(match pat_var_name sl_pat with
23682466
| Some n -> track_int_binding ctx n sl_value
23692467
| None -> ());
23702468
(* Bound after its initializer is emitted: `let len = len(s);` still
23712469
calls the intrinsic. Lasts to the end of the enclosing scope. *)
2372-
let binders = pattern_binders sl_pat in
23732470
List.iter
23742471
(fun n ->
2472+
(match List.assoc_opt n renames with
2473+
| Some r -> Hashtbl.replace ctx.renames n r
2474+
| None -> Hashtbl.remove ctx.renames n);
23752475
Hashtbl.replace ctx.locals n ();
23762476
Hashtbl.replace ctx.block_decls n ();
23772477
Hashtbl.remove ctx.int_callables n)

‎test/test_let_rebind_bun.ml‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
(* SPDX-License-Identifier: MPL-2.0 *)
2+
(** Bun-ESM: a [let] that reads or shadows an enclosing name (#827).
3+
4+
A JS [const x] is in its temporal dead zone for its whole block, so
5+
[const x = (x + 1)] threw [ReferenceError], and a [let] rebinding a
6+
parameter emitted [function p(x) { const x = ... }], a [SyntaxError]
7+
that stopped the module loading. The binder is now emitted under a
8+
fresh [x$N]. These tests check the emitted JS; the run-time behaviour
9+
is checked by [tests/codegen-bun/let_rebind]. *)
10+
11+
open Affinescript
12+
13+
let emit src =
14+
let prog = Parse_driver.parse_string ~file:"<let_rebind>" src in
15+
let loader = Module_loader.create (Module_loader.default_config ()) in
16+
let ctx = match Resolve.resolve_program_with_loader prog loader with
17+
| Ok (ctx, _) -> ctx
18+
| Error (e, _) -> Alcotest.fail (Resolve.show_resolve_error e)
19+
in
20+
match Codegen_deno.codegen_bun prog ctx.symbols with
21+
| Error e -> Alcotest.fail e
22+
| Ok js -> js
23+
24+
let count needle js = Test_int_div_js.count_occurrences ~needle js
25+
26+
let absent what needle js =
27+
Alcotest.(check int) what 0 (count needle js)
28+
29+
let present what needle js =
30+
if count needle js = 0 then Alcotest.failf "%s: %S not in output" what needle
31+
32+
let tests = [
33+
Alcotest.test_case "let rebinding a parameter is renamed" `Quick (fun () ->
34+
let js = emit {|pub fn p(x: Int) -> Int { let x = x + 1; x * 10 }|} in
35+
absent "no second declaration of the parameter" "const x =" js;
36+
present "the rebinding is fresh" "const x$" js);
37+
Alcotest.test_case "nested let reading the outer name is renamed" `Quick (fun () ->
38+
let js = emit {|pub fn f(n: Int) -> Int {
39+
let x = n;
40+
let y = { let x = x + 1; x };
41+
y + x
42+
}|} in
43+
absent "no const reading itself" "const x = (x + 1)" js;
44+
present "the inner binding is fresh" "const x$" js);
45+
Alcotest.test_case "a fresh name is used by later references" `Quick (fun () ->
46+
let js = emit {|pub fn m(x: Int) -> Int { let mut x = x; x = x + 5; x }|} in
47+
absent "no second declaration" "let x =" js;
48+
present "assignment targets the fresh name" "= (x$" js);
49+
Alcotest.test_case "an unshadowed let keeps its name" `Quick (fun () ->
50+
let js = emit {|pub fn g(n: Int) -> Int { let total = n + 1; total }|} in
51+
present "plain binding" "const total = (n + 1)" js;
52+
absent "no rename" "total$" js);
53+
Alcotest.test_case "Int-returning lambda parameter truncates" `Quick (fun () ->
54+
let js = emit {|pub fn f(s: String) -> Int {
55+
let g = fn(len: String -> Int) => len(s) / 2;
56+
g(fn(t: String) => 5)
57+
}|} in
58+
Alcotest.(check int) "len(s) / 2 truncates" 1 (count "Math.trunc(" js));
59+
Alcotest.test_case "Float lambda parameter shadows an outer Int" `Quick (fun () ->
60+
let js = emit {|pub fn f(x: Int, y: Int) -> Float {
61+
let g = fn(x: Float, y: Float) => x / y;
62+
g(5.0, 2.0)
63+
}|} in
64+
Alcotest.(check int) "x / y does not truncate" 0 (count "Math.trunc(" js));
65+
]

‎test/test_main.ml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ let () =
3535
("Module mut (#548)", Test_module_mut.tests);
3636
("Int-div on JS-text backend (#478)", Test_int_div_js.tests);
3737
("JS-text backend refuses unprovided builtins (#832)", Test_js_builtin_refusal.tests);
38+
("Bun-ESM let rebinding (#827)", Test_let_rebind_bun.tests);
3839
("Deno builtins ↔ stdlib decls consistency", Test_deno_builtins_consistency.tests);
3940
("Bun integer block scope", Test_int_scope_bun.tests);
4041
("Same cube: faces compile alike (#601)", Test_same_cube.tests);

0 commit comments

Comments
 (0)