Skip to content

Copy a record spread's base before overrides that need statements - #9416

Merged
cknitt merged 3 commits into
rescript-lang:masterfrom
illusionalsagacity:fix-record-spread-order
Nov 28, 2026
Merged

cknitt merged 3 commits into
rescript-lang:masterfrom
illusionalsagacity:fix-record-spread-order

Conversation

@illusionalsagacity

@illusionalsagacity illusionalsagacity commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Part of #9398 (item 9).

Problem

A spread of a record with an optional field, or with 20 fields or more, is emitted as one object literal. When an override compiles to statements (a try, or a switch that isn't one expression), those statements were placed before the literal, so they ran before the base was evaluated and copied. If the override mutates the base, the copy sees the mutation.

@inline(never) let id = x => x
@inline(never) let trace = (_n: string, v) => v
type r = {a: int, b: int, c?: int}
let f = (base: r) => {
  ...trace("base", base),
  a: try { trace("a", id(5)) } catch { | _ => 0 },
  b: trace("b", 7),
}

Before:

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

After:

function f(base) {
  let newrecord = {...trace("base", base)};
  let tmp;
  try {
    tmp = trace("a", id(5));
  } catch (exn) {
    tmp = 0;
  }
  newrecord.a = tmp;
  newrecord.b = trace("b", 7);
  return newrecord;
}

Reviewing this turned up three more bugs with the same cause: the Lambda sets the overrides last field first. Fields assigned after the spread ended up before the overrides, so the last assignment lost and a value reading the copy named an undefined variable:

type r = {mutable a: int, mutable b: int, c?: int}
let readsCopy = (base: r) => {
  let x = {...base, a: 1}
  x.b = x.a + 1
  x
}
let lastWins = (base: r) => {
  let x = {...base, a: 1}
  x.a = 2
  x
}

Before:

function readsCopy(base) {
  return {
    ...base,
    b: newrecord.a + 1 | 0,
    a: 1
  };
}

function lastWins(base) {
  return {
    ...base,
    a: 2,
    a: 1
  };
}

After:

function readsCopy(base) {
  let newrecord = {...base};
  newrecord.a = 1;
  newrecord.b = newrecord.a + 1 | 0;
  return newrecord;
}

function lastWins(base) {
  let newrecord = {...base};
  newrecord.a = 1;
  newrecord.a = 2;
  return newrecord;
}

Fix

The fields are set in declaration order in the Lambda, followed by later assignments in source order. When an override needs statements, the base is copied first and the overrides are assigned to the copy. The literal stays when the overrides are plain expressions, or when their statements only define pure values. A spread whose later assignments read the copy or set a field twice is also compiled as a copy and assignments. The copy is left out when the result is discarded or an override always throws. An override of a field renamed with @as("__proto__") is set with Object.defineProperty, since assigning it would run the __proto__ setter the copy inherits instead of making an own property, as the literal's ["__proto__"]: v does. Each override is compiled once, so nested spreads compile in linear time.

Overrides run in the order the record type declares its fields, as the fields of a plain record literal already do, not in the order they are written. Whether it should be source order, as #9340 asks for labelled arguments, is a separate question.

Tests

record_spread_order_test.res covers an override that mutates the base, the order of overrides, assignments after the spread, inline and exception records, discarded results, and an override of a field named __proto__. A source-map test checks that the assignments are mapped. No other checked-in output changes.

Not fixed here

Smaller records without an optional field are copied field by field and have the same base-mutation bug (fix-record-copy-order), as do JSX props spreads (fix-jsx-props-spread-order).

12.x

12.x copies the base first, so it doesn't need this fix.

The fix was written by Claude. A second Claude agent reviewed the first version; this version addresses that review and has not been reviewed again.

@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Changelog

🐛 Bug fix

  • Fix evaluation order for a record spread {...base, field: value} compiled to a JavaScript object spread (a record type with an optional field, or with 20 fields or more): the base is copied before an override that needs statements (such as a try) is evaluated, so an override's mutation of the base no longer shows up in the copy; overrides run in the order the record type declares its fields; and fields assigned to the result afterwards are set after them, in source order, with values that can read the result.

Semantic Diff

3 commits · Full page

Copy a record spread's base before overrides that need statements

51c1f64 · illusionalsagacity · Nov 23, 2026, 20:27 UTC

Why

A record spread {...base, f: v} of a record with an optional field (or with 20 fields or more) is a JS object spread. It was emitted as one object literal even when an override compiles to statements (a try, or a switch that is not one expression). Those statements ran before base was evaluated and copied, so a mutation of the base inside the override showed up in the copy. The copy is now taken first and the overrides are assigned to it. The literal stays when the overrides are plain expressions, or when their statements only define pure values and nothing evaluated before them runs code. The Lambda for the overrides also set the last declared field first, and the literal was built from the reversed list. That order was visible when the copy was bound and then used, and it put fields assigned to the copy afterwards before the overrides: the last assignment of a field lost, and a value reading the copy named a variable that was never defined. The fields are now set in declaration order in the Lambda, followed by the later assignments in source order. A spread whose later assignments read the copy, or set a field twice, is compiled as a copy and assignments. The copy is left out when the result is discarded or an override always throws.

JS modified (record spread with an override that needs statements)

@inline(never) let id = x => x
@inline(never) let trace = (_n: string, v) => v
type r = {a: int, b: int, c?: int}
let f = (base: r) => {
  ...trace("base", base),
  a: try { trace("a", id(5)) } catch { | _ => 0 },
  b: trace("b", 7),
}

js

 function f(base) {
+  let newrecord = {...trace("base", base)};
   let tmp;
   try {
     tmp = trace("a", id(5));
   } catch (exn) {
     tmp = 0;
   }
-  return {
-    ...trace("base", base),
-    a: tmp,
-    b: trace("b", 7)
-  };
+  newrecord.a = tmp;
+  newrecord.b = trace("b", 7);
+  return newrecord;
 }

JS modified (field assigned after a record spread)

type r = {mutable a: int, mutable b: int, c?: int}
let readsCopy = (base: r) => {
  let x = {...base, a: 1}
  x.b = x.a + 1
  x
}
let lastWins = (base: r) => {
  let x = {...base, a: 1}
  x.a = 2
  x
}

js

 function readsCopy(base) {
-  return {
-    ...base,
-    b: newrecord.a + 1 | 0,
-    a: 1
-  };
+  let newrecord = {...base};
+  newrecord.a = 1;
+  newrecord.b = newrecord.a + 1 | 0;
+  return newrecord;
 }
 
 function lastWins(base) {
-  return {
-    ...base,
-    a: 2,
-    a: 1
-  };
+  let newrecord = {...base};
+  newrecord.a = 1;
+  newrecord.a = 2;
+  return newrecord;
 }

JS modified (record spread bound and then used)

@inline(never) let id = x => x
@inline(never) let trace = (_n: string, v) => v
type r = {mutable a: int, mutable b: int, c?: int}
let k = (base: r) => {
  let x = {...base, a: trace("a", 1), b: trace("b", 2)}
  ignore(id(x.a))
  x
}

js

 function k(base) {
   let newrecord = {...base};
-  newrecord.b = trace("b", 2);
   newrecord.a = trace("a", 1);
+  newrecord.b = trace("b", 2);
   id(newrecord.a);
   return newrecord;
 }

Review

  • Is each override compiled once? Yes, every form is built from the same compiled overrides. Whether a value reads the copy is decided on the Lambda, before anything is compiled.
  • Which checked-in outputs change? Only the new test's.
Define a __proto__ override on a record spread's copy as its own property

0be5421 · illusionalsagacity · Nov 26, 2026, 22:07 UTC

Why

When an override of a record spread needs statements, the base is copied and the overrides are assigned to the copy. For a field renamed with @as("__proto__") that the base does not have, the assignment runs the __proto__ setter the copy inherits from Object.prototype: an int is dropped and an object becomes the copy's prototype. The object literal used before defines the field as an own property (["__proto__"]: v). The copy now gets the field through Object.defineProperty, as the literal would. Other names are still assigned: Object.prototype has no other setter, so an assignment makes an own property.

JS modified (record spread overriding a __proto__ field with statements)

@inline(never) let id = x => x
type r = {a: int, @as("__proto__") p?: int}
let f = (base: r) => {...base, p: ?(try Some(id(5)) catch { | _ => None })}

js

 function f(base) {
   let newrecord = {...base};
   let tmp;
   try {
     tmp = id(5);
   } catch (exn) {
     tmp = undefined;
   }
-  newrecord.__proto__ = tmp;
+  Object.defineProperty(newrecord, "__proto__", {
+    value: tmp,
+    writable: true,
+    enumerable: true,
+    configurable: true
+  });
   return newrecord;
 }

Review

  • Does an assignment to the field after the spread change? Only one merged into the spread, which the literal also defined as an own property. An assignment elsewhere, x.p = v, is unchanged.
  • Which checked-in outputs change? Only record_spread_order_test's.
Define a __proto__ field set on a record spread's copy as its own property

a35c2d2 · illusionalsagacity · Nov 27, 2026, 21:29 UTC

Why

The copy and assignments of a record spread define a __proto__ field with Object.defineProperty, but only when the copy is returned right after its fields are set and no field is set twice. A field assigned twice (the override and a later x.p = v), a value that reads the copy, or code that uses the copy before it is returned left the spread to the generic code, which assigns newrecord.__proto__ = v: when the base has no own __proto__, the inherited setter drops an int, and the copy has no own property. These cases are now compiled as a copy and assignments too, with the code after the assignments compiled next.

JS modified (record spread whose __proto__ field is set again)

type r = {a: int, @as("__proto__") mutable p?: int}
let f = (base: r) => {
  let x = {...base, p: 5}
  x.p = Some(5)
  x
}

js

 function f(base) {
   let newrecord = {...base};
-  newrecord.__proto__ = 5;
-  newrecord.__proto__ = 5;
+  Object.defineProperty(newrecord, "__proto__", {
+    value: 5,
+    writable: true,
+    enumerable: true,
+    configurable: true
+  });
+  Object.defineProperty(newrecord, "__proto__", {
+    value: 5,
+    writable: true,
+    enumerable: true,
+    configurable: true
+  });
   return newrecord;
 }

JS modified (record spread used before it is returned)

type r = {a: int, @as("__proto__") mutable p?: int}
let g = (base: r) => {
  let x = {...base, p: 5}
  Console.log(x.a)
  x
}

js

 function g(base) {
   let newrecord = {...base};
-  newrecord.__proto__ = 5;
+  Object.defineProperty(newrecord, "__proto__", {
+    value: 5,
+    writable: true,
+    enumerable: true,
+    configurable: true
+  });
   console.log(newrecord.a);
   return newrecord;
 }

Review

  • Does the output change for other field names? No: they are still assigned with Js_of_lam_block.set_field, as the generic code does. Only record_spread_order_test's output changes.
  • Is the copy left out when a value reads it? No: the copy is dropped for a discarded result or a throwing override only when no value reads it and it is returned right after its fields are set.

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.22222% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.34%. Comparing base (3b2d03e) to head (a35c2d2).

Files with missing lines Patch % Lines
compiler/backend/lam_compile.ml 96.92% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9416      +/-   ##
==========================================
+ Coverage   82.32%   82.34%   +0.02%     
==========================================
  Files         462      462              
  Lines       65750    65802      +52     
==========================================
+ Hits        54127    54183      +56     
+ Misses      11623    11619       -4     
Files with missing lines Coverage Δ
compiler/backend/js_exp_make.ml 67.71% <100.00%> (+0.18%) ⬆️
compiler/typing/translcore.ml 88.28% <100.00%> (ø)
compiler/backend/lam_compile.ml 91.00% <96.92%> (+0.28%) ⬆️

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

@rescript/belt

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

@rescript/darwin-arm64

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

@rescript/linux-arm64

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

@rescript/linux-x64

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

@rescript/runtime

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

@rescript/win32-x64

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

commit: a35c2d2

@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:54:36.872955Z 8ef4227 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: 607c25ec3a

ℹ️ 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 +2083 to +2084
(Js_of_lam_block.set_field fld_info copy
(Int32.of_int i) value));

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 Preserve own-property semantics for __proto__ overrides

When an optional field renamed with @as("__proto__") is absent from base and its override needs statements, this path emits newrecord.__proto__ = value. Because the copy has no own property by that name, the assignment invokes the inherited Object.prototype.__proto__ setter: integer values are silently discarded, and object values change the prototype instead of populating the field. The previous literal path correctly emitted a computed ["__proto__"] property through Js_dump_property.property_key, so this regresses valid record spreads. Define an own property for this field instead of using an ordinary assignment.

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. With type r = {a: int, @as("__proto__") p?: int} and {...base, p: ?(try Some(id(5)) catch { | _ => None })}, the branch emitted newrecord.__proto__ = tmp. Run on {a: 1}, the result had no own __proto__ (Object.hasOwn false) and the 5 was dropped; with an object value the copy's prototype changed instead. master builds the literal {...base, ["__proto__"]: tmp} here, so this PR introduced it.

Fixed in 1a81373: when the spread is compiled as a copy and assignments, a field whose runtime name is __proto__ is set with Object.defineProperty(newrecord, "__proto__", {value, writable: true, enumerable: true, configurable: true}), which defines an own data property like the literal does. Other names are still assigned, since Object.prototype has no other setter. record_spread_order_test.res now checks an int and an object override (own property, value kept, prototype unchanged) and a base that already has the field.

An assignment x.p = v outside a spread still compiles to x.__proto__ = v, as on master; that's not touched here.

Investigated by Claude.

@cknitt

cknitt commented Nov 27, 2026

Copy link
Copy Markdown
Member

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1a81373537

ℹ️ 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
collect_dup_overrides copy_id rest ((fld_info, value) :: acc)
| Lvar id' when Ident.same id' copy_id -> Some acc
when Ident.same id' copy_id
&& (not (List.exists (fun (j, _, _, _) -> i = j) acc))

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 Preserve own-property initialization on duplicate-field fallback

For a record with @as("__proto__") mutable p?: int, let x = {...base, p: 5}; x.p = Some(5); x hits the new duplicate-index guard, bypassing the define_own_property fix for statement overrides. The generic fallback still lowers both writes via Js_of_lam_block.set_field to newrecord.__proto__ = 5; when base omits p, the inherited setter discards these integers, leaving the returned record without an own __proto__ property. The parent emitted computed literal properties and correctly preserved the value 5 for this unchanged-value update. Preserve own-property initialization when rejecting this fast path as well.

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. With type r = {a: int, @as("__proto__") mutable p?: int}, let x = {...base, p: 5}; x.p = Some(5); x compiled to newrecord.__proto__ = 5 twice. On f({a: 1}), node printed Object.hasOwn(o, "__proto__") as false, and o.p came back as the prototype instead of 5. It was the same for let x = {...base, p: 5}; Console.log(x.a); x. There the optimizer inlines x, so the copy is used before it is returned, and the spread went to the generic code as well.

Fixed in 8ef4227 ("Define a proto field set on a record spread's copy as its own property"). collect_dup_overrides now always collects the field sets that come right after the copy. A field set twice, a value that reads the copy, or code after the sets that uses the copy no longer falls back to the generic code. These cases now use the copy-and-assign form, which writes __proto__ with Object.defineProperty, and any code after the sets is compiled after it. Both cases now print true 5. Other field names still compile the way they did before, and only record_spread_order_test's output changed.

Regression test: "a proto field set on the copy is an own property" in tests/tests/src/record_spread_order_test.res (protoAssignedAfter, protoUsedAfter).

Investigated by Claude.

@cknitt

cknitt commented Nov 28, 2026

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 8ef4227457

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

Why:
    A record spread `{...base, f: v}` of a record with an optional field
    (or with 20 fields or more) is a JS object spread. It was emitted as one
    object literal even when an override compiles to statements (a `try`,
    or a `switch` that is not one expression). Those statements ran before
    `base` was evaluated and copied, so a mutation of the base inside the
    override showed up in the copy. The copy is now taken first and the
    overrides are assigned to it. The literal stays when the overrides are
    plain expressions, or when their statements only define pure values
    and nothing evaluated before them runs code.
    The Lambda for the overrides also set the last declared field first, and
    the literal was built from the reversed list. That order was visible
    when the copy was bound and then used, and it put fields assigned to
    the copy afterwards before the overrides: the last assignment of a
    field lost, and a value reading the copy named a variable that was
    never defined. The fields are now set in declaration order in the
    Lambda, followed by the later assignments in source order. A spread
    whose later assignments read the copy, or set a field twice, is
    compiled as a copy and assignments. The copy is left out when the
    result is discarded or an override always throws.

JS modified (record spread with an override that needs statements):
Example:
    @inline(never) let id = x => x
    @inline(never) let trace = (_n: string, v) => v
    type r = {a: int, b: int, c?: int}
    let f = (base: r) => {
      ...trace("base", base),
      a: try { trace("a", id(5)) } catch { | _ => 0 },
      b: trace("b", 7),
    }
Before (js):
    function f(base) {
      let tmp;
      try {
        tmp = trace("a", id(5));
      } catch (exn) {
        tmp = 0;
      }
      return {
        ...trace("base", base),
        a: tmp,
        b: trace("b", 7)
      };
    }
After (js):
    function f(base) {
      let newrecord = {...trace("base", base)};
      let tmp;
      try {
        tmp = trace("a", id(5));
      } catch (exn) {
        tmp = 0;
      }
      newrecord.a = tmp;
      newrecord.b = trace("b", 7);
      return newrecord;
    }

JS modified (field assigned after a record spread):
Example:
    type r = {mutable a: int, mutable b: int, c?: int}
    let readsCopy = (base: r) => {
      let x = {...base, a: 1}
      x.b = x.a + 1
      x
    }
    let lastWins = (base: r) => {
      let x = {...base, a: 1}
      x.a = 2
      x
    }
Before (js):
    function readsCopy(base) {
      return {
        ...base,
        b: newrecord.a + 1 | 0,
        a: 1
      };
    }

    function lastWins(base) {
      return {
        ...base,
        a: 2,
        a: 1
      };
    }
After (js):
    function readsCopy(base) {
      let newrecord = {...base};
      newrecord.a = 1;
      newrecord.b = newrecord.a + 1 | 0;
      return newrecord;
    }

    function lastWins(base) {
      let newrecord = {...base};
      newrecord.a = 1;
      newrecord.a = 2;
      return newrecord;
    }

JS modified (record spread bound and then used):
Example:
    @inline(never) let id = x => x
    @inline(never) let trace = (_n: string, v) => v
    type r = {mutable a: int, mutable b: int, c?: int}
    let k = (base: r) => {
      let x = {...base, a: trace("a", 1), b: trace("b", 2)}
      ignore(id(x.a))
      x
    }
Before (js):
    function k(base) {
      let newrecord = {...base};
      newrecord.b = trace("b", 2);
      newrecord.a = trace("a", 1);
      id(newrecord.a);
      return newrecord;
    }
After (js):
    function k(base) {
      let newrecord = {...base};
      newrecord.a = trace("a", 1);
      newrecord.b = trace("b", 2);
      id(newrecord.a);
      return newrecord;
    }

Review: Is each override compiled once? Yes, every form is built from the
    same compiled overrides. Whether a value reads the copy is decided on
    the Lambda, before anything is compiled.
Review: Which checked-in outputs change? Only the new test's.

Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
…erty

Why:
    When an override of a record spread needs statements, the base is
    copied and the overrides are assigned to the copy. For a field renamed
    with @as("__proto__") that the base does not have, the assignment runs
    the __proto__ setter the copy inherits from Object.prototype: an int is
    dropped and an object becomes the copy's prototype. The object literal
    used before defines the field as an own property (["__proto__"]: v).
    The copy now gets the field through Object.defineProperty, as the
    literal would. Other names are still assigned: Object.prototype has no
    other setter, so an assignment makes an own property.

JS modified (record spread overriding a __proto__ field with statements):
Example:
    @inline(never) let id = x => x
    type r = {a: int, @as("__proto__") p?: int}
    let f = (base: r) => {...base, p: ?(try Some(id(5)) catch { | _ => None })}
Before (js):
    function f(base) {
      let newrecord = {...base};
      let tmp;
      try {
        tmp = id(5);
      } catch (exn) {
        tmp = undefined;
      }
      newrecord.__proto__ = tmp;
      return newrecord;
    }
After (js):
    function f(base) {
      let newrecord = {...base};
      let tmp;
      try {
        tmp = id(5);
      } catch (exn) {
        tmp = undefined;
      }
      Object.defineProperty(newrecord, "__proto__", {
        value: tmp,
        writable: true,
        enumerable: true,
        configurable: true
      });
      return newrecord;
    }

Review: Does an assignment to the field after the spread change? Only
    one merged into the spread, which the literal also defined as an own
    property. An assignment elsewhere, x.p = v, is unchanged.
Review: Which checked-in outputs change? Only record_spread_order_test's.
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
…perty

Why:
    The copy and assignments of a record spread define a __proto__ field
    with Object.defineProperty, but only when the copy is returned right
    after its fields are set and no field is set twice. A field assigned
    twice (the override and a later x.p = v), a value that reads the copy,
    or code that uses the copy before it is returned left the spread to
    the generic code, which assigns newrecord.__proto__ = v: when the base
    has no own __proto__, the inherited setter drops an int, and the copy
    has no own property. These cases are now compiled as a copy and
    assignments too, with the code after the assignments compiled next.

JS modified (record spread whose __proto__ field is set again):
Example:
    type r = {a: int, @as("__proto__") mutable p?: int}
    let f = (base: r) => {
      let x = {...base, p: 5}
      x.p = Some(5)
      x
    }
Before (js):
    function f(base) {
      let newrecord = {...base};
      newrecord.__proto__ = 5;
      newrecord.__proto__ = 5;
      return newrecord;
    }
After (js):
    function f(base) {
      let newrecord = {...base};
      Object.defineProperty(newrecord, "__proto__", {
        value: 5,
        writable: true,
        enumerable: true,
        configurable: true
      });
      Object.defineProperty(newrecord, "__proto__", {
        value: 5,
        writable: true,
        enumerable: true,
        configurable: true
      });
      return newrecord;
    }

JS modified (record spread used before it is returned):
Example:
    type r = {a: int, @as("__proto__") mutable p?: int}
    let g = (base: r) => {
      let x = {...base, p: 5}
      Console.log(x.a)
      x
    }
Before (js):
    function g(base) {
      let newrecord = {...base};
      newrecord.__proto__ = 5;
      console.log(newrecord.a);
      return newrecord;
    }
After (js):
    function g(base) {
      let newrecord = {...base};
      Object.defineProperty(newrecord, "__proto__", {
        value: 5,
        writable: true,
        enumerable: true,
        configurable: true
      });
      console.log(newrecord.a);
      return newrecord;
    }

Review: Does the output change for other field names? No: they are
    still assigned with Js_of_lam_block.set_field, as the generic code
    does. Only record_spread_order_test's output changes.
Review: Is the copy left out when a value reads it? No: the copy is
    dropped for a discarded result or a throwing override only when no
    value reads it and it is returned right after its fields are set.
Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
@cknitt
cknitt marked this pull request as ready for review November 28, 2026 07:29
@cknitt
cknitt force-pushed the fix-record-spread-order branch from 8ef4227 to a35c2d2 Compare November 28, 2026 07:29

@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 checked both __proto__ commits (Object.defineProperty gives the same data property a literal key does, ordinary spreads are unchanged), built it merged with current master and regenerated all test outputs: no diffs, all tests pass. I rebased it onto master after #9417 was merged. A related gap outside spreads is filed as #9457.

This review was done by Claude.

@cknitt
cknitt merged commit 83cf1de into rescript-lang:master Nov 28, 2026
23 checks passed
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