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 0000000000..1ba0481162 --- /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 85f46a68a8..c7633e38dd 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 281ec6c412..a82450cb55 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_external_shadow.ml b/compiler/core/js_pass_external_shadow.ml index 7bb44e83d5..95cc08789a 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/js_pass_flatten_and_mark_dead.ml b/compiler/core/js_pass_flatten_and_mark_dead.ml index b647e20ac6..d347ed8b76 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 b05a732686..03300f8ddd 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 ca54be32c3..41fd4fdc03 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 207a90efe6..4017b8a04d 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 f4841957cb..a0d1c570dc 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 e5f925a003..e565e53f07 100644 --- a/compiler/core/lam_compile_main.ml +++ b/compiler/core/lam_compile_main.ml @@ -405,10 +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 |> 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" + (* 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/compiler/core/lam_stats.ml b/compiler/core/lam_stats.ml index bb1c77916d..aa150bb2f5 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 a7f53fe32f..761c8a1bbb 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 0000000000..cea068dc8c --- /dev/null +++ b/tests/tests/src/assigned_variable_read_test.mjs @@ -0,0 +1,263 @@ +// 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 + ]; +} + +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 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 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 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 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 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 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 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 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 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 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 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 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 { + setGlobalCounter, + tuple, + record, + variant, + elementThenCall, + closuresInLoop, + inlinedCall, + inlinedCallThroughFunction, + argumentThenCall, + inlinedRestPattern, + 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 new file mode 100644 index 0000000000..5c02f4d0b6 --- /dev/null +++ b/tests/tests/src/assigned_variable_read_test.res @@ -0,0 +1,205 @@ +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) +} + +// 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)) + }) + + 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()) + }) + + test("a tuple element read from a global named like its variable", () => { + eq(__LOC__, (1, 2), globalNamedLikeElement()) + }) +})