Skip to content

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

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

illusionalsagacity wants to merge 4 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 or a 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. 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.

Behaviour changes

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, without calling wrap. 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), and for a record at the end of a sequence (sequenceCycle), and 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). 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.

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.

The fix was written by Claude.

@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Changelog

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

Semantic Diff

4 commits · Full page

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

8cb8eef · 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

cfbc15c · 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

e74d411 · 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

e1188b7 · illusionalsagacity · Nov 27, 2026, 21:36 UTC · new

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.

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.67442% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 82.29%. Comparing base (6a7e3b8) to head (e1188b7).
⚠️ Report is 4 commits behind head on master.

Files with missing lines Patch % Lines
compiler/typing/rec_check.ml 66.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9427      +/-   ##
==========================================
+ Coverage   82.25%   82.29%   +0.04%     
==========================================
  Files         462      462              
  Lines       65650    65699      +49     
==========================================
+ Hits        53999    54070      +71     
+ Misses      11651    11629      -22     
Files with missing lines Coverage Δ
compiler/backend/lam_compile.ml 91.08% <100.00%> (+0.50%) ⬆️
compiler/typing/translcore.ml 88.42% <100.00%> (+0.13%) ⬆️
compiler/typing/typecore.ml 89.11% <100.00%> (-0.01%) ⬇️
compiler/typing/typedtree.ml 91.80% <100.00%> (+0.57%) ⬆️
compiler/typing/rec_check.ml 49.57% <66.66%> (+2.36%) ⬆️

... and 8 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: e1188b7

@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-28T05:59:07.628803Z e1188b7 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".

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

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

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 👍 / 👎.

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 👍 / 👎.

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.

2 participants