Skip to content

Copy dict and array spreads before later elements that can change them - #9429

Merged
cknitt merged 6 commits into
rescript-lang:masterfrom
illusionalsagacity:fix-dict-array-spread-order
Nov 29, 2026
Merged

cknitt merged 6 commits into
rescript-lang:masterfrom
illusionalsagacity:fix-dict-array-spread-order

Conversation

@illusionalsagacity

@illusionalsagacity illusionalsagacity commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Part of #9398 (item 34), and also fixes #9398 item 21. Found while reviewing the fixes for it.

Problem

dict{...base, "b": v} and [...base, v] copy base before v is evaluated. When v needs statements (a try, or a switch that is not one expression), the copy was taken after them. An array is copied by Primitive_array.spread, which runs after all elements, so there a plain call is enough.

@inline(never) let id = x => x
let f = (base: dict<int>) =>
  dict{...base, "b": try { base->Dict.set("a", 100); id(5) } catch { | _ => 0 }}

Before:

function f(base) {
  let tmp;
  try {
    base["a"] = 100;
    tmp = id(5);
  } catch (exn) {
    tmp = 0;
  }
  return {
    ...base,
    b: tmp
  };
}

After:

function f(base) {
  let tmp = {...base};
  let tmp$1;
  try {
    base["a"] = 100;
    tmp$1 = id(5);
  } catch (exn) {
    tmp$1 = 0;
  }
  return {
    ...tmp,
    b: tmp$1
  };
}

With a call in an array:

let call = (base: array<int>, f) => [...base, f()]
let pure = (base: array<int>, x) => [...base, x + 1]

Before:

function call(base, f) {
  return Primitive_array.spread([
    base,
    [f()]
  ]);
}

function pure(base, x) {
  return Primitive_array.spread([
    base,
    [x + 1 | 0]
  ]);
}

After:

function call(base, f) {
  return [
    ...base,
    f()
  ];
}

function pure(base, x) {
  return Primitive_array.spread([
    base,
    [x + 1 | 0]
  ]);
}

Fix

While the parts of a literal are sequenced, a spread is the copy {...base} or [...base] if statements that can change it run after it: a later part's own statements, or a later call that is held in a temporary in front of them. The copy is made where the sequencing decides what to hold, so the two can't disagree. When a later part of an array runs code in its value (a call, an await, a read of a JS property, or an index read such as Dict.getUnsafe, which can run a getter), the array compiles to a native array literal [...xs, f(x)] instead of Primitive_array.spread: JS evaluates its elements, spreads included, left to right, so xs is copied once, before f(x) runs. Spreads where no later part runs code keep Primitive_array.spread, so their output doesn't change. List spreads are unaffected, since lists are immutable.

The backend takes an array literal apart in two places: dict literals (Pmakedict), whose rows never contain a spread, and @variadic arguments, which now give f(a, ...xs, b). Indexing into a literal, its length and dropping a write to it require no_side_effect, which a spread fails.

Folding typeof and null checks of a literal

typeof of an array literal folded to "object" (and of a number or a .length to "number"), and a null check of an array, tuple or number to false, without looking at the operand, so the calls in it never ran (#9398 item 21). With the native literal above, typeof([...base, f()]) hit the same fold and stopped calling f. These folds now require no_side_effect on the operand; otherwise the check stays as written:

function typeofSpread(base) {
  return typeof [
    ...base,
    tick()
  ];
}

function isNullableLiteral() {
  return [tick()] == null;
}

Literals that run no code still fold (typeof [x] is "object").

Trade-offs

  • In an array with a spread before a part that needs statements and another spread before a later call, such as [...a, try {...} catch {...}, ...b, f()], a is copied into a temporary before the statements and spread again into the literal, so it is copied twice.
  • The copy and the native literal use JS spread syntax, which iterates the array, where Primitive_array.spread reads by index. ReScript arrays are real arrays, so both read the same elements.

Tests

dict_array_spread_order_test.res checks the results at runtime for a later element that runs code in each part of its expression (operands, conditions, indexes, string appends, templates, dicts and records, including a record with an optional field), and pins the cases that run no code. Disabling any one of four checks in can_run_code (record spreads, object spreads, templates, the right side of a string append) makes a runtime test fail. Tests with a later call held in front of a pure statement ([...base, ...f(), {let a = r.a; a * a}], and the dict forms) and with a later Dict.getUnsafe or Array.getUnsafe read check that the spread is read before that code runs; each fails without its fix. A @variadic call with a spread and a later call checks that the elements become the call's arguments. One existing output changes, spread_literal_test.mjs, which now builds a native array literal. literal_fold_effect_test.res checks that typeof and Nullable.isNullable of a plain literal, a spread literal, a tuple and a .length of a call still run the call, and that pure literals still fold; it fails without the fix.

12.x

12.x has no dict spread, but its array spreads have the same bug: there both [...base, f()] and the try case include the mutation ([1, 2, 100, 5]). 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 evaluation order for dict and array spreads dict{...base, "key": value} and [...base, value]: the base is copied before later elements that can change it, such as a try or, in an array, a function call or a Dict.getUnsafe read, so their mutations of the base no longer show up in the result. An array spread that is read where it stands now uses JS spread syntax, which iterates the array, where Primitive_array.spread read it by index; ReScript arrays are real arrays, so both read the same elements.
  • Fix typeof and Nullable.isNullable of an array or tuple literal, or of an array's length, dropping the calls in it: they fold to a constant only when the operand runs no code.

Semantic Diff

6 commits · Full page

Copy dict and array spreads before later elements that can change them

7049023 · illusionalsagacity · Nov 25, 2026, 19:42 UTC

Why

dict{...base, "b": v} and [...base, v] copy base where the spread stands, before v is evaluated. sequence_arguments got the bare spread as an argument. A variable is safe to delay, so it stayed in the literal, after the statements of any later element that needs them (a try, or a switch that is not one expression), and a mutation of the base in those statements showed up in the result. An array spread is copied by Primitive_array.spread, which runs after all elements are evaluated, so there a plain call did the same. While the parts of a literal are sequenced, a spread is now the copy {...base} or [...base] when a later part has such statements or, in an array, a value that can run code (a call, an await, a read of a JS property). Otherwise the spread stays bare as before.

JS modified (dict spread with an element that needs statements)

@inline(never) let id = x => x
let f = (base: dict<int>) =>
  dict{...base, "b": try { base->Dict.set("a", 100); id(5) } catch { | _ => 0 }}

js

 function f(base) {
-  let tmp;
+  let tmp = {...base};
+  let tmp$1;
   try {
     base["a"] = 100;
-    tmp = id(5);
+    tmp$1 = id(5);
   } catch (exn) {
-    tmp = 0;
+    tmp$1 = 0;
   }
   return {
-    ...base,
-    b: tmp
+    ...tmp,
+    b: tmp$1
   };
 }

JS modified (array spread with an element that needs statements)

@inline(never) let id = x => x
let f = (base: array<int>) =>
  [...base, try { base->Array.push(100); id(5) } catch { | _ => 0 }]

js

 function f(base) {
-  let tmp;
+  let tmp = [...base];
+  let tmp$1;
   try {
     base.push(100);
-    tmp = id(5);
+    tmp$1 = id(5);
   } catch (exn) {
-    tmp = 0;
+    tmp$1 = 0;
   }
   return Primitive_array.spread([
-    base,
-    [tmp]
+    tmp,
+    [tmp$1]
   ]);
 }

JS modified (array spread with a call after it)

let call = (base: array<int>, f) => [...base, f()]
let pure = (base: array<int>, x) => [...base, x + 1]

js

 function call(base, f) {
   return Primitive_array.spread([
-    base,
+    [...base],
     [f()]
   ]);
 }
 
 function pure(base, x) {
   return Primitive_array.spread([
     base,
     [x + 1 | 0]
   ]);
 }

Review

  • Are list spreads affected? No, lists are immutable, so when they are copied doesn't show.
  • Why not emit [...base, f()]? An array literal with a spread in it is not safe for the code that looks into array literals (indexing, @variadic arguments), so the copy only ever stands inside the runtime call or a temporary.
  • Which checked-in outputs change? spread_literal_test.mjs, which has a call after a spread.
Build an array spread with a later call as an array literal

c4ec5c1 · illusionalsagacity · Nov 28, 2026, 17:54 UTC

Why

An array spread followed by a part that runs code in its value, such as a call, was copied twice: once as [...xs] before the call and again by Primitive_array.spread. JS evaluates the elements of an array literal, spreads included, left to right, so such a spread now compiles to an array literal with the spreads in it, which copies xs once, before the call runs. Spreads with no later part that runs code keep Primitive_array.spread, so their output doesn't change. An array literal with spreads is held as a whole when later statements need its value first, since a spread can't be held on its own.

JS modified (array spread with a call after it)

let call = (base: array<int>, f) => [...base, f()]
let later = (base: array<int>, f) => [0, ...base, ...f(), ...base]

js

 function call(base, f) {
-  return Primitive_array.spread([
-    [...base],
-    [f()]
-  ]);
+  return [
+    ...base,
+    f()
+  ];
 }
 
 function later(base, f) {
-  return Primitive_array.spread([
-    [0],
-    [...base],
-    f(),
-    base
-  ]);
+  return [
+    0,
+    ...base,
+    ...f(),
+    ...base
+  ];
 }

JS modified (@variadic argument)

@variadic @val external arrayOf: array<int> => array<int> = "Array.of"
let variadicCall = (base: array<int>, f) => arrayOf([...base, f()])

js

 function variadicCall(base, f) {
-  return Array.of(...Primitive_array.spread([
-    [...base],
-    [f()]
-  ]));
+  return Array.of(...base, f());
 }

Review

  • Which translations take an array literal apart, and do they handle spreads in it? Dict literals (Pmakedict), whose rows never contain a spread, and @variadic arguments, where f(a, ...xs, b) means the same as the spread array. Indexing into a literal, its length and dropping a write to it all require no_side_effect, which a spread fails.
  • What if a spread also has statements after it? It is still copied into a temporary before them, as before, and the copy is spread into the literal.
  • Is the in_place parameter of copy_spreads still needed? No, both callers now copy only before later statements, so it is gone.
✨ Keep the calls in an array literal whose typeof or null check is folded

f0b62fa · illusionalsagacity · Nov 28, 2026, 19:44 UTC · new

Why

typeof of an array literal folded to "object", of a number or a .length to "number", and a null check of an array, tuple or number to false, without looking at the operand, so a call in it never ran. Since the previous commit, [...base, f()] is an array literal, so typeof([...base, f()]) stopped calling f too. These folds now require the operand to run no code; otherwise the check stays in the output.

JS modified (typeof and null check of a literal that runs code)

let typeofLiteral = () => Type.typeof([tick()])
let typeofSpread = (base: array<int>) => Type.typeof([...base, tick()])
let typeofLength = () => Type.typeof(Array.length(tickArray()))
let isNullableLiteral = () => Nullable.isNullable(Nullable.make([tick()]))

js

 function typeofLiteral() {
-  return "object";
+  return typeof [tick()];
 }
 
 function typeofSpread(base) {
-  return "object";
+  return typeof [
+    ...base,
+    tick()
+  ];
 }
 
 function typeofLength() {
-  return "number";
+  return typeof tickArray().length;
 }
 
 function isNullableLiteral() {
-  return false;
+  return [tick()] == null;
 }

Review

  • Why keep the check rather than (tick(), "object")? It is the expression as written, and the operand of a spread literal can't be reduced to its calls without dropping the copy.
  • Do literals that run no code still fold? Yes, typeof [x] is still "object" and isNullable([x]) still false.
  • Which checked-in outputs change? None besides the new test.
✨ Share the array spread part helpers in lam_compile

51c77b0 · illusionalsagacity · Nov 28, 2026, 19:54 UTC · new

The parts of an array spread were taken apart into elements in two places, and spreads_in_place repeated the fold of copy_spreads to find the parts with statements after them. It now reads the parts copy_array_spreads returns, where those spreads are already array literals, and an array literal with spreads falls through to the case of evaluate_now that holds any value. The generated JS does not change.

✨ Copy a spread before a later value held in front of pure statements

44208a3 · illusionalsagacity · Nov 28, 2026, 21:05 UTC · new

Why

copy_spreads copied a spread only when a later part's statements did more than define pure values. sequence_arguments also holds a later value that runs code, such as a call, in a temporary when any statement comes after it, even a pure one, so that call ran before the literal read the bare spread in front of it. sequence_arguments now takes the copy as ~copy and applies it to a value it holds in front of statements that are not pure, so the copy follows the same predicate that decides what is held. spreads_in_place reads the values left in the literal after that.

JS modified (spread before a call held in front of a pure statement)

let arrayHeldCall = (base: array<int>, f, r: r) =>
  [...base, ...f(), {let a = r.a; a * a}]
let dictHeldCall = (base: dict<int>, f, r: r) =>
  dict{...base, ...f(), "a": {let a = r.a; a * a}}

js

 function arrayHeldCall(base, f, r) {
-  let tmp = f();
+  let tmp = [...base];
+  let tmp$1 = f();
   let a = r.a;
-  return [
-    ...base,
-    ...tmp,
-    a * a | 0
-  ];
+  return Primitive_array.spread([
+    tmp,
+    tmp$1,
+    [a * a | 0]
+  ]);
 }
 
 function dictHeldCall(base, f, r) {
-  let tmp = f();
+  let tmp = {...base};
+  let tmp$1 = f();
   let a = r.a;
   return {
-    ...base,
     ...tmp,
+    ...tmp$1,
     a: a * a | 0
   };
 }

Review

  • Is a held call copied too? Only when statements that are not pure follow it, as before; f() above is held without a copy, since let a = r.a can't change what it returns.
  • Which checked-in outputs change? None besides the new tests.
✨ Treat an index read as running code after an array spread

3ea462f · illusionalsagacity · Nov 28, 2026, 21:06 UTC · new

Why

can_run_code treated an index read a[i] as running no code when its operands ran none. Dict.getUnsafe and other @get_index externals compile to one on any JS object, where it can run a getter, so [...base, d->Dict.getUnsafe("x")] kept Primitive_array.spread, which reads base only after the getter. Every index read now counts as code, as a read obj["x"] already did, and such a literal keeps the spread where it stands.

JS modified (array spread with a later index read)

let arrayIndexRead = (base: array<int>, d: dict<int>) =>
  [...base, d->Dict.getUnsafe("x")]
let arrayArrayIndexRead = (base: array<int>, items) =>
  [...base, items->Array.getUnsafe(0)]

js

 function arrayIndexRead(base, d) {
-  return Primitive_array.spread([
-    base,
-    [d["x"]]
-  ]);
+  return [
+    ...base,
+    d["x"]
+  ];
 }
 
 function arrayArrayIndexRead(base, items) {
-  return Primitive_array.spread([
-    base,
-    [items[0]]
-  ]);
+  return [
+    ...base,
+    items[0]
+  ];
 }

Review

  • Why every index read, not only one with a string key? A @get_index external with an int key can still be called on any JS object, and the array literal it now gives is as readable as the Primitive_array.spread call it replaces.
  • What about a dict spread? A dict literal keeps its spreads in place already, and the Dict.getUnsafe test there guards the held value of the previous commit.
  • Which checked-in outputs change? arrayPureIndex, which moves to the new test as arrayArrayIndexRead. The changelog fragment now says that a spread read in place uses JS spread syntax, which iterates the array.

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.36364% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.37%. Comparing base (e51ee46) to head (3ea462f).

Files with missing lines Patch % Lines
compiler/backend/lam_compile.ml 85.71% 9 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9429      +/-   ##
==========================================
+ Coverage   82.34%   82.37%   +0.03%     
==========================================
  Files         462      462              
  Lines       65817    65870      +53     
==========================================
+ Hits        54198    54262      +64     
+ Misses      11619    11608      -11     
Files with missing lines Coverage Δ
compiler/backend/js_exp_make.ml 68.14% <100.00%> (+0.43%) ⬆️
compiler/backend/lam_compile.ml 91.84% <85.71%> (+0.84%) ⬆️

... and 4 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@9429

@rescript/belt

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

@rescript/darwin-arm64

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

@rescript/linux-arm64

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

@rescript/linux-x64

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

@rescript/runtime

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

@rescript/win32-x64

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

commit: 3ea462f

@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-29T06:58:53.904908Z 3ea462f 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: bc27b18ddd

ℹ️ 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".

@illusionalsagacity
illusionalsagacity marked this pull request as ready for review November 27, 2026 04:55
@cknitt

cknitt commented Nov 28, 2026

Copy link
Copy Markdown
Member

The fix is correct. I checked arrays with several spreads, the same base spread twice, nested spreads, dicts with several spreads followed by a try, and a %raw element that changes the base.

One cost in common code: an array spread followed by a call now copies the base twice, once with [...xs] and again in Primitive_array.spread:

let a = (xs, x) => [...xs, f(x)]
return Primitive_array.spread([[...xs], [f(x)]]);

Reading a JS object field triggers it too ([...a, obj["x"]]).

Could this case be a native array literal instead?

return [...xs, f(x)];

JS evaluates array elements, spreads included, left to right. So xs is copied before f(x) runs, with one copy and no snapshot. Spreads where no later part runs code can keep Primitive_array.spread, so other output doesn't change. As far as I can see, the backend only takes an array literal apart in two places:

  • dict literals (Pmakedict), which never contain a spread;
  • variadic externals, which would give f(a, ...xs, b). That's valid and means the same.

This PR already emits [...xs], so the printer handles spreads inside array literals.

Small things:

This review was done by Claude.

Why:
    `dict{...base, "b": v}` and `[...base, v]` copy `base` where the spread
    stands, before `v` is evaluated. `sequence_arguments` got the bare spread
    as an argument. A variable is safe to delay, so it stayed in the literal,
    after the statements of any later element that needs them (a `try`, or a
    `switch` that is not one expression), and a mutation of the base in those
    statements showed up in the result. An array spread is copied by
    `Primitive_array.spread`, which runs after all elements are evaluated, so
    there a plain call did the same. While the parts of a literal are
    sequenced, a spread is now the copy `{...base}` or `[...base]` when a later
    part has such statements or, in an array, a value that can run code (a
    call, an `await`, a read of a JS property). Otherwise the spread stays bare
    as before.

JS modified (dict spread with an element that needs statements):
Example:
    @inline(never) let id = x => x
    let f = (base: dict<int>) =>
      dict{...base, "b": try { base->Dict.set("a", 100); id(5) } catch { | _ => 0 }}
Before (js):
    function f(base) {
      let tmp;
      try {
        base["a"] = 100;
        tmp = id(5);
      } catch (exn) {
        tmp = 0;
      }
      return {
        ...base,
        b: tmp
      };
    }
After (js):
    function f(base) {
      let tmp = {...base};
      let tmp$1;
      try {
        base["a"] = 100;
        tmp$1 = id(5);
      } catch (exn) {
        tmp$1 = 0;
      }
      return {
        ...tmp,
        b: tmp$1
      };
    }

JS modified (array spread with an element that needs statements):
Example:
    @inline(never) let id = x => x
    let f = (base: array<int>) =>
      [...base, try { base->Array.push(100); id(5) } catch { | _ => 0 }]
Before (js):
    function f(base) {
      let tmp;
      try {
        base.push(100);
        tmp = id(5);
      } catch (exn) {
        tmp = 0;
      }
      return Primitive_array.spread([
        base,
        [tmp]
      ]);
    }
After (js):
    function f(base) {
      let tmp = [...base];
      let tmp$1;
      try {
        base.push(100);
        tmp$1 = id(5);
      } catch (exn) {
        tmp$1 = 0;
      }
      return Primitive_array.spread([
        tmp,
        [tmp$1]
      ]);
    }

JS modified (array spread with a call after it):
Example:
    let call = (base: array<int>, f) => [...base, f()]
    let pure = (base: array<int>, x) => [...base, x + 1]
Before (js):
    function call(base, f) {
      return Primitive_array.spread([
        base,
        [f()]
      ]);
    }

    function pure(base, x) {
      return Primitive_array.spread([
        base,
        [x + 1 | 0]
      ]);
    }
After (js):
    function call(base, f) {
      return Primitive_array.spread([
        [...base],
        [f()]
      ]);
    }

    function pure(base, x) {
      return Primitive_array.spread([
        base,
        [x + 1 | 0]
      ]);
    }

Review: Are list spreads affected? No, lists are immutable, so when they are
    copied doesn't show.
Review: Why not emit `[...base, f()]`? An array literal with a spread in it is
    not safe for the code that looks into array literals (indexing, `@variadic`
    arguments), so the copy only ever stands inside the runtime call or a
    temporary.
Review: Which checked-in outputs change? spread_literal_test.mjs, which has a
    call after a spread.
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
Why:
    An array spread followed by a part that runs code in its value, such as
    a call, was copied twice: once as `[...xs]` before the call and again by
    `Primitive_array.spread`. JS evaluates the elements of an array literal,
    spreads included, left to right, so such a spread now compiles to an
    array literal with the spreads in it, which copies `xs` once, before the
    call runs. Spreads with no later part that runs code keep
    `Primitive_array.spread`, so their output doesn't change. An array
    literal with spreads is held as a whole when later statements need its
    value first, since a spread can't be held on its own.

JS modified (array spread with a call after it):
Example:
    let call = (base: array<int>, f) => [...base, f()]
    let later = (base: array<int>, f) => [0, ...base, ...f(), ...base]
Before (js):
    function call(base, f) {
      return Primitive_array.spread([
        [...base],
        [f()]
      ]);
    }

    function later(base, f) {
      return Primitive_array.spread([
        [0],
        [...base],
        f(),
        base
      ]);
    }
After (js):
    function call(base, f) {
      return [
        ...base,
        f()
      ];
    }

    function later(base, f) {
      return [
        0,
        ...base,
        ...f(),
        ...base
      ];
    }

JS modified (@variadic argument):
Example:
    @variadic @Val external arrayOf: array<int> => array<int> = "Array.of"
    let variadicCall = (base: array<int>, f) => arrayOf([...base, f()])
Before (js):
    function variadicCall(base, f) {
      return Array.of(...Primitive_array.spread([
        [...base],
        [f()]
      ]));
    }
After (js):
    function variadicCall(base, f) {
      return Array.of(...base, f());
    }

Review: Which translations take an array literal apart, and do they handle
    spreads in it? Dict literals (`Pmakedict`), whose rows never contain a
    spread, and `@variadic` arguments, where `f(a, ...xs, b)` means the
    same as the spread array. Indexing into a literal, its length and
    dropping a write to it all require `no_side_effect`, which a spread
    fails.
Review: What if a spread also has statements after it? It is still copied
    into a temporary before them, as before, and the copy is spread into
    the literal.
Review: Is the `in_place` parameter of `copy_spreads` still needed? No,
    both callers now copy only before later statements, so it is gone.

Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
@illusionalsagacity
illusionalsagacity force-pushed the fix-dict-array-spread-order branch from bc27b18 to c4ec5c1 Compare November 28, 2026 18:21
@illusionalsagacity

Copy link
Copy Markdown
Contributor Author

Agreed, the second copy isn't needed. Thanks for checking where array literals are taken apart. I found the same two places: Pmakedict, whose rows never contain a spread, and @variadic arguments, which now give f(a, ...xs, b). Indexing into a literal, its length and dropping a write to it all require no_side_effect, which a spread fails, so they leave the literal alone.

Fixed in c4ec5c1: when a later part of an array runs code in its value, the parts compile to a native array literal, so [...xs, f(x)] gives return [...xs, f(x)]; with one copy. Spreads where no later part runs code keep Primitive_array.spread, so other output doesn't change. A spread with statements after it is still copied into a temporary before them. One thing the change turned up: when later statements need the whole array's value first (id(([...base, f()], try f() catch {...}))), evaluate_now held each element on its own, which would print let tmp = ...base;. It now holds an array literal with spreads as a whole. copy_spreads lost its in_place parameter, since both callers now copy only before later statements.

New tests in dict_array_spread_order_test.res: variadicCall (@variadic with [...base, f()]), and arrayNested now covers the whole-array hold. The comment above arrayRecordSpreadCall/arrayRecordSpreadField now says they run code, and "No copies" sits above dictCall and the pure cases. Rebased onto master after #9416.

Investigated by Claude.

@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: c4ec5c118b

ℹ️ 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
(* JS evaluates the elements of an array literal, spreads included,
left to right *)
with_source_loc loc
(E.array

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 effects when folding native spread-array literals

When a spread literal is passed directly to typeof, this new Array representation reaches Js_exp_make.typeof, whose Array _ case unconditionally returns "object". Consequently, (base: array<int>, f) => typeof([...base, f()]) now returns a constant without calling f; previously, the Primitive_array.spread call was retained and the callback executed. Js_exp_make.is_null_undefined has the same unguarded array fold, so nullable checks can also discard effects. Guard these folds with no_side_effect or otherwise preserve evaluation of the array before replacing the enclosing expression with a constant.

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. With [...base, f()] now a native array literal, typeof([...base, f()]) hit the Array _ case of Js_exp_make.typeof and folded to "object" without calling f, and Nullable.isNullable of such a literal folded to false the same way. The same folds already dropped the calls in a plain [f()] on master (#9398 item 21), and typeof of Array.length(f()) folded to "number" without calling f.

Fixed in f0b62fa: the Number/Length/Array folds in typeof and the Number/Array/Caml_block fold in is_null_undefined now require no_side_effect, so otherwise the check is kept as written (typeof [...base, tick()], [tick()] == null). Pure literals still fold. This also fixes #9398 item 21. Regression test: tests/tests/src/literal_fold_effect_test.res (typeof and isNullable of a plain literal, a spread literal, a tuple and a .length of a call; fails without the fix).

Investigated by Claude.

@cknitt

cknitt commented Nov 28, 2026

Copy link
Copy Markdown
Member

Thanks, the array literal looks good. [...xs, f(x)] is now one copy, and spreads with no later call are unchanged. I built this merged with master and regenerated all test outputs: no diffs, all tests pass.

I can confirm Codex's P1. Type.typeof([...xs, g()]) folds to "object", and Nullable.isNullable(Nullable.make([...xs, g()])) folds to false, so g() never runs. The two folds in js_exp_make.ml don't check for side effects:

  • typeof: | Array _ -> str L.js_type_object
  • is_null_undefined: | Number _ | Array _ | Caml_block _ -> false_

The same already happens on master for a plain literal: typeof [g()] also gives "object". So adding when no_side_effect e to both cases fixes this PR's case and the old one.

This review was done by Claude.

Why:
    `typeof` of an array literal folded to `"object"`, of a number or a
    `.length` to `"number"`, and a null check of an array, tuple or number
    to `false`, without looking at the operand, so a call in it never ran.
    Since the previous commit, `[...base, f()]` is an array literal, so
    `typeof([...base, f()])` stopped calling `f` too. These folds now
    require the operand to run no code; otherwise the check stays in the
    output.

JS modified (typeof and null check of a literal that runs code):
Example:
    let typeofLiteral = () => Type.typeof([tick()])
    let typeofSpread = (base: array<int>) => Type.typeof([...base, tick()])
    let typeofLength = () => Type.typeof(Array.length(tickArray()))
    let isNullableLiteral = () => Nullable.isNullable(Nullable.make([tick()]))
Before (js):
    function typeofLiteral() {
      return "object";
    }

    function typeofSpread(base) {
      return "object";
    }

    function typeofLength() {
      return "number";
    }

    function isNullableLiteral() {
      return false;
    }
After (js):
    function typeofLiteral() {
      return typeof [tick()];
    }

    function typeofSpread(base) {
      return typeof [
        ...base,
        tick()
      ];
    }

    function typeofLength() {
      return typeof tickArray().length;
    }

    function isNullableLiteral() {
      return [tick()] == null;
    }

Review: Why keep the check rather than `(tick(), "object")`? It is the
    expression as written, and the operand of a spread literal can't be
    reduced to its calls without dropping the copy.
Review: Do literals that run no code still fold? Yes, `typeof [x]` is still
    `"object"` and `isNullable([x])` still `false`.
Review: Which checked-in outputs change? None besides the new test.
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
The parts of an array spread were taken apart into elements in two places,
and `spreads_in_place` repeated the fold of `copy_spreads` to find the parts
with statements after them. It now reads the parts `copy_array_spreads`
returns, where those spreads are already array literals, and an array literal
with spreads falls through to the case of `evaluate_now` that holds any value.
The generated JS does not change.

Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
Why:
    `copy_spreads` copied a spread only when a later part's statements did
    more than define pure values. `sequence_arguments` also holds a later
    value that runs code, such as a call, in a temporary when any statement
    comes after it, even a pure one, so that call ran before the literal
    read the bare spread in front of it. `sequence_arguments` now takes the
    copy as `~copy` and applies it to a value it holds in front of
    statements that are not pure, so the copy follows the same predicate
    that decides what is held. `spreads_in_place` reads the values left in
    the literal after that.

JS modified (spread before a call held in front of a pure statement):
Example:
    let arrayHeldCall = (base: array<int>, f, r: r) =>
      [...base, ...f(), {let a = r.a; a * a}]
    let dictHeldCall = (base: dict<int>, f, r: r) =>
      dict{...base, ...f(), "a": {let a = r.a; a * a}}
Before (js):
    function arrayHeldCall(base, f, r) {
      let tmp = f();
      let a = r.a;
      return [
        ...base,
        ...tmp,
        a * a | 0
      ];
    }

    function dictHeldCall(base, f, r) {
      let tmp = f();
      let a = r.a;
      return {
        ...base,
        ...tmp,
        a: a * a | 0
      };
    }
After (js):
    function arrayHeldCall(base, f, r) {
      let tmp = [...base];
      let tmp$1 = f();
      let a = r.a;
      return Primitive_array.spread([
        tmp,
        tmp$1,
        [a * a | 0]
      ]);
    }

    function dictHeldCall(base, f, r) {
      let tmp = {...base};
      let tmp$1 = f();
      let a = r.a;
      return {
        ...tmp,
        ...tmp$1,
        a: a * a | 0
      };
    }

Review: Is a held call copied too? Only when statements that are not pure
    follow it, as before; `f()` above is held without a copy, since
    `let a = r.a` can't change what it returns.
Review: Which checked-in outputs change? None besides the new tests.
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
Why:
    `can_run_code` treated an index read `a[i]` as running no code when
    its operands ran none. `Dict.getUnsafe` and other `@get_index`
    externals compile to one on any JS object, where it can run a getter,
    so `[...base, d->Dict.getUnsafe("x")]` kept `Primitive_array.spread`,
    which reads `base` only after the getter. Every index read now counts
    as code, as a read `obj["x"]` already did, and such a literal keeps the
    spread where it stands.

JS modified (array spread with a later index read):
Example:
    let arrayIndexRead = (base: array<int>, d: dict<int>) =>
      [...base, d->Dict.getUnsafe("x")]
    let arrayArrayIndexRead = (base: array<int>, items) =>
      [...base, items->Array.getUnsafe(0)]
Before (js):
    function arrayIndexRead(base, d) {
      return Primitive_array.spread([
        base,
        [d["x"]]
      ]);
    }

    function arrayArrayIndexRead(base, items) {
      return Primitive_array.spread([
        base,
        [items[0]]
      ]);
    }
After (js):
    function arrayIndexRead(base, d) {
      return [
        ...base,
        d["x"]
      ];
    }

    function arrayArrayIndexRead(base, items) {
      return [
        ...base,
        items[0]
      ];
    }

Review: Why every index read, not only one with a string key? A
    `@get_index` external with an int key can still be called on any JS
    object, and the array literal it now gives is as readable as the
    `Primitive_array.spread` call it replaces.
Review: What about a dict spread? A dict literal keeps its spreads in
    place already, and the `Dict.getUnsafe` test there guards the held
    value of the previous commit.
Review: Which checked-in outputs change? `arrayPureIndex`, which moves to
    the new test as `arrayArrayIndexRead`. The changelog fragment now says
    that a spread read in place uses JS spread syntax, which iterates the
    array.
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
@illusionalsagacity

Copy link
Copy Markdown
Contributor Author

Thanks. This was fixed by f0b62fa, pushed after your review. The typeof and null-check folds in js_exp_make.ml now require an operand that runs no code, which also fixes the plain literal typeof [g()] that master has. Regression tests are in tests/tests/src/literal_fold_effect_test.res.

Investigated by Claude.

@cknitt

cknitt commented Nov 29, 2026

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 3ea462fbd3

ℹ️ 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".

@cknitt cknitt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good to me. I built it merged with current master (together with the other open #9398 fixes), regenerated all test outputs and ran the full test suite: no diffs, all tests pass.

This review was done by Claude.

@cknitt
cknitt merged commit 1e6aa8a into rescript-lang:master Nov 29, 2026
23 checks passed
@illusionalsagacity
illusionalsagacity deleted the fix-dict-array-spread-order branch November 29, 2026 23:09
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.

Optimizer miscompilations: 31 reproductions ranked by impact

2 participants