Skip to content

Record spread over an array-shaped record produces an object #9196

Closed

Description

@cknitt

A record whose fields have the runtime names "0", "1", … is represented as a JavaScript array (documented under @as). A record spread over such a record can produce an object instead of an array.

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

upd([1, 3]) returns {0: 1, 1: 2} instead of [1, 2], so Array.isArray, .length and iteration break on the result.

The same happens without optional fields once the record has 20 or more fields (type t = {@as("0") f0: int, …, @as("19") f19: int}). With fewer than 20 fields and no optional field the spread copies the fields one by one and the result is an array, as expected.

Cause: transl_record (compiler/ml/translcore.ml) chooses between copying the fields one by one and a shallow copy of the spread with record_copies_fields, which does not consider the array layout. Only js_dump checks Lambda.record_fields_are_array, when it prints a record literal, so the shallow copy is emitted as object spread.

Expected: an array, e.g. by copying the fields one by one for array-shaped records regardless of size and optional fields, or r.slice() followed by the writes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions