Repository navigation
Copy dict and array spreads before later elements that can change them - #9429
Conversation
Changelog🐛 Bug fix
Semantic Diff6 commits · Full page Copy dict and array spreads before later elements that can change them7049023 · illusionalsagacity · Nov 25, 2026, 19:42 UTC
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 }}
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 }]
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]
function call(base, f) {
return Primitive_array.spread([
- base,
+ [...base],
[f()]
]);
}
function pure(base, x) {
return Primitive_array.spread([
base,
[x + 1 | 0]
]);
}Review
Build an array spread with a later call as an array literalc4ec5c1 · illusionalsagacity · Nov 28, 2026, 17:54 UTC
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]
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 @val external arrayOf: array<int> => array<int> = "Array.of"
let variadicCall = (base: array<int>, f) => arrayOf([...base, f()])
function variadicCall(base, f) {
- return Array.of(...Primitive_array.spread([
- [...base],
- [f()]
- ]));
+ return Array.of(...base, f());
}Review
✨ Keep the calls in an array literal whose typeof or null check is foldedf0b62fa · illusionalsagacity · Nov 28, 2026, 19:44 UTC · new
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()]))
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
✨ Share the array spread part helpers in lam_compile51c77b0 · illusionalsagacity · Nov 28, 2026, 19:54 UTC · new The parts of an array spread were taken apart into elements in two places, and ✨ Copy a spread before a later value held in front of pure statements44208a3 · illusionalsagacity · Nov 28, 2026, 21:05 UTC · new
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}}
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
✨ Treat an index read as running code after an array spread3ea462f · illusionalsagacity · Nov 28, 2026, 21:06 UTC · new
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)]
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
|
Codecov Report❌ Patch coverage is
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
🚀 New features to boost your workflow:
|
rescript
@rescript/belt
@rescript/darwin-arm64
@rescript/linux-arm64
@rescript/linux-x64
@rescript/runtime
@rescript/win32-x64
commit: |
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
The fix is correct. I checked arrays with several spreads, the same base spread twice, nested spreads, dicts with several spreads followed by a One cost in common code: an array spread followed by a call now copies the base twice, once with let a = (xs, x) => [...xs, f(x)]return Primitive_array.spread([[...xs], [f(x)]]);Reading a JS object field triggers it too ( Could this case be a native array literal instead? return [...xs, f(x)];JS evaluates array elements, spreads included, left to right. So
This PR already emits 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>
bc27b18 to
c4ec5c1
Compare
|
Agreed, the second copy isn't needed. Thanks for checking where array literals are taken apart. I found the same two places: Fixed in c4ec5c1: when a later part of an array runs code in its value, the parts compile to a native array literal, so New tests in Investigated by Claude. |
|
@codex review |
There was a problem hiding this comment.
💡 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".
| (* JS evaluates the elements of an array literal, spreads included, | ||
| left to right *) | ||
| with_source_loc loc | ||
| (E.array |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
Thanks, the array literal looks good. I can confirm Codex's P1.
The same already happens on master for a plain literal: 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>
|
Thanks. This was fixed by f0b62fa, pushed after your review. The Investigated by Claude. |
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
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]copybasebeforevis evaluated. Whenvneeds statements (atry, or aswitchthat is not one expression), the copy was taken after them. An array is copied byPrimitive_array.spread, which runs after all elements, so there a plain call is enough.Before:
After:
With a call in an array:
Before:
After:
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, anawait, a read of a JS property, or an index read such asDict.getUnsafe, which can run a getter), the array compiles to a native array literal[...xs, f(x)]instead ofPrimitive_array.spread: JS evaluates its elements, spreads included, left to right, soxsis copied once, beforef(x)runs. Spreads where no later part runs code keepPrimitive_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@variadicarguments, which now givef(a, ...xs, b). Indexing into a literal, its length and dropping a write to it requireno_side_effect, which a spread fails.Folding
typeofand null checks of a literaltypeofof an array literal folded to"object"(and of a number or a.lengthto"number"), and a null check of an array, tuple or number tofalse, 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 callingf. These folds now requireno_side_effecton the operand; otherwise the check stays as written:Literals that run no code still fold (
typeof [x]is"object").Trade-offs
[...a, try {...} catch {...}, ...b, f()],ais copied into a temporary before the statements and spread again into the literal, so it is copied twice.Primitive_array.spreadreads by index. ReScript arrays are real arrays, so both read the same elements.Tests
dict_array_spread_order_test.reschecks 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 incan_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 laterDict.getUnsafeorArray.getUnsaferead check that the spread is read before that code runs; each fails without its fix. A@variadiccall 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.reschecks thattypeofandNullable.isNullableof a plain literal, a spread literal, a tuple and a.lengthof 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 thetrycase include the mutation ([1, 2, 100, 5]). I'll backport once this one is reviewed.The fix was written by Claude.