Skip to content

Evaluate the source of a record spread whose fields are all overridden - #9427

Open
illusionalsagacity wants to merge 13 commits into
rescript-lang:masterfrom
illusionalsagacity:fix-spread-source-effect
Open

illusionalsagacity wants to merge 13 commits into
rescript-lang:masterfrom
illusionalsagacity:fix-spread-source-effect

Conversation

@illusionalsagacity

@illusionalsagacity illusionalsagacity commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Part of #9398 (item 35). Found while reviewing the fixes for it.

Problem

When a record literal with a spread writes every field, the type checker reports warning 23 and also drops the source, so a call there never ran. The same held for JSX props spreads.

type t = {a: int, b: int}
@val external f: unit => t = "f"
let make = () => {...f(), a: 1, b: 2}

Before:

function make() {
  return {
    a: 1,
    b: 2
  };
}

After:

function make() {
  f();
  return {
    a: 1,
    b: 2
  };
}
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`

Fix

The source stays in the typed tree. The record is built from the written fields alone, after the source is evaluated, and a source that is a variable, or that the Lambda passes see has no side effects, is left out as before. is_nonexpansive and rec_check treat the source like the first expression of a sequence.

In a let rec, the record then comes after its source, as in let rec n = {...makeSource(), next: n}. The backend only declared a dummy for a bare block, so it declared n with its value and read n before it was initialized. A block that comes after a sequence, a let or a recursive let, with a field other than a function that refers to a binding of the group, is now built into a dummy declared first, like a bare block. So is a block after such an expression that itself refers to a binding of the group while it runs, as in let rec n = {...{let rec tmp = {left: tmp, right: n, value: tick()}; tmp}, left: base, right: base, value: 1}, also when the record's fields are all constants and the record is therefore a constant (left: None, right: None, value: 1). A block whose fields refer to none of the group's bindings, or only inside functions, is still declared directly. This also fixes let rec n = {Console.log("a"); {next: n}}, which fails the same way on master.

A record built into a dummy can read a binding of its group built after it, which the backend declared directly where it was built, after that read, as a in let rec b = {...{let rec s = {next: Some(a), f: () => s, v: logv()}; s}, next: None, f: () => b, v: 1} and a = {next: None, f: () => b, v: 2}. The backend now decides this for the group as a whole: a binding that a binding built before it reads is built into a dummy too, declared first, while its block is still built where it was, so effects keep their order. This also fixes let rec b = {next: Some(a), f: () => b} and a = {next: None, f: () => b}, which throws a ReferenceError on master. A binding that builds no block, such as an array (and x = [{t: y}]) or an option of a record (and x = Some(y)), cannot be a dummy and still comes after the binding reading it, as on master.

Behaviour changes

Breaking: let rec r = {...wrap(r), run: () => 1} is now rejected, because wrap runs and would read r before it is initialized. It was accepted before, with warning 23, without calling wrap. To migrate, remove the spread, whose value was never used, or build the source without reading r. changes/rec-record-spread-source-check.breaking.md records it. let rec r = {...r, a: 1, b: 2} is still accepted.

A module with side effects that such a source is read from ({...Effects.base, a: 1, b: 2}) now stays imported. ignore(Effects.base) keeps the import on master too.

let rec n = {...makeSource(), next: n} and let rec n = {Console.log("a"); {next: n}} now build n as let n = {} followed by Primitive_object.updateDummy(n, ...). A record of a let rec group built after other expressions whose fields don't refer to the group, and recursive modules, are unchanged.

Warning 23 still says the spread can be removed, which now also removes its side effects. I left the text unchanged.

Tests

record_spread_source_effect_test.res: 5 of its 6 tests fail without the change, the sixth checks that pure sources are still left out. It also checks that a recursive record still points at itself after its source runs, with the source sequenced (cycle), with a let before the record (letCycle), for a record at the end of a sequence (sequenceCycle), with a source whose recursive helper is hoisted out of it (letRecCycle, localLetRecCycle), and with a source that refers to the record while it is built (prefixRead, localPrefixRead), also when the record's fields are all constants (constantPrefixRead, localConstantPrefixRead), that a record of a recursive group whose fields don't refer to the group is declared directly after its sequence, without a dummy (counter), and that a binding of the group that a source reads is declared before it, at module level and in a function (sourceReadsLater, localSourceReadsLater). recursive_records_test.res covers the same order for bare records (first, localPair), which throws on master too. Without the backend change, loading the module throws a ReferenceError. Two super_errors fixtures cover the let rec rejection, for a source that is fully and one that is partially overridden. record_spread_pure_source.res pins that a variable source changes neither the order of top-level bindings nor inlining. No existing output changes.

Both test files keep warning 23 on: every spread they test is one it reports, so they only take it out of the errors with -warn-error -23 in @@config, and the build prints it.

A non-variable source without side effects ({...w.p, a: 1, b: 2}) can still add a little to the size that decides inlining. That is from reading the code.

12.x

12.x has the same bug: 5 of the 6 tests in record_spread_source_effect_test fail there. I'll backport once this one is reviewed.

Fixes #9466: a record of a let rec group that an earlier record reads is now declared before that read (7b2e4eb). The issue's example is a test in recursive_records_test.res.

The fix was written by Claude.

@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Changelog

💥 Breaking Change

  • 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.

🐛 Bug fix

  • 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 (A record in a recursive group can be read before it exists #9466).
  • 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.

Semantic Diff

13 commits · Full page

Evaluate the source of a record spread whose fields are all overridden

7dc0d30 · illusionalsagacity · Nov 25, 2026, 19:39 UTC

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)

type t = {a: int, b: int}
@val external f: unit => t = "f"
let make = () => {...f(), a: 1, b: 2}

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
+  Some
+    expression
+      Texp_apply
+      expression
+        Texp_ident "f/1004"
+        <arg>
+          Nolabel
+          expression
+            Texp_construct "()"
+            []

JS modified (record spread with every field overridden)

type t = {a: int, b: int}
@val external f: unit => t = "f"
let make = () => {...f(), a: 1, b: 2}

js

 function make() {
+  f();
   return {
     a: 1,
     b: 2
   };
 }

JS modified (source read from a module with side effects)

let make = () => {...Effects.base, a: 1, b: 2}

js

+import * as Effects from "./Effects.mjs";
+
 function make() {
   return {
     a: 1,
     b: 2
   };
 }
 
 export {
   make,
 }
-/* No side effect */
+/* Effects Not a pure module */

Typing modified (let rec check of an overridden source)

type callback = {run: unit => int}
@val external wrap: callback => callback = "wrap"
let rec callback = {...wrap(callback), run: () => 1}

text · Rec_check

-accepted, without calling wrap
+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.
  • 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.
  • Which existing checked-in outputs change? None.
Build a recursive record into a dummy when its source runs first

c0308e1 · illusionalsagacity · Nov 26, 2026, 21:59 UTC

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)

type rec node = {next: node, v: int}
let rec n = {...makeSource(), next: n, v: 1}

js

-makeSource();
+let n = {};
 
-let n = {
+Primitive_object.updateDummy(n, (makeSource(), {
   next: n,
   v: 1
-};
+}));

JS modified (recursive record at the end of a sequence)

type rec node = {next: node, v: int}
let rec n = {
  Console.log("a")
  {next: n, v: 1}
}

js

-console.log("a");
+let n = {};
 
-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.
  • 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.
Declare a recursive record directly when its fields read none of the group

cd49e27 · illusionalsagacity · Nov 27, 2026, 00:05 UTC

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)

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)}
}

js

-let r = {};
-
 function f(x) {
   return r.b + x | 0;
 }
 
-Primitive_object.updateDummy(r, (log(), {
-  a: compute(),
+log();
+
+let r_a = compute();
+
+function r_run(x) {
+  return r.b + x | 0;
+}
+
+let r = {
+  a: r_a,
   b: 1,
-  run: x => r.b + x | 0
-}));
+  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.
Find a recursive record's block after a recursive let too

6ed51c7 · illusionalsagacity · Nov 27, 2026, 21:36 UTC

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)

type rec node = {value: int, next: node}
let rec n = {
  ...{
    let rec loop = () => if again() {loop()} else {makeSource()}
    loop()
  },
  value: 1,
  next: n,
}

js

-loop();
+let n = {};
 
-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.
  • Which checked-in outputs change? Only record_spread_source_effect_test.mjs, for the new cases.
Build a recursive record into a dummy when a source before it reads it

58424c6 · illusionalsagacity · Nov 28, 2026, 17:54 UTC

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)

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,
}

js

+let n = {};
+
 let tmp = {};
 
 Primitive_object.updateDummy(tmp, {
   left: tmp,
   right: n,
   value: tick()
 });
 
-let n = {
+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.
  • 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.
  • Which checked-in outputs change? Only record_spread_source_effect_test.mjs, for the new cases.
Keep warning 23 on in the record spread source tests

4bf898f · illusionalsagacity · Nov 28, 2026, 17:54 UTC

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.
Build a constant recursive record into a dummy when a source reads it

5ca0d22 · illusionalsagacity · Nov 28, 2026, 19:49 UTC

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)

type rec branch = {lower: option<branch>, upper: option<branch>, weight: int}
let rec n = {
  ...{
    let rec tmp = {lower: Some(tmp), upper: Some(n), weight: tick()}
    tmp
  },
  lower: None,
  upper: None,
  weight: 1,
}

js

+let n = {};
+
 let tmp = {};
 
 Primitive_object.updateDummy(tmp, {
   lower: tmp,
   upper: n,
   weight: tick()
 });
 
-let n = {
+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.
  • Which checked-in outputs change? Only record_spread_source_effect_test.mjs, for the new cases.
Find a recursive record's tail block before checking its reads

744c0e5 · illusionalsagacity · Nov 28, 2026, 19:58 UTC

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.
Declare a recursive binding before an earlier binding reads it

29ad594 · illusionalsagacity · Nov 28, 2026, 21:09 UTC

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)

type rec pair = {other: option<pair>, back: unit => pair}
let rec first = {other: Some(second), back: () => first}
and second = {other: None, back: () => first}

js

 let first = {};
 
+let second = {};
+
 Primitive_object.updateDummy(first, {
   other: second,
   back: () => first
 });
 
-function second_back() {
-  return first;
-}
-
-let second = {
+Primitive_object.updateDummy(second, {
   other: undefined,
-  back: second_back
-};
+  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.
  • 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.
Note that a recursive record's spread source is checked

72fe4ef · illusionalsagacity · Nov 28, 2026, 21:09 UTC

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.

⚠️ 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.

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.
Look for a recursive binding's reads only in bindings built after it

139e756 · illusionalsagacity · Nov 29, 2026, 02:36 UTC

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.
Say that a spread's source is still evaluated in warning 23

d905824 · illusionalsagacity · Nov 29, 2026, 02:52 UTC

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 7b2e4eb; 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.
✨ Recognize record copies and non-nesting options in tail_block

5d51c88 · illusionalsagacity · Nov 29, 2026, 17:56 UTC · new

Why

Codex review of 36c386c 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)

type rec optLink = {optNext: option<optLink>, 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}

js

 let a = {};
+let b = {};
 let s = {};
 Primitive_object.updateDummy(s, {optNext: b, ...});
 Primitive_object.updateDummy(a, ...);
-let b = {
+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).

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.44444% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.46%. Comparing base (6b9bc07) to head (5d51c88).

Files with missing lines Patch % Lines
compiler/backend/lam_compile.ml 93.65% 4 Missing ⚠️
compiler/typing/rec_check.ml 66.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9427      +/-   ##
==========================================
+ Coverage   82.44%   82.46%   +0.02%     
==========================================
  Files         465      465              
  Lines       65935    66001      +66     
==========================================
+ Hits        54357    54431      +74     
+ Misses      11578    11570       -8     
Files with missing lines Coverage Δ
compiler/typing/translcore.ml 88.57% <100.00%> (+0.05%) ⬆️
compiler/typing/typecore.ml 89.16% <100.00%> (+<0.01%) ⬆️
compiler/typing/typedtree.ml 92.06% <100.00%> (+0.83%) ⬆️
compiler/typing/warnings.ml 76.22% <100.00%> (+0.09%) ⬆️
compiler/typing/rec_check.ml 49.57% <66.66%> (+2.36%) ⬆️
compiler/backend/lam_compile.ml 92.63% <93.65%> (+0.31%) ⬆️

... and 3 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pkg-pr-new

pkg-pr-new Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

rescript

npm i https://pkg.pr.new/rescript@9427

@rescript/belt

npm i https://pkg.pr.new/@rescript/belt@9427

@rescript/darwin-arm64

npm i https://pkg.pr.new/@rescript/darwin-arm64@9427

@rescript/linux-arm64

npm i https://pkg.pr.new/@rescript/linux-arm64@9427

@rescript/linux-x64

npm i https://pkg.pr.new/@rescript/linux-x64@9427

@rescript/runtime

npm i https://pkg.pr.new/@rescript/runtime@9427

@rescript/win32-x64

npm i https://pkg.pr.new/@rescript/win32-x64@9427

commit: 5d51c88

@cknitt

cknitt commented Nov 26, 2026

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-29T07:03:57.678167Z 36c386c Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7a1536c691

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread compiler/typing/translcore.ml Outdated
| Some init_expr ->
let init = transl_exp init_expr in
if drops_record_source fields init then lam
else let_ Strict init_id init lam

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve backpatching for cyclic records with effectful spreads

For type rec node = {next: node}, the valid initializer let rec n = {...makeSource(), next: n} (where makeSource: unit => node) now wraps the record's Pmakeblock in an Llet, which dead-binding elimination turns into an Lsequence. However, Lam_compile.compile_recursive_let only allocates/backpatches a dummy for a bare Pmakeblock; neither wrapper reaches that path. Its normal-declaration fallback consequently reads n before initialization instead of constructing the cycle. Previously, discarding the fully overridden source left a bare block and this worked. Preserve recursive-record backpatching when sequencing the source, and add a direct-cycle regression checked both with and without Lambda optimization.

AGENTS.md reference: compiler/AGENTS.md:L160-L160

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed. On this branch, let rec n = {...makeSource(), next: n, v: 1} compiled to makeSource(); let n = {next: n, v: 1};, and loading it threw ReferenceError: Cannot access 'n' before initialization. compile_recursive_let only declared a dummy for a bare Pmakeblock. With the source kept, the block comes after an Llet (or, after dead-binding elimination, an Lsequence), so it fell through to the plain declaration.

The same hole exists on master for a record built at the end of a sequence: let rec n = {Console.log("a"); {next: n, v: 1}} throws the same ReferenceError.

Fixed in 6e80d99 in compiler/backend/lam_compile.ml. When a block comes after a sequence or a let and one of its fields reads a binding of the recursive group, the binding is now declared as a dummy first, and the block is copied into it with updateDummy, the same way a bare block with such fields already was:

let n = {};

Primitive_object.updateDummy(n, (makeSource(), {
  next: n,
  v: 1
}));

Recursive modules, whose blocks come after lets of their functions, are still declared directly because their fields are variables bound before the group. No other checked-in output changes.

There is no switch to turn off the Lambda passes, so I covered both shapes in record_spread_source_effect_test.res instead. cycle gets the sequence the passes leave behind, and letCycle keeps an Llet before the block. sequenceCycle covers the master case. All three check that x.next === x. Without the fix, loading the test module throws.

Investigated by Claude.

@cknitt

cknitt commented Nov 27, 2026

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e74d411b45

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread compiler/backend/lam_compile.ml Outdated
Comment on lines +107 to +108
| Lsequence (_, body) | Llet (_, _, _, body) -> block_tag body
| _ -> None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle recursive-let prefixes when locating cyclic record blocks

When a fully overridden spread source contains a local recursive helper, e.g. let rec n = {...{let rec loop = () => if again() {loop()} else {makeSource()}; loop()}, next: n}, Lam_pass_deep_flatten hoists its recursive binding and leaves Lletrec (..., Lsequence (..., Pmakeblock ...)) as n's RHS. Unlike the simple wrappers covered by the new cycle tests, this outer Lletrec hits None, so compile_recursive_let takes its normal-declaration fallback and reads n in its own initializer, throwing ReferenceError when the module loads. Traverse recursive-let prefixes too and add a regression with and without optimization.

AGENTS.md reference: compiler/AGENTS.md:L160-L160

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real. let rec n = {...{let rec loop = () => if again() {loop()} else {makeSource()}; loop()}, value: 1, next: n} compiled to loop(); let n = {value: 1, next: n};, and Node threw ReferenceError: Cannot access 'n' before initialization when the module loaded. block_after_effects only looked through sequences and lets, and the hoisted helper leaves the block after an Lletrec.

Fixed in e1188b7: block_after_effects now also looks through recursive lets, so n is declared as a dummy and filled by updateDummy after loop() runs. Lambda passes can't be turned off, so the regression covers the record at module level (letRecCycle) and local to a function (localLetRecCycle), in "sources of module-level and recursive records run" in record_spread_source_effect_test.

Investigated by Claude.

illusionalsagacity added a commit to illusionalsagacity/rescript-compiler that referenced this pull request Nov 27, 2026
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 rescript-lang#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 <illusionalsagacity@users.noreply.github.com>
@cknitt

cknitt commented Nov 28, 2026

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e1188b7170

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@@ -0,0 +1,194 @@
@@warning("-23")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep warning 23 enabled in the new regression fixtures

The root AGENTS.md explicitly prohibits warning suppressions, but this file disables warning 23 for the entire module; record_spread_pure_source.res adds the same suppression. These fixtures exercise the spread syntax associated with that diagnostic, so keep warning emission enabled and use the existing expected-diagnostic fixtures where the warning needs to be asserted rather than adding file-wide suppressions.

AGENTS.md reference: AGENTS.md:L60-L60

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real, but the warning can't be avoided here. Every spread in both files has all its fields overridden, which is the case under test (the source used to be dropped) and exactly what warning 23 reports, so no rewrite keeps the tests and loses the warning. tests/tests builds with -warn-error A-110, so just dropping @@warning("-23") fails the build.

Fixed in 6438cdf: both files drop @@warning("-23") and instead add -warn-error -23 to their @@config flags. The warning stays on and is printed for each of these spreads; it just doesn't fail the build. The diagnostic itself is still asserted in the rec_record_spread_source super_errors fixture. No output changes.

Investigated by Claude.

Comment thread compiler/backend/lam_compile.ml Outdated
let rec block_tag ~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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Account for eager reads in the prefixes before a record block

For type rec node = {left: node, right: node, value: int}, an existing base: node, and effectful tick: unit => int, the accepted initializer let rec n = {...{let rec tmp = {left: tmp, right: n, value: tick()}; tmp}, left: base, right: base, value: 1} still reads n before initialization. Although the recursive-let prefix is now traversed, this predicate examines only the final record’s fields and returns None, overlooking the eager right: n read while constructing tmp. That recursive value survives optimization, so the normal-declaration fallback constructs it before declaring n, causing a JavaScript ReferenceError. Include eager prefix reads in the dummy-allocation decision and add a regression with and without Lambda optimization, as required by compiler/AGENTS.md.

AGENTS.md reference: compiler/AGENTS.md:L160-L160

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real. block_after_effects looked only at the fields of the final block, so in let rec n = {...{let rec tmp = {left: tmp, right: n, value: tick()}; tmp}, left: base, right: base, value: 1} the recursive let of tmp was built first with right: n, and n was declared after it: ReferenceError: Cannot access 'n' before initialization at module load (and on the call, for a local record).

Fixed in 6fd9317: an expression of a sequence, let or recursive let before the block that reads a binding of the group (functions excepted, as for fields) now also makes the record a dummy that tmp can point at and that the block is copied into. A closure in the source that is called and reads the record ({...{let g = () => k; ignore(g()); base}, ...}) is already rejected by the recursive value check. Regressions: prefixRead (module level) and localPrefixRead (local to a function) in record_spread_source_effect_test.res; without the fix the module throws the ReferenceError when it loads. There is still no switch to turn the Lambda passes off, so the two placements stand in for that.

Investigated by Claude.

illusionalsagacity added a commit to illusionalsagacity/rescript-compiler that referenced this pull request Nov 28, 2026
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 rescript-lang#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 <illusionalsagacity@users.noreply.github.com>
illusionalsagacity added a commit to illusionalsagacity/rescript-compiler that referenced this pull request Nov 28, 2026
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 rescript-lang#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 <illusionalsagacity@users.noreply.github.com>
illusionalsagacity added a commit to illusionalsagacity/rescript-compiler that referenced this pull request Nov 28, 2026
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 rescript-lang#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 <illusionalsagacity@users.noreply.github.com>
@cknitt

cknitt commented Nov 28, 2026

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6438cdf9e1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread compiler/backend/lam_compile.ml Outdated
Comment on lines +111 to +113
| Lprim {primitive = Pmakeblock tag_info; args} when after_effects ->
if prefix_reads || List.exists reads_binding args then Some tag_info
else None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle constant record blocks after recursive prefixes

For type rec node = {left: option<node>, right: option<node>, value: int}, the initializer let rec n = {...{let rec tmp = {left: Some(tmp), right: Some(n), value: tick()}; tmp}, left: None, right: None, value: 1} is accepted, with an effectful tick: unit => int. Unlike the new prefixRead fixture, its final record is emitted by transl_record as Lconst (Const_block ...), so this matcher returns None despite the eager prefix read. The normal-declaration fallback consequently constructs tmp before declaring n, causing a module-load ReferenceError. Recognize constant-block terminals when prefix_reads is true, and cover this case with and without optimization.

AGENTS.md reference: compiler/AGENTS.md:L160-L160

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real. When every field of the final record is a constant, transl_record emits it as Lconst (Const_block ...) instead of a Pmakeblock, so block_after_effects didn't see a block at the end of the chain even though the spread source before it reads n. compile_recursive_let then declared n after building tmp, and the module threw ReferenceError: Cannot access 'n' before initialization at load (a local one read n from the temporal dead zone the same way).

Fixed in 3c89b3c: a constant block at the end of the chain is now built into a dummy when an expression before it reads the group, like a Pmakeblock; the constant itself reads nothing. constantPrefixRead (module level) and localConstantPrefixRead (local to a function) in record_spread_source_effect_test.res cover it; both threw before the fix. I also checked the other final shapes: the recursive value check accepts expressions before the record only for the record spread, whose final record is one of these two, and rejects an immediate such as None there.

Investigated by Claude.

@cknitt

cknitt commented Nov 28, 2026

Copy link
Copy Markdown
Member

Thanks, the recursive record fixes work. I tried mutually recursive records, a record inside a variant, local let rec, closures reading the group, and sources with lets and sequences. All are correct, and none of these sources is dropped any more. Mutually recursive records and records inside a variant have no test yet. I built this merged with master and regenerated all test outputs: no diffs, all tests pass. -warn-error -23 in the tests is fine with me.

One thing the PR doesn't change: warning 23 still says "You can remove the ... spread" (compiler/typing/warnings.ml). Since this PR, the source is evaluated, so for {...f(), a: 1, b: 2} that advice would drop the call to f(). Could the text say what the spread still does, or only suggest removing it when the source is a plain variable? The rec_record_spread_source.res.expected snapshot would change with it.

Separately, a bug master already has, not caused by this PR, which I'll file as an issue: in a mutually recursive group, a record declared directly can be read before it exists by an earlier record built into a dummy (let rec b = {next: a, v: 1} and a = {f: () => b, w: 2} throws a ReferenceError).

This review was done by Claude.

illusionalsagacity added a commit to illusionalsagacity/rescript-compiler that referenced this pull request Nov 29, 2026
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 rescript-lang#9427.

JS modified (constant recursive record after a source that reads it):
Example:
    type rec branch = {lower: option<branch>, upper: option<branch>, 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 <illusionalsagacity@users.noreply.github.com>
illusionalsagacity added a commit to illusionalsagacity/rescript-compiler that referenced this pull request Nov 29, 2026
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 rescript-lang#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<pair>, 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 <illusionalsagacity@users.noreply.github.com>
illusionalsagacity added a commit to illusionalsagacity/rescript-compiler that referenced this pull request Nov 29, 2026
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 rescript-lang#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 <illusionalsagacity@users.noreply.github.com>
illusionalsagacity added a commit to illusionalsagacity/rescript-compiler that referenced this pull request Nov 29, 2026
Why:
    The benchmarks job of rescript-lang#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 rescript-lang#9427.

Review: Does any output change? No: the same bindings are built into
    dummies, and no checked-in output changes.
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
@illusionalsagacity

Copy link
Copy Markdown
Contributor Author

The benchmarks job found stress/LetRec.res allocating 114% more and running 33% more instructions. It came from 7b2e4eb: read_before_built compared every binding of a let rec group with every other, functions included. fc10821 skips bindings that evaluate only functions and only looks forward from each binding. On the generated LetRec.res it now allocates 31.86M words, against 31.88M without this PR (67.99M before the fix). No checked-in output changes.

Investigated by Claude.

illusionalsagacity added a commit to illusionalsagacity/rescript-compiler that referenced this pull request Nov 29, 2026
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 rescript-lang#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 rescript-lang#9466 (an earlier record of a `let rec` group reading a
    later one declared directly) is fixed by 7b2e4eb; 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 <illusionalsagacity@users.noreply.github.com>
@illusionalsagacity

Copy link
Copy Markdown
Contributor Author

Thanks. Addressed in 36c386c on top of fc10821:

  • Warning 23: Useless_record_with now records whether the source is a variable. For a variable the message is unchanged. For any other source it reads: "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." rec_record_spread_source.res.expected changes, and warning_23_useless_record_with_call.res pins the new text for {...make(), a: 3, b: 4}.
  • Tests: mutually recursive records, each with its own source, and a record inside a variant (Shape({...source, around: wrapped, size: 24})) are now in record_spread_source_effect_test.res.
  • A record in a recursive group can be read before it exists #9466: 7b2e4eb already fixes it, since it was pushed after your review. A binding that an earlier binding of the group reads is built into a dummy declared before that read. Your example is now a test in recursive_records_test.res, it compiles to let b = {}; let a = {}; updateDummy(b, ...); updateDummy(a, ...), and the PR body says it fixes A record in a recursive group can be read before it exists #9466.

Separately, the benchmarks job flagged stress/LetRec.res; that's fixed in fc10821 (see the comment above).

Investigated by Claude.

@cknitt

cknitt commented Nov 29, 2026

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 36c386cf13

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +813 to +814
| Some _ | None ->
compile_recursive_let ~all_bindings:id_args cxt ident arg

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Allocate a dummy for forward-read record copies

When a later recursive binding partially spreads a record with optional fields, transl_record emits a Pduprecord binding ending in Lvar copy_id, not a terminal block. For example, in the new sourceReadsLater scenario, make link.weight optional and use later = {...base, back: () => sourceReadsLater} with an existing base: link. read_before_built correctly marks later, but tail_block returns None, so this fallback still declares it after the earlier source has read it, causing a module-load ReferenceError. Previously the fully overridden source was discarded, so that read did not happen. Support dummy allocation for copied-record results too, and cover this with and without Lambda optimization.

AGENTS.md reference: compiler/AGENTS.md:L160-L160

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real. When a later binding in a let rec group partially spreads a record with optional fields (later = {...base, back: () => sourceReadsLater}), transl_record emits Llet (copy_id, Pduprecord, ...) ending in Lvar copy_id. tail_block returned None, so later was still declared after sourceReadsLater's spread source read it, throwing ReferenceError: Cannot access 'later' before initialization.

Fixed in 5d51c88 (after rebasing onto master): tail_block now tracks Pduprecord bindings (and aliases of them) through their Psetfield sequences to the terminal Lvar, treating the copy as an object block so compile_recursive_lets_aux allocates let later = {}; up front and fills it with Primitive_object.updateDummy(later, {...base, ...}). Regression tests: sourceReadsLaterCopy (module level) and localSourceReadsLaterCopy (local to a function) in record_spread_source_effect_test.res.

| Lprim {primitive = Pmakeblock tag_info; args} ->
Some (tag_info, args @ before)
| Lconst (Const_block (tag_info, _)) -> Some (tag_info, before)
| _ -> None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Look through non-nesting options when locating record tails

For type rec node = {left: option<node>, right: option<node>, value: int} and an effectful tick, the accepted initializer let rec n = Some({...{let rec tmp = {left: Some(tmp), right: n, value: tick()}; tmp}, left: None, right: None, value: 1}) has an outer Psome_not_nest. This fallback therefore hides both the terminal record and its eager prefix read from tail_block; compile_recursive_let declares n normally, and constructing tmp reads it before initialization, throwing ReferenceError. Previously the fully overridden spread source was dropped, leaving a constant initializer without that read. Traverse the allocation-free option wrapper when locating the block, and cover this with and without optimization.

AGENTS.md reference: compiler/AGENTS.md:L160-L160

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real. Wrapping the recursive record in a non-nesting Some(...) produced an outer Psome_not_nest, so tail_block returned None and declared n after tmp read it, throwing ReferenceError: Cannot access 'n' before initialization.

Fixed in 5d51c88: tail_block now traverses Psome_not_nest wrappers when locating the terminal block and its prefix reads, so n is declared as a dummy before tmp is constructed and filled via updateDummy. Regression tests: optionalPrefixRead (module level) and localOptionalPrefixRead (local to a function) in record_spread_source_effect_test.res.

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"
          [
            <arg>
              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 <illusionalsagacity@users.noreply.github.com>
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 <illusionalsagacity@users.noreply.github.com>
…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 <illusionalsagacity@users.noreply.github.com>
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 rescript-lang#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 <illusionalsagacity@users.noreply.github.com>
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 rescript-lang#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 <illusionalsagacity@users.noreply.github.com>
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 rescript-lang#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 <illusionalsagacity@users.noreply.github.com>
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 rescript-lang#9427.

JS modified (constant recursive record after a source that reads it):
Example:
    type rec branch = {lower: option<branch>, upper: option<branch>, 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 <illusionalsagacity@users.noreply.github.com>
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 <illusionalsagacity@users.noreply.github.com>
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 rescript-lang#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<pair>, 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 <illusionalsagacity@users.noreply.github.com>
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 rescript-lang#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 <illusionalsagacity@users.noreply.github.com>
Why:
    The benchmarks job of rescript-lang#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 rescript-lang#9427.

Review: Does any output change? No: the same bindings are built into
    dummies, and no checked-in output changes.
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
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 rescript-lang#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 rescript-lang#9466 (an earlier record of a `let rec` group reading a
    later one declared directly) is fixed by 7b2e4eb; 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 <illusionalsagacity@users.noreply.github.com>
Why:
    Codex review of 36c386c 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<optLink>, 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 <illusionalsagacity@users.noreply.github.com>
@illusionalsagacity
illusionalsagacity marked this pull request as ready for review November 29, 2026 18:04

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A record in a recursive group can be read before it exists

2 participants