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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions docs/SOUNDNESS.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
142 changes: 121 additions & 21 deletions lib/codegen_deno.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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<Int>]-typed params. Returns [ctx] with the
fresh tables installed. *)
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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 () =
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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 ^ ";"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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) };`
Expand All @@ -2356,22 +2448,30 @@ 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
| Some n -> track_int_binding ctx n sl_value
| 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)
Expand Down
65 changes: 65 additions & 0 deletions test/test_let_rebind_bun.ml
Original file line number Diff line number Diff line change
@@ -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:"<let_rebind>" 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));
]
1 change: 1 addition & 0 deletions test/test_main.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading
Loading