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
let r = { x: 0 };r.x = 1;console.log(0); // r.x, folded to its initial value
diagnostic
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.