Skip to content

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

Open
illusionalsagacity wants to merge 1 commit into
rescript-lang:masterfrom
illusionalsagacity:fix-dict-array-spread-order
Open

illusionalsagacity wants to merge 1 commit 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). 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 Primitive_array.spread([
    [...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 a later part needs statements or, in an array, can run code. Otherwise it stays bare. List spreads are unaffected, since lists are immutable.

Trade-offs

  • [...xs, f(x)] is common and now copies xs twice. Emitting native [...xs, f(x)] would avoid that, but passes that look into array literals (indexing, @variadic) would need auditing first. I'd like your opinion on this one.
  • The copy uses JS iteration, so a non-iterable array-like typed as array now throws where a copy is made.

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. One existing output changes, spread_literal_test.mjs.

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.

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>
@github-actions

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, so their mutations of the base no longer show up in the result.

Semantic Diff

1 commit · Full page

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

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

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.33333% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.25%. Comparing base (aacaf72) to head (bc27b18).
⚠️ Report is 4 commits behind head on master.

Files with missing lines Patch % Lines
compiler/backend/lam_compile.ml 83.33% 7 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9429      +/-   ##
==========================================
+ Coverage   82.21%   82.25%   +0.03%     
==========================================
  Files         461      462       +1     
  Lines       65573    65620      +47     
==========================================
+ Hits        53914    53973      +59     
+ Misses      11659    11647      -12     
Files with missing lines Coverage Δ
compiler/backend/lam_compile.ml 91.61% <83.33%> (+1.04%) ⬆️

... and 9 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: bc27b18

@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-26T20:25:32.326710Z bc27b18 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.

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