Skip to content

Empty record literal {} with a mutable optional field is generalized (unsound) #9150

Closed

Description

@cknitt

An empty record literal {} of a record type whose fields are all optional generalizes the record's type variables, even when a field is mutable. One binding can then be written at one type and read at another:

type cell<'a> = {tag?: int, mutable value?: 'a}

let cell: cell<_> = {}
cell.value = Some(1)
let s: option<string> = cell.value

This compiles on master (b3f2c80) and generates:

let cell = {};
cell.value = 1;
let s = cell.value;

so s, typed option<string>, holds the number 1.

The same binding with any field written is correctly rejected (This has type: option<int>, but it's expected to have type: option<string>):

type cell<'a> = {tag?: int, mutable value?: 'a}

let cell: cell<_> = {tag: 0}
cell.value = Some(1)
let s: option<string> = cell.value // error, as expected

Cause

The value restriction (Typecore.is_nonexpansive) treats a record literal as non-expansive when none of its fields is mutable. For {}, the type checker builds a Texp_record with an empty fields array (the [], Some representation when lid_sexp_list = [] case in type_expect_), so there is no field, and no label, to check, and the literal counts as non-expansive. A mutable record allocation must be expansive whether or not the literal writes its mutable fields.

Found while fixing the same problem for literals that leave out mutable optional fields in #9149, which now checks all labels of the record (lbl_all) when there is no spread. {} carries no label to reach lbl_all through, so it needs its own fix.

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