Skip to content

Represent records with the runtime names "0", "1", ... as Record_array - #9224

Merged
cknitt merged 3 commits into
masterfrom
record-array-representation
Nov 4, 2026
Merged

cknitt merged 3 commits into
masterfrom
record-array-representation

Conversation

@cknitt

@cknitt cknitt commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Fixes #9196.

A record whose fields have the runtime names "0", "1", … in declaration order is a JavaScript array. Until now only js_dump knew that, by checking the field names whenever it printed a record literal. Every other path treated such a record as an object:

  • {...r, b: 2} became an object spread when the record has an optional field or 20+ fields.
  • {} printed {}.
  • A record rest pattern, or a coercion, could put an object where the type promises an array.

The type declaration now decides once. typedecl gives such a record the new representation Record_array, and every phase that builds or reads records matches on it:

  • Field reads and writes, and pattern matching: the same as a regular record (r[1], r[0] = x).
  • Literals: Blk_record carries array, which js_dump and the constant classification read. Lambda.record_fields_are_array and runtime_names_are_array are gone.
  • Spreads: always copy the fields one by one, never an object spread. {} is [].
  • JSX props: an array props record still compiles as an ordinary call. That is now a match on the representation instead of a name check.
  • Record rest: a rest type that is an array record is an error.
  • Coercion: records coerce only to records of the same representation, so a value of an object record type is never an array. Coercing between an array record and an object record is an error in either direction, with a dedicated message.
  • Untagged variants: an array record payload is classified as an array. It conflicts with an array or tuple case and is told apart from an object record case. Because coercion is exact, a coerced array can't reach the object case.

These errors are a small breaking change, recorded in a breaking fragment:

  • a rest type that is an array record
  • coercion between an array record and an object record (master allowed both directions)
  • an array record next to an array or tuple case in an untagged variant

Each case produced an object where the type promised an array, or matched the wrong case.

Representation changes only affect array-shaped records. On other code the output is the same as master, including for records with numeric keys out of order, such as {@as("1") p, @as("0") q}.

New tests:

  • tests/tests/src/array_record_test.res covers:
    • spreads with an optional field, with 20 fields, and with mutable fields
    • the empty literal
    • a type spread extending an array record
    • out-of-order names (object)
    • pattern matching
    • rest into an object record
  • super_errors fixtures record_rest_array_record, record_coercion_into_array_record, record_coercion_array_to_object and untagged_array_record_and_array.
  • A dispatch test for an untagged variant with an array record, an object record and a string case. It goes through Array.map, so the match runs instead of being constant-folded.
  • The unit test of the old name check now tests Record_runtime.is_array on label declarations, including out-of-order and unnamed fields.

Not included: gentype output for these records is unchanged. Emitting a TypeScript tuple type for them could be a follow-up.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Kbf3gLWSz9kGHhX9sue9WB

Why:
    Whether a record is a JavaScript array was rediscovered from its field
    names only when js_dump printed a record literal. Every other path
    treated it as an object: a spread over a record with an optional field
    or 20 fields became an object spread, and `{}` printed `{}` (#9196).

The type declaration now decides once: a record whose fields have the
runtime names "0", "1", ... in declaration order gets the representation
Record_array, and its blocks carry `array` to js_dump. A spread over such
a record copies its fields one by one. Record rest patterns and coercions
whose target is an array record are rejected, as an object spread or an
object can't produce an array.

JS modified (record spread):
Example:
    type t = {@as("0") a?: int, @as("1") b: int}
    let upd = (r: t) => {...r, b: 2}
    type e = {@as("0") x?: int}
    let empty: e = {}
Before (js):
    function upd(r) {
      return {
        ...r,
        "1": 2
      };
    }
    let empty = {};
After (js):
    function upd(r) {
      return [
        r[0],
        2
      ];
    }
    let empty = [];

Diagnostic added (record rest into an array record):
Example:
    type source = {@as("0") s0: int, @as("1") s1: int, @as("2") s2: int}
    type head = {@as("0") s0: int, @as("1") s1: int}
    let split = (r: source) => {
      let {s2, ...head as rest} = r
      (s2, rest)
    }
Before (js):
    let {"2": __rest_field0, ...rest} = r;
After (diagnostic):
    The rest of a record pattern cannot have a record type represented as an array (fields with the runtime names "0", "1", ...).

Diagnostic added (coercion into an array record):
Example:
    type obj = {@as("0") a: int, @as("1") b: int, x: int}
    type arr = {@as("0") a: int, @as("1") b: int}
    let toArr = (x: obj) => (x :> arr)
Before (js):
    function toArr(x) {
      return x;
    }
After (diagnostic):
    Type obj is not a subtype of arr

    The record arr is represented as a JavaScript array (its fields have the runtime names "0", "1", ...), but obj is represented as an object, so it cannot be coerced to it.

Review: Why not keep checking the names in js_dump? Only the literal
printer looked at them. A representation is matched exhaustively by every
phase that builds or reads a record, so each of them has to say what an
array record means, and no path can miss it again.
Review: Is coercing an array record to an object record still allowed?
Yes: an array has its elements as the properties "0", "1", ..., so
`{"0", "1", "2"} :> {"1"}` stays valid. Only the other direction is
rejected.
Breaking: A record rest pattern whose rest type is an array record, and a
coercion from an object record to an array record, are now errors. Both
produced an object where the type promised an array.

Fixes: #9196
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Kbf3gLWSz9kGHhX9sue9WB
Signed-off-by: Christoph Knittel <ck@cca.io>
@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Changelog

💥 Breaking Change

  • A record rest pattern whose rest type is a record with the runtime names "0", "1", …, a coercion between such a record and a record represented as an object (in either direction), and an untagged variant with such a record and an array or tuple case are now errors, as they produced an object where the type promises a JavaScript array, or matched the wrong case.

🐛 Bug fix

  • Keep records whose fields have the runtime names "0", "1", … JavaScript arrays when they are spread or written as {}, and match them as arrays when they are untagged variant payloads.

Semantic Diff

3 commits · Full page

Represent records with the runtime names "0", "1", ... as Record_array

6d7560e · cknitt + Claude · Nov 04, 2026, 19:21 UTC

Why

Whether a record is a JavaScript array was rediscovered from its field names only when js_dump printed a record literal. Every other path treated it as an object: a spread over a record with an optional field or 20 fields became an object spread, and {} printed {} (#9196).

The type declaration now decides once: a record whose fields have the runtime names "0", "1", ... in declaration order gets the representation Record_array, and its blocks carry array to js_dump. A spread over such a record copies its fields one by one. Record rest patterns and coercions whose target is an array record are rejected, as an object spread or an object can't produce an array.

JS modified (record spread)

type t = {@as("0") a?: int, @as("1") b: int}
let upd = (r: t) => {...r, b: 2}
type e = {@as("0") x?: int}
let empty: e = {}

js

 function upd(r) {
-  return {
-    ...r,
-    "1": 2
-  };
+  return [
+    r[0],
+    2
+  ];
 }
-let empty = {};
+let empty = [];

Diagnostic added (record rest into an array record)

type source = {@as("0") s0: int, @as("1") s1: int, @as("2") s2: int}
type head = {@as("0") s0: int, @as("1") s1: int}
let split = (r: source) => {
  let {s2, ...head as rest} = r
  (s2, rest)
}

js · Before

let {"2": __rest_field0, ...rest} = r;

diagnostic · After

The rest of a record pattern cannot have a record type represented as an array (fields with the runtime names "0", "1", ...).

Diagnostic added (coercion into an array record)

type obj = {@as("0") a: int, @as("1") b: int, x: int}
type arr = {@as("0") a: int, @as("1") b: int}
let toArr = (x: obj) => (x :> arr)

js · Before

function toArr(x) {
  return x;
}

diagnostic · After

Type obj is not a subtype of arr

The record arr is represented as a JavaScript array (its fields have the runtime names "0", "1", ...), but obj is represented as an object, so it cannot be coerced to it.

⚠️ Breaking: A record rest pattern whose rest type is an array record, and a coercion from an object record to an array record, are now errors. Both produced an object where the type promised an array.

Review

  • Why not keep checking the names in js_dump? Only the literal printer looked at them. A representation is matched exhaustively by every phase that builds or reads a record, so each of them has to say what an array record means, and no path can miss it again.
  • Is coercing an array record to an object record still allowed? Yes: an array has its elements as the properties "0", "1", ..., so {"0", "1", "2"} :> {"1"} stays valid. Only the other direction is rejected.
Classify a Record_array payload of an untagged variant as an array

ee87f9d · cknitt + Claude · Nov 04, 2026, 19:54 UTC

Codex review: an untagged variant payload that is an array record was classified as an object, so R({}), now [], matched an array case. The same already happened on master for R({x: 1}), which is [1].

Diagnostic modified (untagged variant with an array record and an array)

type pair = {@as("0") x?: int, @as("1") y?: int}
@unboxed type v = Pair(pair) | List(array<int>)
let classify = (v: v) =>
  switch v {
  | Pair(_) => "pair"
  | List(_) => "list"
  }

js · Before

function classify(v) {
  if (Array.isArray(v)) {
    return "list";
  } else {
    return "pair";
  }
}

diagnostic · After

This untagged variant definition is invalid: At most one case can be an array, a tuple or a record represented as an array.

⚠️ Breaking: An untagged variant with an array record case and an array or tuple case is now an error; its match picked the array case for the record. A variant with an array record and an object record case is now accepted, as the two are told apart.

✨ Reject coercing an array record to a record represented as an object

b41952a · cknitt + Claude · Nov 04, 2026, 20:31 UTC · new

Review (cristianoc): an array record coerced to an object record stays a JavaScript array, so in @unboxed type v = Pair(pair) | Tail(tail) the value Tail((r :> tail)) passed the array test and matched Pair. A record's representation is now exact: records coerce only to records of the same representation, and the error names the mismatch either way. The untagged dispatch test now runs through Array.map, so the match is not folded at compile time.

Diagnostic modified (coercion between an array record and an object record)

type pair = {@as("0") a: int, @as("1") b: int}
type tail = {@as("1") b: int}
let toTail = (r: pair) => (r :> tail)

js · Before

function toTail(r) {
  return r;
}

diagnostic · After

Type pair is not a subtype of tail

The record pair is represented as a JavaScript array (its fields have the runtime names "0", "1", ...) and tail as an object, so neither can be coerced to the other.

⚠️ Breaking: Coercing a record represented as an array to one represented as an object, which master accepted, is now an error.

@codecov

codecov Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 79.24528% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.74%. Comparing base (0f92894) to head (b41952a).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
compiler/ml/printlambda.ml 0.00% 3 Missing ⚠️
compiler/ml/ctype.ml 50.00% 2 Missing ⚠️
compiler/gentype/translate_type_declarations.ml 0.00% 1 Missing ⚠️
compiler/ml/printtyped.ml 0.00% 1 Missing ⚠️
compiler/ml/rec_check.ml 0.00% 1 Missing ⚠️
compiler/ml/translcore.ml 93.33% 1 Missing ⚠️
compiler/ml/typecore_record_rest.ml 66.66% 1 Missing ⚠️
compiler/ml/types.ml 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9224      +/-   ##
==========================================
- Coverage   81.76%   81.74%   -0.03%     
==========================================
  Files         457      457              
  Lines       65351    65560     +209     
==========================================
+ Hits        53434    53591     +157     
- Misses      11917    11969      +52     
Files with missing lines Coverage Δ
compiler/core/js_dump.ml 93.81% <100.00%> (ø)
compiler/ml/ast_untagged_variants.ml 84.26% <100.00%> (ø)
compiler/ml/lambda.ml 68.08% <100.00%> (-3.23%) ⬇️
compiler/ml/matching.ml 77.96% <100.00%> (ø)
compiler/ml/printtyp.ml 72.85% <100.00%> (+0.08%) ⬆️
compiler/ml/record_runtime.ml 95.45% <100.00%> (+1.01%) ⬆️
compiler/ml/typedecl.ml 83.53% <100.00%> (-0.02%) ⬇️
compiler/ml/variant_layout.ml 94.64% <100.00%> (+0.04%) ⬆️
tests/ounit_tests/ounit_lambda_constant_tests.ml 95.18% <100.00%> (+0.08%) ⬆️
tests/ounit_tests/ounit_sroa_tests.ml 92.66% <ø> (ø)
... and 8 more

... and 14 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 4, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

rescript

npm i https://pkg.pr.new/rescript@9224

@rescript/belt

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

@rescript/darwin-arm64

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

@rescript/linux-arm64

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

@rescript/linux-x64

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

@rescript/runtime

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

@rescript/win32-x64

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

commit: b41952a

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

@cknitt

cknitt commented Nov 4, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-05T05:58:18.684517Z 3c88840 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: 6d7560ed86

ℹ️ 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/core/js_dump.ml Resolved
Codex review: an untagged variant payload that is an array record was
classified as an object, so `R({})`, now `[]`, matched an array case. The
same already happened on master for `R({x: 1})`, which is `[1]`.

Diagnostic modified (untagged variant with an array record and an array):
Example:
    type pair = {@as("0") x?: int, @as("1") y?: int}
    @unboxed type v = Pair(pair) | List(array<int>)
    let classify = (v: v) =>
      switch v {
      | Pair(_) => "pair"
      | List(_) => "list"
      }
Before (js):
    function classify(v) {
      if (Array.isArray(v)) {
        return "list";
      } else {
        return "pair";
      }
    }
After (diagnostic):
    This untagged variant definition is invalid: At most one case can be an array, a tuple or a record represented as an array.

Breaking: An untagged variant with an array record case and an array or
tuple case is now an error; its match picked the array case for the
record. A variant with an array record and an object record case is now
accepted, as the two are told apart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Kbf3gLWSz9kGHhX9sue9WB
Signed-off-by: Christoph Knittel <ck@cca.io>
@cknitt

cknitt commented Nov 4, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: ee87f9dae8

ℹ️ 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 requested a review from cristianoc November 4, 2026 20:03
@cknitt
cknitt marked this pull request as ready for review November 4, 2026 20:03

@cristianoc cristianoc left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Please address the interaction between array-to-object record coercion and untagged variant dispatch before merging.

Ctype.subtype_rec explicitly allows Record_array -> Record_regular, preserving the original JavaScript array. Meanwhile, Variant_layout.payload_kind now accepts an array record and an ordinary record as distinguishable untagged cases. A coerced array can therefore enter the ordinary-record case while still satisfying the array discriminant:

type pair = {@as("0") a: int, @as("1") b: int}
type tail = {@as("1") b: int}
@unboxed type v = Pair(pair) | Tail(tail)

let classify = (v: v) =>
  switch v {
  | Pair(_) => "pair"
  | Tail(_) => "tail"
  }

let fromPair = (r: pair) => classify(Tail((r :> tail)))

The expected result is "tail", but the source-level lowering indicates runtime dispatch will select Pair: the coercion retains the array, the untagged constructor adds no wrapper, and Array.isArray succeeds. Before this PR, this particular two-record variant was rejected as two object cases; it is newly accepted here.

Please reconcile the permitted coercion with the runtime discriminant guarantees and add a regression test through a nonconstant argument. The new dispatch assertions in array_record_test.mjs currently constant-fold, so a runtime-path test would also strengthen coverage.

Validation: this finding is traced through the compiler source at this commit, not reproduced by compiling the ReScript example. A small JavaScript check confirms the described runtime discrimination, but it is not a compiler test.

Review (cristianoc): an array record coerced to an object record stays a
JavaScript array, so in `@unboxed type v = Pair(pair) | Tail(tail)` the
value `Tail((r :> tail))` passed the array test and matched `Pair`. A
record's representation is now exact: records coerce only to records of
the same representation, and the error names the mismatch either way.
The untagged dispatch test now runs through `Array.map`, so the match is
not folded at compile time.

Diagnostic modified (coercion between an array record and an object record):
Example:
    type pair = {@as("0") a: int, @as("1") b: int}
    type tail = {@as("1") b: int}
    let toTail = (r: pair) => (r :> tail)
Before (js):
    function toTail(r) {
      return r;
    }
After (diagnostic):
    Type pair is not a subtype of tail

    The record pair is represented as a JavaScript array (its fields have the runtime names "0", "1", ...) and tail as an object, so neither can be coerced to the other.

Breaking: Coercing a record represented as an array to one represented as
an object, which master accepted, is now an error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Kbf3gLWSz9kGHhX9sue9WB
Signed-off-by: Christoph Knittel <ck@cca.io>
@cknitt

cknitt commented Nov 4, 2026

Copy link
Copy Markdown
Member Author

@cristianoc Thanks, addressed in b41952a. I made the representation exact instead of weakening the dispatch:

  • Coercion: records now coerce only to records of the same representation, so a value of an object record type can no longer be an array.
    • Your example now fails at (r :> tail) with: "The record pair is represented as a JavaScript array (its fields have the runtime names "0", "1", ...) and tail as an object, so neither can be coerced to the other."
    • The same message covers the other direction.
  • Breaking: master accepted array → object coercion, so this is listed in the breaking fragment.
  • Tests:
    • record_coercion_array_to_object is your example, as a super_errors fixture.
    • The untagged dispatch test now goes through Array.map(classify), so the generated test calls classify at runtime instead of comparing folded constants.

@cknitt
cknitt requested a review from cristianoc November 4, 2026 20:54
@cknitt
cknitt merged commit 3c88840 into master Nov 4, 2026
26 checks passed
@cknitt
cknitt deleted the record-array-representation branch November 4, 2026 21:06
@cknitt

cknitt commented Nov 5, 2026

Copy link
Copy Markdown
Member Author

@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: 3c88840030

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

| Tconstr (path, _, _) -> (
match Env.find_type path env with
| {type_kind = Type_record (_, Record_unboxed _)} -> None
| {type_kind = Type_record (_, Record_array)} -> Some (InstanceType 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.

P2 Badge Allocate recursive array-record placeholders as arrays

For recursive array records, this classification disagrees with the actual runtime value: with type node = {@as("0") next: node} and let rec cyclic = {next: cyclic}, Lam_compile.compile_recursive_binding uses Js_exp_make.dummy_obj, which still allocates {} for every Blk_record, ignoring the new array flag. Consequently, the newly accepted @unboxed type payload = Node(node) | Named({name: string}) dispatches Node(cyclic) to Named when matched at runtime, since Array.isArray(cyclic) is false. Update recursive placeholder allocation to honor the array representation as well.

AGENTS.md reference: AGENTS.md:L56-L56

Useful? React with 👍 / 👎.

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.

Record spread over an array-shaped record produces an object

2 participants