Breaking: Mut<T> is nominal and a value is lent with mut(x); tsc refuses covariant loans, new rules missing-mut and aliased-mut #116
Loading…
Reference in a new issue
No description provided.
Delete branch "nominal-mut"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Based on
return-types(#123), and contains the pieces below it: the diff shown is this piece alone. The open pieces above #118 form one chain, each branch containing the ones below it: #119, #120, #121, #123, then #116 and #122. Merge them in that order, and merge #122 together with this one: it fixes a false refusal in this PR'sMuttype (a value could not be lent where a union containing its type is asked) and addsmutEach, the way to lend a list's elements without an array copy.Adoption cost, corrected. An earlier version of this description gave 71 type errors left on an adopter's project after
safe-ts migrate mut. That copy could not resolve the project's workspace packages, so calls across them were not type-checked. With them resolved the number is 339, and 201 at 52 places once #122 is in; the table of what is left, and how many declarations each kind takes, is in #122 and indocs/guide/adoption.mdthere.This is a breaking change. Every call that passes a value to a
Mutparameter changes, and it should ship as its own release with the migration below.The problem
Mut<T>is SAFE-TS's&mut T, but std saidtype Mut<T> = T, so TypeScript saw nothing. All of these passedtscin strict mode andsafe-ts check, with no cast:And nothing at a call site showed which arguments would be changed.
What changes
Mut<T>is nominal, and a value is lent by writingmut(x), like Rust's&mut x.mutreturns its argument, and the build transform erases the call.tscitself now refuses the first two programs above. The mark onMut<T>compares the two types property by property:Dog[]is not lent asMut<Animal[]>;{ readonly dogs: Dog[] }is not lent where{ readonly dogs: Animal[] }is asked;New rules
missing-mut(error): a value given to aMutparameter, field, default or return withoutmut(...).tscrefuses the same, but the editor and lint paths don't runtsc. Its quick fix is the migration.aliased-mut(error): one call in whichmut(x)appears and another argument isxor a part of it. Rust's E0499 and E0502.mut(p)of a parameter not declaredMut, or of module state, is whereno-param-mutationandno-mutable-globalnow report.Mut<C>.Upgrading
Measured on a real project
On a copy of an adopter's project (744 files), with its own
tscover its ten projects:tscerrors before, with today's stdtscerrors after migration, caused byMuttsctime and peak memoryaliased-mut, 97no-param-mutationThe 71 this copy showed, by kind (the same kinds, in other proportions, make up the 339; two of them, the union and the list of loans, are removed by #122):
Mut<A>whereMut<A | B>is asked)Mutinside another type (readonly Mut<Unit>[])mutEach(units), from #122 (the.mapform copies the array at run time)mut(...)Mutplace whose type is inferredMutfunction in a read-only callback slotThe first version of the type gave 251 errors on the same code, about 180 of them safe. Three rounds of review brought it to 71 while closing holes that the looser versions opened.
A decision for the maintainer
missing-mutasks formut(x)at every call that passes to aMutparameter, even whenxis already aMut. Of the 14,846 wrappers on the adopter, 5,081 are of that kind;tscwould accept those calls without them. The alternative is Rust's rule: writemutonly where a loan starts. That would remove about a third of the wrappers, and each remaining one would mark a new loan. The type is the same either way; only the rule and the migration differ.Two holes left open, each a listed class in the soundness corpus
readonlywhere nothing should replace it.readonlyunion.Not in this PR: a borrowed value stored and changed later, a getter that changes its object, and a mutable part of a borrowed value handed out.
How it was checked
test:std(381),typecheck, the docs examples (867 compile),test:vite, the docs site build,bench:checkand the soundness corpus pass.Mapand a typed array inreadonlyfields, a subclass, a spread with one more field), and programs written to break the type. Four of the latter compiled against the third version and failed at run time; three are now refused, at any depth, and the fourth is the first hole above.Created with Claude Opus 5.5 (implementation) and Claude Fable 5.2 (review, acceptance and attack programs, and the per-property mark) in Claude Code.
Open: the mark `(value: T) => void` compared whole types, so a value with more properties than asked for (a Tree where Mut<Entity> is asked, a Sprite for Mut<Container>), a writable list where Mut<readonly T[]> is asked and a typed array made with `new` were refused, though the callee can't break any of them: 134 + 27 + 3 of 251 tsc errors on a migrated adopter. And the advice to make such callees generic was unsound: TypeScript lets a generic body write the bound's type into a narrower `T["x"]`. Closes it: the mark lists, per property of T, a slot: invariant where the callee may write it, covariant where it can only read it (`readonly`) or calls it (a method, rebuilt as a plain function type so its parameters count one way, which keeps `Map<string, 1>` out of `Mut<Map<string, number>>`). Every hazard stays refused (Dog[] as Mut<Animal[]>, { x: 0 | 1 } as Mut<{ x: number }>, a Map of a narrower value, Mut<Builder> as Mut<Unit>, a narrower override); width, subclasses, readonly views, typed arrays and narrowed unions are accepted. What it newly accepts (a delete through a Record target, Object.assign through Mut<object>) is reachable under the old mark by a plain assignment first. mut.check.ts pins each case. Co-Authored-By: Claude Opus 5.5 <[email protected]>Open: a value put into a place declared Mut<...> without a call (an initializer or assignment, a parameter's default, a field, a `return`, an array literal where readonly Mut<T>[] is asked) wasn't reported or migrated, and a fresh literal at a Mut slot got no fix: 30 + 17 tsc errors after the migration on an adopter, all mechanical. Closes it: `missing-mut` reports those places (per file, as Slot), and its fix, which `safe-ts migrate mut` applies, lends them; a fresh literal is lent with the place's type (`mut<Cost>({ ... })`, `mut<number[]>([])`) where the file can name it, else only `[]`/`{}` are left as notes. Returns count through Promise<Mut<T>> and Generator<Y, Mut<T>, N>. Fixtures, the codemod case (tsc on its output) and meaning.rs cover it. Docs: the state guide's table and "what to write" for the new mark, missing-mut, adoption, README, CHANGELOG, skill. Co-Authored-By: Claude Opus 5.5 <[email protected]>Open: the mark compared a `readonly` property one way, as covariant, but `readonly` is shallow. A `{ readonly dogs: Dog[] }` lent as `Mut<{ readonly dogs: Animal[] }>` was accepted and the callee pushed a cat into the list (`Dog[]` as `Animal[]` one property down); also a `{ readonly state: { on: 0 | 1 } }` lent where `on: number` is written, a subclass narrowing a `readonly` field that holds a list, a `Map` of a narrower value in a `readonly` field. And two `Shared<...>` were compared by the variance TypeScript measures for the alias, which ignores `readonly`: a `{ readonly n: number }` was lent where the callee writes `n`. Closes them: each property's slot is `{ w, r }`: `w` whether the callee may replace it (the same type both ways, or never), `r` what it holds, an object lent as a loan of its own (`Lent<X>`: each member of the value lendable as some member asked, so a typed array's `ArrayBuffer` fits `ArrayBufferLike`). `Shared` and the slots are written so TypeScript compares them structurally. Recursive types (nodes with `readonly children`) check, and an adopter's ten projects reach no depth limit; tsc takes 8.3 s and 1,295 MB where the round-3 mark took 8.0 s and 1,210 MB (minimum of three interleaved rounds). Left open, documented on `Mut`, in the guide and as escaping corpus classes: a function in a writable property replaced by one that needs more (compared one way like a method: compared both ways, 97 more of the adopter's errors, subclasses lent as their base and typed arrays), and a write through a member shared by a `readonly` property's union. Corpus: mut-readonly-field-list, -object, -subclass (refused; each escapes with the round-3 mark), mut-function-field-replaced and mut-readonly-union-field-write (escaping.txt). mut.check.ts pins the refusals, the recursive tree and the two open holes. Co-Authored-By: Claude Opus 5.5 <[email protected]>declareis a cast #119Resultkept in a local #120promise-as-value,floating-promise#121this, parts handed out, kept copies, wider aliases, loans alive at once #122.oxlintrc.json, the file that sets themOpen (review): `const r = flag ? save(1) : save(2)` and `const [a, b] = await Promise.all([...])` weren't seen as kept Results; the kept-Result analysis built a graph for one function in five on the adopter's largest entry (2,561 of ~10,500) and use-after-consume for 539, mostly for calls that can't matter; and the layer was held only by ten unit tests and the rules' fixtures. Closes: - Kept: each call of a `?:` / `??` / `||` / `&&` / parenthesised / awaited initialiser, and each element of an array destructuring of `Promise.all` / `allSettled` over a list written in place, in the binding at its place (fixtures). `const { result } = pair()` isn't (only `pair`'s return type says what `result` is). - The cheap test first. Kept Results: the local pass only lists the kept calls (no graph), after two syntactic tests (a const looked at unconditionally by the very next statement; a call whose callee the file shows returns a plain type, or a method of a value declared with one); the whole-program pass keeps those whose function returns a Result and only then parses the file again and builds graphs for them (`unsafe(...)` / `parseJson` stay local). use-after-consume: a function gets a graph only if an operation there would use a binding up (`Array.from(list)` of an array doesn't); the generator walk runs only in a file with a `function*`. On the adopter's `apps/client/src/start.ts`: 3,119 graphs before (2,561 kept, 539 consumed, 19 number-parse-nan), 40 after (21, 0, 19). - flow::tests::path_cases: 39 shapes with their answers on some / every path, independent of any rule (labelled break and continue, do...while, a loop's update clause, for await, continue in try/finally, finally after a return, nested finally, switch with default in the middle and falling into it, && / || in a statement and a test, ?:, ??, ||=, optional calls, yield and await between, reset, an exception into catch, nested functions, unreachable code). - Docs: the libraries guide says a pack's `consumes` is read from its safe-ts.json (and the manifest example shows it); use-after-consume's page covers views, second names and optional calls; must-use-result's covers branches and Promise.all; README gaps, CHANGELOG, tool gaps. Co-Authored-By: Claude Opus 5.5 <[email protected]>asynconeConflicts, all kept from both sides: ecmascript-api.json gets both new sections (`callbacks` and `consumes`, merged as JSON: each side only added its own key); package.json takes `test:std` from this side (vue-tsc tools for the TypeScript-versions test) and `test:browsers` from the other (the browsers' consumes test); the soundness class list imports both new groups; the migration skill has both sections ("A promise used as its value", "A value used after it was used up") and census.mjs both pointers; the CHANGELOG's Added and Changed keep every entry. Co-Authored-By: Claude Opus 5.5 <[email protected]>Resultgets one finding, not two