@@ -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 =
14551464let 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. *)
17261786let 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+
19592046and 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)
0 commit comments