From f0c8e7ae47693d92ff11167aee394345b40c98fe Mon Sep 17 00:00:00 2001 From: mununki Date: Tue, 10 Nov 2026 00:06:48 +0900 Subject: [PATCH 1/2] Bind elements and inlined arguments read from assigned variables MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Why: A local ref that does not escape compiles to a JavaScript variable that is assigned with `=`, and a `@val` external reads a JS global that JS code may assign. Two JS passes replace a read of a value taken from such a variable with a read of the variable itself, which gives the value of a later assignment (#9227). Js_pass_flatten_and_mark_dead replaces `t[i]` and `t.field` of an immutable tuple, record or constructor with two or more elements by the element when it is a variable, and binds the other elements before the block, so such a variable was also read after the call of a later element. Js_pass_tailcall_inline replaces a parameter of a function inlined at a tail call by its variable argument; since #8617 turns a ref captured by a closure into a variable too, that argument can be a ref that the body assigns. Js_pass_record_rest then read a field of such an argument after the assignment from the rest pattern's destructured fields. Both passes now bind an element or argument that is a variable some `Lassign` assigns (`Lam_stats.assignable`) or a JS global, as they bind other expressions. That is the rule Lam_compile.delay_safe applies to a variable so as not to delay reading it, now shared by the three as `Js_analyzer.var_may_change`; other variables are still read in place. JS modified (tuple and record elements): Example: type point = {x: int, label: string} let f = y => { let x = ref(1) let t = (x.contents, y) x := 2 let (a, b) = t a + b } let g = label => { let x = ref(1) let p = {x: x.contents, label} x := 2 (p.x, p.label) } Before (js): f(10) returns 12, g("p") returns [2, "p"] function f(y) { let x = 1; x = 2; return x + y | 0; } function g(label) { let x = 1; x = 2; return [ x, label ]; } After (js): f(10) returns 11, g("p") returns [1, "p"]; y and label are still read in place function f(y) { let x = 1; let t_0 = x; x = 2; return t_0 + y | 0; } function g(label) { let x = 1; let p_x = x; x = 2; return [ p_x, label ]; } JS modified (tuple elements read in closures): Example: let snapshots = () => { let i = ref(0) let out = [] while i.contents < 3 { let pair = (i.contents, "x") out->Array.push(() => { let (n, _) = pair n }) i := i.contents + 1 } out->Array.map(get => get()) } Before (js): snapshots() returns [3, 3, 3] while (i < 3) { out.push(() => i); i = i + 1 | 0; }; After (js): snapshots() returns [0, 1, 2] while (i < 3) { let pair_0 = i; out.push(() => pair_0); i = i + 1 | 0; }; JS modified (an element before a call): Example: let f = () => { let x = ref(1) let bump = () => { x := x.contents + 1 x.contents * 10 } let t = (x.contents, bump()) let (a, b) = t a + b } Before (js): f() returns 22, x is read after bump() let t_1 = bump(); return x + t_1 | 0; After (js): f() returns 21 let t_0 = x; let t_1 = bump(); return t_0 + t_1 | 0; JS modified (arguments of a function inlined at a tail call): Example: let run = step => { let count = ref(0) let bump = (before, by) => { count := count.contents + by (before, count.contents) } bump(count.contents, step) } Before (js): run(3) returns [3, 3] function run(step) { let count = 0; count = count + step | 0; return [ count, count ]; } After (js): run(3) returns [0, 3]; step still replaces by function run(step) { let count = 0; let before = count; count = count + step | 0; return [ before, count ]; } JS modified (a rest pattern parameter of an inlined function): Example: type config = {name: string, version: string, debug: bool} type restConfig = {version: string, debug: bool} let replace = () => { let c = ref({name: "a", version: "1", debug: true}) let k = ({name: _, ...restConfig as rest}: config) => { c := {name: "b", version: "2", debug: false} (rest.version, c.contents.name) } k(c.contents) } Before (js): replace() returns ["1", "a"]; Js_pass_record_rest read c.name from the rest pattern let {name, ...rest} = c; c = { name: "b", version: "2", debug: false }; return [ rest.version, name ]; After (js): replace() returns ["1", "b"] let param = c; let {name: __unused0, ...rest} = param; c = { name: "b", version: "2", debug: false }; return [ rest.version, c.name ]; JS modified (JS globals): Example: @val external counter: int = "counter" @val external bump: unit => unit = "bump" let saved = () => { let t = (counter, "b") bump() let (a, _) = t a } let report = () => { let show = before => { bump() (before, counter) } show(counter) } Before (js): with counter 1 and bump incrementing it, saved() returns 2, then report() returns [3, 3] function saved() { bump(); return counter; } function report() { bump(); return [ counter, counter ]; } After (js): saved() returns 1, then report() returns [2, 3] function saved() { let t_0 = counter; bump(); return t_0; } function report() { let before = counter; bump(); return [ before, counter ]; } JS modified (correct programs that get a binding): Example: type item = {id: int, name: string} let single = n => { let id = ref(0) let out = [] for _ in 1 to n { let item = {id: id.contents, name: "x"} out->Array.push(item) id := id.contents + 1 } out } let afterLoop = () => { let i = ref(0) while i.contents < 10 { i := i.contents + 1 } let report = n => { Console.log("report") Console.log(n) n * 2 } report(i.contents) } Before (js): no assignment comes between the element or argument and its read let item = { id: id, name: "x" }; … console.log("report"); console.log(i); return (i << 1); After (js): the same results, with a binding let item_id = id; let item = { id: item_id, name: "x" }; … let n = i; console.log("report"); console.log(n); return (n << 1); Review: Why `Lam_stats.assignable` and JS globals, and not every variable that the JS assigns? Binding every variable that the JS assigns changed inline_condition_with_pattern_matching.mjs and mario_game.mjs, whose output was correct. The JS assigns switch results, static-catch bindings, exit variables and the temporaries of `&&` and `||` only before reading them, and reads the parameter `_x` of a tail-recursive loop only through the `let x = _x` of each iteration. A `for` index that Lam_compile.compile_for declares before the loop (`let i = e; for (; i <= n; ++i)`) changes between iterations, so a closure that captures it reads the last value, with or without these passes; that is a bug of compile_for, left to a separate change. With `Js_analyzer.var_may_change` no checked-in output changes, and the set is already computed, so the fix adds no traversal. Review: Why bind the element instead of keeping `t[i]`? Keeping `t[i]` would keep the block alive and would still read the element after the call of a later element, which is bound before the block. With the binding the block is still dead when every use is a read like `t[i]`, as with other expressions. A block that stays alive, like a variant matched with `typeof`, keeps the binding next to it (`let v_0 = x; let v = {TAG: "Pair", _0: v_0, ...}`), as it does for other expressions. Review: Does a correct program get longer output? Yes, when the element or argument is such a variable but no assignment comes between, as in the last block: an element of a block that escapes gets a binding, as an element that is a call already does, and so does an argument that the inlined body does not assign. Telling these cases apart needs to know where the variable is assigned, closures included, which is a new analysis; no checked-in output changes. Review: Do other JS passes substitute the same way? Js_pass_record_rest replaces `source.label` after a record rest pattern by the destructured field, and a rest pattern rejects mutable fields. Its source is the `match` variable Lambda binds to the matched value or a parameter, and before this commit Js_pass_tailcall_inline could replace such a parameter by an assigned variable (the rest pattern block); with the argument bound, nothing assigns the source. Js_pass_scope, Js_pass_get_used and Js_shake only analyze or remove code, and Js_pass_flatten and Js_pass_external_shadow only restructure statements or qualify globals. Review: Does cross-module inlining add assigned variables that the set misses? With the experimental -bs-cross-module-opt, Lam_compile adds the variables an inlined body assigns only to the stats it compiles that body with; the functions with an assigned ref that were tried fail earlier, in Lam_dce, as they did before this commit, so this path is left as it is. Signed-off-by: mununki --- ...ind-assigned-variables-in-js-passes.fix.md | 1 + compiler/core/js_analyzer.ml | 3 + compiler/core/js_analyzer.mli | 7 + .../core/js_pass_flatten_and_mark_dead.ml | 22 +- .../core/js_pass_flatten_and_mark_dead.mli | 6 +- compiler/core/js_pass_tailcall_inline.ml | 27 +- compiler/core/js_pass_tailcall_inline.mli | 5 +- compiler/core/lam_compile.ml | 3 +- compiler/core/lam_compile_main.ml | 7 +- compiler/core/lam_stats.ml | 3 +- compiler/core/lam_stats.mli | 3 +- .../tests/src/assigned_variable_read_test.mjs | 242 ++++++++++++++++++ .../tests/src/assigned_variable_read_test.res | 188 ++++++++++++++ 13 files changed, 495 insertions(+), 22 deletions(-) create mode 100644 changes/bind-assigned-variables-in-js-passes.fix.md create mode 100644 tests/tests/src/assigned_variable_read_test.mjs create mode 100644 tests/tests/src/assigned_variable_read_test.res diff --git a/changes/bind-assigned-variables-in-js-passes.fix.md b/changes/bind-assigned-variables-in-js-passes.fix.md new file mode 100644 index 00000000000..1ba0481162b --- /dev/null +++ b/changes/bind-assigned-variables-in-js-passes.fix.md @@ -0,0 +1 @@ +- Fix a value read from a ref or `@val` global into a tuple, record or variant, or passed to a local function, changing when the ref or global is assigned later. diff --git a/compiler/core/js_analyzer.ml b/compiler/core/js_analyzer.ml index 85f46a68a8a..c7633e38dd2 100644 --- a/compiler/core/js_analyzer.ml +++ b/compiler/core/js_analyzer.ml @@ -99,6 +99,9 @@ let is_array_function (e : J.expression) = Ext_ident.is_js ident | _ -> false +let var_may_change ~assignable (id : Ident.t) = + Ext_ident.is_js id || Set_ident.mem id assignable + let rec no_side_effect_expression_desc (x : J.expression_desc) = match x with | Undefined _ | Null | Bool _ | Var _ -> true diff --git a/compiler/core/js_analyzer.mli b/compiler/core/js_analyzer.mli index 281ec6c4127..a82450cb551 100644 --- a/compiler/core/js_analyzer.mli +++ b/compiler/core/js_analyzer.mli @@ -33,6 +33,13 @@ val free_variables_of_expression : J.expression -> Set_ident.t val is_array_function : J.expression -> bool +val var_may_change : assignable:Set_ident.t -> Ident.t -> bool +(** Whether reading the variable [id] after other code may give another value + than reading it now: [id] is a JS global, such as a [@val] external, which + JS code may assign, or one of [assignable], the local variables some + [Lassign] assigns (see [Lam_stats.assignable]), which the other code or a + closure it calls may assign. *) + (* val no_side_effect_expression_desc : J.expression_desc -> bool *) diff --git a/compiler/core/js_pass_flatten_and_mark_dead.ml b/compiler/core/js_pass_flatten_and_mark_dead.ml index b647e20ac62..d347ed8b768 100644 --- a/compiler/core/js_pass_flatten_and_mark_dead.ml +++ b/compiler/core/js_pass_flatten_and_mark_dead.ml @@ -171,7 +171,15 @@ let super = Js_record_map.super let add_substitue substitution (ident : Ident.t) (e : J.expression) = Hash_ident.replace substitution ident e -let subst_map (substitution : J.expression Hash_ident.t) = +(* Whether [e] is a variable that may hold another value when it is read + later, see [Js_analyzer.var_may_change]. *) +let is_changing_var ~assignable (e : J.expression) = + match e.expression_desc with + | Var (Id id) -> Js_analyzer.var_may_change ~assignable id + | _ -> false + +let subst_map (assignable : Set_ident.t) + (substitution : J.expression Hash_ident.t) = { super with statement = @@ -208,8 +216,14 @@ let subst_map (substitution : J.expression Hash_ident.t) = Ext_list.fold_left ls (0, [], []) (fun (i, e, acc) x -> match x.expression_desc with | Var _ | Number _ | Str _ | Template_literal _ | J.Bool _ - | Undefined _ -> + | Undefined _ + when not (is_changing_var ~assignable x) -> (* TODO: check the optimization *) + (* The element stays in the block, and [expression] below + replaces a later [ident[i]] with it. A JS global or a + variable in [assignable] is bound like other expressions + instead: by the time of that read, an assignment may have + changed it. *) (i + 1, x :: e, acc) | _ -> (* tradeoff, @@ -306,8 +320,8 @@ let subst_map (substitution : J.expression Hash_ident.t) = there is no need to add another pass *) -let program (js : J.program) = - let obj = subst_map (Hash_ident.create 32) in +let program ~assignable (js : J.program) = + let obj = subst_map assignable (Hash_ident.create 32) in let js = obj.program obj js in mark_dead_code js (* |> mark_dead_code *) diff --git a/compiler/core/js_pass_flatten_and_mark_dead.mli b/compiler/core/js_pass_flatten_and_mark_dead.mli index b05a7326862..03300f8ddd4 100644 --- a/compiler/core/js_pass_flatten_and_mark_dead.mli +++ b/compiler/core/js_pass_flatten_and_mark_dead.mli @@ -24,4 +24,8 @@ (** A pass to mark some declarations in JS IR as dead code *) -val program : J.program -> J.program +val program : assignable:Set_ident.t -> J.program -> J.program +(** [assignable] are the variables some [Lassign] assigns, see + [Lam_stats.assignable]. An element of a block that is one of them or a JS + global is bound before the block instead of replacing a later read of the + block's field. *) diff --git a/compiler/core/js_pass_tailcall_inline.ml b/compiler/core/js_pass_tailcall_inline.ml index ca54be32c3a..41fd4fdc03b 100644 --- a/compiler/core/js_pass_tailcall_inline.ml +++ b/compiler/core/js_pass_tailcall_inline.ml @@ -53,7 +53,10 @@ let rec substituted_truth (consts : J.expression Map_ident.t) (e : J.expression) (* [vars] maps a parameter to the variable argument that replaces it, [consts] to the constant argument that replaces it. Both apply only to parameters - that are never assigned, so every occurrence of such a parameter is a read. + that are never assigned, so every occurrence of such a parameter is a read, + and [vars] only to variables for which [Js_analyzer.var_may_change] is + false (see [inline_call]), so reading one in place of the parameter gives + the value it had at the call. A conditional whose condition becomes a constant keeps only the branch it takes, and the negation of such a condition becomes a boolean. *) let substitute_arguments (vars : Ident.t Map_ident.t) @@ -117,11 +120,17 @@ let is_substitutable_constant (e : J.expression) = if it is substitued, the assignment will align the value which is incorrect *) -let inline_call (immutable_list : bool list) params (args : J.expression list) - processed_blocks = +(* [assignable] are the variables some [Lassign] assigns, see + [Lam_stats.assignable]. An argument that is one of them or a JS global + ([Js_analyzer.var_may_change]) is bound like other expressions: where the + inlined body reads the parameter, the variable may already hold a value + that the body, a function it calls or a later assignment stored. *) +let inline_call (assignable : Set_ident.t) (immutable_list : bool list) params + (args : J.expression list) processed_blocks = let substitute param (arg : J.expression) (vars, consts, acc) = match arg.expression_desc with - | Var (Id id) -> (Map_ident.add param id vars, consts, acc) + | Var (Id id) when not (Js_analyzer.var_may_change ~assignable id) -> + (Map_ident.add param id vars, consts, acc) | _ when is_substitutable_constant arg -> (vars, Map_ident.add param arg consts, acc) | _ -> (vars, consts, S.define_variable ~kind:Variable param arg :: acc) @@ -170,7 +179,7 @@ let inline_call (immutable_list : bool list) params (args : J.expression list) *) let super = Js_record_map.super -let subst (export_set : Set_ident.t) stats = +let subst (export_set : Set_ident.t) (assignable : Set_ident.t) stats = { super with statement = @@ -254,7 +263,7 @@ let subst (export_set : Set_ident.t) stats = self.block self body (* see #278 before changes*) in - inline_call no_tailcall params args processed_blocks + inline_call assignable no_tailcall params args processed_blocks (* Ext_list.fold_right2 params args processed_blocks (fun param arg acc -> @@ -293,13 +302,13 @@ let subst (export_set : Set_ident.t) stats = self.block self body (* see #278 before changes*) in - inline_call no_tailcall params args processed_blocks + inline_call assignable no_tailcall params args processed_blocks | x :: xs -> self.statement self x :: self.block self xs | [] -> []); } -let tailcall_inline (program : J.program) = +let tailcall_inline ~assignable (program : J.program) = let stats = Js_pass_get_used.get_stats program in let export_set = program.export_set in - let obj = subst export_set stats in + let obj = subst export_set assignable stats in obj.program obj program diff --git a/compiler/core/js_pass_tailcall_inline.mli b/compiler/core/js_pass_tailcall_inline.mli index 207a90efe61..4017b8a04dc 100644 --- a/compiler/core/js_pass_tailcall_inline.mli +++ b/compiler/core/js_pass_tailcall_inline.mli @@ -35,4 +35,7 @@ ]} *) -val tailcall_inline : J.program -> J.program +val tailcall_inline : assignable:Set_ident.t -> J.program -> J.program +(** [assignable] are the variables some [Lassign] assigns, see + [Lam_stats.assignable]. An argument that is one of them or a JS global is + bound to the parameter instead of replacing it in the inlined body. *) diff --git a/compiler/core/lam_compile.ml b/compiler/core/lam_compile.ml index f4841957cba..a0d1c570dcb 100644 --- a/compiler/core/lam_compile.ml +++ b/compiler/core/lam_compile.ml @@ -250,8 +250,7 @@ let rec delay_safe ~assignable (e : J.expression) = | Json_literal _ | Fun _ | Var (Qualified _) -> true - | Var (Id id) -> - (not (Ext_ident.is_js id)) && not (Set_ident.mem id assignable) + | Var (Id id) -> not (Js_analyzer.var_may_change ~assignable id) | Bin (Eq, _, _) -> false | Bin (_, a, b) -> Js_analyzer.no_side_effect_expression e diff --git a/compiler/core/lam_compile_main.ml b/compiler/core/lam_compile_main.ml index e5f925a0030..678fd56a0e1 100644 --- a/compiler/core/lam_compile_main.ml +++ b/compiler/core/lam_compile_main.ml @@ -406,9 +406,10 @@ let compile ?on_optimized_lambda (output_prefix : string) let js : J.program = {exports = meta_exports; export_set; block = body} in js |> j "initial" |> Js_pass_flatten.program |> j "flatten" |> Js_pass_external_shadow.program |> j "external_shadow" - |> Js_pass_tailcall_inline.tailcall_inline |> j "inline_and_shake" - |> Js_pass_record_rest.program |> j "record_rest" - |> Js_pass_flatten_and_mark_dead.program |> j "flatten_and_mark_dead" + |> Js_pass_tailcall_inline.tailcall_inline ~assignable:meta.assignable + |> j "inline_and_shake" |> Js_pass_record_rest.program |> j "record_rest" + |> Js_pass_flatten_and_mark_dead.program ~assignable:meta.assignable + |> j "flatten_and_mark_dead" |> (fun js -> ignore @@ Js_pass_scope.program js; js) diff --git a/compiler/core/lam_stats.ml b/compiler/core/lam_stats.ml index bb1c77916db..aa150bb2f50 100644 --- a/compiler/core/lam_stats.ml +++ b/compiler/core/lam_stats.ml @@ -49,7 +49,8 @@ type t = { awaited_units: Set_ident.t; assignable: Set_ident.t; (** The variables some [Lassign] assigns. [Lam_compile] never delays - reading one of them past other code. *) + reading one of them past other code, and neither do + [Js_pass_tailcall_inline] and [Js_pass_flatten_and_mark_dead]. *) } let pp = Format.fprintf diff --git a/compiler/core/lam_stats.mli b/compiler/core/lam_stats.mli index a7f53fe32f4..761c8a1bbb0 100644 --- a/compiler/core/lam_stats.mli +++ b/compiler/core/lam_stats.mli @@ -42,7 +42,8 @@ type t = { them use the flat exports too. *) assignable: Set_ident.t; (** The variables some [Lassign] assigns. [Lam_compile] never delays - reading one of them past other code. *) + reading one of them past other code, and neither do + [Js_pass_tailcall_inline] and [Js_pass_flatten_and_mark_dead]. *) } val print : Format.formatter -> t -> unit diff --git a/tests/tests/src/assigned_variable_read_test.mjs b/tests/tests/src/assigned_variable_read_test.mjs new file mode 100644 index 00000000000..49869e8f944 --- /dev/null +++ b/tests/tests/src/assigned_variable_read_test.mjs @@ -0,0 +1,242 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Mocha from "mocha"; +import * as Test_utils from "./test_utils.mjs"; + +globalThis.assignedVariableReadCounter = 0 +; + +let setGlobalCounter = (n => { globalThis.assignedVariableReadCounter = n }); + +function tuple(y) { + let x = 1; + let t_0 = x; + x = 2; + return [ + t_0, + y, + x + ]; +} + +function record(label) { + let x = 1; + let p_x = x; + x = 2; + return [ + p_x, + label, + x + ]; +} + +function variant() { + let x = 1; + let v_0 = x; + let v = { + TAG: "Pair", + _0: v_0, + _1: "b" + }; + x = 2; + if (typeof v !== "object") { + return [ + 0, + x + ]; + } else { + return [ + v_0, + x + ]; + } +} + +function elementThenCall() { + let x = 1; + let bump = () => { + x = x + 1 | 0; + return x * 10 | 0; + }; + let t_0 = x; + let t_1 = bump(); + return [ + t_0, + t_1, + x + ]; +} + +function closuresInLoop() { + let i = 0; + let out = []; + while (i < 3) { + let pair_0 = i; + out.push(() => pair_0); + i = i + 1 | 0; + }; + return out.map(get => get()); +} + +function inlinedCall(step) { + let count = 0; + let before = count; + count = count + step | 0; + return [ + before, + count + ]; +} + +function inlinedCallThroughFunction() { + let count = 0; + let incr = () => { + count = count + 1 | 0; + }; + let before = count; + incr(); + return [ + before, + count + ]; +} + +function argumentThenCall() { + let count = 0; + let bumpAndGet = () => { + count = count + 1 | 0; + return count * 10 | 0; + }; + let before = count; + let after = bumpAndGet(); + return [ + before, + after, + count + ]; +} + +function inlinedRestPattern() { + let c = { + name: "a", + version: "1", + debug: true + }; + let param = c; + let {name: __unused0, ...rest} = param; + c = { + name: "b", + version: "2", + debug: false + }; + return [ + rest.version, + c.name + ]; +} + +function globalTuple() { + setGlobalCounter(1); + let t_0 = assignedVariableReadCounter; + setGlobalCounter(2); + return [ + t_0, + assignedVariableReadCounter + ]; +} + +function globalInlinedCall() { + setGlobalCounter(0); + let before = assignedVariableReadCounter; + setGlobalCounter(assignedVariableReadCounter + 1 | 0); + return [ + before, + assignedVariableReadCounter + ]; +} + +let topLevelRef = 1; + +let topLevelPair_0 = topLevelRef; + +topLevelRef = 2; + +function topLevel() { + return [ + topLevelPair_0, + topLevelRef + ]; +} + +Mocha.describe("Assigned_variable_read_test", () => { + Mocha.test("a tuple element read from a ref", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 142, characters 7-14", [ + 1, + 5, + 2 + ], tuple(5))); + Mocha.test("a record field read from a ref", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 146, characters 7-14", [ + 1, + "p", + 2 + ], record("p"))); + Mocha.test("a constructor payload read from a ref", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 150, characters 7-14", [ + 1, + 2 + ], variant())); + Mocha.test("a tuple element read from a ref before a call that assigns the ref", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 154, characters 7-14", [ + 1, + 20, + 2 + ], elementThenCall())); + Mocha.test("tuple elements read from a ref by closures created in a loop", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 158, characters 7-14", [ + 0, + 1, + 2 + ], closuresInLoop())); + Mocha.test("an argument read from a ref that the inlined body assigns", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 162, characters 7-14", [ + 0, + 3 + ], inlinedCall(3))); + Mocha.test("an argument read from a ref that a function called in the inlined body assigns", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 166, characters 7-14", [ + 0, + 1 + ], inlinedCallThroughFunction())); + Mocha.test("an argument read from a ref before a later argument's call assigns it", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 170, characters 7-14", [ + 0, + 10, + 1 + ], argumentThenCall())); + Mocha.test("a field of a rest pattern parameter whose argument is read from a ref", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 174, characters 7-14", [ + "1", + "b" + ], inlinedRestPattern())); + Mocha.test("a tuple element read from a JS global", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 178, characters 7-14", [ + 1, + 2 + ], globalTuple())); + Mocha.test("an argument read from a JS global that the inlined body assigns", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 182, characters 7-14", [ + 0, + 1 + ], globalInlinedCall())); + Mocha.test("a tuple element read from a top-level ref", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 186, characters 7-14", [ + 1, + 2 + ], topLevel())); +}); + +export { + setGlobalCounter, + tuple, + record, + variant, + elementThenCall, + closuresInLoop, + inlinedCall, + inlinedCallThroughFunction, + argumentThenCall, + inlinedRestPattern, + globalTuple, + globalInlinedCall, + topLevel, +} +/* Not a pure module */ diff --git a/tests/tests/src/assigned_variable_read_test.res b/tests/tests/src/assigned_variable_read_test.res new file mode 100644 index 00000000000..38ac13caf61 --- /dev/null +++ b/tests/tests/src/assigned_variable_read_test.res @@ -0,0 +1,188 @@ +open Mocha +open Test_utils + +// A local ref that does not escape compiles to a JS variable that is assigned +// with `=`. A value read from it and stored in a tuple, record or variant, or +// passed to a local function that gets inlined, keeps the value it had then: +// the generated JS binds it to a new variable instead of reading the ref's +// variable again. The same holds for a JS global read through a @val +// external, which JS code may assign. An element or argument that is a +// variable no assignment changes, such as `y`, `label` or `step` below, is +// still read in place, and the checked-in JS shows it without a new binding. + +type point = {x: int, label: string} + +type pair = Pair(int, string) | Empty + +type config = {name: string, version: string, debug: bool} + +type restConfig = {version: string, debug: bool} + +%%raw(`globalThis.assignedVariableReadCounter = 0`) + +@val external globalCounter: int = "assignedVariableReadCounter" +let setGlobalCounter: int => unit = %raw(`n => { globalThis.assignedVariableReadCounter = n }`) + +let tuple = y => { + let x = ref(1) + let t = (x.contents, y) + x := 2 + let (a, b) = t + (a, b, x.contents) +} + +let record = label => { + let x = ref(1) + let p = {x: x.contents, label} + x := 2 + (p.x, p.label, x.contents) +} + +let variant = () => { + let x = ref(1) + let v = Pair(x.contents, "b") + x := 2 + switch v { + | Pair(a, _) => (a, x.contents) + | Empty => (0, x.contents) + } +} + +let elementThenCall = () => { + let x = ref(1) + let bump = () => { + x := x.contents + 1 + x.contents * 10 + } + let t = (x.contents, bump()) + let (a, b) = t + (a, b, x.contents) +} + +let closuresInLoop = () => { + let i = ref(0) + let out = [] + while i.contents < 3 { + let pair = (i.contents, "x") + out->Array.push(() => { + let (n, _) = pair + n + }) + i := i.contents + 1 + } + out->Array.map(get => get()) +} + +let inlinedCall = step => { + let count = ref(0) + let bump = (before, by) => { + count := count.contents + by + (before, count.contents) + } + bump(count.contents, step) +} + +let inlinedCallThroughFunction = () => { + let count = ref(0) + let incr = () => count := count.contents + 1 + let report = before => { + incr() + (before, count.contents) + } + report(count.contents) +} + +let argumentThenCall = () => { + let count = ref(0) + let bumpAndGet = () => { + count := count.contents + 1 + count.contents * 10 + } + let report = (before, after) => (before, after, count.contents) + report(count.contents, bumpAndGet()) +} + +let inlinedRestPattern = () => { + let c = ref({name: "a", version: "1", debug: true}) + let replace = ({name: _, ...restConfig as rest}: config) => { + c := {name: "b", version: "2", debug: false} + (rest.version, c.contents.name) + } + replace(c.contents) +} + +let globalTuple = () => { + setGlobalCounter(1) + let t = (globalCounter, "b") + setGlobalCounter(2) + let (a, _) = t + (a, globalCounter) +} + +let globalInlinedCall = () => { + setGlobalCounter(0) + let report = before => { + setGlobalCounter(globalCounter + 1) + (before, globalCounter) + } + report(globalCounter) +} + +%%private(let topLevelRef = ref(1)) +%%private(let topLevelPair = (topLevelRef.contents, "b")) +let () = topLevelRef := 2 + +let topLevel = () => { + let (a, _) = topLevelPair + (a, topLevelRef.contents) +} + +describe(__MODULE__, () => { + test("a tuple element read from a ref", () => { + eq(__LOC__, (1, 5, 2), tuple(5)) + }) + + test("a record field read from a ref", () => { + eq(__LOC__, (1, "p", 2), record("p")) + }) + + test("a constructor payload read from a ref", () => { + eq(__LOC__, (1, 2), variant()) + }) + + test("a tuple element read from a ref before a call that assigns the ref", () => { + eq(__LOC__, (1, 20, 2), elementThenCall()) + }) + + test("tuple elements read from a ref by closures created in a loop", () => { + eq(__LOC__, [0, 1, 2], closuresInLoop()) + }) + + test("an argument read from a ref that the inlined body assigns", () => { + eq(__LOC__, (0, 3), inlinedCall(3)) + }) + + test("an argument read from a ref that a function called in the inlined body assigns", () => { + eq(__LOC__, (0, 1), inlinedCallThroughFunction()) + }) + + test("an argument read from a ref before a later argument's call assigns it", () => { + eq(__LOC__, (0, 10, 1), argumentThenCall()) + }) + + test("a field of a rest pattern parameter whose argument is read from a ref", () => { + eq(__LOC__, ("1", "b"), inlinedRestPattern()) + }) + + test("a tuple element read from a JS global", () => { + eq(__LOC__, (1, 2), globalTuple()) + }) + + test("an argument read from a JS global that the inlined body assigns", () => { + eq(__LOC__, (0, 1), globalInlinedCall()) + }) + + test("a tuple element read from a top-level ref", () => { + eq(__LOC__, (1, 2), topLevel()) + }) +}) From 5b097c02a394ed6b5febcf901a15ee01419286d5 Mon Sep 17 00:00:00 2001 From: mununki Date: Wed, 11 Nov 2026 02:30:37 +0900 Subject: [PATCH 2/2] Protect JS globals from the bindings that later passes add Why: `Js_pass_external_shadow` reads a JS global `x` through `globalThis.x` where a binding printed as `x` is in scope. It ran before `Js_pass_tailcall_inline` and `Js_pass_flatten_and_mark_dead`, which add bindings of their own: the elements of a block and the arguments of an inlined function. One of those could capture the global it reads. A top-level tuple whose element reads a global named like the element's variable, `t_0`, compiled to `let t_0 = t_0;`, which throws a `ReferenceError` when the module loads. The previous commit binds such an element; before it, an element that is an expression did the same, as `let t_0 = t_0 + 1 | 0;`. Inside a function the printer renames the binding, since it reserves the names the function refers to. The pass now runs after the two passes. They put the bindings they add in a `Block` statement, which is printed without braces, so the pass also collects the declarations of a nested `Block`. JS modified (global named like the variable of an element): Example: @val external tZero: int = "t_0" let setTZero: int => unit = %raw(`n => { globalThis.t_0 = n }`) let () = setTZero(1) %%private(let t = (tZero, "b")) let () = setTZero(2) let globalNamedLikeElement = () => { let (a, _) = t (a, tZero) } Before (js): setTZero(1); let t_0 = t_0; setTZero(2); function globalNamedLikeElement() { return [ t_0, t_0 ]; } After (js): setTZero(1); let t_0 = globalThis.t_0; setTZero(2); function globalNamedLikeElement() { return [ t_0, globalThis.t_0 ]; } Review: Does running the pass later change other output? No checked-in output changes besides the new test. The pass decides by the name a binding is printed with before the printer renames it, so where the printer would rename a binding inside a function, the global is now read through `globalThis` as well. Review: Why look into nested `Block` statements? At its old place the pass ran right after `Js_pass_flatten`, which splices nested blocks into their parent, so a block's declarations were all at its top level. `Js_pass_flatten_and_mark_dead` returns the bindings it adds as a `Block`, and `Js_dump` prints a `Block` without braces. Review: Why no changelog entry? A global named like a generated variable, such as `t_0`, is rare, and the entry for the previous commit covers the bindings this protects. Signed-off-by: mununki --- compiler/core/js_pass_external_shadow.ml | 6 ++- compiler/core/lam_compile_main.ml | 5 ++- .../tests/src/assigned_variable_read_test.mjs | 45 ++++++++++++++----- .../tests/src/assigned_variable_read_test.res | 17 +++++++ 4 files changed, 58 insertions(+), 15 deletions(-) diff --git a/compiler/core/js_pass_external_shadow.ml b/compiler/core/js_pass_external_shadow.ml index 7bb44e83d5c..95cc08789a3 100644 --- a/compiler/core/js_pass_external_shadow.ml +++ b/compiler/core/js_pass_external_shadow.ml @@ -39,11 +39,13 @@ let add_binding (ident : Ident.t) names = else String_set.add (Ext_ident.convert ident.name) names (* A JS [let], [const] or function declaration is in scope in its whole block, - including before the declaration. *) -let add_declarations (block : J.block) names = + including before the declaration. A [Block] statement is printed without + braces, so its declarations are in the enclosing block. *) +let rec add_declarations (block : J.block) names = Ext_list.fold_left block names (fun acc (st : J.statement) -> match st.statement_desc with | Variable {ident} -> add_binding ident acc + | Block block -> add_declarations block acc | _ -> acc) (* The cases of a switch are printed without braces, so they share one scope. *) diff --git a/compiler/core/lam_compile_main.ml b/compiler/core/lam_compile_main.ml index 678fd56a0e1..e565e53f073 100644 --- a/compiler/core/lam_compile_main.ml +++ b/compiler/core/lam_compile_main.ml @@ -405,11 +405,14 @@ let compile ?on_optimized_lambda (output_prefix : string) let export_set = Set_ident.of_list meta_exports in let js : J.program = {exports = meta_exports; export_set; block = body} in js |> j "initial" |> Js_pass_flatten.program |> j "flatten" - |> Js_pass_external_shadow.program |> j "external_shadow" |> Js_pass_tailcall_inline.tailcall_inline ~assignable:meta.assignable |> j "inline_and_shake" |> Js_pass_record_rest.program |> j "record_rest" |> Js_pass_flatten_and_mark_dead.program ~assignable:meta.assignable |> j "flatten_and_mark_dead" + (* After the passes that add bindings, so that a JS global read in one of + them, as in [let t_0 = t_0], is not captured by the binding *) + |> Js_pass_external_shadow.program + |> j "external_shadow" |> (fun js -> ignore @@ Js_pass_scope.program js; js) diff --git a/tests/tests/src/assigned_variable_read_test.mjs b/tests/tests/src/assigned_variable_read_test.mjs index 49869e8f944..cea068dc8c7 100644 --- a/tests/tests/src/assigned_variable_read_test.mjs +++ b/tests/tests/src/assigned_variable_read_test.mjs @@ -168,60 +168,79 @@ function topLevel() { ]; } +let setTZero = (n => { globalThis.t_0 = n }); + +setTZero(1); + +let t_0 = globalThis.t_0; + +setTZero(2); + +function globalNamedLikeElement() { + return [ + t_0, + globalThis.t_0 + ]; +} + Mocha.describe("Assigned_variable_read_test", () => { - Mocha.test("a tuple element read from a ref", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 142, characters 7-14", [ + Mocha.test("a tuple element read from a ref", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 155, characters 7-14", [ 1, 5, 2 ], tuple(5))); - Mocha.test("a record field read from a ref", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 146, characters 7-14", [ + Mocha.test("a record field read from a ref", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 159, characters 7-14", [ 1, "p", 2 ], record("p"))); - Mocha.test("a constructor payload read from a ref", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 150, characters 7-14", [ + Mocha.test("a constructor payload read from a ref", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 163, characters 7-14", [ 1, 2 ], variant())); - Mocha.test("a tuple element read from a ref before a call that assigns the ref", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 154, characters 7-14", [ + Mocha.test("a tuple element read from a ref before a call that assigns the ref", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 167, characters 7-14", [ 1, 20, 2 ], elementThenCall())); - Mocha.test("tuple elements read from a ref by closures created in a loop", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 158, characters 7-14", [ + Mocha.test("tuple elements read from a ref by closures created in a loop", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 171, characters 7-14", [ 0, 1, 2 ], closuresInLoop())); - Mocha.test("an argument read from a ref that the inlined body assigns", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 162, characters 7-14", [ + Mocha.test("an argument read from a ref that the inlined body assigns", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 175, characters 7-14", [ 0, 3 ], inlinedCall(3))); - Mocha.test("an argument read from a ref that a function called in the inlined body assigns", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 166, characters 7-14", [ + Mocha.test("an argument read from a ref that a function called in the inlined body assigns", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 179, characters 7-14", [ 0, 1 ], inlinedCallThroughFunction())); - Mocha.test("an argument read from a ref before a later argument's call assigns it", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 170, characters 7-14", [ + Mocha.test("an argument read from a ref before a later argument's call assigns it", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 183, characters 7-14", [ 0, 10, 1 ], argumentThenCall())); - Mocha.test("a field of a rest pattern parameter whose argument is read from a ref", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 174, characters 7-14", [ + Mocha.test("a field of a rest pattern parameter whose argument is read from a ref", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 187, characters 7-14", [ "1", "b" ], inlinedRestPattern())); - Mocha.test("a tuple element read from a JS global", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 178, characters 7-14", [ + Mocha.test("a tuple element read from a JS global", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 191, characters 7-14", [ 1, 2 ], globalTuple())); - Mocha.test("an argument read from a JS global that the inlined body assigns", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 182, characters 7-14", [ + Mocha.test("an argument read from a JS global that the inlined body assigns", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 195, characters 7-14", [ 0, 1 ], globalInlinedCall())); - Mocha.test("a tuple element read from a top-level ref", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 186, characters 7-14", [ + Mocha.test("a tuple element read from a top-level ref", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 199, characters 7-14", [ 1, 2 ], topLevel())); + Mocha.test("a tuple element read from a global named like its variable", () => Test_utils.eq("File \"assigned_variable_read_test.res\", line 203, characters 7-14", [ + 1, + 2 + ], globalNamedLikeElement())); }); export { @@ -238,5 +257,7 @@ export { globalTuple, globalInlinedCall, topLevel, + setTZero, + globalNamedLikeElement, } /* Not a pure module */ diff --git a/tests/tests/src/assigned_variable_read_test.res b/tests/tests/src/assigned_variable_read_test.res index 38ac13caf61..5c02f4d0b6d 100644 --- a/tests/tests/src/assigned_variable_read_test.res +++ b/tests/tests/src/assigned_variable_read_test.res @@ -137,6 +137,19 @@ let topLevel = () => { (a, topLevelRef.contents) } +// A JS global named like the variable that the element of [t] gets, [t_0]. +// The binding must not capture the global it reads. +@val external tZero: int = "t_0" +let setTZero: int => unit = %raw(`n => { globalThis.t_0 = n }`) +let () = setTZero(1) +%%private(let t = (tZero, "b")) +let () = setTZero(2) + +let globalNamedLikeElement = () => { + let (a, _) = t + (a, tZero) +} + describe(__MODULE__, () => { test("a tuple element read from a ref", () => { eq(__LOC__, (1, 5, 2), tuple(5)) @@ -185,4 +198,8 @@ describe(__MODULE__, () => { test("a tuple element read from a top-level ref", () => { eq(__LOC__, (1, 2), topLevel()) }) + + test("a tuple element read from a global named like its variable", () => { + eq(__LOC__, (1, 2), globalNamedLikeElement()) + }) })