Semantic Diff

#9086 Check field mutability in record coercion

2 commits

cd641cbc06120a7d0a0a62776a3301e536cae415..pr-9086

5f2f636b2 · cknitt + Claude · Oct 27, 2026, 13:09 UTC

Check field mutability in record coercion

Why

:> between record types compared field names, optionality and runtime names, but not mutability. A record with an immutable field could be coerced to one where the field is mutable and written through it, although the compiler treats the field as immutable: reads of it were constant-folded to the stale value. A field mutable in both records was also coerced covariantly, so a wider value could be written into a narrower field.

modifiedDiagnostic coercion that makes a field writable

type ro = {x: float}type rw = {mutable x: float} let toRw = (r: ro) => (r :> rw)
js
Before
let r = { x: 0 };r.x = 1;console.log(0);   // r.x, folded to its initial value
diagnostic
After
Type ro is not a subtype of rw The record ro cannot be coerced to the record rw because:- The field x is mutable in record rw, but not in record ro. A coercion can't make a field writable.

modifiedDiagnostic mutable field of a wider type

type narrow = {mutable tag: [#A]}type wide = {mutable tag: [#A | #B]} let widen = (n: narrow) => (n :> wide)
diagnostic
Before
After
accepted Type narrow is not a subtype of wide The second polymorphic variant is closed and doesn't include the constructor: #B.

Review

  • Is coercing a mutable field to an immutable one still allowed? Yes. A read-only view is sound: the source is known to be mutable, so its reads are not folded.
ac95c4a54 · cknitt + Claude · Oct 27, 2026, 17:32 UTC

Test the record coercions that stay allowed

Codex review on #9086: the fixtures only covered rejected coercions. The new test runs a read-only view of a mutable field, a mutable field kept mutable with shared writes through both views, and an immutable target field of a wider type.