From 117aee30d59149a0c35d61d46d4d66047320c970 Mon Sep 17 00:00:00 2001 From: Rob Date: Wed, 25 Nov 2026 14:39:35 -0500 Subject: [PATCH 01/14] Evaluate the source of a record spread whose fields are all overridden Why: When a record literal with a spread writes every field, the type checker reports warning 23 and also dropped the spread's source from the typed tree, so a source with side effects, such as a call, never ran. The same held for JSX props spreads. The source now stays in the typed tree; the record is built from the written fields alone, after the source is evaluated. A source that is a variable is left out of the Lambda term, so the size of a function and the output stay as they were; the Lambda passes drop any other source without side effects. A module with side effects that a source is read from stays imported. Typedtree modified (Texp_record): Example: type t = {a: int, b: int} @val external f: unit => t = "f" let make = () => {...f(), a: 1, b: 2} Before (typed): expression Texp_record fields = [ "a" expression Texp_constant Const_int 1 "b" expression Texp_constant Const_int 2 ] representation = Record_regular extended_expression = None After (typed): expression Texp_record fields = [ "a" expression Texp_constant Const_int 1 "b" expression Texp_constant Const_int 2 ] representation = Record_regular extended_expression = Some expression Texp_apply expression Texp_ident "f/1004" [ Nolabel expression Texp_construct "()" [] ] JS modified (record spread with every field overridden): Example: type t = {a: int, b: int} @val external f: unit => t = "f" let make = () => {...f(), a: 1, b: 2} Before (js): function make() { return { a: 1, b: 2 }; } After (js): function make() { f(); return { a: 1, b: 2 }; } JS modified (source read from a module with side effects): Example: let make = () => {...Effects.base, a: 1, b: 2} Before (js): function make() { return { a: 1, b: 2 }; } export { make, } /* No side effect */ After (js): import * as Effects from "./Effects.mjs"; function make() { return { a: 1, b: 2 }; } export { make, } /* Effects Not a pure module */ Typing modified (let rec check of an overridden source): Example: type callback = {run: unit => int} @val external wrap: callback => callback = "wrap" let rec callback = {...wrap(callback), run: () => 1} Before (text): `Rec_check` accepted, without calling wrap After (text): `Rec_check` This kind of expression is not allowed as right-hand side of `let rec` Review: Does a copy of the source remain when the record has optional fields or 20 fields or more? No: `record_copies_fields` holds when every field is written, so the source is never spread into the result. Review: Does the source affect generalization or `let rec`? As the first expression of a sequence would: its value is discarded, so the record stays polymorphic and `let rec r = {...r, a: 1, b: 2}` stays accepted, but a source that uses the recursive value early is now rejected, as is a source with a field left to take from it, as before. Review: Which existing checked-in outputs change? None. Signed-off-by: Rob --- changes/record-spread-source-effect.fix.md | 1 + compiler/typing/rec_check.ml | 11 +- compiler/typing/translcore.ml | 24 +- compiler/typing/typecore.ml | 17 +- compiler/typing/typedtree.ml | 8 + compiler/typing/typedtree.mli | 7 + .../src/record_spread_pure_source.mjs | 60 +++++ .../src/record_spread_pure_source.res | 28 +++ .../src/record_spread_source_effect_dep.mjs | 17 ++ .../src/record_spread_source_effect_dep.res | 7 + .../src/record_spread_source_effect_test.mjs | 222 ++++++++++++++++++ .../src/record_spread_source_effect_test.res | 113 +++++++++ ..._record_spread_partial_source.res.expected | 10 + .../rec_record_spread_source.res.expected | 21 ++ .../rec_record_spread_partial_source.res | 3 + .../fixtures/rec_record_spread_source.res | 5 + 16 files changed, 536 insertions(+), 18 deletions(-) create mode 100644 changes/record-spread-source-effect.fix.md create mode 100644 tests/compiler_tests/src/record_spread_pure_source.mjs create mode 100644 tests/compiler_tests/src/record_spread_pure_source.res create mode 100644 tests/compiler_tests/src/record_spread_source_effect_dep.mjs create mode 100644 tests/compiler_tests/src/record_spread_source_effect_dep.res create mode 100644 tests/compiler_tests/src/record_spread_source_effect_test.mjs create mode 100644 tests/compiler_tests/src/record_spread_source_effect_test.res create mode 100644 tests/error_tests/single/expected/rec_record_spread_partial_source.res.expected create mode 100644 tests/error_tests/single/expected/rec_record_spread_source.res.expected create mode 100644 tests/error_tests/single/fixtures/rec_record_spread_partial_source.res create mode 100644 tests/error_tests/single/fixtures/rec_record_spread_source.res diff --git a/changes/record-spread-source-effect.fix.md b/changes/record-spread-source-effect.fix.md new file mode 100644 index 0000000000..72ea9246df --- /dev/null +++ b/changes/record-spread-source-effect.fix.md @@ -0,0 +1 @@ +- Fix the source of a record spread (or JSX props spread) not being evaluated when every field is overridden, as in `{...f(), a: 1, b: 2}`. diff --git a/compiler/typing/rec_check.ml b/compiler/typing/rec_check.ml index 9744e66a23..bcd00759fb 100644 --- a/compiler/typing/rec_check.ml +++ b/compiler/typing/rec_check.ml @@ -298,7 +298,10 @@ let rec expression : Env.env -> Typedtree.expression -> Use.t = Use.guard in let field env (_, _, e) = expression env e in - Use.join (use (array field env es)) (option expression env eo) + let source = option expression env eo in + (* A source whose fields are all overridden is evaluated and dropped *) + let source = if writes_all_labels es then Use.discard source else source in + Use.join (use (array field env es)) source | Texp_ifthenelse (cond, ifso, ifnot) -> Use.( join @@ -498,7 +501,11 @@ let check_recursive_bindings valbinds = List.iter (fun {vb_expr} -> match vb_expr.exp_desc with - | Texp_record {fields = [|(lbl, _, {exp_desc = Texp_function _})|]} + | Texp_record + { + fields = [|(lbl, _, {exp_desc = Texp_function _})|]; + extended_expression = None; + } when Array.length lbl.lbl_all = 1 -> () | Texp_function _ -> () diff --git a/compiler/typing/translcore.ml b/compiler/typing/translcore.ml index b50eb03221..957f6ffc74 100644 --- a/compiler/typing/translcore.ml +++ b/compiler/typing/translcore.ml @@ -1100,8 +1100,10 @@ let bind_strict defs body = (* How [transl_record] builds a record: by copying the fields of [init] one by one (or with no [init] at all), or by taking a shallow copy of [init] - and setting the other fields. JSX props follow the same rule. A shallow - copy is an object spread, so an array record always copies its fields. + and setting the other fields. With no field left to take from [init], it is + evaluated for its side effects and not copied. JSX props follow the same + rule. A shallow copy is an object spread, so an array record always copies + its fields. TODO: More strategies 3 + 2 * List.length lbl_expr_list >= size (density) *) let record_copies_fields @@ -1109,6 +1111,7 @@ let record_copies_fields ~(init : expression option) = match init with | None -> true + | Some _ when writes_all_labels fields -> true | Some _ -> ( let lbl_all = all_labels fields in match lbl_all.(0).lbl_repres with @@ -1117,6 +1120,14 @@ let record_copies_fields Array.length lbl_all < 20 && not (Array.exists (fun lbl -> lbl.lbl_optional) lbl_all)) +(* Whether [transl_record] leaves out the record's source: with no field to + take from it, a variable has nothing to evaluate. A binding for it would + count toward the size that decides whether a function is inlined. *) +let drops_record_source fields (init : Lambda.t) = + match init with + | Lvar _ -> writes_all_labels fields + | _ -> false + let jsx_props_of ~multi (props : expression) = match props.exp_desc with | Texp_record @@ -1769,6 +1780,7 @@ and transl_jsx_element loc (* An optional prop that is statically [undefined] can be left out, unless it overrides a prop of the spread *) let has_spread = Option.is_some init && not copy_fields in + let drops_source = drops_record_source fields in let field (lbl : label_description) value = (lbl.lbl_runtime_name, lbl.lbl_optional && not has_spread, value) in @@ -1799,7 +1811,9 @@ and transl_jsx_element loc let init, spread = match init with | None -> (None, None) - | Some init when copy_fields -> (Some (transl_exp init), None) + | Some init when copy_fields -> + let init = transl_exp init in + ((if drops_source init then None else Some init), None) | Some init -> (None, Some (transl_exp init)) in (init, spread, defs, fields, children) @@ -1970,7 +1984,9 @@ and transl_record loc env fields repres opt_init_expr = match opt_init_expr with | None -> lam | Some init_expr -> - let_ Strict init_id (transl_exp init_expr) (bind_strict defs lam) + let init = transl_exp init_expr in + if drops_record_source fields init then lam + else let_ Strict init_id init (bind_strict defs lam) else (* Take a shallow copy of the init record, then mutate the fields of the copy *) diff --git a/compiler/typing/typecore.ml b/compiler/typing/typecore.ml index 4fde5f8812..3372397521 100644 --- a/compiler/typing/typecore.ml +++ b/compiler/typing/typecore.ml @@ -2087,7 +2087,9 @@ let rec is_nonexpansive exp = | Texp_variant (_, arg) -> is_nonexpansive_opt arg | Texp_record {fields; extended_expression} -> ( Array.for_all (fun (_, _, exp) -> is_nonexpansive exp) fields - && is_nonexpansive_opt extended_expression + (* A source whose fields are all overridden is evaluated and dropped, like + the first expression of a sequence *) + && (writes_all_labels fields || is_nonexpansive_opt extended_expression) && (* The literal allocates every field of the record: written, copied from the spread, or left out *) @@ -3168,22 +3170,13 @@ and type_expect_ ?deprecated_context ~context ?(recarg = Rejected) Array.iter unify_kept lbl.lbl_all; Some {exp with exp_type = ty_exp} in - let num_fields = - match lbl_exp_list with - | [] -> assert false - | (_, lbl, _, _) :: _ -> Array.length lbl.lbl_all - in - let opt_exp = - if List.length lid_sexp_list = num_fields then ( - Loc_report.prerr_warning loc Warnings.Useless_record_with; - None) - else opt_exp - in let representation = let _, {lbl_repres}, _, _ = List.hd lbl_exp_list in lbl_repres in let fields = record_fields lbl_exp_list in + if writes_all_labels fields then + Loc_report.prerr_warning loc Warnings.Useless_record_with; re { exp_desc = diff --git a/compiler/typing/typedtree.ml b/compiler/typing/typedtree.ml index 1a688c604c..d2d174ac5d 100644 --- a/compiler/typing/typedtree.ml +++ b/compiler/typing/typedtree.ml @@ -568,3 +568,11 @@ let rec alpha_pat env p = let mkloc = Location.mkloc let mknoloc = Location.mknoloc + +let writes_all_labels + (fields : (label_description * Longident.t loc * expression) array) = + match fields with + | [||] -> false + | _ -> + let lbl, _, _ = fields.(0) in + Array.length fields = Array.length lbl.lbl_all diff --git a/compiler/typing/typedtree.mli b/compiler/typing/typedtree.mli index 558cc3821f..9b512a196a 100644 --- a/compiler/typing/typedtree.mli +++ b/compiler/typing/typedtree.mli @@ -230,6 +230,9 @@ and expression_desc = one, and is otherwise an optional field set to [None]. The record's other labels are in [lbl_all] of any written label. + When the literal writes every field (see [writes_all_labels]), E0 + is evaluated only for its side effects. + If the type is { l1: t1; l2: t2 }, the expression { E0 with t2=P2 } is represented as Texp_record @@ -599,3 +602,7 @@ val exp_warning_attributes : expression -> attributes (** The attributes whose warning settings apply to an expression, in the order [Builtin_attributes.warning_scope] takes them: its own, then those of the type constraints around it, which [exp_extra] holds outermost first. *) + +val writes_all_labels : + (Types.label_description * Longident.t loc * expression) array -> bool +(** Whether the [fields] of a [Texp_record] hold every label of the record *) diff --git a/tests/compiler_tests/src/record_spread_pure_source.mjs b/tests/compiler_tests/src/record_spread_pure_source.mjs new file mode 100644 index 0000000000..1b1281a307 --- /dev/null +++ b/tests/compiler_tests/src/record_spread_pure_source.mjs @@ -0,0 +1,60 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as JsxRuntime from "react/jsx-runtime"; + +let overridden = { + x: 3, + y: 4 +}; + +function override(source, x) { + return { + x: x, + y: 2 + }; +} + +function callOverride(x) { + return x; +} + +function Record_spread_pure_source$Component(props) { + return props.a + props.b | 0; +} + +let Component = { + make: Record_spread_pure_source$Component +}; + +function overrideJsx(props) { + return JsxRuntime.jsx(Record_spread_pure_source$Component, { + a: 1, + b: 2 + }); +} + +function callOverrideJsx(props) { + return JsxRuntime.jsx(Record_spread_pure_source$Component, { + a: 1, + b: 2 + }); +} + +let base = { + x: 1, + y: 2 +}; + +let Component$make = Record_spread_pure_source$Component; + +export { + base, + overridden, + override, + callOverride, + Component, + overrideJsx, + callOverrideJsx, + Component$make, +} +/* react/jsx-runtime Not a pure module */ diff --git a/tests/compiler_tests/src/record_spread_pure_source.res b/tests/compiler_tests/src/record_spread_pure_source.res new file mode 100644 index 0000000000..3785894094 --- /dev/null +++ b/tests/compiler_tests/src/record_spread_pure_source.res @@ -0,0 +1,28 @@ +// A variable as the source of a record spread whose fields are all overridden +// leaves no trace in the output: `override` and `overrideJsx` are still small +// enough to be inlined, and `overridden` is emitted before `base`, as a record +// without the spread would be. +@@warning("-23") +@@config({flags: ["-bs-jsx", "4"]}) + +type point = {x: int, y: int} + +let base = {x: 1, y: 2} +let overridden = {...base, x: 3, y: 4} + +let _ = overridden + +let override = (source, x) => {...source, x, y: 2} + +let callOverride = x => override({x: 0, y: 0}, x).x + +module Component = { + type props = {a: int, b: int} + + @react.componentWithProps + let make = props => React.int(props.a + props.b) +} + +let overrideJsx = props => + +let callOverrideJsx = props => overrideJsx(props) diff --git a/tests/compiler_tests/src/record_spread_source_effect_dep.mjs b/tests/compiler_tests/src/record_spread_source_effect_dep.mjs new file mode 100644 index 0000000000..2199da6424 --- /dev/null +++ b/tests/compiler_tests/src/record_spread_source_effect_dep.mjs @@ -0,0 +1,17 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + + +let loads = [1]; + +loads.push(2); + +let base = { + x: 0, + y: 0 +}; + +export { + loads, + base, +} +/* Not a pure module */ diff --git a/tests/compiler_tests/src/record_spread_source_effect_dep.res b/tests/compiler_tests/src/record_spread_source_effect_dep.res new file mode 100644 index 0000000000..dfd92724d1 --- /dev/null +++ b/tests/compiler_tests/src/record_spread_source_effect_dep.res @@ -0,0 +1,7 @@ +type point = {x: int, y: int} + +let loads = [1] + +loads->Array.push(2) + +let base = {x: 0, y: 0} diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.mjs b/tests/compiler_tests/src/record_spread_source_effect_test.mjs new file mode 100644 index 0000000000..b457654b1e --- /dev/null +++ b/tests/compiler_tests/src/record_spread_source_effect_test.mjs @@ -0,0 +1,222 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Mocha from "mocha"; +import * as Test_utils from "./test_utils.mjs"; +import * as Stdlib_JsError from "@rescript/runtime/lib/es6/Stdlib_JsError.mjs"; +import * as JsxRuntime from "react/jsx-runtime"; +import * as Primitive_exceptions from "@rescript/runtime/lib/es6/Primitive_exceptions.mjs"; +import * as Record_spread_source_effect_dep from "./record_spread_source_effect_dep.mjs"; + +function Record_spread_source_effect_test$Component(props) { + let __b = props.b; + let __b_value = __b !== undefined ? __b : 2; + return props.a + __b_value | 0; +} + +let Component = { + make: Record_spread_source_effect_test$Component +}; + +function id(x) { + return x; +} + +let calls = []; + +function logged(name, value) { + calls.push(name); + return value; +} + +function takeCalls() { + let taken = calls.slice(); + calls.splice(0, calls.length); + return taken; +} + +logged("polymorphic", id({ + compare: undefined, + first: 1 +})); + +let polymorphic = { + compare: undefined, + first: undefined +}; + +function base_self() { + return base; +} + +let base = { + self: base_self, + value: 0 +}; + +logged("recursive", id(base)); + +function recursive_self() { + return recursive; +} + +let recursive = { + self: recursive_self, + value: 2 +}; + +function selfSpread_self() { + return selfSpread; +} + +let selfSpread = { + self: selfSpread_self, + value: 3 +}; + +let singleCallback = { + run: () => 4 +}; + +let moduleCalls = takeCalls(); + +let fromOtherModule = { + x: 5, + y: 6 +}; + +function overridePure(source) { + return { + x: 1, + y: logged("y", 2) + }; +} + +function overrideJsxPure(props) { + return JsxRuntime.jsx(Record_spread_source_effect_test$Component, { + a: 1, + b: 2 + }); +} + +Mocha.describe("Record_spread_source_effect_test", () => { + Mocha.test("a source whose fields are all overridden runs first", () => { + logged("source", { + x: 0, + y: 0 + }); + let point_x = logged("x", id(1)); + let point_y = logged("y", id(2)); + let point = { + x: point_x, + y: point_y + }; + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 70, characters 7-14", takeCalls(), [ + "source", + "x", + "y" + ]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 71, characters 7-14", point, { + x: 1, + y: 2 + }); + }); + Mocha.test("a source of a record with optional fields runs", () => { + logged("source", { + height: 0 + }); + let options = { + width: 1, + height: 2 + }; + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 76, characters 7-14", takeCalls(), ["source"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 77, characters 7-14", options, { + width: 1, + height: 2 + }); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 79, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); + }); + Mocha.test("a source that raises stops the record from being built", () => { + let result; + try { + logged("source", Stdlib_JsError.throwWithMessage("source")); + result = 1; + } catch (raw_exn) { + let exn = Primitive_exceptions.internalToException(raw_exn); + if (exn.RE_EXN_ID === "JsExn") { + result = -1; + } else { + throw exn; + } + } + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 89, characters 7-14", result, -1); + }); + Mocha.test("the source of a JSX element's props runs", () => { + logged("props", { + a: 0 + }); + JsxRuntime.jsx(Record_spread_source_effect_test$Component, { + a: 1, + b: 2 + }); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 94, characters 7-14", takeCalls(), ["props"]); + }); + Mocha.test("sources of module-level and recursive records run", () => { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 99, characters 7-14", moduleCalls, [ + "polymorphic", + "recursive" + ]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 100, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 101, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 102, characters 7-14", recursive_self().value, 2); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 103, characters 7-14", selfSpread_self().value, 3); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 104, characters 7-14", singleCallback.run(), 4); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 105, characters 7-14", fromOtherModule, { + x: 5, + y: 6 + }); + }); + Mocha.test("a pure source is left out", () => { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 109, characters 7-14", overridePure(id({ + x: 0, + y: 0 + })), { + x: 1, + y: 2 + }); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 110, characters 7-14", takeCalls(), ["y"]); + id({ + a: 0 + }); + JsxRuntime.jsx(Record_spread_source_effect_test$Component, { + a: 1, + b: 2 + }); + }); +}); + +let strings = polymorphic; + +let ints = polymorphic; + +let Component$make = Record_spread_source_effect_test$Component; + +export { + Component, + id, + calls, + logged, + takeCalls, + polymorphic, + strings, + ints, + base, + recursive, + selfSpread, + singleCallback, + moduleCalls, + fromOtherModule, + overridePure, + overrideJsxPure, + Component$make, +} +/* Not a pure module */ diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.res b/tests/compiler_tests/src/record_spread_source_effect_test.res new file mode 100644 index 0000000000..b9eb2bd13c --- /dev/null +++ b/tests/compiler_tests/src/record_spread_source_effect_test.res @@ -0,0 +1,113 @@ +@@warning("-23") +@@config({flags: ["-bs-jsx", "4"]}) + +open Mocha +open Test_utils + +type point = {x: int, y: int} +type options = {width?: int, height: int} +type polymorphic<'a> = {compare: option<('a, 'a) => int>, first: option<'a>} +type rec recursive = {self: unit => recursive, value: int} +type callback = {run: unit => int} + +module Component = { + @react.component + let make = (~a: int, ~b: int=2) => React.int(a + b) +} + +@inline(never) +let id = x => x + +let calls = [] + +@inline(never) +let logged = (name, value) => { + calls->Array.push(name) + value +} + +let takeCalls = () => { + let taken = calls->Array.copy + calls->Array.splice(~start=0, ~remove=calls->Array.length, ~insert=[]) + taken +} + +// The source doesn't stop the record from being polymorphic +let polymorphic = { + ...logged("polymorphic", id({compare: None, first: Some(1)})), + compare: None, + first: None, +} + +let strings: polymorphic = polymorphic +let ints: polymorphic = polymorphic + +let rec base = {self: () => base, value: 0} + +let rec recursive = { + ...logged("recursive", id(base)), + self: () => recursive, + value: 2, +} + +let rec selfSpread = {...selfSpread, self: () => selfSpread, value: 3} + +let rec singleCallback = {...singleCallback, run: () => 4} + +let moduleCalls = takeCalls() + +// The source is evaluated, so the module it comes from stays imported when it +// has side effects, even though its value is not needed +let fromOtherModule = {...Record_spread_source_effect_dep.base, x: 5, y: 6} + +let overridePure = (source: point) => {...source, x: 1, y: logged("y", 2)} + +let overrideJsxPure = props => + +describe(__MODULE__, () => { + test("a source whose fields are all overridden runs first", () => { + let point = {...logged("source", {x: 0, y: 0}), x: logged("x", id(1)), y: logged("y", id(2))} + eq(__LOC__, takeCalls(), ["source", "x", "y"]) + eq(__LOC__, point, {x: 1, y: 2}) + }) + + test("a source of a record with optional fields runs", () => { + let options = {...logged("source", {height: 0}), width: 1, height: 2} + eq(__LOC__, takeCalls(), ["source"]) + eq(__LOC__, options, {width: 1, height: 2}) + // A copy of the source would have `height` first + eq(__LOC__, JSON.stringifyAny(options), Some(`{"width":1,"height":2}`)) + }) + + test("a source that raises stops the record from being built", () => { + let result = try { + let point = {...logged("source", JsError.throwWithMessage("source")), x: 1, y: 2} + point.x + } catch { + | JsExn(_) => -1 + } + eq(__LOC__, result, -1) + }) + + test("the source of a JSX element's props runs", () => { + let element = + eq(__LOC__, takeCalls(), ["props"]) + ignore(element) + }) + + test("sources of module-level and recursive records run", () => { + eq(__LOC__, moduleCalls, ["polymorphic", "recursive"]) + eq(__LOC__, strings.first, None) + eq(__LOC__, ints.first, None) + eq(__LOC__, recursive.self().value, 2) + eq(__LOC__, selfSpread.self().value, 3) + eq(__LOC__, singleCallback.run(), 4) + eq(__LOC__, fromOtherModule, {x: 5, y: 6}) + }) + + test("a pure source is left out", () => { + eq(__LOC__, overridePure(id({x: 0, y: 0})), {x: 1, y: 2}) + eq(__LOC__, takeCalls(), ["y"]) + ignore(overrideJsxPure(id({Component.a: 0}))) + }) +}) diff --git a/tests/error_tests/single/expected/rec_record_spread_partial_source.res.expected b/tests/error_tests/single/expected/rec_record_spread_partial_source.res.expected new file mode 100644 index 0000000000..fa3b9b9c7f --- /dev/null +++ b/tests/error_tests/single/expected/rec_record_spread_partial_source.res.expected @@ -0,0 +1,10 @@ + + We've found a bug for you! + /.../fixtures/rec_record_spread_partial_source.res:3:17-32 + + 1 │ type point = {x: int, y: int} + 2 │ + 3 │ let rec point = {...point, x: 1} + 4 │ + + This kind of expression is not allowed as right-hand side of `let rec` \ No newline at end of file diff --git a/tests/error_tests/single/expected/rec_record_spread_source.res.expected b/tests/error_tests/single/expected/rec_record_spread_source.res.expected new file mode 100644 index 0000000000..e88c89cd63 --- /dev/null +++ b/tests/error_tests/single/expected/rec_record_spread_source.res.expected @@ -0,0 +1,21 @@ + + Warning number 23 + /.../fixtures/rec_record_spread_source.res:5:20-52 + + 3 │ @val external wrap: callback => callback = "wrap" + 4 │ + 5 │ let rec callback = {...wrap(callback), run: () => 1} + 6 │ + + All the fields are already explicitly listed in this record. You can remove the `...` spread. + + + We've found a bug for you! + /.../fixtures/rec_record_spread_source.res:5:20-52 + + 3 │ @val external wrap: callback => callback = "wrap" + 4 │ + 5 │ let rec callback = {...wrap(callback), run: () => 1} + 6 │ + + This kind of expression is not allowed as right-hand side of `let rec` \ No newline at end of file diff --git a/tests/error_tests/single/fixtures/rec_record_spread_partial_source.res b/tests/error_tests/single/fixtures/rec_record_spread_partial_source.res new file mode 100644 index 0000000000..abb4addc9c --- /dev/null +++ b/tests/error_tests/single/fixtures/rec_record_spread_partial_source.res @@ -0,0 +1,3 @@ +type point = {x: int, y: int} + +let rec point = {...point, x: 1} diff --git a/tests/error_tests/single/fixtures/rec_record_spread_source.res b/tests/error_tests/single/fixtures/rec_record_spread_source.res new file mode 100644 index 0000000000..720f6795c4 --- /dev/null +++ b/tests/error_tests/single/fixtures/rec_record_spread_source.res @@ -0,0 +1,5 @@ +type callback = {run: unit => int} + +@val external wrap: callback => callback = "wrap" + +let rec callback = {...wrap(callback), run: () => 1} From 316c515f8e9559c1603f1222221372508c4e3ef4 Mon Sep 17 00:00:00 2001 From: Rob Date: Thu, 26 Nov 2026 16:59:33 -0500 Subject: [PATCH 02/14] Build a recursive record into a dummy when its source runs first Why: The record spread fix keeps a source whose fields are all overridden, so `let rec n = {...makeSource(), next: n}` becomes a block after a sequence or a let. `compile_recursive_let` only declared a dummy for a bare block, and otherwise declared the binding with its value, which read `n` before it was initialized. A block reached after a sequence or a let whose fields read one of the group's bindings is now built into a dummy declared first, as a bare block with such fields is. The same applied on master to a record built at the end of a sequence. JS modified (recursive record after its spread source): Example: type rec node = {next: node, v: int} let rec n = {...makeSource(), next: n, v: 1} Before (js): makeSource(); let n = { next: n, v: 1 }; After (js): let n = {}; Primitive_object.updateDummy(n, (makeSource(), { next: n, v: 1 })); JS modified (recursive record at the end of a sequence): Example: type rec node = {next: node, v: int} let rec n = { Console.log("a") {next: n, v: 1} } Before (js): console.log("a"); let n = { next: n, v: 1 }; After (js): let n = {}; Primitive_object.updateDummy(n, (console.log("a"), { next: n, v: 1 })); Review: Do recursive modules, whose blocks follow lets of their functions, change? No: their fields are variables bound before the group, so they are still declared directly. No checked-in output other than the new tests changes. Review: Is the Lambda term without optimization covered? There is no switch to turn Lambda passes off; `letCycle` keeps a let before the block and `cycle` the sequence the passes leave of the source's let. Signed-off-by: Rob --- changes/let-rec-record-after-effects.fix.md | 1 + compiler/backend/lam_compile.ml | 64 +++++++++++---- .../src/record_spread_source_effect_test.mjs | 79 +++++++++++++++---- .../src/record_spread_source_effect_test.res | 32 +++++++- 4 files changed, 141 insertions(+), 35 deletions(-) create mode 100644 changes/let-rec-record-after-effects.fix.md diff --git a/changes/let-rec-record-after-effects.fix.md b/changes/let-rec-record-after-effects.fix.md new file mode 100644 index 0000000000..384195e57d --- /dev/null +++ b/changes/let-rec-record-after-effects.fix.md @@ -0,0 +1 @@ +- Fix a `let rec` record that refers to itself and is built after other expressions, as in `let rec r = {...f(), next: r}` or `let rec r = {log(); {next: r}}`, reading itself before it is initialized. diff --git a/compiler/backend/lam_compile.ml b/compiler/backend/lam_compile.ml index 6fe20f7a1d..c2201c1775 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -84,6 +84,29 @@ let with_block_source_loc lam block = | stmt :: rest -> with_statement_source_loc (source_map_loc_of_lam lam) stmt :: rest +(* The tag of the block that [lam] builds after evaluating other expressions, + when a field of the block may read one of the recursive [all_bindings], as + in [let rec r = {...f(), next: r}], whose spread source [f()] is evaluated + for its side effects first. Such a binding is declared as a dummy before + those expressions run, and the block is copied into it. A field that is a + function, a constant or a variable bound before the group reads none. *) +let rec block_after_effects ~(all_bindings : (Ident.t * Lambda.t) list) + (lam : Lambda.t) = + let reads_binding (arg : Lambda.t) = + match arg with + | Lfunction _ | Lconst _ -> false + | Lvar pid -> + List.exists (fun (other, _) -> Ident.same other pid) all_bindings + | _ -> true + in + match lam with + | Lsequence (_, Lprim {primitive = Pmakeblock tag_info; args}) + | Llet (_, _, _, Lprim {primitive = Pmakeblock tag_info; args}) -> + if List.exists reads_binding args then Some tag_info else None + | Lsequence (_, body) | Llet (_, _, _, body) -> + block_after_effects ~all_bindings body + | _ -> None + let args_either_function_or_const (args : Lambda.t list) = List.for_all (fun (x : Lambda.t) -> @@ -755,26 +778,13 @@ let compile output_prefix = | _ -> assert false))) ls), [] ) - | Lprim {primitive = Pmakeblock tag_info} -> ( + | Lprim {primitive = Pmakeblock tag_info} -> (* Lconst should not appear here if we do [scc] optimization, since it's faked recursive value, however it would affect scope issues, we have to declare it first *) - match compile_lambda {cxt with continuation = NeedValue Not_tail} arg with - | {block = b; value = Some v} -> - (* TODO: check recursive value .. - could be improved for simple cases - *) - ( Js_output.make - (List.append b - [ - S.exp - (E.runtime_call Primitive_modules.object_ "updateDummy" - [E.var id; v]); - ]), - [S.define_variable ~kind:Variable id (E.dummy_obj tag_info)] ) - | _ -> assert false) - | _ -> + compile_into_dummy cxt id tag_info arg + | _ -> ( (* pathological case: fail to capture taill call? {[ let rec a = @@ -796,7 +806,27 @@ let compile output_prefix = fun _-> print_endline "hey"; v () ]} *) - (compile_lambda {cxt with continuation = Declare (Alias, id)} arg, []) + match block_after_effects ~all_bindings arg with + | Some tag_info -> compile_into_dummy cxt id tag_info arg + | None -> + (compile_lambda {cxt with continuation = Declare (Alias, id)} arg, [])) + (* [id] is declared as a dummy object, which the block [arg] evaluates to is + copied into *) + and compile_into_dummy cxt id tag_info arg = + match compile_lambda {cxt with continuation = NeedValue Not_tail} arg with + | {block = b; value = Some v} -> + (* TODO: check recursive value .. + could be improved for simple cases + *) + ( Js_output.make + (List.append b + [ + S.exp + (E.runtime_call Primitive_modules.object_ "updateDummy" + [E.var id; v]); + ]), + [S.define_variable ~kind:Variable id (E.dummy_obj tag_info)] ) + | _ -> assert false and compile_recursive_lets_aux cxt (id_args : (Ident.t * Lambda.t) list) : Js_output.t = (* #1716 *) diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.mjs b/tests/compiler_tests/src/record_spread_source_effect_test.mjs index b457654b1e..76a9419927 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.mjs +++ b/tests/compiler_tests/src/record_spread_source_effect_test.mjs @@ -3,6 +3,7 @@ import * as Mocha from "mocha"; import * as Test_utils from "./test_utils.mjs"; import * as Stdlib_JsError from "@rescript/runtime/lib/es6/Stdlib_JsError.mjs"; +import * as Primitive_object from "@rescript/runtime/lib/es6/Primitive_object.mjs"; import * as JsxRuntime from "react/jsx-runtime"; import * as Primitive_exceptions from "@rescript/runtime/lib/es6/Primitive_exceptions.mjs"; import * as Record_spread_source_effect_dep from "./record_spread_source_effect_dep.mjs"; @@ -77,6 +78,36 @@ let singleCallback = { run: () => 4 }; +function makeNode(value) { + let node = {}; + node.next = node; + node.value = value; + return node; +} + +let cycle = {}; + +Primitive_object.updateDummy(cycle, (logged("cycle", makeNode(0)), { + next: cycle, + value: 7 +})); + +let letCycle = {}; + +let value = logged("letCycle", id(8)); + +Primitive_object.updateDummy(letCycle, (logged("letCycleSource", makeNode(0)), { + next: letCycle, + value: value +})); + +let sequenceCycle = {}; + +Primitive_object.updateDummy(sequenceCycle, (logged("sequenceCycle", undefined), { + next: sequenceCycle, + value: 9 +})); + let moduleCalls = takeCalls(); let fromOtherModule = { @@ -110,12 +141,12 @@ Mocha.describe("Record_spread_source_effect_test", () => { x: point_x, y: point_y }; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 70, characters 7-14", takeCalls(), [ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 90, characters 7-14", takeCalls(), [ "source", "x", "y" ]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 71, characters 7-14", point, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 91, characters 7-14", point, { x: 1, y: 2 }); @@ -128,12 +159,12 @@ Mocha.describe("Record_spread_source_effect_test", () => { width: 1, height: 2 }; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 76, characters 7-14", takeCalls(), ["source"]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 77, characters 7-14", options, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 96, characters 7-14", takeCalls(), ["source"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 97, characters 7-14", options, { width: 1, height: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 79, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 99, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); }); Mocha.test("a source that raises stops the record from being built", () => { let result; @@ -148,7 +179,7 @@ Mocha.describe("Record_spread_source_effect_test", () => { throw exn; } } - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 89, characters 7-14", result, -1); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 109, characters 7-14", result, -1); }); Mocha.test("the source of a JSX element's props runs", () => { logged("props", { @@ -158,32 +189,42 @@ Mocha.describe("Record_spread_source_effect_test", () => { a: 1, b: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 94, characters 7-14", takeCalls(), ["props"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 114, characters 7-14", takeCalls(), ["props"]); }); Mocha.test("sources of module-level and recursive records run", () => { - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 99, characters 7-14", moduleCalls, [ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 120, characters 6-13", moduleCalls, [ "polymorphic", - "recursive" + "recursive", + "cycle", + "letCycle", + "letCycleSource", + "sequenceCycle" ]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 100, characters 7-14", undefined, undefined); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 101, characters 7-14", undefined, undefined); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 102, characters 7-14", recursive_self().value, 2); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 103, characters 7-14", selfSpread_self().value, 3); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 104, characters 7-14", singleCallback.run(), 4); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 105, characters 7-14", fromOtherModule, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 124, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 125, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 126, characters 7-14", recursive_self().value, 2); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 127, characters 7-14", selfSpread_self().value, 3); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 128, characters 7-14", singleCallback.run(), 4); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 129, characters 7-14", cycle.next === cycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 130, characters 7-14", cycle.next.value, 7); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 131, characters 7-14", letCycle.next === letCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 132, characters 7-14", letCycle.next.value, 8); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 133, characters 7-14", sequenceCycle.next === sequenceCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 134, characters 7-14", sequenceCycle.next.value, 9); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 135, characters 7-14", fromOtherModule, { x: 5, y: 6 }); }); Mocha.test("a pure source is left out", () => { - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 109, characters 7-14", overridePure(id({ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 139, characters 7-14", overridePure(id({ x: 0, y: 0 })), { x: 1, y: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 110, characters 7-14", takeCalls(), ["y"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 140, characters 7-14", takeCalls(), ["y"]); id({ a: 0 }); @@ -213,6 +254,10 @@ export { recursive, selfSpread, singleCallback, + makeNode, + cycle, + letCycle, + sequenceCycle, moduleCalls, fromOtherModule, overridePure, diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.res b/tests/compiler_tests/src/record_spread_source_effect_test.res index b9eb2bd13c..96cc950bef 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.res +++ b/tests/compiler_tests/src/record_spread_source_effect_test.res @@ -9,6 +9,7 @@ type options = {width?: int, height: int} type polymorphic<'a> = {compare: option<('a, 'a) => int>, first: option<'a>} type rec recursive = {self: unit => recursive, value: int} type callback = {run: unit => int} +type rec node = {next: node, value: int} module Component = { @react.component @@ -54,6 +55,25 @@ let rec selfSpread = {...selfSpread, self: () => selfSpread, value: 3} let rec singleCallback = {...singleCallback, run: () => 4} +let makeNode = value => { + let rec node = {next: node, value} + node +} + +// The record still refers to itself once its source has been evaluated +let rec cycle = {...logged("cycle", makeNode(0)), next: cycle, value: 7} + +let rec letCycle = { + let value = logged("letCycle", id(8)) + {...logged("letCycleSource", makeNode(0)), next: letCycle, value} +} + +// The same holds for a record built at the end of a sequence +let rec sequenceCycle = { + ignore(logged("sequenceCycle", ())) + {next: sequenceCycle, value: 9} +} + let moduleCalls = takeCalls() // The source is evaluated, so the module it comes from stays imported when it @@ -96,12 +116,22 @@ describe(__MODULE__, () => { }) test("sources of module-level and recursive records run", () => { - eq(__LOC__, moduleCalls, ["polymorphic", "recursive"]) + eq( + __LOC__, + moduleCalls, + ["polymorphic", "recursive", "cycle", "letCycle", "letCycleSource", "sequenceCycle"], + ) eq(__LOC__, strings.first, None) eq(__LOC__, ints.first, None) eq(__LOC__, recursive.self().value, 2) eq(__LOC__, selfSpread.self().value, 3) eq(__LOC__, singleCallback.run(), 4) + eq(__LOC__, cycle.next === cycle, true) + eq(__LOC__, cycle.next.value, 7) + eq(__LOC__, letCycle.next === letCycle, true) + eq(__LOC__, letCycle.next.value, 8) + eq(__LOC__, sequenceCycle.next === sequenceCycle, true) + eq(__LOC__, sequenceCycle.next.value, 9) eq(__LOC__, fromOtherModule, {x: 5, y: 6}) }) From b24282cf67983900f7e0956a19772060fd83115a Mon Sep 17 00:00:00 2001 From: Rob Date: Thu, 26 Nov 2026 19:05:14 -0500 Subject: [PATCH 03/14] Declare a recursive record directly when its fields read none of the group Why: `block_after_effects` took every field of a block after a sequence or a let, other than a function, a constant or a variable, to read the recursive group. A record of a `let rec` group whose fields are calls or reads of values outside the group was then built into a dummy with `updateDummy` when it could be declared directly. A field other than a function now reads the group only when `Lam_hit.hit_variables` finds one of the group's bindings in it. JS modified (record of a recursive group after a sequence): Example: type r = {a: int, b: int, run: int => int} @val external log: unit => unit = "log" @val external compute: unit => int = "compute" let rec f = x => r.b + x and r = { log() {a: compute(), b: 1, run: x => f(x)} } Before (js): let r = {}; function f(x) { return r.b + x | 0; } Primitive_object.updateDummy(r, (log(), { a: compute(), b: 1, run: x => r.b + x | 0 })); After (js): function f(x) { return r.b + x | 0; } log(); let r_a = compute(); function r_run(x) { return r.b + x | 0; } let r = { a: r_a, b: 1, run: r_run }; Review: Do `cycle`, `letCycle` and `sequenceCycle` still use a dummy? Yes: their `next` field is the binding itself. Only the new `counter` case of the test changes. Signed-off-by: Rob --- compiler/backend/lam_compile.ml | 28 ++++---- .../src/record_spread_source_effect_test.mjs | 69 ++++++++++++------- .../src/record_spread_source_effect_test.res | 22 +++++- 3 files changed, 82 insertions(+), 37 deletions(-) diff --git a/compiler/backend/lam_compile.ml b/compiler/backend/lam_compile.ml index c2201c1775..67b9e747d7 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -89,23 +89,25 @@ let with_block_source_loc lam block = in [let rec r = {...f(), next: r}], whose spread source [f()] is evaluated for its side effects first. Such a binding is declared as a dummy before those expressions run, and the block is copied into it. A field that is a - function, a constant or a variable bound before the group reads none. *) -let rec block_after_effects ~(all_bindings : (Ident.t * Lambda.t) list) + function reads none when the block is built, whatever it refers to; any + other field reads one when it refers to a binding of the group. *) +let block_after_effects ~(all_bindings : (Ident.t * Lambda.t) list) (lam : Lambda.t) = + let group = Set_ident.of_list (List.map fst all_bindings) in let reads_binding (arg : Lambda.t) = match arg with - | Lfunction _ | Lconst _ -> false - | Lvar pid -> - List.exists (fun (other, _) -> Ident.same other pid) all_bindings - | _ -> true + | Lfunction _ -> false + | _ -> Lam_hit.hit_variables group arg in - match lam with - | Lsequence (_, Lprim {primitive = Pmakeblock tag_info; args}) - | Llet (_, _, _, Lprim {primitive = Pmakeblock tag_info; args}) -> - if List.exists reads_binding args then Some tag_info else None - | Lsequence (_, body) | Llet (_, _, _, body) -> - block_after_effects ~all_bindings body - | _ -> None + let rec block_tag (lam : Lambda.t) = + match lam with + | Lsequence (_, Lprim {primitive = Pmakeblock tag_info; args}) + | Llet (_, _, _, Lprim {primitive = Pmakeblock tag_info; args}) -> + if List.exists reads_binding args then Some tag_info else None + | Lsequence (_, body) | Llet (_, _, _, body) -> block_tag body + | _ -> None + in + block_tag lam let args_either_function_or_const (args : Lambda.t list) = List.for_all diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.mjs b/tests/compiler_tests/src/record_spread_source_effect_test.mjs index 76a9419927..6300f4bc01 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.mjs +++ b/tests/compiler_tests/src/record_spread_source_effect_test.mjs @@ -108,6 +108,23 @@ Primitive_object.updateDummy(sequenceCycle, (logged("sequenceCycle", undefined), value: 9 })); +function nextCount() { + return counter.start + 1 | 0; +} + +logged("counter", undefined); + +let counter_start = logged("counterStart", id(10)); + +function counter_step() { + return counter.start + 1 | 0; +} + +let counter = { + start: counter_start, + step: counter_step +}; + let moduleCalls = takeCalls(); let fromOtherModule = { @@ -141,12 +158,12 @@ Mocha.describe("Record_spread_source_effect_test", () => { x: point_x, y: point_y }; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 90, characters 7-14", takeCalls(), [ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 99, characters 7-14", takeCalls(), [ "source", "x", "y" ]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 91, characters 7-14", point, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 100, characters 7-14", point, { x: 1, y: 2 }); @@ -159,12 +176,12 @@ Mocha.describe("Record_spread_source_effect_test", () => { width: 1, height: 2 }; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 96, characters 7-14", takeCalls(), ["source"]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 97, characters 7-14", options, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 105, characters 7-14", takeCalls(), ["source"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 106, characters 7-14", options, { width: 1, height: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 99, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 108, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); }); Mocha.test("a source that raises stops the record from being built", () => { let result; @@ -179,7 +196,7 @@ Mocha.describe("Record_spread_source_effect_test", () => { throw exn; } } - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 109, characters 7-14", result, -1); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 118, characters 7-14", result, -1); }); Mocha.test("the source of a JSX element's props runs", () => { logged("props", { @@ -189,42 +206,46 @@ Mocha.describe("Record_spread_source_effect_test", () => { a: 1, b: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 114, characters 7-14", takeCalls(), ["props"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 123, characters 7-14", takeCalls(), ["props"]); }); Mocha.test("sources of module-level and recursive records run", () => { - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 120, characters 6-13", moduleCalls, [ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 129, characters 6-13", moduleCalls, [ "polymorphic", "recursive", "cycle", "letCycle", "letCycleSource", - "sequenceCycle" + "sequenceCycle", + "counter", + "counterStart" ]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 124, characters 7-14", undefined, undefined); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 125, characters 7-14", undefined, undefined); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 126, characters 7-14", recursive_self().value, 2); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 127, characters 7-14", selfSpread_self().value, 3); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 128, characters 7-14", singleCallback.run(), 4); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 129, characters 7-14", cycle.next === cycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 130, characters 7-14", cycle.next.value, 7); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 131, characters 7-14", letCycle.next === letCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 132, characters 7-14", letCycle.next.value, 8); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 133, characters 7-14", sequenceCycle.next === sequenceCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 134, characters 7-14", sequenceCycle.next.value, 9); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 135, characters 7-14", fromOtherModule, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 142, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 143, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 144, characters 7-14", recursive_self().value, 2); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 145, characters 7-14", selfSpread_self().value, 3); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 146, characters 7-14", singleCallback.run(), 4); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 147, characters 7-14", cycle.next === cycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 148, characters 7-14", cycle.next.value, 7); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 149, characters 7-14", letCycle.next === letCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 150, characters 7-14", letCycle.next.value, 8); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 151, characters 7-14", sequenceCycle.next === sequenceCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 152, characters 7-14", sequenceCycle.next.value, 9); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 153, characters 7-14", counter_start, 10); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 154, characters 7-14", counter_step(), 11); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 155, characters 7-14", fromOtherModule, { x: 5, y: 6 }); }); Mocha.test("a pure source is left out", () => { - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 139, characters 7-14", overridePure(id({ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 159, characters 7-14", overridePure(id({ x: 0, y: 0 })), { x: 1, y: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 140, characters 7-14", takeCalls(), ["y"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 160, characters 7-14", takeCalls(), ["y"]); id({ a: 0 }); @@ -258,6 +279,8 @@ export { cycle, letCycle, sequenceCycle, + nextCount, + counter, moduleCalls, fromOtherModule, overridePure, diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.res b/tests/compiler_tests/src/record_spread_source_effect_test.res index 96cc950bef..8d1584055e 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.res +++ b/tests/compiler_tests/src/record_spread_source_effect_test.res @@ -10,6 +10,7 @@ type polymorphic<'a> = {compare: option<('a, 'a) => int>, first: option<'a>} type rec recursive = {self: unit => recursive, value: int} type callback = {run: unit => int} type rec node = {next: node, value: int} +type counter = {start: int, step: unit => int} module Component = { @react.component @@ -74,6 +75,14 @@ let rec sequenceCycle = { {next: sequenceCycle, value: 9} } +// A record of a recursive group whose fields read none of the group's bindings +// when it is built is declared directly, after the expressions before it +let rec nextCount = () => counter.start + 1 +and counter = { + ignore(logged("counter", ())) + {start: logged("counterStart", id(10)), step: () => nextCount()} +} + let moduleCalls = takeCalls() // The source is evaluated, so the module it comes from stays imported when it @@ -119,7 +128,16 @@ describe(__MODULE__, () => { eq( __LOC__, moduleCalls, - ["polymorphic", "recursive", "cycle", "letCycle", "letCycleSource", "sequenceCycle"], + [ + "polymorphic", + "recursive", + "cycle", + "letCycle", + "letCycleSource", + "sequenceCycle", + "counter", + "counterStart", + ], ) eq(__LOC__, strings.first, None) eq(__LOC__, ints.first, None) @@ -132,6 +150,8 @@ describe(__MODULE__, () => { eq(__LOC__, letCycle.next.value, 8) eq(__LOC__, sequenceCycle.next === sequenceCycle, true) eq(__LOC__, sequenceCycle.next.value, 9) + eq(__LOC__, counter.start, 10) + eq(__LOC__, counter.step(), 11) eq(__LOC__, fromOtherModule, {x: 5, y: 6}) }) From e7e5d3e6bc9158f97450b5fc794464ce2fd87ac0 Mon Sep 17 00:00:00 2001 From: Rob Date: Fri, 27 Nov 2026 16:36:24 -0500 Subject: [PATCH 04/14] Find a recursive record's block after a recursive let too MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Why: `block_after_effects` looked for the block of a `let rec` record after sequences and lets only. A spread source with a recursive helper, as in `let rec n = {...{let rec loop = ...; loop()}, next: n}`, has its helper hoisted out of it by Lam_pass_deep_flatten, which leaves the block after an `Lletrec`. `compile_recursive_let` then declared `n` with its value, which read `n` before it was initialized and threw a ReferenceError when the module loaded. The block is now also found after a recursive let. This answers Codex's review finding on #9427. JS modified (recursive record after a source with a recursive helper): Example: type rec node = {value: int, next: node} let rec n = { ...{ let rec loop = () => if again() {loop()} else {makeSource()} loop() }, value: 1, next: n, } Before (js): loop(); let n = { value: 1, next: n }; After (js): let n = {}; function loop() { … } Primitive_object.updateDummy(n, (loop(), { value: 1, next: n })); Review: Is the Lambda term without optimization covered? There is still no switch to turn Lambda passes off; the test has the record both at module level and local to a function, where the helper stays a local binding. Review: Which checked-in outputs change? Only record_spread_source_effect_test.mjs, for the new cases. Signed-off-by: Rob --- compiler/backend/lam_compile.ml | 16 ++-- .../src/record_spread_source_effect_test.mjs | 93 ++++++++++++++----- .../src/record_spread_source_effect_test.res | 31 +++++++ 3 files changed, 110 insertions(+), 30 deletions(-) diff --git a/compiler/backend/lam_compile.ml b/compiler/backend/lam_compile.ml index 67b9e747d7..402858a315 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -87,7 +87,9 @@ let with_block_source_loc lam block = (* The tag of the block that [lam] builds after evaluating other expressions, when a field of the block may read one of the recursive [all_bindings], as in [let rec r = {...f(), next: r}], whose spread source [f()] is evaluated - for its side effects first. Such a binding is declared as a dummy before + for its side effects first. The block may follow any chain of sequences, + lets and recursive lets, such as the one [Lam_pass_deep_flatten] leaves when + it hoists the bindings of a source out of it. Such a binding is declared as a dummy before those expressions run, and the block is copied into it. A field that is a function reads none when the block is built, whatever it refers to; any other field reads one when it refers to a binding of the group. *) @@ -99,15 +101,17 @@ let block_after_effects ~(all_bindings : (Ident.t * Lambda.t) list) | Lfunction _ -> false | _ -> Lam_hit.hit_variables group arg in - let rec block_tag (lam : Lambda.t) = + (* [after_effects]: [lam] is evaluated after other expressions. A bare block + is compiled into a dummy by the caller already. *) + let rec block_tag ~after_effects (lam : Lambda.t) = match lam with - | Lsequence (_, Lprim {primitive = Pmakeblock tag_info; args}) - | Llet (_, _, _, Lprim {primitive = Pmakeblock tag_info; args}) -> + | Lprim {primitive = Pmakeblock tag_info; args} when after_effects -> if List.exists reads_binding args then Some tag_info else None - | Lsequence (_, body) | Llet (_, _, _, body) -> block_tag body + | Lsequence (_, body) | Llet (_, _, _, body) | Lletrec (_, body) -> + block_tag ~after_effects:true body | _ -> None in - block_tag lam + block_tag ~after_effects:false lam let args_either_function_or_const (args : Lambda.t list) = List.for_all diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.mjs b/tests/compiler_tests/src/record_spread_source_effect_test.mjs index 6300f4bc01..21808bdb79 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.mjs +++ b/tests/compiler_tests/src/record_spread_source_effect_test.mjs @@ -108,6 +108,43 @@ Primitive_object.updateDummy(sequenceCycle, (logged("sequenceCycle", undefined), value: 9 })); +let letRecCycle = {}; + +function retry(_attempts) { + while (true) { + let attempts = _attempts; + if (attempts <= 0) { + return logged("letRecCycle", makeNode(0)); + } + _attempts = attempts - 1 | 0; + continue; + }; +} + +Primitive_object.updateDummy(letRecCycle, (retry(id(2)), { + next: letRecCycle, + value: 12 +})); + +function localLetRecCycle(value) { + let node = {}; + let retry = _attempts => { + while (true) { + let attempts = _attempts; + if (attempts <= 0) { + return makeNode(0); + } + _attempts = attempts - 1 | 0; + continue; + }; + }; + Primitive_object.updateDummy(node, (retry(id(2)), { + next: node, + value: value + })); + return node; +} + function nextCount() { return counter.start + 1 | 0; } @@ -158,12 +195,12 @@ Mocha.describe("Record_spread_source_effect_test", () => { x: point_x, y: point_y }; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 99, characters 7-14", takeCalls(), [ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 124, characters 7-14", takeCalls(), [ "source", "x", "y" ]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 100, characters 7-14", point, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 125, characters 7-14", point, { x: 1, y: 2 }); @@ -176,12 +213,12 @@ Mocha.describe("Record_spread_source_effect_test", () => { width: 1, height: 2 }; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 105, characters 7-14", takeCalls(), ["source"]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 106, characters 7-14", options, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 130, characters 7-14", takeCalls(), ["source"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 131, characters 7-14", options, { width: 1, height: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 108, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 133, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); }); Mocha.test("a source that raises stops the record from being built", () => { let result; @@ -196,7 +233,7 @@ Mocha.describe("Record_spread_source_effect_test", () => { throw exn; } } - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 118, characters 7-14", result, -1); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 143, characters 7-14", result, -1); }); Mocha.test("the source of a JSX element's props runs", () => { logged("props", { @@ -206,46 +243,52 @@ Mocha.describe("Record_spread_source_effect_test", () => { a: 1, b: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 123, characters 7-14", takeCalls(), ["props"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 148, characters 7-14", takeCalls(), ["props"]); }); Mocha.test("sources of module-level and recursive records run", () => { - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 129, characters 6-13", moduleCalls, [ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 154, characters 6-13", moduleCalls, [ "polymorphic", "recursive", "cycle", "letCycle", "letCycleSource", "sequenceCycle", + "letRecCycle", "counter", "counterStart" ]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 142, characters 7-14", undefined, undefined); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 143, characters 7-14", undefined, undefined); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 144, characters 7-14", recursive_self().value, 2); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 145, characters 7-14", selfSpread_self().value, 3); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 146, characters 7-14", singleCallback.run(), 4); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 147, characters 7-14", cycle.next === cycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 148, characters 7-14", cycle.next.value, 7); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 149, characters 7-14", letCycle.next === letCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 150, characters 7-14", letCycle.next.value, 8); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 151, characters 7-14", sequenceCycle.next === sequenceCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 152, characters 7-14", sequenceCycle.next.value, 9); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 153, characters 7-14", counter_start, 10); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 154, characters 7-14", counter_step(), 11); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 155, characters 7-14", fromOtherModule, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 168, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 169, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 170, characters 7-14", recursive_self().value, 2); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 171, characters 7-14", selfSpread_self().value, 3); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 172, characters 7-14", singleCallback.run(), 4); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 173, characters 7-14", cycle.next === cycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 174, characters 7-14", cycle.next.value, 7); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 175, characters 7-14", letCycle.next === letCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 176, characters 7-14", letCycle.next.value, 8); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 177, characters 7-14", sequenceCycle.next === sequenceCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 178, characters 7-14", sequenceCycle.next.value, 9); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 179, characters 7-14", letRecCycle.next === letRecCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 180, characters 7-14", letRecCycle.next.value, 12); + let local = localLetRecCycle(13); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 182, characters 7-14", local.next === local, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 183, characters 7-14", local.next.value, 13); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 184, characters 7-14", counter_start, 10); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 185, characters 7-14", counter_step(), 11); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 186, characters 7-14", fromOtherModule, { x: 5, y: 6 }); }); Mocha.test("a pure source is left out", () => { - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 159, characters 7-14", overridePure(id({ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 190, characters 7-14", overridePure(id({ x: 0, y: 0 })), { x: 1, y: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 160, characters 7-14", takeCalls(), ["y"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 191, characters 7-14", takeCalls(), ["y"]); id({ a: 0 }); @@ -279,6 +322,8 @@ export { cycle, letCycle, sequenceCycle, + letRecCycle, + localLetRecCycle, nextCount, counter, moduleCalls, diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.res b/tests/compiler_tests/src/record_spread_source_effect_test.res index 8d1584055e..2c3e28441f 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.res +++ b/tests/compiler_tests/src/record_spread_source_effect_test.res @@ -75,6 +75,31 @@ let rec sequenceCycle = { {next: sequenceCycle, value: 9} } +// A recursive helper of the source is hoisted out of it, which leaves the +// record after a recursive let +let rec letRecCycle = { + ...{ + let rec retry = attempts => + attempts > 0 ? retry(attempts - 1) : logged("letRecCycle", makeNode(0)) + retry(id(2)) + }, + next: letRecCycle, + value: 12, +} + +// The same holds for a record local to a function +let localLetRecCycle = value => { + let rec node = { + ...{ + let rec retry = attempts => attempts > 0 ? retry(attempts - 1) : makeNode(0) + retry(id(2)) + }, + next: node, + value, + } + node +} + // A record of a recursive group whose fields read none of the group's bindings // when it is built is declared directly, after the expressions before it let rec nextCount = () => counter.start + 1 @@ -135,6 +160,7 @@ describe(__MODULE__, () => { "letCycle", "letCycleSource", "sequenceCycle", + "letRecCycle", "counter", "counterStart", ], @@ -150,6 +176,11 @@ describe(__MODULE__, () => { eq(__LOC__, letCycle.next.value, 8) eq(__LOC__, sequenceCycle.next === sequenceCycle, true) eq(__LOC__, sequenceCycle.next.value, 9) + eq(__LOC__, letRecCycle.next === letRecCycle, true) + eq(__LOC__, letRecCycle.next.value, 12) + let local = localLetRecCycle(13) + eq(__LOC__, local.next === local, true) + eq(__LOC__, local.next.value, 13) eq(__LOC__, counter.start, 10) eq(__LOC__, counter.step(), 11) eq(__LOC__, fromOtherModule, {x: 5, y: 6}) From c8b0a31b7e93c147cb58ed25c1c9ab9ee8cacdb3 Mon Sep 17 00:00:00 2001 From: Rob Date: Sat, 28 Nov 2026 12:54:03 -0500 Subject: [PATCH 05/14] Build a recursive record into a dummy when a source before it reads it Why: `block_after_effects` decided on a dummy from the fields of the final block only. A spread source that reads the record while it is built, as in `let rec n = {...{let rec tmp = {left: tmp, right: n, value: tick()}; tmp}, left: base, right: base, value: 1}`, leaves a recursive let before the block whose fields read nothing of the group. `compile_recursive_let` then declared `n` with its value after building `tmp`, which read `n` before it was initialized and threw a ReferenceError. An expression of a sequence, a let or a recursive let before the block that reads a binding of the group now also builds the record into a dummy. This answers Codex's review finding on #9427. JS modified (recursive record after a source that reads it): Example: type rec tree = {left: tree, right: tree, value: int} let rec n = { ...{ let rec tmp = {left: tmp, right: n, value: tick()} tmp }, left: base, right: base, value: 1, } Before (js): let tmp = {}; Primitive_object.updateDummy(tmp, { left: tmp, right: n, value: tick() }); let n = { left: base, right: base, value: 1 }; After (js): let n = {}; let tmp = {}; Primitive_object.updateDummy(tmp, { left: tmp, right: n, value: tick() }); Primitive_object.updateDummy(n, { left: base, right: base, value: 1 }); Review: Is a closure in a source that calls back into the record covered? `let rec k = {...{let g = () => k; ignore(g()); base}, ...}` is rejected by the recursive value check, so only direct reads need the dummy; a function before the block reads none, as for fields. Review: Is the Lambda term without optimization covered? There is still no switch to turn Lambda passes off; the test has the record both at module level and local to a function. Review: Which checked-in outputs change? Only record_spread_source_effect_test.mjs, for the new cases. Signed-off-by: Rob --- compiler/backend/lam_compile.ml | 40 ++++--- .../src/record_spread_source_effect_test.mjs | 102 +++++++++++++----- .../src/record_spread_source_effect_test.res | 34 ++++++ 3 files changed, 134 insertions(+), 42 deletions(-) diff --git a/compiler/backend/lam_compile.ml b/compiler/backend/lam_compile.ml index 402858a315..43a94896e5 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -85,14 +85,16 @@ let with_block_source_loc lam block = with_statement_source_loc (source_map_loc_of_lam lam) stmt :: rest (* The tag of the block that [lam] builds after evaluating other expressions, - when a field of the block may read one of the recursive [all_bindings], as - in [let rec r = {...f(), next: r}], whose spread source [f()] is evaluated - for its side effects first. The block may follow any chain of sequences, + when the block or the expressions before it may read one of the recursive + [all_bindings], as in [let rec r = {...f(), next: r}], whose spread source + [f()] is evaluated for its side effects first, or in + [let rec r = {...{let rec s = {next: r}; s}, next: base}], whose source + reads [r] while it is built. The block may follow any chain of sequences, lets and recursive lets, such as the one [Lam_pass_deep_flatten] leaves when - it hoists the bindings of a source out of it. Such a binding is declared as a dummy before - those expressions run, and the block is copied into it. A field that is a - function reads none when the block is built, whatever it refers to; any - other field reads one when it refers to a binding of the group. *) + it hoists the bindings of a source out of it. Such a binding is declared as + a dummy before those expressions run, and the block is copied into it. A + function reads none of the group when it is built, whatever it refers to; + any other expression reads one when it refers to a binding of the group. *) let block_after_effects ~(all_bindings : (Ident.t * Lambda.t) list) (lam : Lambda.t) = let group = Set_ident.of_list (List.map fst all_bindings) in @@ -101,17 +103,27 @@ let block_after_effects ~(all_bindings : (Ident.t * Lambda.t) list) | Lfunction _ -> false | _ -> Lam_hit.hit_variables group arg in - (* [after_effects]: [lam] is evaluated after other expressions. A bare block - is compiled into a dummy by the caller already. *) - let rec block_tag ~after_effects (lam : Lambda.t) = + (* [prefix_reads]: an expression evaluated before [lam] reads a binding of the + group. [after_effects]: [lam] is evaluated after other expressions. A bare + block is compiled into a dummy by the caller already. *) + let rec block_tag ~prefix_reads ~after_effects (lam : Lambda.t) = match lam with | Lprim {primitive = Pmakeblock tag_info; args} when after_effects -> - if List.exists reads_binding args then Some tag_info else None - | Lsequence (_, body) | Llet (_, _, _, body) | Lletrec (_, body) -> - block_tag ~after_effects:true body + if prefix_reads || List.exists reads_binding args then Some tag_info + else None + | Lsequence (prefix, body) | Llet (_, _, prefix, body) -> + block_tag + ~prefix_reads:(prefix_reads || reads_binding prefix) + ~after_effects:true body + | Lletrec (bindings, body) -> + block_tag + ~prefix_reads: + (prefix_reads + || List.exists (fun (_, binding) -> reads_binding binding) bindings) + ~after_effects:true body | _ -> None in - block_tag ~after_effects:false lam + block_tag ~prefix_reads:false ~after_effects:false lam let args_either_function_or_const (args : Lambda.t list) = List.for_all diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.mjs b/tests/compiler_tests/src/record_spread_source_effect_test.mjs index 21808bdb79..bb03b4cd42 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.mjs +++ b/tests/compiler_tests/src/record_spread_source_effect_test.mjs @@ -145,6 +145,44 @@ function localLetRecCycle(value) { return node; } +let leaf = {}; + +leaf.left = leaf; + +leaf.right = leaf; + +leaf.value = 0; + +let prefixRead = {}; + +let source = {}; + +Primitive_object.updateDummy(source, { + left: source, + right: prefixRead, + value: logged("prefixRead", id(14)) +}); + +Primitive_object.updateDummy(prefixRead, { + left: leaf, + right: leaf, + value: 14 +}); + +function localPrefixRead(value) { + let tree = {}; + let source = {}; + source.left = source; + source.right = tree; + source.value = value; + Primitive_object.updateDummy(tree, { + left: leaf, + right: leaf, + value: value + }); + return tree; +} + function nextCount() { return counter.start + 1 | 0; } @@ -195,12 +233,12 @@ Mocha.describe("Record_spread_source_effect_test", () => { x: point_x, y: point_y }; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 124, characters 7-14", takeCalls(), [ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 154, characters 7-14", takeCalls(), [ "source", "x", "y" ]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 125, characters 7-14", point, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 155, characters 7-14", point, { x: 1, y: 2 }); @@ -213,12 +251,12 @@ Mocha.describe("Record_spread_source_effect_test", () => { width: 1, height: 2 }; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 130, characters 7-14", takeCalls(), ["source"]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 131, characters 7-14", options, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 160, characters 7-14", takeCalls(), ["source"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 161, characters 7-14", options, { width: 1, height: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 133, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 163, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); }); Mocha.test("a source that raises stops the record from being built", () => { let result; @@ -233,7 +271,7 @@ Mocha.describe("Record_spread_source_effect_test", () => { throw exn; } } - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 143, characters 7-14", result, -1); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 173, characters 7-14", result, -1); }); Mocha.test("the source of a JSX element's props runs", () => { logged("props", { @@ -243,10 +281,10 @@ Mocha.describe("Record_spread_source_effect_test", () => { a: 1, b: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 148, characters 7-14", takeCalls(), ["props"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 178, characters 7-14", takeCalls(), ["props"]); }); Mocha.test("sources of module-level and recursive records run", () => { - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 154, characters 6-13", moduleCalls, [ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 184, characters 6-13", moduleCalls, [ "polymorphic", "recursive", "cycle", @@ -254,41 +292,46 @@ Mocha.describe("Record_spread_source_effect_test", () => { "letCycleSource", "sequenceCycle", "letRecCycle", + "prefixRead", "counter", "counterStart" ]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 168, characters 7-14", undefined, undefined); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 169, characters 7-14", undefined, undefined); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 170, characters 7-14", recursive_self().value, 2); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 171, characters 7-14", selfSpread_self().value, 3); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 172, characters 7-14", singleCallback.run(), 4); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 173, characters 7-14", cycle.next === cycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 174, characters 7-14", cycle.next.value, 7); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 175, characters 7-14", letCycle.next === letCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 176, characters 7-14", letCycle.next.value, 8); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 177, characters 7-14", sequenceCycle.next === sequenceCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 178, characters 7-14", sequenceCycle.next.value, 9); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 179, characters 7-14", letRecCycle.next === letRecCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 180, characters 7-14", letRecCycle.next.value, 12); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 199, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 200, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 201, characters 7-14", recursive_self().value, 2); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 202, characters 7-14", selfSpread_self().value, 3); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 203, characters 7-14", singleCallback.run(), 4); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 204, characters 7-14", cycle.next === cycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 205, characters 7-14", cycle.next.value, 7); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 206, characters 7-14", letCycle.next === letCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 207, characters 7-14", letCycle.next.value, 8); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 208, characters 7-14", sequenceCycle.next === sequenceCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 209, characters 7-14", sequenceCycle.next.value, 9); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 210, characters 7-14", letRecCycle.next === letRecCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 211, characters 7-14", letRecCycle.next.value, 12); let local = localLetRecCycle(13); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 182, characters 7-14", local.next === local, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 183, characters 7-14", local.next.value, 13); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 184, characters 7-14", counter_start, 10); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 185, characters 7-14", counter_step(), 11); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 186, characters 7-14", fromOtherModule, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 213, characters 7-14", local.next === local, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 214, characters 7-14", local.next.value, 13); + let localPrefix = localPrefixRead(15); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 216, characters 7-14", prefixRead.left === leaf, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 217, characters 7-14", prefixRead.value, 14); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 218, characters 7-14", localPrefix.value, 15); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 219, characters 7-14", counter_start, 10); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 220, characters 7-14", counter_step(), 11); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 221, characters 7-14", fromOtherModule, { x: 5, y: 6 }); }); Mocha.test("a pure source is left out", () => { - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 190, characters 7-14", overridePure(id({ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 225, characters 7-14", overridePure(id({ x: 0, y: 0 })), { x: 1, y: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 191, characters 7-14", takeCalls(), ["y"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 226, characters 7-14", takeCalls(), ["y"]); id({ a: 0 }); @@ -324,6 +367,9 @@ export { sequenceCycle, letRecCycle, localLetRecCycle, + leaf, + prefixRead, + localPrefixRead, nextCount, counter, moduleCalls, diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.res b/tests/compiler_tests/src/record_spread_source_effect_test.res index 2c3e28441f..9ed573b96c 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.res +++ b/tests/compiler_tests/src/record_spread_source_effect_test.res @@ -10,6 +10,7 @@ type polymorphic<'a> = {compare: option<('a, 'a) => int>, first: option<'a>} type rec recursive = {self: unit => recursive, value: int} type callback = {run: unit => int} type rec node = {next: node, value: int} +type rec tree = {left: tree, right: tree, value: int} type counter = {start: int, step: unit => int} module Component = { @@ -100,6 +101,34 @@ let localLetRecCycle = value => { node } +// A source that reads the record while it is built sees the record, even +// though none of the record's own fields reads it +let rec leaf = {left: leaf, right: leaf, value: 0} + +let rec prefixRead = { + ...{ + let rec source = {left: source, right: prefixRead, value: logged("prefixRead", id(14))} + source + }, + left: leaf, + right: leaf, + value: 14, +} + +// The same holds for a record local to a function +let localPrefixRead = value => { + let rec tree = { + ...{ + let rec source = {left: source, right: tree, value} + source + }, + left: leaf, + right: leaf, + value, + } + tree +} + // A record of a recursive group whose fields read none of the group's bindings // when it is built is declared directly, after the expressions before it let rec nextCount = () => counter.start + 1 @@ -161,6 +190,7 @@ describe(__MODULE__, () => { "letCycleSource", "sequenceCycle", "letRecCycle", + "prefixRead", "counter", "counterStart", ], @@ -181,6 +211,10 @@ describe(__MODULE__, () => { let local = localLetRecCycle(13) eq(__LOC__, local.next === local, true) eq(__LOC__, local.next.value, 13) + let localPrefix = localPrefixRead(15) + eq(__LOC__, prefixRead.left === leaf, true) + eq(__LOC__, prefixRead.value, 14) + eq(__LOC__, localPrefix.value, 15) eq(__LOC__, counter.start, 10) eq(__LOC__, counter.step(), 11) eq(__LOC__, fromOtherModule, {x: 5, y: 6}) From 3b332e52dd047e512e58261c66e8c9c5df003780 Mon Sep 17 00:00:00 2001 From: Rob Date: Sat, 28 Nov 2026 12:54:19 -0500 Subject: [PATCH 06/14] Keep warning 23 on in the record spread source tests Why: record_spread_source_effect_test.res and record_spread_pure_source.res turned warning 23 off for the whole file with `@@warning("-23")`, which AGENTS.md rules out. Every spread they test has all its fields overridden, the very case the warning reports, so no rewrite avoids it, and tests/tests builds with `-warn-error A-110`, where it would fail the build. The files now leave the warning on and only take it out of the errors with `-warn-error -23` in their `@@config` flags, so it is still reported. This answers Codex's review finding on #9427. Review: Does any output change? No: the flags only decide whether the warning fails the build. The build prints the warning for each of these spreads. Signed-off-by: Rob --- tests/compiler_tests/src/record_spread_pure_source.res | 4 ++-- .../compiler_tests/src/record_spread_source_effect_test.res | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/tests/compiler_tests/src/record_spread_pure_source.res b/tests/compiler_tests/src/record_spread_pure_source.res index 3785894094..ec100f94cc 100644 --- a/tests/compiler_tests/src/record_spread_pure_source.res +++ b/tests/compiler_tests/src/record_spread_pure_source.res @@ -2,8 +2,8 @@ // leaves no trace in the output: `override` and `overrideJsx` are still small // enough to be inlined, and `overridden` is emitted before `base`, as a record // without the spread would be. -@@warning("-23") -@@config({flags: ["-bs-jsx", "4"]}) +// Warning 23 reports these spreads; it stays on, but not as an error. +@@config({flags: ["-bs-jsx", "4", "-warn-error", "-23"]}) type point = {x: int, y: int} diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.res b/tests/compiler_tests/src/record_spread_source_effect_test.res index 9ed573b96c..027ee81d6b 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.res +++ b/tests/compiler_tests/src/record_spread_source_effect_test.res @@ -1,5 +1,6 @@ -@@warning("-23") -@@config({flags: ["-bs-jsx", "4"]}) +// Every spread here has all its fields overridden, which warning 23 reports. +// The warning stays on, but not as an error, since that spread is under test. +@@config({flags: ["-bs-jsx", "4", "-warn-error", "-23"]}) open Mocha open Test_utils From c68d7d34195e05c799778b68c03e9e9532e6c636 Mon Sep 17 00:00:00 2001 From: Rob Date: Sat, 28 Nov 2026 14:49:37 -0500 Subject: [PATCH 07/14] Build a constant recursive record into a dummy when a source reads it Why: `block_after_effects` recognized only a `Pmakeblock` at the end of the chain before a recursive record. When every field of the final record is a constant, `transl_record` makes it an `Lconst (Const_block ...)`, as in `let rec n = {...{let rec tmp = {left: Some(tmp), right: Some(n), value: tick()}; tmp}, left: None, right: None, value: 1}`. `compile_recursive_let` then declared `n` after building `tmp`, which read `n` before it was initialized and threw a ReferenceError, at module level and in a function. A constant block after an expression that reads the group now also builds the record into a dummy; the constant itself reads nothing. This answers Codex's review finding on #9427. JS modified (constant recursive record after a source that reads it): Example: type rec branch = {lower: option, upper: option, weight: int} let rec n = { ...{ let rec tmp = {lower: Some(tmp), upper: Some(n), weight: tick()} tmp }, lower: None, upper: None, weight: 1, } Before (js): let tmp = {}; Primitive_object.updateDummy(tmp, { lower: tmp, upper: n, weight: tick() }); let n = { lower: undefined, upper: undefined, weight: 1 }; After (js): let n = {}; let tmp = {}; Primitive_object.updateDummy(tmp, { lower: tmp, upper: n, weight: tick() }); Primitive_object.updateDummy(n, { lower: undefined, upper: undefined, weight: 1 }); Review: Are other final shapes missed? The recursive value check accepts effects before the record only for the record spread, whose final record is a `Pmakeblock` or, with constant fields, an `Lconst (Const_block ...)`; both are handled now. A constant constructor or other immediate there is rejected by that check. Review: Which checked-in outputs change? Only record_spread_source_effect_test.mjs, for the new cases. Signed-off-by: Rob --- compiler/backend/lam_compile.ml | 7 +- .../src/record_spread_source_effect_test.mjs | 107 +++++++++++++----- .../src/record_spread_source_effect_test.res | 34 ++++++ 3 files changed, 116 insertions(+), 32 deletions(-) diff --git a/compiler/backend/lam_compile.ml b/compiler/backend/lam_compile.ml index 43a94896e5..85ce8d9f88 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -91,7 +91,9 @@ let with_block_source_loc lam block = [let rec r = {...{let rec s = {next: r}; s}, next: base}], whose source reads [r] while it is built. The block may follow any chain of sequences, lets and recursive lets, such as the one [Lam_pass_deep_flatten] leaves when - it hoists the bindings of a source out of it. Such a binding is declared as + it hoists the bindings of a source out of it. The block is built by + [Pmakeblock], or is a constant when its fields are all constants, as + [transl_record] makes [{...s, next: None}]. Such a binding is declared as a dummy before those expressions run, and the block is copied into it. A function reads none of the group when it is built, whatever it refers to; any other expression reads one when it refers to a binding of the group. *) @@ -111,6 +113,9 @@ let block_after_effects ~(all_bindings : (Ident.t * Lambda.t) list) | Lprim {primitive = Pmakeblock tag_info; args} when after_effects -> if prefix_reads || List.exists reads_binding args then Some tag_info else None + | Lconst (Const_block (tag_info, _)) when after_effects -> + (* A constant reads nothing itself *) + if prefix_reads then Some tag_info else None | Lsequence (prefix, body) | Llet (_, _, prefix, body) -> block_tag ~prefix_reads:(prefix_reads || reads_binding prefix) diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.mjs b/tests/compiler_tests/src/record_spread_source_effect_test.mjs index bb03b4cd42..69e9f0f45b 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.mjs +++ b/tests/compiler_tests/src/record_spread_source_effect_test.mjs @@ -183,6 +183,38 @@ function localPrefixRead(value) { return tree; } +let constantPrefixRead = {}; + +let source$1 = {}; + +Primitive_object.updateDummy(source$1, { + lower: source$1, + upper: constantPrefixRead, + weight: logged("constantPrefixRead", id(16)) +}); + +Primitive_object.updateDummy(constantPrefixRead, { + lower: undefined, + upper: undefined, + weight: 16 +}); + +function localConstantPrefixRead(value) { + let branch = {}; + let source = {}; + Primitive_object.updateDummy(source, { + lower: source, + upper: branch, + weight: value + }); + Primitive_object.updateDummy(branch, { + lower: undefined, + upper: undefined, + weight: 17 + }); + return branch; +} + function nextCount() { return counter.start + 1 | 0; } @@ -233,12 +265,12 @@ Mocha.describe("Record_spread_source_effect_test", () => { x: point_x, y: point_y }; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 154, characters 7-14", takeCalls(), [ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 185, characters 7-14", takeCalls(), [ "source", "x", "y" ]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 155, characters 7-14", point, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 186, characters 7-14", point, { x: 1, y: 2 }); @@ -251,12 +283,12 @@ Mocha.describe("Record_spread_source_effect_test", () => { width: 1, height: 2 }; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 160, characters 7-14", takeCalls(), ["source"]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 161, characters 7-14", options, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 191, characters 7-14", takeCalls(), ["source"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 192, characters 7-14", options, { width: 1, height: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 163, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 194, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); }); Mocha.test("a source that raises stops the record from being built", () => { let result; @@ -271,7 +303,7 @@ Mocha.describe("Record_spread_source_effect_test", () => { throw exn; } } - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 173, characters 7-14", result, -1); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 204, characters 7-14", result, -1); }); Mocha.test("the source of a JSX element's props runs", () => { logged("props", { @@ -281,10 +313,10 @@ Mocha.describe("Record_spread_source_effect_test", () => { a: 1, b: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 178, characters 7-14", takeCalls(), ["props"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 209, characters 7-14", takeCalls(), ["props"]); }); Mocha.test("sources of module-level and recursive records run", () => { - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 184, characters 6-13", moduleCalls, [ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 215, characters 6-13", moduleCalls, [ "polymorphic", "recursive", "cycle", @@ -293,45 +325,56 @@ Mocha.describe("Record_spread_source_effect_test", () => { "sequenceCycle", "letRecCycle", "prefixRead", + "constantPrefixRead", "counter", "counterStart" ]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 199, characters 7-14", undefined, undefined); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 200, characters 7-14", undefined, undefined); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 201, characters 7-14", recursive_self().value, 2); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 202, characters 7-14", selfSpread_self().value, 3); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 203, characters 7-14", singleCallback.run(), 4); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 204, characters 7-14", cycle.next === cycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 205, characters 7-14", cycle.next.value, 7); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 206, characters 7-14", letCycle.next === letCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 207, characters 7-14", letCycle.next.value, 8); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 208, characters 7-14", sequenceCycle.next === sequenceCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 209, characters 7-14", sequenceCycle.next.value, 9); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 210, characters 7-14", letRecCycle.next === letRecCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 211, characters 7-14", letRecCycle.next.value, 12); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 231, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 232, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 233, characters 7-14", recursive_self().value, 2); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 234, characters 7-14", selfSpread_self().value, 3); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 235, characters 7-14", singleCallback.run(), 4); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 236, characters 7-14", cycle.next === cycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 237, characters 7-14", cycle.next.value, 7); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 238, characters 7-14", letCycle.next === letCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 239, characters 7-14", letCycle.next.value, 8); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 240, characters 7-14", sequenceCycle.next === sequenceCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 241, characters 7-14", sequenceCycle.next.value, 9); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 242, characters 7-14", letRecCycle.next === letRecCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 243, characters 7-14", letRecCycle.next.value, 12); let local = localLetRecCycle(13); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 213, characters 7-14", local.next === local, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 214, characters 7-14", local.next.value, 13); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 245, characters 7-14", local.next === local, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 246, characters 7-14", local.next.value, 13); let localPrefix = localPrefixRead(15); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 216, characters 7-14", prefixRead.left === leaf, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 217, characters 7-14", prefixRead.value, 14); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 218, characters 7-14", localPrefix.value, 15); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 219, characters 7-14", counter_start, 10); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 220, characters 7-14", counter_step(), 11); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 221, characters 7-14", fromOtherModule, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 248, characters 7-14", prefixRead.left === leaf, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 249, characters 7-14", prefixRead.value, 14); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 250, characters 7-14", localPrefix.value, 15); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 251, characters 7-14", constantPrefixRead, { + lower: undefined, + upper: undefined, + weight: 16 + }); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 252, characters 7-14", localConstantPrefixRead(18), { + lower: undefined, + upper: undefined, + weight: 17 + }); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 253, characters 7-14", counter_start, 10); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 254, characters 7-14", counter_step(), 11); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 255, characters 7-14", fromOtherModule, { x: 5, y: 6 }); }); Mocha.test("a pure source is left out", () => { - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 225, characters 7-14", overridePure(id({ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 259, characters 7-14", overridePure(id({ x: 0, y: 0 })), { x: 1, y: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 226, characters 7-14", takeCalls(), ["y"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 260, characters 7-14", takeCalls(), ["y"]); id({ a: 0 }); @@ -370,6 +413,8 @@ export { leaf, prefixRead, localPrefixRead, + constantPrefixRead, + localConstantPrefixRead, nextCount, counter, moduleCalls, diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.res b/tests/compiler_tests/src/record_spread_source_effect_test.res index 027ee81d6b..b7f071cbb5 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.res +++ b/tests/compiler_tests/src/record_spread_source_effect_test.res @@ -13,6 +13,7 @@ type callback = {run: unit => int} type rec node = {next: node, value: int} type rec tree = {left: tree, right: tree, value: int} type counter = {start: int, step: unit => int} +type rec branch = {lower: option, upper: option, weight: int} module Component = { @react.component @@ -130,6 +131,36 @@ let localPrefixRead = value => { tree } +// The same holds when the record's fields are all constants, so that the +// record is a constant +let rec constantPrefixRead = { + ...{ + let rec source = { + lower: Some(source), + upper: Some(constantPrefixRead), + weight: logged("constantPrefixRead", id(16)), + } + source + }, + lower: None, + upper: None, + weight: 16, +} + +// The same holds for a record local to a function +let localConstantPrefixRead = value => { + let rec branch = { + ...{ + let rec source = {lower: Some(source), upper: Some(branch), weight: value} + source + }, + lower: None, + upper: None, + weight: 17, + } + branch +} + // A record of a recursive group whose fields read none of the group's bindings // when it is built is declared directly, after the expressions before it let rec nextCount = () => counter.start + 1 @@ -192,6 +223,7 @@ describe(__MODULE__, () => { "sequenceCycle", "letRecCycle", "prefixRead", + "constantPrefixRead", "counter", "counterStart", ], @@ -216,6 +248,8 @@ describe(__MODULE__, () => { eq(__LOC__, prefixRead.left === leaf, true) eq(__LOC__, prefixRead.value, 14) eq(__LOC__, localPrefix.value, 15) + eq(__LOC__, constantPrefixRead, {lower: None, upper: None, weight: 16}) + eq(__LOC__, localConstantPrefixRead(18), {lower: None, upper: None, weight: 17}) eq(__LOC__, counter.start, 10) eq(__LOC__, counter.step(), 11) eq(__LOC__, fromOtherModule, {x: 5, y: 6}) From c4907efb9ceca55fff13623984352f45140d8839 Mon Sep 17 00:00:00 2001 From: Rob Date: Sat, 28 Nov 2026 14:58:45 -0500 Subject: [PATCH 08/14] Find a recursive record's tail block before checking its reads Why: `block_after_effects` threaded two flags through its walk of the chain before a recursive record and tested the group's reads once for a `Pmakeblock` and once for a constant block. It now finds the block at the end of the chain with the expressions evaluated to build it, and only then tests whether one of them reads the group, so the set of the group's bindings is built only when a block is found. The tags it gives are the same. `writes_all_labels` read the first label's `lbl_all` as `Translcore.all_labels` does; `all_labels` moves to `Typedtree` and `writes_all_labels` uses it. Review: Does any output change? No: this is a refactor, and no checked-in output changes. Signed-off-by: Rob --- compiler/backend/lam_compile.ml | 44 ++++++++++++++------------------- compiler/typing/translcore.ml | 10 -------- compiler/typing/typedtree.ml | 10 +++++--- compiler/typing/typedtree.mli | 6 +++++ 4 files changed, 32 insertions(+), 38 deletions(-) diff --git a/compiler/backend/lam_compile.ml b/compiler/backend/lam_compile.ml index 85ce8d9f88..0a669916eb 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -99,36 +99,30 @@ let with_block_source_loc lam block = any other expression reads one when it refers to a binding of the group. *) let block_after_effects ~(all_bindings : (Ident.t * Lambda.t) list) (lam : Lambda.t) = - let group = Set_ident.of_list (List.map fst all_bindings) in - let reads_binding (arg : Lambda.t) = - match arg with - | Lfunction _ -> false - | _ -> Lam_hit.hit_variables group arg - in - (* [prefix_reads]: an expression evaluated before [lam] reads a binding of the - group. [after_effects]: [lam] is evaluated after other expressions. A bare - block is compiled into a dummy by the caller already. *) - let rec block_tag ~prefix_reads ~after_effects (lam : Lambda.t) = + (* The tag of the block at the end of the chain, with the expressions + evaluated to build it: those before it and its fields. A bare block is + compiled into a dummy by the caller already. *) + let rec tail_block ~before (lam : Lambda.t) = match lam with - | Lprim {primitive = Pmakeblock tag_info; args} when after_effects -> - if prefix_reads || List.exists reads_binding args then Some tag_info - else None - | Lconst (Const_block (tag_info, _)) when after_effects -> - (* A constant reads nothing itself *) - if prefix_reads then Some tag_info else None | Lsequence (prefix, body) | Llet (_, _, prefix, body) -> - block_tag - ~prefix_reads:(prefix_reads || reads_binding prefix) - ~after_effects:true body + tail_block ~before:(prefix :: before) body | Lletrec (bindings, body) -> - block_tag - ~prefix_reads: - (prefix_reads - || List.exists (fun (_, binding) -> reads_binding binding) bindings) - ~after_effects:true body + tail_block ~before:(List.map snd bindings @ before) body + | Lprim {primitive = Pmakeblock tag_info; args} -> + Some (tag_info, args @ before) + | Lconst (Const_block (tag_info, _)) -> Some (tag_info, before) | _ -> None in - block_tag ~prefix_reads:false ~after_effects:false lam + match tail_block ~before:[] lam with + | Some (tag_info, evaluated) -> + let group = Set_ident.of_list (List.map fst all_bindings) in + let reads_binding (arg : Lambda.t) = + match arg with + | Lfunction _ -> false + | _ -> Lam_hit.hit_variables group arg + in + if List.exists reads_binding evaluated then Some tag_info else None + | None -> None let args_either_function_or_const (args : Lambda.t list) = List.for_all diff --git a/compiler/typing/translcore.ml b/compiler/typing/translcore.ml index 957f6ffc74..18bc98ed95 100644 --- a/compiler/typing/translcore.ml +++ b/compiler/typing/translcore.ml @@ -1032,16 +1032,6 @@ let jsx_children ~multi (lbl : label_description) (child : expression) = Some children | _ -> None -(* All labels of the record a [Texp_record] builds. Its [fields] hold only the - written ones. *) -let all_labels - (fields : (label_description * Longident.t loc * expression) array) = - match fields with - | [||] -> [||] - | _ -> - let lbl, _, _ = fields.(0) in - lbl.lbl_all - (* Each label of the record with the expression the literal writes for it, if any, in position order. A list rather than an array: [Array.map] over more than 256 labels (JSX props) forces a minor collection, which stops every diff --git a/compiler/typing/typedtree.ml b/compiler/typing/typedtree.ml index d2d174ac5d..398c379356 100644 --- a/compiler/typing/typedtree.ml +++ b/compiler/typing/typedtree.ml @@ -569,10 +569,14 @@ let rec alpha_pat env p = let mkloc = Location.mkloc let mknoloc = Location.mknoloc -let writes_all_labels +let all_labels (fields : (label_description * Longident.t loc * expression) array) = match fields with - | [||] -> false + | [||] -> [||] | _ -> let lbl, _, _ = fields.(0) in - Array.length fields = Array.length lbl.lbl_all + lbl.lbl_all + +let writes_all_labels fields = + Array.length fields > 0 + && Array.length fields = Array.length (all_labels fields) diff --git a/compiler/typing/typedtree.mli b/compiler/typing/typedtree.mli index 9b512a196a..a4fad7b6f9 100644 --- a/compiler/typing/typedtree.mli +++ b/compiler/typing/typedtree.mli @@ -603,6 +603,12 @@ val exp_warning_attributes : expression -> attributes [Builtin_attributes.warning_scope] takes them: its own, then those of the type constraints around it, which [exp_extra] holds outermost first. *) +val all_labels : + (Types.label_description * Longident.t loc * expression) array -> + Types.label_description array +(** All labels of the record a [Texp_record] builds. Its [fields] hold only the + written ones. *) + val writes_all_labels : (Types.label_description * Longident.t loc * expression) array -> bool (** Whether the [fields] of a [Texp_record] hold every label of the record *) From 37bb2f04c5cea12566bd11d4bf6be6f2c5b38859 Mon Sep 17 00:00:00 2001 From: Rob Date: Sat, 28 Nov 2026 16:09:00 -0500 Subject: [PATCH 09/14] Declare a recursive binding before an earlier binding reads it Why: `compile_recursive_lets` decided for each binding of a `let rec` group on its own whether to build it into a dummy declared before the group or to declare it directly where it is built. A binding built into a dummy may read another binding of the group while it is built, and when that one came later and was declared directly, as `a` in `let rec b = {next: Some(a), f: () => b} and a = {next: None, f: () => b}`, it was read before its `let` and loading the module, or calling the function holding the group, threw a ReferenceError. Since the source of a record spread is evaluated, it reaches this through a source that reads a later binding as well, as in `let rec b = {...{let rec s = {next: Some(a), ...}; s}, ...} and a = {...}`, which the review of #9427 found. The group is now looked at as a whole: a binding that a binding built before it reads is built into a dummy too, so it is declared before that read. Its block is built where it was, so the order of effects is kept. `block_after_effects` shares the walk to the block at the end of the chain and the test of the reads with this check. JS modified (record of a recursive group read by a record built before it): Example: type rec pair = {other: option, back: unit => pair} let rec first = {other: Some(second), back: () => first} and second = {other: None, back: () => first} Before (js): let first = {}; Primitive_object.updateDummy(first, { other: second, back: () => first }); function second_back() { return first; } let second = { other: undefined, back: second_back }; After (js): let first = {}; let second = {}; Primitive_object.updateDummy(first, { other: second, back: () => first }); Primitive_object.updateDummy(second, { other: undefined, back: () => first }); Review: Which checked-in outputs change? Only those of the new cases in recursive_records_test.mjs and record_spread_source_effect_test.mjs; a binding is built into a dummy only when a binding built before it may read it, which could throw a ReferenceError before. Review: Is a binding that builds no block covered? No: an array or an option of a record, as `x` in `let rec y = {f: x, g: () => 1} and x = Some(y)`, cannot be a dummy, and is still declared after the binding reading it, as on master. Signed-off-by: Rob --- compiler/backend/lam_compile.ml | 105 ++++++++++----- .../src/record_spread_source_effect_test.mjs | 121 +++++++++++++----- .../src/record_spread_source_effect_test.res | 39 ++++++ .../src/recursive_records_test.mjs | 58 ++++++++- .../src/recursive_records_test.res | 25 ++++ 5 files changed, 279 insertions(+), 69 deletions(-) diff --git a/compiler/backend/lam_compile.ml b/compiler/backend/lam_compile.ml index 0a669916eb..c76ef1c2b8 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -84,45 +84,83 @@ let with_block_source_loc lam block = | stmt :: rest -> with_statement_source_loc (source_map_loc_of_lam lam) stmt :: rest -(* The tag of the block that [lam] builds after evaluating other expressions, - when the block or the expressions before it may read one of the recursive - [all_bindings], as in [let rec r = {...f(), next: r}], whose spread source - [f()] is evaluated for its side effects first, or in - [let rec r = {...{let rec s = {next: r}; s}, next: base}], whose source - reads [r] while it is built. The block may follow any chain of sequences, - lets and recursive lets, such as the one [Lam_pass_deep_flatten] leaves when - it hoists the bindings of a source out of it. The block is built by - [Pmakeblock], or is a constant when its fields are all constants, as - [transl_record] makes [{...s, next: None}]. Such a binding is declared as - a dummy before those expressions run, and the block is copied into it. A - function reads none of the group when it is built, whatever it refers to; - any other expression reads one when it refers to a binding of the group. *) -let block_after_effects ~(all_bindings : (Ident.t * Lambda.t) list) - (lam : Lambda.t) = - (* The tag of the block at the end of the chain, with the expressions - evaluated to build it: those before it and its fields. A bare block is - compiled into a dummy by the caller already. *) - let rec tail_block ~before (lam : Lambda.t) = +(* The tag of the block that [lam] builds at the end of a chain of sequences, + lets and recursive lets, with the expressions evaluated to build it: those + before it and its fields. Such a chain is the one [Lam_pass_deep_flatten] + leaves when it hoists the bindings of a spread source out of a record. The + block is built by [Pmakeblock], or is a constant when its fields are all + constants, as [transl_record] makes [{...s, next: None}]. *) +let tail_block (lam : Lambda.t) = + let rec find ~before (lam : Lambda.t) = match lam with | Lsequence (prefix, body) | Llet (_, _, prefix, body) -> - tail_block ~before:(prefix :: before) body + find ~before:(prefix :: before) body | Lletrec (bindings, body) -> - tail_block ~before:(List.map snd bindings @ before) body + find ~before:(List.map snd bindings @ before) body | Lprim {primitive = Pmakeblock tag_info; args} -> Some (tag_info, args @ before) | Lconst (Const_block (tag_info, _)) -> Some (tag_info, before) | _ -> None in - match tail_block ~before:[] lam with - | Some (tag_info, evaluated) -> - let group = Set_ident.of_list (List.map fst all_bindings) in - let reads_binding (arg : Lambda.t) = + find ~before:[] lam + +(* Whether evaluating the expressions [evaluated] may read a binding of + [group]. A function reads none of them when it is built, whatever it refers + to; any other expression reads one when it refers to it. *) +let reads_any group (evaluated : Lambda.t list) = + List.exists + (fun (arg : Lambda.t) -> match arg with | Lfunction _ -> false - | _ -> Lam_hit.hit_variables group arg - in - if List.exists reads_binding evaluated then Some tag_info else None - | None -> None + | _ -> Lam_hit.hit_variables group arg) + evaluated + +(* The tag of the block that [lam] builds after evaluating other expressions, + when the block or the expressions before it may read one of the recursive + [all_bindings], as in [let rec r = {...f(), next: r}], whose spread source + [f()] is evaluated for its side effects first, or in + [let rec r = {...{let rec s = {next: r}; s}, next: base}], whose source + reads [r] while it is built. Such a binding is declared as a dummy before + those expressions run, and the block is copied into it. A bare block is + compiled into a dummy by the caller already. *) +let block_after_effects ~(all_bindings : (Ident.t * Lambda.t) list) + (lam : Lambda.t) = + match tail_block lam with + | Some (tag_info, evaluated) + when reads_any (Set_ident.of_list (List.map fst all_bindings)) evaluated -> + Some tag_info + | Some _ | None -> None + +(* The bindings of [group] that building [lam] may read: those the + expressions evaluated to build its block read, or, for any other value, + those it reads. *) +let reads_when_built group (lam : Lambda.t) = + let evaluated = + match tail_block lam with + | Some (_, evaluated) -> evaluated + | None -> [lam] + in + Set_ident.filter + (fun id -> reads_any (Set_ident.singleton id) evaluated) + group + +(* The bindings of the recursive group [id_args], listed in the order they are + built, that a binding built before them reads, as [a] in + [let rec b = {next: Some(a), f: () => b} and a = {next: None, f: () => b}]. + Such a binding must be declared before that read, so it is built into a + dummy even when it could be declared directly where it is built. *) +let read_before_built (id_args : (Ident.t * Lambda.t) list) = + let group = Set_ident.of_list (List.map fst id_args) in + snd + (List.fold_left + (fun (read, read_before) (id, arg) -> + let read_before = + if Set_ident.mem id read then Set_ident.add id read_before + else read_before + in + (Set_ident.union read (reads_when_built group arg), read_before)) + (Set_ident.empty, Set_ident.empty) + id_args) let args_either_function_or_const (args : Lambda.t list) = List.for_all @@ -847,11 +885,18 @@ let compile output_prefix = and compile_recursive_lets_aux cxt (id_args : (Ident.t * Lambda.t) list) : Js_output.t = (* #1716 *) + let read_before = read_before_built id_args in let output_code, ids = List.fold_right (fun (ident, arg) (acc, ids) -> + (* A binding read before it is built that builds no block, such as + an array, cannot be a dummy and is declared where it is built *) let code, declare_ids = - compile_recursive_let ~all_bindings:id_args cxt ident arg + match tail_block arg with + | Some (tag_info, _) when Set_ident.mem ident read_before -> + compile_into_dummy cxt ident tag_info arg + | Some _ | None -> + compile_recursive_let ~all_bindings:id_args cxt ident arg in (Js_output.append_output code acc, List.append declare_ids ids)) id_args (Js_output.dummy, []) diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.mjs b/tests/compiler_tests/src/record_spread_source_effect_test.mjs index 69e9f0f45b..8efbd10219 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.mjs +++ b/tests/compiler_tests/src/record_spread_source_effect_test.mjs @@ -215,6 +215,52 @@ function localConstantPrefixRead(value) { return branch; } +let sourceReadsLater = {}; + +let later = {}; + +let source$2 = {}; + +Primitive_object.updateDummy(source$2, { + next: later, + back: () => source$2, + weight: logged("sourceReadsLater", id(19)) +}); + +Primitive_object.updateDummy(sourceReadsLater, { + next: undefined, + back: () => sourceReadsLater, + weight: 19 +}); + +Primitive_object.updateDummy(later, { + next: undefined, + back: () => sourceReadsLater, + weight: 20 +}); + +function localSourceReadsLater(weight) { + let link = {}; + let later = {}; + let source = {}; + Primitive_object.updateDummy(source, { + next: later, + back: () => source, + weight: weight + }); + Primitive_object.updateDummy(link, { + next: undefined, + back: () => link, + weight: weight + }); + Primitive_object.updateDummy(later, { + next: undefined, + back: () => link, + weight: weight + 1 | 0 + }); + return link; +} + function nextCount() { return counter.start + 1 | 0; } @@ -265,12 +311,12 @@ Mocha.describe("Record_spread_source_effect_test", () => { x: point_x, y: point_y }; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 185, characters 7-14", takeCalls(), [ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 218, characters 7-14", takeCalls(), [ "source", "x", "y" ]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 186, characters 7-14", point, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 219, characters 7-14", point, { x: 1, y: 2 }); @@ -283,12 +329,12 @@ Mocha.describe("Record_spread_source_effect_test", () => { width: 1, height: 2 }; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 191, characters 7-14", takeCalls(), ["source"]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 192, characters 7-14", options, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 224, characters 7-14", takeCalls(), ["source"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 225, characters 7-14", options, { width: 1, height: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 194, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 227, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); }); Mocha.test("a source that raises stops the record from being built", () => { let result; @@ -303,7 +349,7 @@ Mocha.describe("Record_spread_source_effect_test", () => { throw exn; } } - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 204, characters 7-14", result, -1); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 237, characters 7-14", result, -1); }); Mocha.test("the source of a JSX element's props runs", () => { logged("props", { @@ -313,10 +359,10 @@ Mocha.describe("Record_spread_source_effect_test", () => { a: 1, b: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 209, characters 7-14", takeCalls(), ["props"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 242, characters 7-14", takeCalls(), ["props"]); }); Mocha.test("sources of module-level and recursive records run", () => { - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 215, characters 6-13", moduleCalls, [ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 248, characters 6-13", moduleCalls, [ "polymorphic", "recursive", "cycle", @@ -326,55 +372,61 @@ Mocha.describe("Record_spread_source_effect_test", () => { "letRecCycle", "prefixRead", "constantPrefixRead", + "sourceReadsLater", "counter", "counterStart" ]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 231, characters 7-14", undefined, undefined); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 232, characters 7-14", undefined, undefined); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 233, characters 7-14", recursive_self().value, 2); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 234, characters 7-14", selfSpread_self().value, 3); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 235, characters 7-14", singleCallback.run(), 4); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 236, characters 7-14", cycle.next === cycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 237, characters 7-14", cycle.next.value, 7); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 238, characters 7-14", letCycle.next === letCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 239, characters 7-14", letCycle.next.value, 8); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 240, characters 7-14", sequenceCycle.next === sequenceCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 241, characters 7-14", sequenceCycle.next.value, 9); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 242, characters 7-14", letRecCycle.next === letRecCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 243, characters 7-14", letRecCycle.next.value, 12); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 265, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 266, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 267, characters 7-14", recursive_self().value, 2); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 268, characters 7-14", selfSpread_self().value, 3); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 269, characters 7-14", singleCallback.run(), 4); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 270, characters 7-14", cycle.next === cycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 271, characters 7-14", cycle.next.value, 7); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 272, characters 7-14", letCycle.next === letCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 273, characters 7-14", letCycle.next.value, 8); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 274, characters 7-14", sequenceCycle.next === sequenceCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 275, characters 7-14", sequenceCycle.next.value, 9); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 276, characters 7-14", letRecCycle.next === letRecCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 277, characters 7-14", letRecCycle.next.value, 12); let local = localLetRecCycle(13); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 245, characters 7-14", local.next === local, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 246, characters 7-14", local.next.value, 13); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 279, characters 7-14", local.next === local, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 280, characters 7-14", local.next.value, 13); let localPrefix = localPrefixRead(15); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 248, characters 7-14", prefixRead.left === leaf, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 249, characters 7-14", prefixRead.value, 14); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 250, characters 7-14", localPrefix.value, 15); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 251, characters 7-14", constantPrefixRead, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 282, characters 7-14", prefixRead.left === leaf, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 283, characters 7-14", prefixRead.value, 14); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 284, characters 7-14", localPrefix.value, 15); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 285, characters 7-14", constantPrefixRead, { lower: undefined, upper: undefined, weight: 16 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 252, characters 7-14", localConstantPrefixRead(18), { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 286, characters 7-14", localConstantPrefixRead(18), { lower: undefined, upper: undefined, weight: 17 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 253, characters 7-14", counter_start, 10); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 254, characters 7-14", counter_step(), 11); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 255, characters 7-14", fromOtherModule, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 287, characters 7-14", sourceReadsLater.weight, 19); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 288, characters 7-14", later.back() === sourceReadsLater, true); + let localLink = localSourceReadsLater(21); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 290, characters 7-14", localLink.weight, 21); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 291, characters 7-14", localLink.back() === localLink, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 292, characters 7-14", counter_start, 10); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 293, characters 7-14", counter_step(), 11); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 294, characters 7-14", fromOtherModule, { x: 5, y: 6 }); }); Mocha.test("a pure source is left out", () => { - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 259, characters 7-14", overridePure(id({ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 298, characters 7-14", overridePure(id({ x: 0, y: 0 })), { x: 1, y: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 260, characters 7-14", takeCalls(), ["y"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 299, characters 7-14", takeCalls(), ["y"]); id({ a: 0 }); @@ -415,6 +467,9 @@ export { localPrefixRead, constantPrefixRead, localConstantPrefixRead, + sourceReadsLater, + later, + localSourceReadsLater, nextCount, counter, moduleCalls, diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.res b/tests/compiler_tests/src/record_spread_source_effect_test.res index b7f071cbb5..6e0e410bfd 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.res +++ b/tests/compiler_tests/src/record_spread_source_effect_test.res @@ -14,6 +14,7 @@ type rec node = {next: node, value: int} type rec tree = {left: tree, right: tree, value: int} type counter = {start: int, step: unit => int} type rec branch = {lower: option, upper: option, weight: int} +type rec link = {next: option, back: unit => link, weight: int} module Component = { @react.component @@ -161,6 +162,38 @@ let localConstantPrefixRead = value => { branch } +// A binding of the group that a source reads while it is built is declared +// before that read, even one that could be declared where it is built +let rec sourceReadsLater = { + ...{ + let rec source = { + next: Some(later), + back: () => source, + weight: logged("sourceReadsLater", id(19)), + } + source + }, + next: None, + back: () => sourceReadsLater, + weight: 19, +} +and later = {next: None, back: () => sourceReadsLater, weight: 20} + +// The same holds for a record local to a function +let localSourceReadsLater = weight => { + let rec link = { + ...{ + let rec source = {next: Some(later), back: () => source, weight} + source + }, + next: None, + back: () => link, + weight, + } + and later = {next: None, back: () => link, weight: weight + 1} + link +} + // A record of a recursive group whose fields read none of the group's bindings // when it is built is declared directly, after the expressions before it let rec nextCount = () => counter.start + 1 @@ -224,6 +257,7 @@ describe(__MODULE__, () => { "letRecCycle", "prefixRead", "constantPrefixRead", + "sourceReadsLater", "counter", "counterStart", ], @@ -250,6 +284,11 @@ describe(__MODULE__, () => { eq(__LOC__, localPrefix.value, 15) eq(__LOC__, constantPrefixRead, {lower: None, upper: None, weight: 16}) eq(__LOC__, localConstantPrefixRead(18), {lower: None, upper: None, weight: 17}) + eq(__LOC__, sourceReadsLater.weight, 19) + eq(__LOC__, later.back() === sourceReadsLater, true) + let localLink = localSourceReadsLater(21) + eq(__LOC__, localLink.weight, 21) + eq(__LOC__, localLink.back() === localLink, true) eq(__LOC__, counter.start, 10) eq(__LOC__, counter.step(), 11) eq(__LOC__, fromOtherModule, {x: 5, y: 6}) diff --git a/tests/compiler_tests/src/recursive_records_test.mjs b/tests/compiler_tests/src/recursive_records_test.mjs index 758ab04f20..f81a788e58 100644 --- a/tests/compiler_tests/src/recursive_records_test.mjs +++ b/tests/compiler_tests/src/recursive_records_test.mjs @@ -69,6 +69,43 @@ rec_cell3.hd = 3; rec_cell3.tl = rec_cell3; +let first = {}; + +let second = {}; + +Primitive_object.updateDummy(first, { + other: second, + back: () => first +}); + +Primitive_object.updateDummy(second, { + other: undefined, + back: () => first +}); + +function localPair() { + let first = {}; + let second = {}; + Primitive_object.updateDummy(first, { + other: second, + back: () => first + }); + Primitive_object.updateDummy(second, { + other: undefined, + back: () => first + }); + return first; +} + +function pointsBack(pair) { + let other = pair.other; + if (other !== undefined) { + return other.back() === pair; + } else { + return false; + } +} + function f3(x) { let rec_cell3 = {}; Primitive_object.updateDummy(rec_cell3, {hd: (x * x | 0) - 6 | 0, tl: rec_cell3}); @@ -77,18 +114,23 @@ function f3(x) { Mocha.describe("Recursive_records_test", () => { Mocha.test("recursive record operations", () => { - Test_utils.eq("File \"recursive_records_test.res\", line 57, characters 7-14", a0(rec_cell), 9); - Test_utils.eq("File \"recursive_records_test.res\", line 58, characters 7-14", a0(f0(3)), 9); + Test_utils.eq("File \"recursive_records_test.res\", line 76, characters 7-14", a0(rec_cell), 9); + Test_utils.eq("File \"recursive_records_test.res\", line 77, characters 7-14", a0(f0(3)), 9); }); Mocha.test("recursive inline record operations", () => { - Test_utils.eq("File \"recursive_records_test.res\", line 62, characters 7-14", (hd(rec_cell2) + hd(tl_exn(rec_cell2)) | 0) + hd(tl_exn(tl_exn(rec_cell2))) | 0, 9); + Test_utils.eq("File \"recursive_records_test.res\", line 81, characters 7-14", (hd(rec_cell2) + hd(tl_exn(rec_cell2)) | 0) + hd(tl_exn(tl_exn(rec_cell2))) | 0, 9); let rec_cell2$1 = f2(3); - Test_utils.eq("File \"recursive_records_test.res\", line 64, characters 7-14", (hd(rec_cell2$1) + hd(tl_exn(rec_cell2$1)) | 0) + hd(tl_exn(tl_exn(rec_cell2$1))) | 0, 9); + Test_utils.eq("File \"recursive_records_test.res\", line 83, characters 7-14", (hd(rec_cell2$1) + hd(tl_exn(rec_cell2$1)) | 0) + hd(tl_exn(tl_exn(rec_cell2$1))) | 0, 9); + }); + Mocha.test("recursive records reading a record built after them", () => { + Test_utils.eq("File \"recursive_records_test.res\", line 87, characters 7-14", pointsBack(first), true); + Test_utils.eq("File \"recursive_records_test.res\", line 88, characters 7-14", second.back() === first, true); + Test_utils.eq("File \"recursive_records_test.res\", line 89, characters 7-14", pointsBack(localPair()), true); }); Mocha.test("recursive variant list operations", () => { - Test_utils.eq("File \"recursive_records_test.res\", line 70, characters 7-14", (Stdlib_List.headOrThrow(rec_cell3) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(rec_cell3)) | 0) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(Stdlib_List.tailOrThrow(rec_cell3))) | 0, 9); + Test_utils.eq("File \"recursive_records_test.res\", line 95, characters 7-14", (Stdlib_List.headOrThrow(rec_cell3) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(rec_cell3)) | 0) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(Stdlib_List.tailOrThrow(rec_cell3))) | 0, 9); let rec_cell3$1 = f3(3); - Test_utils.eq("File \"recursive_records_test.res\", line 72, characters 7-14", (Stdlib_List.headOrThrow(rec_cell3$1) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(rec_cell3$1)) | 0) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(Stdlib_List.tailOrThrow(rec_cell3$1))) | 0, 9); + Test_utils.eq("File \"recursive_records_test.res\", line 97, characters 7-14", (Stdlib_List.headOrThrow(rec_cell3$1) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(rec_cell3$1)) | 0) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(Stdlib_List.tailOrThrow(rec_cell3$1))) | 0, 9); }); }); @@ -101,6 +143,10 @@ export { hd, tl_exn, rec_cell3, + first, + second, + localPair, + pointsBack, f3, } /* Not a pure module */ diff --git a/tests/compiler_tests/src/recursive_records_test.res b/tests/compiler_tests/src/recursive_records_test.res index 0a3b8cea24..b8e2495eca 100644 --- a/tests/compiler_tests/src/recursive_records_test.res +++ b/tests/compiler_tests/src/recursive_records_test.res @@ -47,6 +47,25 @@ let tl_exn = x => let rec rec_cell3 = list{3, ...rec_cell3} /* over variant */ +type rec pair = {other: option, back: unit => pair} + +// A record built into a dummy reads a record of its group built after it, +// which is declared before that read +let rec first = {other: Some(second), back: () => first} +and second = {other: None, back: () => first} + +let localPair = () => { + let rec first = {other: Some(second), back: () => first} + and second = {other: None, back: () => first} + first +} + +let pointsBack = pair => + switch pair.other { + | Some(other) => other.back() === pair + | None => false + } + let f3 = x => { let rec rec_cell3 = list{x * x - 6, ...rec_cell3} /* over variant */ rec_cell3 @@ -64,6 +83,12 @@ describe(__MODULE__, () => { eq(__LOC__, hd(rec_cell2) + hd(tl_exn(rec_cell2)) + hd(tl_exn(tl_exn(rec_cell2))), 9) }) + test("recursive records reading a record built after them", () => { + eq(__LOC__, pointsBack(first), true) + eq(__LOC__, second.back() === first, true) + eq(__LOC__, pointsBack(localPair()), true) + }) + test("recursive variant list operations", () => { let hd = List.headOrThrow let tl = List.tailOrThrow From eba91e0efa31cad4073563d05a81d3b809960e25 Mon Sep 17 00:00:00 2001 From: Rob Date: Sat, 28 Nov 2026 16:09:11 -0500 Subject: [PATCH 10/14] Note that a recursive record's spread source is checked Why: Since the source of a record spread whose fields are all overridden is evaluated, a `let rec` checks it as it does any other expression, so code that compiled before, with warning 23, is now rejected. Only a `.fix.md` fragment described the change; this adds a breaking one, which the review of #9427 asked for. Review: Which code stops compiling? A recursive record whose overridden spread source reads the binding outside a function, as `let rec callback = {...wrap(callback), run: () => 1}`, where `wrap(callback)` was never called before. Breaking: `let rec r = {...f(r), ...}` with every field of `r` given is now the error "This kind of expression is not allowed as right-hand side of `let rec`" instead of warning 23. Remove the spread, whose value was never used, or build the source without reading `r`. Signed-off-by: Rob --- changes/rec-record-spread-source-check.breaking.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changes/rec-record-spread-source-check.breaking.md diff --git a/changes/rec-record-spread-source-check.breaking.md b/changes/rec-record-spread-source-check.breaking.md new file mode 100644 index 0000000000..6bf008dc90 --- /dev/null +++ b/changes/rec-record-spread-source-check.breaking.md @@ -0,0 +1 @@ +- The source of a record spread whose fields are all overridden is now checked in a `let rec` like any other expression, since it is evaluated. `let rec callback = {...wrap(callback), run: () => 1}`, which compiled with warning 23 and never called `wrap`, is now an error: remove the spread, or build the source without reading the binding. From 311b970ebbdadc6d2c18db96a290424ceb67f351 Mon Sep 17 00:00:00 2001 From: Rob Date: Sat, 28 Nov 2026 21:36:12 -0500 Subject: [PATCH 11/14] Look for a recursive binding's reads only in bindings built after it Why: The benchmarks job of #9427 found `stress/LetRec.res`, a `let rec` group of 2000 functions, allocating 114% more and running 33% more instructions. `read_before_built` tested every binding of the group against every other, building a singleton set for each test, even for a function, which reads nothing when it is built. It now skips a binding that evaluates nothing other than functions, and looks for the bindings built after a binding only in what that binding evaluates. The bindings it marks are the same. Measured locally on the generated `LetRec.res`: 67,988,696 words allocated before, 31,860,259 after, 31,878,175 without #9427. Review: Does any output change? No: the same bindings are built into dummies, and no checked-in output changes. Signed-off-by: Rob --- compiler/backend/lam_compile.ml | 52 +++++++++++++++++++++------------ 1 file changed, 33 insertions(+), 19 deletions(-) diff --git a/compiler/backend/lam_compile.ml b/compiler/backend/lam_compile.ml index c76ef1c2b8..e49d58a47d 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -131,36 +131,50 @@ let block_after_effects ~(all_bindings : (Ident.t * Lambda.t) list) Some tag_info | Some _ | None -> None -(* The bindings of [group] that building [lam] may read: those the - expressions evaluated to build its block read, or, for any other value, - those it reads. *) -let reads_when_built group (lam : Lambda.t) = +(* The expressions evaluated to build [lam] that may read a variable while + they are evaluated: those evaluated to build its block or, for any other + value, [lam] itself. A function reads none when it is built, so a group of + functions, the common [let rec], has none to look at. *) +let evaluated_reads (lam : Lambda.t) = let evaluated = match tail_block lam with | Some (_, evaluated) -> evaluated | None -> [lam] in - Set_ident.filter - (fun id -> reads_any (Set_ident.singleton id) evaluated) - group + List.filter + (fun (arg : Lambda.t) -> + match arg with + | Lfunction _ -> false + | _ -> true) + evaluated (* The bindings of the recursive group [id_args], listed in the order they are built, that a binding built before them reads, as [a] in [let rec b = {next: Some(a), f: () => b} and a = {next: None, f: () => b}]. Such a binding must be declared before that read, so it is built into a - dummy even when it could be declared directly where it is built. *) + dummy even when it could be declared directly where it is built. Only the + bindings built after a binding are looked for in what it reads, and only + when it evaluates something other than functions, so a group of functions + costs one walk over its bindings. *) let read_before_built (id_args : (Ident.t * Lambda.t) list) = - let group = Set_ident.of_list (List.map fst id_args) in - snd - (List.fold_left - (fun (read, read_before) (id, arg) -> - let read_before = - if Set_ident.mem id read then Set_ident.add id read_before - else read_before - in - (Set_ident.union read (reads_when_built group arg), read_before)) - (Set_ident.empty, Set_ident.empty) - id_args) + let rec mark read_before (id_args : (Ident.t * Lambda.t) list) = + match id_args with + | [] -> read_before + | (_, arg) :: later -> ( + match evaluated_reads arg with + | [] -> mark read_before later + | evaluated -> + let read_before = + List.fold_left + (fun read_before (id, _) -> + if List.exists (Lam_hit.hit_variable id) evaluated then + Set_ident.add id read_before + else read_before) + read_before later + in + mark read_before later) + in + mark Set_ident.empty id_args let args_either_function_or_const (args : Lambda.t list) = List.for_all From ea859072e2b315a61e112fc759e11bf422b67ad5 Mon Sep 17 00:00:00 2001 From: Rob Date: Sat, 28 Nov 2026 21:52:37 -0500 Subject: [PATCH 12/14] Say that a spread's source is still evaluated in warning 23 Why: Since this PR the source of a record spread whose fields are all overridden is evaluated, so warning 23's advice to remove the spread would drop the call in `{...f(), a: 1, b: 2}`, as the review of #9427 noted. `Useless_record_with` now records whether the source is a variable: for a variable the message is unchanged, for any other source it says that the spread copies none of the fields and that the source is still evaluated. The review also asked for tests of mutually recursive records and of a record inside a variant whose sources are evaluated, and #9466 (an earlier record of a `let rec` group reading a later one declared directly) is fixed by 7b2e4ebb2; tests for all three are added and the changelog fragments mention them. Review: Which outputs change? The warning text in rec_record_spread_source.res.expected, the new warning_23_useless_record_with_call.res fixture, and the outputs of the new test cases in record_spread_source_effect_test.mjs and recursive_records_test.mjs. Signed-off-by: Rob --- changes/let-rec-record-after-effects.fix.md | 2 +- changes/record-spread-source-effect.fix.md | 2 +- compiler/typing/typecore.ml | 10 +- compiler/typing/warnings.ml | 10 +- compiler/typing/warnings.mli | 4 +- .../src/record_spread_source_effect_test.mjs | 135 +++++++++++++----- .../src/record_spread_source_effect_test.res | 43 ++++++ .../src/recursive_records_test.mjs | 36 +++-- .../src/recursive_records_test.res | 11 ++ .../rec_record_spread_source.res.expected | 2 +- ...g_23_useless_record_with_call.res.expected | 11 ++ .../warning_23_useless_record_with_call.res | 6 + 12 files changed, 217 insertions(+), 55 deletions(-) create mode 100644 tests/error_tests/single/expected/warning_23_useless_record_with_call.res.expected create mode 100644 tests/error_tests/single/fixtures/warning_23_useless_record_with_call.res diff --git a/changes/let-rec-record-after-effects.fix.md b/changes/let-rec-record-after-effects.fix.md index 384195e57d..31839d3734 100644 --- a/changes/let-rec-record-after-effects.fix.md +++ b/changes/let-rec-record-after-effects.fix.md @@ -1 +1 @@ -- Fix a `let rec` record that refers to itself and is built after other expressions, as in `let rec r = {...f(), next: r}` or `let rec r = {log(); {next: r}}`, reading itself before it is initialized. +- Fix a `let rec` record that refers to itself and is built after other expressions, as in `let rec r = {...f(), next: r}` or `let rec r = {log(); {next: r}}`, reading itself before it is initialized, and a record of a `let rec` group being read by a record built before it, as `a` in `let rec b = {next: a, v: 1} and a = {f: () => b, w: 2}`, before it is declared (#9466). diff --git a/changes/record-spread-source-effect.fix.md b/changes/record-spread-source-effect.fix.md index 72ea9246df..b31a614e09 100644 --- a/changes/record-spread-source-effect.fix.md +++ b/changes/record-spread-source-effect.fix.md @@ -1 +1 @@ -- Fix the source of a record spread (or JSX props spread) not being evaluated when every field is overridden, as in `{...f(), a: 1, b: 2}`. +- Fix the source of a record spread (or JSX props spread) not being evaluated when every field is overridden, as in `{...f(), a: 1, b: 2}`. Warning 23 on such a spread now says that its source is still evaluated, instead of suggesting to remove the spread, unless the source is a variable. diff --git a/compiler/typing/typecore.ml b/compiler/typing/typecore.ml index 3372397521..3b4a1e562c 100644 --- a/compiler/typing/typecore.ml +++ b/compiler/typing/typecore.ml @@ -3175,8 +3175,14 @@ and type_expect_ ?deprecated_context ~context ?(recarg = Rejected) lbl_repres in let fields = record_fields lbl_exp_list in - if writes_all_labels fields then - Loc_report.prerr_warning loc Warnings.Useless_record_with; + (if writes_all_labels fields then + let source_is_variable = + match exp.exp_desc with + | Texp_ident _ -> true + | _ -> false + in + Loc_report.prerr_warning loc + (Warnings.Useless_record_with {source_is_variable})); re { exp_desc = diff --git a/compiler/typing/warnings.ml b/compiler/typing/warnings.ml index 6d98ad2126..41e4b961e0 100644 --- a/compiler/typing/warnings.ml +++ b/compiler/typing/warnings.ml @@ -39,7 +39,7 @@ type t = | Unused_argument (* 20 *) | Nonreturning_statement (* 21 *) | Preprocessor of string (* 22 *) - | Useless_record_with (* 23 *) + | Useless_record_with of {source_is_variable: bool} (* 23 *) | All_clauses_guarded (* 8, used to be 25 *) | Unused_var of string (* 26 *) | Unused_var_strict of string (* 27 *) @@ -94,7 +94,7 @@ let number = function | Unused_argument -> 20 | Nonreturning_statement -> 21 | Preprocessor _ -> 22 - | Useless_record_with -> 23 + | Useless_record_with _ -> 23 | All_clauses_guarded -> 8 (* used to be 25 *) | Unused_var _ -> 26 | Unused_var_strict _ -> 27 @@ -307,9 +307,13 @@ let message = function | Nonreturning_statement -> "This statement does not continue execution; following code is unreachable." | Preprocessor s -> s - | Useless_record_with -> + | Useless_record_with {source_is_variable = true} -> "All the fields are already explicitly listed in this record. You can \ remove the `...` spread." + | Useless_record_with {source_is_variable = false} -> + "All the fields are already explicitly listed in this record, so the `...` \ + spread copies none of them. Its source is still evaluated: if you remove \ + the spread, keep any effect the source has." | All_clauses_guarded -> "this pattern-matching is not exhaustive.\n\ All clauses in this pattern-matching are guarded." diff --git a/compiler/typing/warnings.mli b/compiler/typing/warnings.mli index 71d9e4c865..fb9b85d0eb 100644 --- a/compiler/typing/warnings.mli +++ b/compiler/typing/warnings.mli @@ -32,7 +32,9 @@ type t = | Unused_argument (* 20 *) | Nonreturning_statement (* 21 *) | Preprocessor of string (* 22 *) - | Useless_record_with (* 23 *) + | Useless_record_with of {source_is_variable: bool} + (* 23: whether the source of the spread is a variable, which can be + removed without dropping an effect *) | All_clauses_guarded (* 8, used to be 25 *) | Unused_var of string (* 26 *) | Unused_var_strict of string (* 27 *) diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.mjs b/tests/compiler_tests/src/record_spread_source_effect_test.mjs index 8efbd10219..663f904071 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.mjs +++ b/tests/compiler_tests/src/record_spread_source_effect_test.mjs @@ -2,6 +2,7 @@ import * as Mocha from "mocha"; import * as Test_utils from "./test_utils.mjs"; +import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.mjs"; import * as Stdlib_JsError from "@rescript/runtime/lib/es6/Stdlib_JsError.mjs"; import * as Primitive_object from "@rescript/runtime/lib/es6/Primitive_object.mjs"; import * as JsxRuntime from "react/jsx-runtime"; @@ -261,6 +262,53 @@ function localSourceReadsLater(weight) { return link; } +function makeLink(weight) { + let link = {}; + Primitive_object.updateDummy(link, { + next: undefined, + back: () => link, + weight: weight + }); + return link; +} + +let mutualFirst = {}; + +let mutualSecond = {}; + +Primitive_object.updateDummy(mutualFirst, (logged("mutualFirst", makeLink(0)), { + next: mutualSecond, + back: () => mutualSecond, + weight: 22 +})); + +Primitive_object.updateDummy(mutualSecond, (logged("mutualSecond", makeLink(0)), { + next: mutualFirst, + back: () => mutualFirst, + weight: 23 +})); + +let wrapped = {}; + +Primitive_object.updateDummy(wrapped, { + TAG: "Shape", + _0: (logged("wrapped", id({ + around: "NoShape", + size: 0 + })), { + around: wrapped, + size: 24 + }) +}); + +function isWrapped(shape) { + if (typeof shape !== "object") { + return false; + } else { + return shape._0.around === shape; + } +} + function nextCount() { return counter.start + 1 | 0; } @@ -311,12 +359,12 @@ Mocha.describe("Record_spread_source_effect_test", () => { x: point_x, y: point_y }; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 218, characters 7-14", takeCalls(), [ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 253, characters 7-14", takeCalls(), [ "source", "x", "y" ]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 219, characters 7-14", point, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 254, characters 7-14", point, { x: 1, y: 2 }); @@ -329,12 +377,12 @@ Mocha.describe("Record_spread_source_effect_test", () => { width: 1, height: 2 }; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 224, characters 7-14", takeCalls(), ["source"]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 225, characters 7-14", options, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 259, characters 7-14", takeCalls(), ["source"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 260, characters 7-14", options, { width: 1, height: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 227, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 262, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); }); Mocha.test("a source that raises stops the record from being built", () => { let result; @@ -349,7 +397,7 @@ Mocha.describe("Record_spread_source_effect_test", () => { throw exn; } } - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 237, characters 7-14", result, -1); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 272, characters 7-14", result, -1); }); Mocha.test("the source of a JSX element's props runs", () => { logged("props", { @@ -359,10 +407,10 @@ Mocha.describe("Record_spread_source_effect_test", () => { a: 1, b: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 242, characters 7-14", takeCalls(), ["props"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 277, characters 7-14", takeCalls(), ["props"]); }); Mocha.test("sources of module-level and recursive records run", () => { - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 248, characters 6-13", moduleCalls, [ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 283, characters 6-13", moduleCalls, [ "polymorphic", "recursive", "cycle", @@ -373,60 +421,68 @@ Mocha.describe("Record_spread_source_effect_test", () => { "prefixRead", "constantPrefixRead", "sourceReadsLater", + "mutualFirst", + "mutualSecond", + "wrapped", "counter", "counterStart" ]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 265, characters 7-14", undefined, undefined); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 266, characters 7-14", undefined, undefined); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 267, characters 7-14", recursive_self().value, 2); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 268, characters 7-14", selfSpread_self().value, 3); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 269, characters 7-14", singleCallback.run(), 4); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 270, characters 7-14", cycle.next === cycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 271, characters 7-14", cycle.next.value, 7); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 272, characters 7-14", letCycle.next === letCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 273, characters 7-14", letCycle.next.value, 8); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 274, characters 7-14", sequenceCycle.next === sequenceCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 275, characters 7-14", sequenceCycle.next.value, 9); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 276, characters 7-14", letRecCycle.next === letRecCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 277, characters 7-14", letRecCycle.next.value, 12); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 303, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 304, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 305, characters 7-14", recursive_self().value, 2); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 306, characters 7-14", selfSpread_self().value, 3); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 307, characters 7-14", singleCallback.run(), 4); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 308, characters 7-14", cycle.next === cycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 309, characters 7-14", cycle.next.value, 7); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 310, characters 7-14", letCycle.next === letCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 311, characters 7-14", letCycle.next.value, 8); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 312, characters 7-14", sequenceCycle.next === sequenceCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 313, characters 7-14", sequenceCycle.next.value, 9); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 314, characters 7-14", letRecCycle.next === letRecCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 315, characters 7-14", letRecCycle.next.value, 12); let local = localLetRecCycle(13); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 279, characters 7-14", local.next === local, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 280, characters 7-14", local.next.value, 13); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 317, characters 7-14", local.next === local, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 318, characters 7-14", local.next.value, 13); let localPrefix = localPrefixRead(15); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 282, characters 7-14", prefixRead.left === leaf, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 283, characters 7-14", prefixRead.value, 14); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 284, characters 7-14", localPrefix.value, 15); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 285, characters 7-14", constantPrefixRead, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 320, characters 7-14", prefixRead.left === leaf, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 321, characters 7-14", prefixRead.value, 14); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 322, characters 7-14", localPrefix.value, 15); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 323, characters 7-14", constantPrefixRead, { lower: undefined, upper: undefined, weight: 16 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 286, characters 7-14", localConstantPrefixRead(18), { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 324, characters 7-14", localConstantPrefixRead(18), { lower: undefined, upper: undefined, weight: 17 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 287, characters 7-14", sourceReadsLater.weight, 19); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 288, characters 7-14", later.back() === sourceReadsLater, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 325, characters 7-14", sourceReadsLater.weight, 19); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 326, characters 7-14", later.back() === sourceReadsLater, true); let localLink = localSourceReadsLater(21); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 290, characters 7-14", localLink.weight, 21); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 291, characters 7-14", localLink.back() === localLink, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 292, characters 7-14", counter_start, 10); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 293, characters 7-14", counter_step(), 11); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 294, characters 7-14", fromOtherModule, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 328, characters 7-14", localLink.weight, 21); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 329, characters 7-14", localLink.back() === localLink, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 330, characters 7-14", Stdlib_Option.map(mutualFirst.next, next => next === mutualSecond), true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 331, characters 7-14", Stdlib_Option.map(mutualSecond.next, next => next === mutualFirst), true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 332, characters 7-14", mutualFirst.back() === mutualSecond, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 333, characters 7-14", mutualSecond.weight, 23); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 334, characters 7-14", isWrapped(wrapped), true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 335, characters 7-14", counter_start, 10); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 336, characters 7-14", counter_step(), 11); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 337, characters 7-14", fromOtherModule, { x: 5, y: 6 }); }); Mocha.test("a pure source is left out", () => { - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 298, characters 7-14", overridePure(id({ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 341, characters 7-14", overridePure(id({ x: 0, y: 0 })), { x: 1, y: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 299, characters 7-14", takeCalls(), ["y"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 342, characters 7-14", takeCalls(), ["y"]); id({ a: 0 }); @@ -470,6 +526,11 @@ export { sourceReadsLater, later, localSourceReadsLater, + makeLink, + mutualFirst, + mutualSecond, + wrapped, + isWrapped, nextCount, counter, moduleCalls, diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.res b/tests/compiler_tests/src/record_spread_source_effect_test.res index 6e0e410bfd..bf67356d37 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.res +++ b/tests/compiler_tests/src/record_spread_source_effect_test.res @@ -16,6 +16,9 @@ type counter = {start: int, step: unit => int} type rec branch = {lower: option, upper: option, weight: int} type rec link = {next: option, back: unit => link, weight: int} +type rec shape = Shape(shapeRecord) | NoShape +and shapeRecord = {around: shape, size: int} + module Component = { @react.component let make = (~a: int, ~b: int=2) => React.int(a + b) @@ -194,6 +197,38 @@ let localSourceReadsLater = weight => { link } +// Each record of a mutually recursive group evaluates its own source +let makeLink = weight => { + let rec link = {next: None, back: () => link, weight} + link +} + +let rec mutualFirst = { + ...logged("mutualFirst", makeLink(0)), + next: Some(mutualSecond), + back: () => mutualSecond, + weight: 22, +} +and mutualSecond = { + ...logged("mutualSecond", makeLink(0)), + next: Some(mutualFirst), + back: () => mutualFirst, + weight: 23, +} + +// The same holds for a record inside a variant +let rec wrapped = Shape({ + ...logged("wrapped", id({around: NoShape, size: 0})), + around: wrapped, + size: 24, +}) + +let isWrapped = shape => + switch shape { + | Shape({around}) => around === shape + | NoShape => false + } + // A record of a recursive group whose fields read none of the group's bindings // when it is built is declared directly, after the expressions before it let rec nextCount = () => counter.start + 1 @@ -258,6 +293,9 @@ describe(__MODULE__, () => { "prefixRead", "constantPrefixRead", "sourceReadsLater", + "mutualFirst", + "mutualSecond", + "wrapped", "counter", "counterStart", ], @@ -289,6 +327,11 @@ describe(__MODULE__, () => { let localLink = localSourceReadsLater(21) eq(__LOC__, localLink.weight, 21) eq(__LOC__, localLink.back() === localLink, true) + eq(__LOC__, mutualFirst.next->Option.map(next => next === mutualSecond), Some(true)) + eq(__LOC__, mutualSecond.next->Option.map(next => next === mutualFirst), Some(true)) + eq(__LOC__, mutualFirst.back() === mutualSecond, true) + eq(__LOC__, mutualSecond.weight, 23) + eq(__LOC__, isWrapped(wrapped), true) eq(__LOC__, counter.start, 10) eq(__LOC__, counter.step(), 11) eq(__LOC__, fromOtherModule, {x: 5, y: 6}) diff --git a/tests/compiler_tests/src/recursive_records_test.mjs b/tests/compiler_tests/src/recursive_records_test.mjs index f81a788e58..389a4e3743 100644 --- a/tests/compiler_tests/src/recursive_records_test.mjs +++ b/tests/compiler_tests/src/recursive_records_test.mjs @@ -97,6 +97,20 @@ function localPair() { return first; } +let holder = {}; + +let held = {}; + +Primitive_object.updateDummy(holder, { + held: held, + size: 1 +}); + +Primitive_object.updateDummy(held, { + holder: () => holder, + weight: 2 +}); + function pointsBack(pair) { let other = pair.other; if (other !== undefined) { @@ -114,23 +128,25 @@ function f3(x) { Mocha.describe("Recursive_records_test", () => { Mocha.test("recursive record operations", () => { - Test_utils.eq("File \"recursive_records_test.res\", line 76, characters 7-14", a0(rec_cell), 9); - Test_utils.eq("File \"recursive_records_test.res\", line 77, characters 7-14", a0(f0(3)), 9); + Test_utils.eq("File \"recursive_records_test.res\", line 85, characters 7-14", a0(rec_cell), 9); + Test_utils.eq("File \"recursive_records_test.res\", line 86, characters 7-14", a0(f0(3)), 9); }); Mocha.test("recursive inline record operations", () => { - Test_utils.eq("File \"recursive_records_test.res\", line 81, characters 7-14", (hd(rec_cell2) + hd(tl_exn(rec_cell2)) | 0) + hd(tl_exn(tl_exn(rec_cell2))) | 0, 9); + Test_utils.eq("File \"recursive_records_test.res\", line 90, characters 7-14", (hd(rec_cell2) + hd(tl_exn(rec_cell2)) | 0) + hd(tl_exn(tl_exn(rec_cell2))) | 0, 9); let rec_cell2$1 = f2(3); - Test_utils.eq("File \"recursive_records_test.res\", line 83, characters 7-14", (hd(rec_cell2$1) + hd(tl_exn(rec_cell2$1)) | 0) + hd(tl_exn(tl_exn(rec_cell2$1))) | 0, 9); + Test_utils.eq("File \"recursive_records_test.res\", line 92, characters 7-14", (hd(rec_cell2$1) + hd(tl_exn(rec_cell2$1)) | 0) + hd(tl_exn(tl_exn(rec_cell2$1))) | 0, 9); }); Mocha.test("recursive records reading a record built after them", () => { - Test_utils.eq("File \"recursive_records_test.res\", line 87, characters 7-14", pointsBack(first), true); - Test_utils.eq("File \"recursive_records_test.res\", line 88, characters 7-14", second.back() === first, true); - Test_utils.eq("File \"recursive_records_test.res\", line 89, characters 7-14", pointsBack(localPair()), true); + Test_utils.eq("File \"recursive_records_test.res\", line 96, characters 7-14", pointsBack(first), true); + Test_utils.eq("File \"recursive_records_test.res\", line 97, characters 7-14", second.back() === first, true); + Test_utils.eq("File \"recursive_records_test.res\", line 98, characters 7-14", pointsBack(localPair()), true); + Test_utils.eq("File \"recursive_records_test.res\", line 99, characters 7-14", held.holder().held === held, true); + Test_utils.eq("File \"recursive_records_test.res\", line 100, characters 7-14", held.holder() === holder, true); }); Mocha.test("recursive variant list operations", () => { - Test_utils.eq("File \"recursive_records_test.res\", line 95, characters 7-14", (Stdlib_List.headOrThrow(rec_cell3) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(rec_cell3)) | 0) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(Stdlib_List.tailOrThrow(rec_cell3))) | 0, 9); + Test_utils.eq("File \"recursive_records_test.res\", line 106, characters 7-14", (Stdlib_List.headOrThrow(rec_cell3) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(rec_cell3)) | 0) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(Stdlib_List.tailOrThrow(rec_cell3))) | 0, 9); let rec_cell3$1 = f3(3); - Test_utils.eq("File \"recursive_records_test.res\", line 97, characters 7-14", (Stdlib_List.headOrThrow(rec_cell3$1) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(rec_cell3$1)) | 0) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(Stdlib_List.tailOrThrow(rec_cell3$1))) | 0, 9); + Test_utils.eq("File \"recursive_records_test.res\", line 108, characters 7-14", (Stdlib_List.headOrThrow(rec_cell3$1) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(rec_cell3$1)) | 0) + Stdlib_List.headOrThrow(Stdlib_List.tailOrThrow(Stdlib_List.tailOrThrow(rec_cell3$1))) | 0, 9); }); }); @@ -146,6 +162,8 @@ export { first, second, localPair, + holder, + held, pointsBack, f3, } diff --git a/tests/compiler_tests/src/recursive_records_test.res b/tests/compiler_tests/src/recursive_records_test.res index b8e2495eca..5a62bfc7ed 100644 --- a/tests/compiler_tests/src/recursive_records_test.res +++ b/tests/compiler_tests/src/recursive_records_test.res @@ -60,6 +60,15 @@ let localPair = () => { first } +type rec holder = {held: held, size: int} +and held = {holder: unit => holder, weight: int} + +// The same holds when the record built after it reads nothing of the group +// while it is built, as its only reference to the group is in a function +// (#9466) +let rec holder = {held, size: 1} +and held = {holder: () => holder, weight: 2} + let pointsBack = pair => switch pair.other { | Some(other) => other.back() === pair @@ -87,6 +96,8 @@ describe(__MODULE__, () => { eq(__LOC__, pointsBack(first), true) eq(__LOC__, second.back() === first, true) eq(__LOC__, pointsBack(localPair()), true) + eq(__LOC__, held.holder().held === held, true) + eq(__LOC__, held.holder() === holder, true) }) test("recursive variant list operations", () => { diff --git a/tests/error_tests/single/expected/rec_record_spread_source.res.expected b/tests/error_tests/single/expected/rec_record_spread_source.res.expected index e88c89cd63..3e237ea8f4 100644 --- a/tests/error_tests/single/expected/rec_record_spread_source.res.expected +++ b/tests/error_tests/single/expected/rec_record_spread_source.res.expected @@ -7,7 +7,7 @@ 5 │ let rec callback = {...wrap(callback), run: () => 1} 6 │ - All the fields are already explicitly listed in this record. You can remove the `...` spread. + All the fields are already explicitly listed in this record, so the `...` spread copies none of them. Its source is still evaluated: if you remove the spread, keep any effect the source has. We've found a bug for you! diff --git a/tests/error_tests/single/expected/warning_23_useless_record_with_call.res.expected b/tests/error_tests/single/expected/warning_23_useless_record_with_call.res.expected new file mode 100644 index 0000000000..15ae479884 --- /dev/null +++ b/tests/error_tests/single/expected/warning_23_useless_record_with_call.res.expected @@ -0,0 +1,11 @@ + + Warning number 23 + /.../fixtures/warning_23_useless_record_with_call.res:4:10-32 + + 2 │ + 3 │ let make = () => {a: 1, b: 2} + 4 │ let r2 = {...make(), a: 3, b: 4} + 5 │ + 6 │ let _ = r2 + + All the fields are already explicitly listed in this record, so the `...` spread copies none of them. Its source is still evaluated: if you remove the spread, keep any effect the source has. \ No newline at end of file diff --git a/tests/error_tests/single/fixtures/warning_23_useless_record_with_call.res b/tests/error_tests/single/fixtures/warning_23_useless_record_with_call.res new file mode 100644 index 0000000000..7518280396 --- /dev/null +++ b/tests/error_tests/single/fixtures/warning_23_useless_record_with_call.res @@ -0,0 +1,6 @@ +type t = {a: int, b: int} + +let make = () => {a: 1, b: 2} +let r2 = {...make(), a: 3, b: 4} + +let _ = r2 From ef8c7b9cd8d835702b5bdb495bf57050ff871e43 Mon Sep 17 00:00:00 2001 From: Rob Date: Sun, 29 Nov 2026 12:56:37 -0500 Subject: [PATCH 13/14] Recognize record copies and non-nesting options in tail_block Why: Codex review of 36c386cf1 found two recursive-record shapes that `tail_block` missed, leaving the binding declared after a read of it and throwing `ReferenceError` at runtime: 1. A later binding built by a partial spread of a record with optional fields (`transl_record` emits `Pduprecord`, field assignments, and ends in `Lvar copy_id` instead of a terminal `Pmakeblock`). 2. A recursive record wrapped in a non-nesting `Some(...)` (`Psome_not_nest`), which hid both the terminal record and its eager prefix read. `tail_block` now looks through `Psome_not_nest` wrappers and tracks `Pduprecord` bindings (and aliases of them) through their `Psetfield` sequences to their terminal `Lvar`, treating the copy as an object block. Only the field values assigned by `Psetfield` enter the evaluated-reads list, so function overrides do not trigger unnecessary dummies. JS modified (forward-read shallow copy and non-nesting Some wrapper): Example: type rec optLink = {optNext: option, optBack: unit => optLink, optWeight?: int} let rec baseOptLink = {optNext: None, optBack: () => baseOptLink, optWeight: 25} let rec a = { ...{let rec s = {optNext: Some(b), optBack: () => s, optWeight: tick()}; s}, optNext: None, optBack: () => a, optWeight: 1, } and b = {...baseOptLink, optBack: () => a} Before (js): let a = {}; let s = {}; Primitive_object.updateDummy(s, {optNext: b, ...}); Primitive_object.updateDummy(a, ...); let b = { ...baseOptLink, optBack: () => a }; After (js): let a = {}; let b = {}; let s = {}; Primitive_object.updateDummy(s, {optNext: b, ...}); Primitive_object.updateDummy(a, ...); Primitive_object.updateDummy(b, { ...baseOptLink, optBack: () => a }); Review: Which checked-in outputs change? Only `record_spread_source_effect_test.mjs` for the new module-level and local cases (`sourceReadsLaterCopy`, `localSourceReadsLaterCopy`, `optionalPrefixRead`, `localOptionalPrefixRead`). Signed-off-by: Rob --- compiler/backend/lam_compile.ml | 38 +++- .../src/record_spread_source_effect_test.mjs | 206 ++++++++++++++---- .../src/record_spread_source_effect_test.res | 78 +++++++ 3 files changed, 270 insertions(+), 52 deletions(-) diff --git a/compiler/backend/lam_compile.ml b/compiler/backend/lam_compile.ml index e49d58a47d..6b1c3afbcd 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -85,24 +85,44 @@ let with_block_source_loc lam block = with_statement_source_loc (source_map_loc_of_lam lam) stmt :: rest (* The tag of the block that [lam] builds at the end of a chain of sequences, - lets and recursive lets, with the expressions evaluated to build it: those - before it and its fields. Such a chain is the one [Lam_pass_deep_flatten] - leaves when it hoists the bindings of a spread source out of a record. The - block is built by [Pmakeblock], or is a constant when its fields are all - constants, as [transl_record] makes [{...s, next: None}]. *) + lets, recursive lets and allocation-free [Psome_not_nest] option wrappers, + with the expressions evaluated to build it: those before it and its fields. + Such a chain is the one [Lam_pass_deep_flatten] leaves when it hoists the + bindings of a spread source out of a record. The block is built by + [Pmakeblock], is a constant when its fields are all constants (as + [transl_record] makes [{...s, next: None}]), or is a shallow copy built by + [Pduprecord] followed by field assignments and ending in the copy's + variable (as [transl_record] makes for a partial spread of a record with + optional fields). *) let tail_block (lam : Lambda.t) = - let rec find ~before (lam : Lambda.t) = + let rec find ~before ~dups (lam : Lambda.t) = match lam with + | Lprim {primitive = Psome_not_nest; args = [body]} -> + find ~before ~dups body + | Llet (_, id, Lprim {primitive = Pduprecord; args}, body) -> + find ~before:(args @ before) ~dups:(Set_ident.add id dups) body + | Llet + ( _, + id, + (Lvar src | Lprim {primitive = Psome_not_nest; args = [Lvar src]}), + body ) + when Set_ident.mem src dups -> + find ~before ~dups:(Set_ident.add id dups) body + | Lsequence (Lprim {primitive = Psetfield _; args = [Lvar id; value]}, body) + when Set_ident.mem id dups -> + find ~before:(value :: before) ~dups body | Lsequence (prefix, body) | Llet (_, _, prefix, body) -> - find ~before:(prefix :: before) body + find ~before:(prefix :: before) ~dups body | Lletrec (bindings, body) -> - find ~before:(List.map snd bindings @ before) body + find ~before:(List.map snd bindings @ before) ~dups body | Lprim {primitive = Pmakeblock tag_info; args} -> Some (tag_info, args @ before) | Lconst (Const_block (tag_info, _)) -> Some (tag_info, before) + | Lvar id when Set_ident.mem id dups -> + Some (Lambda.blk_record [||] Immutable ~array:false, before) | _ -> None in - find ~before:[] lam + find ~before:[] ~dups:Set_ident.empty lam (* Whether evaluating the expressions [evaluated] may read a binding of [group]. A function reads none of them when it is built, whatever it refers diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.mjs b/tests/compiler_tests/src/record_spread_source_effect_test.mjs index 663f904071..5898db5dc8 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.mjs +++ b/tests/compiler_tests/src/record_spread_source_effect_test.mjs @@ -2,9 +2,9 @@ import * as Mocha from "mocha"; import * as Test_utils from "./test_utils.mjs"; -import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.mjs"; import * as Stdlib_JsError from "@rescript/runtime/lib/es6/Stdlib_JsError.mjs"; import * as Primitive_object from "@rescript/runtime/lib/es6/Primitive_object.mjs"; +import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.mjs"; import * as JsxRuntime from "react/jsx-runtime"; import * as Primitive_exceptions from "@rescript/runtime/lib/es6/Primitive_exceptions.mjs"; import * as Record_spread_source_effect_dep from "./record_spread_source_effect_dep.mjs"; @@ -262,6 +262,97 @@ function localSourceReadsLater(weight) { return link; } +function baseOptLink_optBack() { + return baseOptLink; +} + +let baseOptLink_optWeight = 25; + +let baseOptLink = { + optNext: undefined, + optBack: baseOptLink_optBack, + optWeight: baseOptLink_optWeight +}; + +let sourceReadsLaterCopy = {}; + +let laterCopy = {}; + +let source$3 = {}; + +Primitive_object.updateDummy(source$3, { + optNext: laterCopy, + optBack: () => source$3, + optWeight: logged("sourceReadsLaterCopy", id(26)) +}); + +Primitive_object.updateDummy(sourceReadsLaterCopy, { + optNext: undefined, + optBack: () => sourceReadsLaterCopy, + optWeight: 26 +}); + +Primitive_object.updateDummy(laterCopy, { + ...baseOptLink, + optBack: () => sourceReadsLaterCopy +}); + +function localSourceReadsLaterCopy(weight) { + let link = {}; + let later = {}; + let source = {}; + Primitive_object.updateDummy(source, { + optNext: later, + optBack: () => source, + optWeight: weight + }); + Primitive_object.updateDummy(link, { + optNext: undefined, + optBack: () => link, + optWeight: weight + }); + Primitive_object.updateDummy(later, { + ...baseOptLink, + optBack: () => link + }); + return [ + link, + later + ]; +} + +let optionalPrefixRead = {}; + +let source$4 = {}; + +Primitive_object.updateDummy(source$4, { + lower: source$4, + upper: optionalPrefixRead, + weight: logged("optionalPrefixRead", id(27)) +}); + +Primitive_object.updateDummy(optionalPrefixRead, { + lower: undefined, + upper: undefined, + weight: 27 +}); + +function localOptionalPrefixRead(weight) { + let node = {}; + let source = {}; + Primitive_object.updateDummy(source, { + lower: source, + upper: node, + weight: weight + }); + Primitive_object.updateDummy(node, { + lower: undefined, + upper: undefined, + weight: weight + 1 | 0 + }); + return node; +} + function makeLink(weight) { let link = {}; Primitive_object.updateDummy(link, { @@ -359,12 +450,12 @@ Mocha.describe("Record_spread_source_effect_test", () => { x: point_x, y: point_y }; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 253, characters 7-14", takeCalls(), [ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 320, characters 7-14", takeCalls(), [ "source", "x", "y" ]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 254, characters 7-14", point, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 321, characters 7-14", point, { x: 1, y: 2 }); @@ -377,12 +468,12 @@ Mocha.describe("Record_spread_source_effect_test", () => { width: 1, height: 2 }; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 259, characters 7-14", takeCalls(), ["source"]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 260, characters 7-14", options, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 326, characters 7-14", takeCalls(), ["source"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 327, characters 7-14", options, { width: 1, height: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 262, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 329, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); }); Mocha.test("a source that raises stops the record from being built", () => { let result; @@ -397,7 +488,7 @@ Mocha.describe("Record_spread_source_effect_test", () => { throw exn; } } - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 272, characters 7-14", result, -1); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 339, characters 7-14", result, -1); }); Mocha.test("the source of a JSX element's props runs", () => { logged("props", { @@ -407,10 +498,10 @@ Mocha.describe("Record_spread_source_effect_test", () => { a: 1, b: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 277, characters 7-14", takeCalls(), ["props"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 344, characters 7-14", takeCalls(), ["props"]); }); Mocha.test("sources of module-level and recursive records run", () => { - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 283, characters 6-13", moduleCalls, [ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 350, characters 6-13", moduleCalls, [ "polymorphic", "recursive", "cycle", @@ -421,68 +512,91 @@ Mocha.describe("Record_spread_source_effect_test", () => { "prefixRead", "constantPrefixRead", "sourceReadsLater", + "sourceReadsLaterCopy", + "optionalPrefixRead", "mutualFirst", "mutualSecond", "wrapped", "counter", "counterStart" ]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 303, characters 7-14", undefined, undefined); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 304, characters 7-14", undefined, undefined); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 305, characters 7-14", recursive_self().value, 2); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 306, characters 7-14", selfSpread_self().value, 3); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 307, characters 7-14", singleCallback.run(), 4); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 308, characters 7-14", cycle.next === cycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 309, characters 7-14", cycle.next.value, 7); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 310, characters 7-14", letCycle.next === letCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 311, characters 7-14", letCycle.next.value, 8); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 312, characters 7-14", sequenceCycle.next === sequenceCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 313, characters 7-14", sequenceCycle.next.value, 9); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 314, characters 7-14", letRecCycle.next === letRecCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 315, characters 7-14", letRecCycle.next.value, 12); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 372, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 373, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 374, characters 7-14", recursive_self().value, 2); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 375, characters 7-14", selfSpread_self().value, 3); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 376, characters 7-14", singleCallback.run(), 4); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 377, characters 7-14", cycle.next === cycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 378, characters 7-14", cycle.next.value, 7); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 379, characters 7-14", letCycle.next === letCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 380, characters 7-14", letCycle.next.value, 8); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 381, characters 7-14", sequenceCycle.next === sequenceCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 382, characters 7-14", sequenceCycle.next.value, 9); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 383, characters 7-14", letRecCycle.next === letRecCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 384, characters 7-14", letRecCycle.next.value, 12); let local = localLetRecCycle(13); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 317, characters 7-14", local.next === local, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 318, characters 7-14", local.next.value, 13); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 386, characters 7-14", local.next === local, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 387, characters 7-14", local.next.value, 13); let localPrefix = localPrefixRead(15); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 320, characters 7-14", prefixRead.left === leaf, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 321, characters 7-14", prefixRead.value, 14); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 322, characters 7-14", localPrefix.value, 15); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 323, characters 7-14", constantPrefixRead, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 389, characters 7-14", prefixRead.left === leaf, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 390, characters 7-14", prefixRead.value, 14); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 391, characters 7-14", localPrefix.value, 15); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 392, characters 7-14", constantPrefixRead, { lower: undefined, upper: undefined, weight: 16 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 324, characters 7-14", localConstantPrefixRead(18), { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 393, characters 7-14", localConstantPrefixRead(18), { lower: undefined, upper: undefined, weight: 17 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 325, characters 7-14", sourceReadsLater.weight, 19); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 326, characters 7-14", later.back() === sourceReadsLater, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 394, characters 7-14", sourceReadsLater.weight, 19); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 395, characters 7-14", later.back() === sourceReadsLater, true); let localLink = localSourceReadsLater(21); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 328, characters 7-14", localLink.weight, 21); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 329, characters 7-14", localLink.back() === localLink, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 330, characters 7-14", Stdlib_Option.map(mutualFirst.next, next => next === mutualSecond), true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 331, characters 7-14", Stdlib_Option.map(mutualSecond.next, next => next === mutualFirst), true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 332, characters 7-14", mutualFirst.back() === mutualSecond, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 333, characters 7-14", mutualSecond.weight, 23); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 334, characters 7-14", isWrapped(wrapped), true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 335, characters 7-14", counter_start, 10); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 336, characters 7-14", counter_step(), 11); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 337, characters 7-14", fromOtherModule, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 397, characters 7-14", localLink.weight, 21); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 398, characters 7-14", localLink.back() === localLink, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 399, characters 7-14", sourceReadsLaterCopy.optWeight, 26); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 400, characters 7-14", laterCopy.optBack() === sourceReadsLaterCopy, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 401, characters 7-14", laterCopy.optWeight, 25); + let match = localSourceReadsLaterCopy(28); + let localLaterCopy = match[1]; + let localCopyLink = match[0]; + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 403, characters 7-14", localCopyLink.optWeight, 28); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 404, characters 7-14", localLaterCopy.optBack() === localCopyLink, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 405, characters 7-14", localLaterCopy.optWeight, 25); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 406, characters 7-14", optionalPrefixRead, { + lower: undefined, + upper: undefined, + weight: 27 + }); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 407, characters 7-14", localOptionalPrefixRead(29), { + lower: undefined, + upper: undefined, + weight: 30 + }); + let opt = mutualFirst.next; + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 408, characters 7-14", opt !== undefined ? Primitive_option.some(Primitive_option.valFromOption(opt) === mutualSecond) : undefined, true); + let opt$1 = mutualSecond.next; + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 409, characters 7-14", opt$1 !== undefined ? Primitive_option.some(Primitive_option.valFromOption(opt$1) === mutualFirst) : undefined, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 410, characters 7-14", mutualFirst.back() === mutualSecond, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 411, characters 7-14", mutualSecond.weight, 23); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 412, characters 7-14", isWrapped(wrapped), true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 413, characters 7-14", counter_start, 10); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 414, characters 7-14", counter_step(), 11); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 415, characters 7-14", fromOtherModule, { x: 5, y: 6 }); }); Mocha.test("a pure source is left out", () => { - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 341, characters 7-14", overridePure(id({ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 419, characters 7-14", overridePure(id({ x: 0, y: 0 })), { x: 1, y: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 342, characters 7-14", takeCalls(), ["y"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 420, characters 7-14", takeCalls(), ["y"]); id({ a: 0 }); @@ -526,6 +640,12 @@ export { sourceReadsLater, later, localSourceReadsLater, + baseOptLink, + sourceReadsLaterCopy, + laterCopy, + localSourceReadsLaterCopy, + optionalPrefixRead, + localOptionalPrefixRead, makeLink, mutualFirst, mutualSecond, diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.res b/tests/compiler_tests/src/record_spread_source_effect_test.res index bf67356d37..0f74d95ca9 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.res +++ b/tests/compiler_tests/src/record_spread_source_effect_test.res @@ -197,6 +197,73 @@ let localSourceReadsLater = weight => { link } +// A later binding built by a shallow-copy partial spread (record with an +// optional field) is also declared as a dummy before an earlier source reads it +type rec optLink = { + optNext: option, + optBack: unit => optLink, + optWeight?: int, +} + +let rec baseOptLink = {optNext: None, optBack: () => baseOptLink, optWeight: 25} + +let rec sourceReadsLaterCopy = { + ...{ + let rec source = { + optNext: Some(laterCopy), + optBack: () => source, + optWeight: logged("sourceReadsLaterCopy", id(26)), + } + source + }, + optNext: None, + optBack: () => sourceReadsLaterCopy, + optWeight: 26, +} +and laterCopy = {...baseOptLink, optBack: () => sourceReadsLaterCopy} + +let localSourceReadsLaterCopy = weight => { + let rec link = { + ...{ + let rec source = {optNext: Some(later), optBack: () => source, optWeight: weight} + source + }, + optNext: None, + optBack: () => link, + optWeight: weight, + } + and later = {...baseOptLink, optBack: () => link} + (link, later) +} + +// A non-nesting Some wrapper around a recursive record with a prefix read +let rec optionalPrefixRead = Some({ + ...{ + let rec source = { + lower: Some(source), + upper: optionalPrefixRead, + weight: logged("optionalPrefixRead", id(27)), + } + source + }, + lower: None, + upper: None, + weight: 27, +}) + +let localOptionalPrefixRead = weight => { + let rec node = Some({ + ...{ + let rec source = {lower: Some(source), upper: node, weight} + source + }, + lower: None, + upper: None, + weight: weight + 1, + }) + node +} + // Each record of a mutually recursive group evaluates its own source let makeLink = weight => { let rec link = {next: None, back: () => link, weight} @@ -293,6 +360,8 @@ describe(__MODULE__, () => { "prefixRead", "constantPrefixRead", "sourceReadsLater", + "sourceReadsLaterCopy", + "optionalPrefixRead", "mutualFirst", "mutualSecond", "wrapped", @@ -327,6 +396,15 @@ describe(__MODULE__, () => { let localLink = localSourceReadsLater(21) eq(__LOC__, localLink.weight, 21) eq(__LOC__, localLink.back() === localLink, true) + eq(__LOC__, sourceReadsLaterCopy.optWeight, Some(26)) + eq(__LOC__, laterCopy.optBack() === sourceReadsLaterCopy, true) + eq(__LOC__, laterCopy.optWeight, Some(25)) + let (localCopyLink, localLaterCopy) = localSourceReadsLaterCopy(28) + eq(__LOC__, localCopyLink.optWeight, Some(28)) + eq(__LOC__, localLaterCopy.optBack() === localCopyLink, true) + eq(__LOC__, localLaterCopy.optWeight, Some(25)) + eq(__LOC__, optionalPrefixRead, Some({lower: None, upper: None, weight: 27})) + eq(__LOC__, localOptionalPrefixRead(29), Some({lower: None, upper: None, weight: 30})) eq(__LOC__, mutualFirst.next->Option.map(next => next === mutualSecond), Some(true)) eq(__LOC__, mutualSecond.next->Option.map(next => next === mutualFirst), Some(true)) eq(__LOC__, mutualFirst.back() === mutualSecond, true) From eb6b9e3d935837dceea689ea10080e33fba5ac05 Mon Sep 17 00:00:00 2001 From: Rob Date: Thu, 3 Dec 2026 20:24:50 -0500 Subject: [PATCH 14/14] Traverse nesting-capable option wrappers in tail_block Why: Codex review of ef8c7b9cd found that `tail_block` only traversed `Psome_not_nest`, so a recursive record with an effectful spread source wrapped in a nesting-capable option (`Some(Some({...source, ...}))`, compiled with `Psome`) returned `None` and left the binding declared after its source read it, throwing `ReferenceError` at runtime. When the payload ends in a known block (`Pmakeblock`, `Const_block`, or a `Pduprecord` copy), `Psome` preserves the block's JS representation just like `Psome_not_nest`. `tail_block` now traverses `Psome` (as well as `Const_some` around `Const_block` and nested option aliases of `Pduprecord` copies), so the binding is declared as a dummy before its source runs. JS modified (nested option around a recursive record with a prefix read): Example: type rec nestedOpt = { nestedLeft: option, nestedRight: option>, nestedWeight: int, } let rec n = Some( Some({ ...{ let rec source = {nestedLeft: Some(source), nestedRight: n, nestedWeight: tick()} source }, nestedLeft: None, nestedRight: None, nestedWeight: 1, }), ) Before (js): let source = {}; Primitive_object.updateDummy(source, { nestedLeft: source, nestedRight: n, nestedWeight: tick() }); let n = Primitive_option.some({ nestedLeft: undefined, nestedRight: undefined, nestedWeight: 1 }); After (js): let n = {}; let source = {}; Primitive_object.updateDummy(source, { nestedLeft: source, nestedRight: n, nestedWeight: tick() }); Primitive_object.updateDummy(n, Primitive_option.some({ nestedLeft: undefined, nestedRight: undefined, nestedWeight: 1 })); Review: Does `tail_block` match `Some(None)` or an arbitrary `Some(x)`? No: `const_block_tag` only unwraps `Const_some` down to a `Const_block`, and `Psome` only succeeds when its payload ends in a `Pmakeblock`, `Const_block`, or tracked `Pduprecord` copy. Review: Which checked-in outputs change? Only `record_spread_source_effect_test.mjs` for the new module-level, local, and mutually-recursive copy cases (`nestedOptionalPrefixRead`, `localNestedOptionalPrefixRead`, `nestedSourceReadsLaterCopy` / `nestedLaterCopy`). Signed-off-by: Rob --- compiler/backend/lam_compile.ml | 44 ++-- .../src/record_spread_source_effect_test.mjs | 196 +++++++++++++----- .../src/record_spread_source_effect_test.res | 92 ++++++++ 3 files changed, 266 insertions(+), 66 deletions(-) diff --git a/compiler/backend/lam_compile.ml b/compiler/backend/lam_compile.ml index 6b1c3afbcd..1398f49b69 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -84,29 +84,38 @@ let with_block_source_loc lam block = | stmt :: rest -> with_statement_source_loc (source_map_loc_of_lam lam) stmt :: rest +let rec const_block_tag (c : Lambda.structured_constant) = + match c with + | Const_block (tag_info, _) -> Some tag_info + | Const_some inner -> const_block_tag inner + | _ -> None + +let rec is_dups_alias dups (lam : Lambda.t) = + match lam with + | Lvar src -> Set_ident.mem src dups + | Lprim {primitive = Psome | Psome_not_nest; args = [inner]} -> + is_dups_alias dups inner + | _ -> false + (* The tag of the block that [lam] builds at the end of a chain of sequences, - lets, recursive lets and allocation-free [Psome_not_nest] option wrappers, - with the expressions evaluated to build it: those before it and its fields. + lets, recursive lets and [Psome] / [Psome_not_nest] option wrappers, with + the expressions evaluated to build it: those before it and its fields. Such a chain is the one [Lam_pass_deep_flatten] leaves when it hoists the - bindings of a spread source out of a record. The block is built by - [Pmakeblock], is a constant when its fields are all constants (as - [transl_record] makes [{...s, next: None}]), or is a shallow copy built by - [Pduprecord] followed by field assignments and ending in the copy's - variable (as [transl_record] makes for a partial spread of a record with - optional fields). *) + bindings of a spread source out of a record. Both option wrappers preserve + the block's JS representation when their payload is a known block. The + block is built by [Pmakeblock], is a constant when its fields are all + constants (as [transl_record] makes [{...s, next: None}]), or is a shallow + copy built by [Pduprecord] followed by field assignments and ending in the + copy's variable (as [transl_record] makes for a partial spread of a record + with optional fields). *) let tail_block (lam : Lambda.t) = let rec find ~before ~dups (lam : Lambda.t) = match lam with - | Lprim {primitive = Psome_not_nest; args = [body]} -> + | Lprim {primitive = Psome | Psome_not_nest; args = [body]} -> find ~before ~dups body | Llet (_, id, Lprim {primitive = Pduprecord; args}, body) -> find ~before:(args @ before) ~dups:(Set_ident.add id dups) body - | Llet - ( _, - id, - (Lvar src | Lprim {primitive = Psome_not_nest; args = [Lvar src]}), - body ) - when Set_ident.mem src dups -> + | Llet (_, id, rhs, body) when is_dups_alias dups rhs -> find ~before ~dups:(Set_ident.add id dups) body | Lsequence (Lprim {primitive = Psetfield _; args = [Lvar id; value]}, body) when Set_ident.mem id dups -> @@ -117,7 +126,10 @@ let tail_block (lam : Lambda.t) = find ~before:(List.map snd bindings @ before) ~dups body | Lprim {primitive = Pmakeblock tag_info; args} -> Some (tag_info, args @ before) - | Lconst (Const_block (tag_info, _)) -> Some (tag_info, before) + | Lconst c -> ( + match const_block_tag c with + | Some tag_info -> Some (tag_info, before) + | None -> None) | Lvar id when Set_ident.mem id dups -> Some (Lambda.blk_record [||] Immutable ~array:false, before) | _ -> None diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.mjs b/tests/compiler_tests/src/record_spread_source_effect_test.mjs index 5898db5dc8..24de8126a1 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.mjs +++ b/tests/compiler_tests/src/record_spread_source_effect_test.mjs @@ -353,6 +353,73 @@ function localOptionalPrefixRead(weight) { return node; } +let nestedOptionalPrefixRead = {}; + +let source$5 = {}; + +Primitive_object.updateDummy(source$5, { + nestedLeft: source$5, + nestedRight: nestedOptionalPrefixRead, + nestedWeight: logged("nestedOptionalPrefixRead", id(31)) +}); + +Primitive_object.updateDummy(nestedOptionalPrefixRead, Primitive_option.some({ + nestedLeft: undefined, + nestedRight: undefined, + nestedWeight: 31 +})); + +function localNestedOptionalPrefixRead(weight) { + let node = {}; + let source = {}; + Primitive_object.updateDummy(source, { + nestedLeft: source, + nestedRight: node, + nestedWeight: weight + }); + Primitive_object.updateDummy(node, Primitive_option.some({ + nestedLeft: undefined, + nestedRight: undefined, + nestedWeight: weight + 1 | 0 + })); + return node; +} + +function baseNestedOptLink_nestedOptBack() { + return baseNestedOptLink; +} + +let baseNestedOptLink_nestedOptWeight = 32; + +let baseNestedOptLink = { + nestedOptNext: undefined, + nestedOptBack: baseNestedOptLink_nestedOptBack, + nestedOptWeight: baseNestedOptLink_nestedOptWeight +}; + +let nestedSourceReadsLaterCopy = {}; + +let nestedLaterCopy = {}; + +let source$6 = {}; + +Primitive_object.updateDummy(source$6, { + nestedOptNext: nestedLaterCopy, + nestedOptBack: () => source$6, + nestedOptWeight: logged("nestedSourceReadsLaterCopy", id(33)) +}); + +Primitive_object.updateDummy(nestedSourceReadsLaterCopy, { + nestedOptNext: undefined, + nestedOptBack: () => nestedSourceReadsLaterCopy, + nestedOptWeight: 33 +}); + +Primitive_object.updateDummy(nestedLaterCopy, Primitive_option.some({ + ...baseNestedOptLink, + nestedOptBack: () => nestedSourceReadsLaterCopy +})); + function makeLink(weight) { let link = {}; Primitive_object.updateDummy(link, { @@ -450,12 +517,12 @@ Mocha.describe("Record_spread_source_effect_test", () => { x: point_x, y: point_y }; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 320, characters 7-14", takeCalls(), [ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 388, characters 7-14", takeCalls(), [ "source", "x", "y" ]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 321, characters 7-14", point, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 389, characters 7-14", point, { x: 1, y: 2 }); @@ -468,12 +535,12 @@ Mocha.describe("Record_spread_source_effect_test", () => { width: 1, height: 2 }; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 326, characters 7-14", takeCalls(), ["source"]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 327, characters 7-14", options, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 394, characters 7-14", takeCalls(), ["source"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 395, characters 7-14", options, { width: 1, height: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 329, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 397, characters 7-14", JSON.stringify(options), `{"width":1,"height":2}`); }); Mocha.test("a source that raises stops the record from being built", () => { let result; @@ -488,7 +555,7 @@ Mocha.describe("Record_spread_source_effect_test", () => { throw exn; } } - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 339, characters 7-14", result, -1); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 407, characters 7-14", result, -1); }); Mocha.test("the source of a JSX element's props runs", () => { logged("props", { @@ -498,10 +565,10 @@ Mocha.describe("Record_spread_source_effect_test", () => { a: 1, b: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 344, characters 7-14", takeCalls(), ["props"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 412, characters 7-14", takeCalls(), ["props"]); }); Mocha.test("sources of module-level and recursive records run", () => { - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 350, characters 6-13", moduleCalls, [ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 418, characters 6-13", moduleCalls, [ "polymorphic", "recursive", "cycle", @@ -514,89 +581,113 @@ Mocha.describe("Record_spread_source_effect_test", () => { "sourceReadsLater", "sourceReadsLaterCopy", "optionalPrefixRead", + "nestedOptionalPrefixRead", + "nestedSourceReadsLaterCopy", "mutualFirst", "mutualSecond", "wrapped", "counter", "counterStart" ]); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 372, characters 7-14", undefined, undefined); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 373, characters 7-14", undefined, undefined); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 374, characters 7-14", recursive_self().value, 2); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 375, characters 7-14", selfSpread_self().value, 3); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 376, characters 7-14", singleCallback.run(), 4); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 377, characters 7-14", cycle.next === cycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 378, characters 7-14", cycle.next.value, 7); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 379, characters 7-14", letCycle.next === letCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 380, characters 7-14", letCycle.next.value, 8); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 381, characters 7-14", sequenceCycle.next === sequenceCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 382, characters 7-14", sequenceCycle.next.value, 9); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 383, characters 7-14", letRecCycle.next === letRecCycle, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 384, characters 7-14", letRecCycle.next.value, 12); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 442, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 443, characters 7-14", undefined, undefined); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 444, characters 7-14", recursive_self().value, 2); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 445, characters 7-14", selfSpread_self().value, 3); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 446, characters 7-14", singleCallback.run(), 4); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 447, characters 7-14", cycle.next === cycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 448, characters 7-14", cycle.next.value, 7); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 449, characters 7-14", letCycle.next === letCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 450, characters 7-14", letCycle.next.value, 8); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 451, characters 7-14", sequenceCycle.next === sequenceCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 452, characters 7-14", sequenceCycle.next.value, 9); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 453, characters 7-14", letRecCycle.next === letRecCycle, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 454, characters 7-14", letRecCycle.next.value, 12); let local = localLetRecCycle(13); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 386, characters 7-14", local.next === local, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 387, characters 7-14", local.next.value, 13); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 456, characters 7-14", local.next === local, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 457, characters 7-14", local.next.value, 13); let localPrefix = localPrefixRead(15); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 389, characters 7-14", prefixRead.left === leaf, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 390, characters 7-14", prefixRead.value, 14); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 391, characters 7-14", localPrefix.value, 15); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 392, characters 7-14", constantPrefixRead, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 459, characters 7-14", prefixRead.left === leaf, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 460, characters 7-14", prefixRead.value, 14); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 461, characters 7-14", localPrefix.value, 15); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 462, characters 7-14", constantPrefixRead, { lower: undefined, upper: undefined, weight: 16 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 393, characters 7-14", localConstantPrefixRead(18), { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 463, characters 7-14", localConstantPrefixRead(18), { lower: undefined, upper: undefined, weight: 17 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 394, characters 7-14", sourceReadsLater.weight, 19); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 395, characters 7-14", later.back() === sourceReadsLater, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 464, characters 7-14", sourceReadsLater.weight, 19); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 465, characters 7-14", later.back() === sourceReadsLater, true); let localLink = localSourceReadsLater(21); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 397, characters 7-14", localLink.weight, 21); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 398, characters 7-14", localLink.back() === localLink, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 399, characters 7-14", sourceReadsLaterCopy.optWeight, 26); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 400, characters 7-14", laterCopy.optBack() === sourceReadsLaterCopy, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 401, characters 7-14", laterCopy.optWeight, 25); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 467, characters 7-14", localLink.weight, 21); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 468, characters 7-14", localLink.back() === localLink, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 469, characters 7-14", sourceReadsLaterCopy.optWeight, 26); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 470, characters 7-14", laterCopy.optBack() === sourceReadsLaterCopy, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 471, characters 7-14", laterCopy.optWeight, 25); let match = localSourceReadsLaterCopy(28); let localLaterCopy = match[1]; let localCopyLink = match[0]; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 403, characters 7-14", localCopyLink.optWeight, 28); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 404, characters 7-14", localLaterCopy.optBack() === localCopyLink, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 405, characters 7-14", localLaterCopy.optWeight, 25); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 406, characters 7-14", optionalPrefixRead, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 473, characters 7-14", localCopyLink.optWeight, 28); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 474, characters 7-14", localLaterCopy.optBack() === localCopyLink, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 475, characters 7-14", localLaterCopy.optWeight, 25); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 476, characters 7-14", optionalPrefixRead, { lower: undefined, upper: undefined, weight: 27 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 407, characters 7-14", localOptionalPrefixRead(29), { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 477, characters 7-14", localOptionalPrefixRead(29), { lower: undefined, upper: undefined, weight: 30 }); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 479, characters 6-13", nestedOptionalPrefixRead, { + nestedLeft: undefined, + nestedRight: undefined, + nestedWeight: 31 + }); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 484, characters 6-13", localNestedOptionalPrefixRead(34), { + nestedLeft: undefined, + nestedRight: undefined, + nestedWeight: 35 + }); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 488, characters 7-14", nestedSourceReadsLaterCopy.nestedOptWeight, 33); + let copy = Primitive_option.valFromOption(nestedLaterCopy); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 490, characters 6-13", copy !== undefined ? [ + copy.nestedOptBack() === nestedSourceReadsLaterCopy, + copy.nestedOptWeight + ] : [ + false, + undefined + ], [ + true, + 32 + ]); let opt = mutualFirst.next; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 408, characters 7-14", opt !== undefined ? Primitive_option.some(Primitive_option.valFromOption(opt) === mutualSecond) : undefined, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 500, characters 7-14", opt !== undefined ? Primitive_option.some(Primitive_option.valFromOption(opt) === mutualSecond) : undefined, true); let opt$1 = mutualSecond.next; - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 409, characters 7-14", opt$1 !== undefined ? Primitive_option.some(Primitive_option.valFromOption(opt$1) === mutualFirst) : undefined, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 410, characters 7-14", mutualFirst.back() === mutualSecond, true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 411, characters 7-14", mutualSecond.weight, 23); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 412, characters 7-14", isWrapped(wrapped), true); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 413, characters 7-14", counter_start, 10); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 414, characters 7-14", counter_step(), 11); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 415, characters 7-14", fromOtherModule, { + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 501, characters 7-14", opt$1 !== undefined ? Primitive_option.some(Primitive_option.valFromOption(opt$1) === mutualFirst) : undefined, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 502, characters 7-14", mutualFirst.back() === mutualSecond, true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 503, characters 7-14", mutualSecond.weight, 23); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 504, characters 7-14", isWrapped(wrapped), true); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 505, characters 7-14", counter_start, 10); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 506, characters 7-14", counter_step(), 11); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 507, characters 7-14", fromOtherModule, { x: 5, y: 6 }); }); Mocha.test("a pure source is left out", () => { - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 419, characters 7-14", overridePure(id({ + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 511, characters 7-14", overridePure(id({ x: 0, y: 0 })), { x: 1, y: 2 }); - Test_utils.eq("File \"record_spread_source_effect_test.res\", line 420, characters 7-14", takeCalls(), ["y"]); + Test_utils.eq("File \"record_spread_source_effect_test.res\", line 512, characters 7-14", takeCalls(), ["y"]); id({ a: 0 }); @@ -646,6 +737,11 @@ export { localSourceReadsLaterCopy, optionalPrefixRead, localOptionalPrefixRead, + nestedOptionalPrefixRead, + localNestedOptionalPrefixRead, + baseNestedOptLink, + nestedSourceReadsLaterCopy, + nestedLaterCopy, makeLink, mutualFirst, mutualSecond, diff --git a/tests/compiler_tests/src/record_spread_source_effect_test.res b/tests/compiler_tests/src/record_spread_source_effect_test.res index 0f74d95ca9..04a68b389d 100644 --- a/tests/compiler_tests/src/record_spread_source_effect_test.res +++ b/tests/compiler_tests/src/record_spread_source_effect_test.res @@ -264,6 +264,74 @@ let localOptionalPrefixRead = weight => { node } +// A nesting-capable Some(Some(...)) wrapper around a recursive record with a +// prefix read (both constant and non-constant final blocks, and a Pduprecord copy) +type rec nestedOpt = { + nestedLeft: option, + nestedRight: option>, + nestedWeight: int, +} + +let rec nestedOptionalPrefixRead = Some( + Some({ + ...{ + let rec source = { + nestedLeft: Some(source), + nestedRight: nestedOptionalPrefixRead, + nestedWeight: logged("nestedOptionalPrefixRead", id(31)), + } + source + }, + nestedLeft: None, + nestedRight: None, + nestedWeight: 31, + }), +) + +let localNestedOptionalPrefixRead = weight => { + let rec node = Some( + Some({ + ...{ + let rec source = {nestedLeft: Some(source), nestedRight: node, nestedWeight: weight} + source + }, + nestedLeft: None, + nestedRight: None, + nestedWeight: weight + 1, + }), + ) + node +} + +type rec nestedOptLink = { + nestedOptNext: option>, + nestedOptBack: unit => nestedOptLink, + nestedOptWeight?: int, +} + +let rec baseNestedOptLink = { + nestedOptNext: None, + nestedOptBack: () => baseNestedOptLink, + nestedOptWeight: 32, +} + +let rec nestedSourceReadsLaterCopy = { + ...{ + let rec source = { + nestedOptNext: nestedLaterCopy, + nestedOptBack: () => source, + nestedOptWeight: logged("nestedSourceReadsLaterCopy", id(33)), + } + source + }, + nestedOptNext: None, + nestedOptBack: () => nestedSourceReadsLaterCopy, + nestedOptWeight: 33, +} +and nestedLaterCopy = Some( + Some({...baseNestedOptLink, nestedOptBack: () => nestedSourceReadsLaterCopy}), +) + // Each record of a mutually recursive group evaluates its own source let makeLink = weight => { let rec link = {next: None, back: () => link, weight} @@ -362,6 +430,8 @@ describe(__MODULE__, () => { "sourceReadsLater", "sourceReadsLaterCopy", "optionalPrefixRead", + "nestedOptionalPrefixRead", + "nestedSourceReadsLaterCopy", "mutualFirst", "mutualSecond", "wrapped", @@ -405,6 +475,28 @@ describe(__MODULE__, () => { eq(__LOC__, localLaterCopy.optWeight, Some(25)) eq(__LOC__, optionalPrefixRead, Some({lower: None, upper: None, weight: 27})) eq(__LOC__, localOptionalPrefixRead(29), Some({lower: None, upper: None, weight: 30})) + eq( + __LOC__, + nestedOptionalPrefixRead, + Some(Some({nestedLeft: None, nestedRight: None, nestedWeight: 31})), + ) + eq( + __LOC__, + localNestedOptionalPrefixRead(34), + Some(Some({nestedLeft: None, nestedRight: None, nestedWeight: 35})), + ) + eq(__LOC__, nestedSourceReadsLaterCopy.nestedOptWeight, Some(33)) + eq( + __LOC__, + switch nestedLaterCopy { + | Some(Some(copy)) => ( + copy.nestedOptBack() === nestedSourceReadsLaterCopy, + copy.nestedOptWeight, + ) + | _ => (false, None) + }, + (true, Some(32)), + ) eq(__LOC__, mutualFirst.next->Option.map(next => next === mutualSecond), Some(true)) eq(__LOC__, mutualSecond.next->Option.map(next => next === mutualFirst), Some(true)) eq(__LOC__, mutualFirst.back() === mutualSecond, true)