diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ad4d8584e..8a0d739c29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,7 @@ - Fix references to a `@val` global reading a binding with the same name, e.g. a toplevel `let` declared before them. https://github.com/rescript-lang/rescript/pull/8785 - Evaluate the unused arguments of an inlined function call in parameter order. https://github.com/rescript-lang/rescript/pull/8786 +- Fix shadowed variables in generated JS colliding with identifiers or external names containing `$`. https://github.com/rescript-lang/rescript/pull/8778 - Fix editor completion of values from modules included with `include await M`. https://github.com/rescript-lang/rescript/pull/8770 - Fix editor completion inside dict literals and dict patterns, which suggested untyped values. https://github.com/rescript-lang/rescript/pull/8770 - Report the required Node.js version 22 when the platform package can't be found. https://github.com/rescript-lang/rescript/pull/8770 diff --git a/compiler/core/js_dump_program.ml b/compiler/core/js_dump_program.ml index c861aeb5fa..7710351610 100644 --- a/compiler/core/js_dump_program.ml +++ b/compiler/core/js_dump_program.ml @@ -57,13 +57,29 @@ let extract_file_comments (x : J.deps_program) = let comments, new_block = extract_block_comments [] x.program.block in (comments, {x with program = {x.program with block = new_block}}) +(* The initial scope for printing [x], reserving the raw JS names it refers + to so that renamed locals can't capture them. *) +let initial_scope (x : J.program) = + let names = ref Set_string.empty in + let super = Js_record_iter.super in + let self = + { + super with + ident = + (fun _ id -> + if Ext_ident.is_js id then names := Set_string.add id.name !names); + } + in + self.program self x; + Ext_pp_scope.reserve Ext_pp_scope.empty !names + let program f cxt (x : J.program) = P.at_least_two_lines f; let cxt = Js_dump.statements true cxt f x.block in Js_dump_import_export.exports cxt f x.exports let dump_program (x : J.program) oc = - ignore (program (P.from_channel oc) Ext_pp_scope.empty x) + ignore (program (P.from_channel oc) (initial_scope x) x) let[@inline] is_default (x : Js_op.kind) = match x with @@ -74,7 +90,7 @@ let commonjs_program ~output_dir f (x : J.deps_program) = P.string f L.strict_directive; P.newline f; let cxt = - Js_dump_import_export.requires L.require Ext_pp_scope.empty f + Js_dump_import_export.requires L.require (initial_scope x.program) f (* Not be emitted in require statements *) (Ext_list.filter_map x.modules (fun x -> match x.dynamic_import with @@ -89,7 +105,7 @@ let commonjs_program ~output_dir f (x : J.deps_program) = let esmodule_program ~output_dir fmt f (x : J.deps_program) = let cxt = - Js_dump_import_export.imports Ext_pp_scope.empty f + Js_dump_import_export.imports (initial_scope x.program) f (* Not be emitted in import statements *) (Ext_list.filter_map x.modules (fun x -> match x.dynamic_import with diff --git a/compiler/ext/ext_pp_scope.ml b/compiler/ext/ext_pp_scope.ml index 63910b03d7..2eebcbf8a8 100644 --- a/compiler/ext/ext_pp_scope.ml +++ b/compiler/ext/ext_pp_scope.ml @@ -22,32 +22,57 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) -(* Stamps seen for one mangled name, each mapped to its index suffix. - [count] is the number of entries in [stamps], which is also the next index. *) -type stamps = {count: int; stamps: int Map_int.t} +(* Stamps seen for one mangled name, each mapped to its printed name. + [next] is the first suffix to try; every suffix below it is assigned or + was already taken when skipped. *) +type stamps = {next: int; stamps: string Map_int.t} -(* - -- "name" --> int map -- stamp --> index suffix -*) -type t = stamps Map_string.t +(* [used] holds every printed name in scope. Identifiers may contain [$], so + a suffixed name like [x$1] can equal another identifier's mangled name; + new names are checked against [used] instead of being assumed fresh. + [reserved] holds the raw JS names the program refers to (see {!reserve}), + which a suffixed name must not capture. *) +type t = { + names: stamps Map_string.t; + used: Set_string.t; + reserved: Set_string.t; +} + +let empty : t = + { + names = Map_string.empty; + used = Set_string.empty; + reserved = Set_string.empty; + } -let empty : t = Map_string.empty +let reserve (cxt : t) (reserved : Set_string.t) : t = {cxt with reserved} -let add_ident ~mangled:name (stamp : int) (cxt : t) : int * t = - match Map_string.find_opt name cxt with +let add_ident ~mangled:name (stamp : int) (cxt : t) : string * t = + let {next; stamps} = + match Map_string.find_opt name cxt.names with + | None -> {next = 0; stamps = Map_int.empty} + | Some s -> s + in + match Map_int.find_opt stamp stamps with + | Some str -> (str, cxt) | None -> - ( 0, - Map_string.add name - {count = 1; stamps = Map_int.add stamp 0 Map_int.empty} - cxt ) - | Some {count; stamps} -> ( - match Map_int.find_opt stamp stamps with - | None -> - ( count, - Map_string.add name - {count = count + 1; stamps = Map_int.add stamp count stamps} - cxt ) - | Some i -> (i, cxt)) + let rec pick i = + let str = if i = 0 then name else Printf.sprintf "%s$%d" name i in + if + Set_string.mem str cxt.used || (i > 0 && Set_string.mem str cxt.reserved) + then pick (i + 1) + else (i, str) + in + let i, str = pick next in + ( str, + { + names = + Map_string.add name + {next = i + 1; stamps = Map_int.add stamp str stamps} + cxt.names; + used = Set_string.add str cxt.used; + reserved = cxt.reserved; + } ) (** same as {!ident} except it generates a string instead of doing the printing @@ -86,8 +111,7 @@ let str_of_ident (cxt : t) (id : Ident.t) : string * t = else let id_name = id.name in let name = Ext_ident.convert id_name in - let i, new_cxt = add_ident ~mangled:name id.stamp cxt in - ((if i == 0 then name else Printf.sprintf "%s$%d" name i), new_cxt) + add_ident ~mangled:name id.stamp cxt let ident (cxt : t) f (id : Ident.t) : t = let str, cxt = str_of_ident cxt id in @@ -108,9 +132,18 @@ let sub_scope (scope : t) (idents : Set_ident.t) : t = Set_ident.fold (fun {name} acc -> let mangled = Ext_ident.convert name in - match Map_string.find mangled scope with + match Map_string.find mangled scope.names with | exception Not_found -> assert false | stamps -> - if Map_string.mem mangled acc then acc - else Map_string.add mangled stamps acc) - idents empty + if Map_string.mem mangled acc.names then acc + else + { + acc with + names = Map_string.add mangled stamps acc.names; + used = + Map_int.fold + (fun _ str used -> Set_string.add str used) + stamps.stamps acc.used; + }) + idents + {empty with reserved = scope.reserved} diff --git a/compiler/ext/ext_pp_scope.mli b/compiler/ext/ext_pp_scope.mli index 2eae91087f..d3c4a67a28 100644 --- a/compiler/ext/ext_pp_scope.mli +++ b/compiler/ext/ext_pp_scope.mli @@ -33,6 +33,10 @@ type t val empty : t +val reserve : t -> Set_string.t -> t +(** [reserve cxt names] keeps generated [$N] suffixes from producing any of + [names], the raw JS names (globals, externals) the program refers to. *) + val sub_scope : t -> Set_ident.t -> t val merge : t -> Set_ident.t -> t diff --git a/tests/tests/src/shadow_dollar_test.mjs b/tests/tests/src/shadow_dollar_test.mjs new file mode 100644 index 0000000000..88254be853 --- /dev/null +++ b/tests/tests/src/shadow_dollar_test.mjs @@ -0,0 +1,126 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Mocha from "mocha"; +import * as Test_utils from "./test_utils.mjs"; + +function paramCollision(x, x$1) { + let x$2 = x$1(x); + let y = x$1(2); + return x$2 + y | 0; +} + +function laterBinding(x) { + let x$1 = x + 1 | 0; + let x$1$1 = x$1 * 10 | 0; + return [ + x$1, + x$1$1, + x$1, + x$1$1 + ]; +} + +function earlierBinding(x) { + let x$1 = x * 10 | 0; + let x$2 = x + 1 | 0; + return [ + x$2, + x$1, + x$2, + x$1 + ]; +} + +function nested(x) { + let inner = () => { + let x$1 = x + 1 | 0; + let x$1$1 = x$1 * 10 | 0; + return [ + x$1, + x$1$1, + x$1, + x$1$1 + ]; + }; + let x$1 = x + 2 | 0; + return [ + x$1, + inner(), + x$1 + ]; +} + +globalThis["y$1"] = 100; globalThis["z$2"] = 200; globalThis["w$1"] = 300 +; + +let base = 1; + +let y = (base << 1); + +let y$2 = y + y$1 | 0; + +let topShadow = y$2 + y$2 | 0; + +let z = (base << 1); + +let topSibling; + +if (z < 0) { + let z$1 = z * 10 | 0; + topSibling = z$1 + z$1 | 0; +} else { + let z$3 = z + z$2 | 0; + topSibling = z$3 + z$3 | 0; +} + +function fnShadow(w) { + let w$2 = w + w$1 | 0; + return w$2 + w$2 | 0; +} + +Mocha.describe("Shadow_dollar_test", () => { + Mocha.test("shadowed names do not collide with $ identifiers", () => { + Test_utils.eq("File \"shadow_dollar_test.res\", line 65, characters 7-14", paramCollision(1, v => v * 10 | 0), 30); + Test_utils.eq("File \"shadow_dollar_test.res\", line 66, characters 7-14", laterBinding(1), [ + 2, + 20, + 2, + 20 + ]); + Test_utils.eq("File \"shadow_dollar_test.res\", line 67, characters 7-14", earlierBinding(1), [ + 2, + 10, + 2, + 10 + ]); + Test_utils.eq("File \"shadow_dollar_test.res\", line 68, characters 7-14", nested(1), [ + 3, + [ + 2, + 20, + 2, + 20 + ], + 3 + ]); + }); + Mocha.test("shadowed names do not capture raw JS names", () => { + Test_utils.eq("File \"shadow_dollar_test.res\", line 72, characters 7-14", topShadow, 204); + Test_utils.eq("File \"shadow_dollar_test.res\", line 73, characters 7-14", topSibling, 404); + Test_utils.eq("File \"shadow_dollar_test.res\", line 74, characters 7-14", fnShadow(1), 602); + }); +}); + +export { + paramCollision, + laterBinding, + earlierBinding, + nested, + base, + y, + topShadow, + z, + topSibling, + fnShadow, +} +/* Not a pure module */ diff --git a/tests/tests/src/shadow_dollar_test.res b/tests/tests/src/shadow_dollar_test.res new file mode 100644 index 0000000000..f65bd1bf05 --- /dev/null +++ b/tests/tests/src/shadow_dollar_test.res @@ -0,0 +1,76 @@ +open Mocha +open Test_utils + +// Shadowed variables get a `$N` suffix in JS; it must not collide with +// identifiers that already contain `$`. + +let paramCollision = (x, \"x$1") => { + let x = \"x$1"(x) + let y = \"x$1"(2) + x + y +} + +let laterBinding = x => { + let x = x + 1 + let \"x$1" = x * 10 + (x, \"x$1", x, \"x$1") +} + +let earlierBinding = x => { + let \"x$1" = x * 10 + let x = x + 1 + (x, \"x$1", x, \"x$1") +} + +let nested = x => { + let inner = () => { + let x = x + 1 + let \"x$1" = x * 10 + (x, \"x$1", x, \"x$1") + } + let x = x + 2 + (x, inner(), x) +} + +// Raw JS names the program refers to must not be captured by a renamed local. +%%raw(`globalThis["y$1"] = 100; globalThis["z$2"] = 200; globalThis["w$1"] = 300`) +@val external y1: int = "y$1" +@val external z2: int = "z$2" +@val external w1: int = "w$1" + +let base: int = %raw("1") + +let y = base * 2 +let topShadow = { + let y = y + y1 + y + y +} + +let z = base * 2 +let topSibling = if z < 0 { + let \"z$1" = z * 10 + \"z$1" + \"z$1" +} else { + let z = z + z2 + z + z +} + +let fnShadow = w => { + let w = w + w1 + w + w +} + +describe(__MODULE__, () => { + test("shadowed names do not collide with $ identifiers", () => { + eq(__LOC__, paramCollision(1, v => v * 10), 30) + eq(__LOC__, laterBinding(1), (2, 20, 2, 20)) + eq(__LOC__, earlierBinding(1), (2, 10, 2, 10)) + eq(__LOC__, nested(1), (3, (2, 20, 2, 20), 3)) + }) + + test("shadowed names do not capture raw JS names", () => { + eq(__LOC__, topShadow, 204) + eq(__LOC__, topSibling, 404) + eq(__LOC__, fnShadow(1), 602) + }) +})