Borrowed stays borrowed: elements, methods that change this, parts handed out, kept copies, wider aliases, loans alive at once #122

Merged
sionzee merged 88 commits from borrow-escapes into main 2026-11-21 23:36:00 +01:00
Owner

Based on nominal-mut (#116), and it should land with it: this changes two things in that PR's Mut type and its migration (see "What this fixes in #116"). 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. This is the top of the chain.

Combined with the pieces below. The API map's returns section (this piece) and callbacks section (#121) are held together by a test: Array.from(xs, mapper) hands back what the mapper returns, which removes a false positive this piece had alone on Array.from(xs, (x) => ({ ...x })). A Readonly<Store> receiver is opened by #123's opener, so a method that changes the store is reported through it.

SAFE-TS's ownership rule is Rust's, by convention: a parameter is borrowed, and a function may change it only when it says so with Mut<T>. #116 made Mut nominal, so TypeScript itself refuses a call that lends without mut(...). What was left is every way a borrowed object is changed with no Mut in sight. Each of these passed tsc strict, safe-ts check --deny-warnings and oxlint:

function tick(order: Order): void {
  for (const line of order.lines) line.qty += 1;        // the elements of a borrowed list
}
function bumpCounter(c: Counter): void { c.bump(); }    // a method that changes `this`
function peek(o: Outer): Inner { return o.inner; }      // a part handed out, then changed by the caller
class Registry {
  add(item: Inner): void { this.items.push(item); }     // a borrowed object kept,
  zero(): void { for (const item of this.items) item.value = 0; }   // and changed later through the copy
}
const bases: Base[] = subs;  bases.push(plainBase);     // a Sub[] seen as a writable Base[]
await Promise.all([addOne(mut(ledger)), addOne(mut(ledger))]);     // two mutable loans alive at once

The principle

What is reached through a borrowed value is borrowed, however it got there, and one mutable loan at a time.

  • Elements. A container and what it holds are tracked separately. A loop variable, find / at / Map.get, an index and destructuring give an object the container holds. filter, slice, toSorted and a spread give a new container (the function's own) holding the same objects. map and structuredClone give new objects. What each built-in hands back is data in the ECMAScript map.
  • Methods and getters that change this. Decided from the method's body, across the class hierarchy, including a method that lends this to a helper. Calling one on a borrowed value is no-param-mutation. A getter that changes its object is the new rule mutating-getter; a memo goes in a /** @cache */ field.
  • A part handed out. A function whose every return gives back a part of the same parameter returns something borrowed.
  • A kept copy. Storing a borrowed parameter in a field that is later changed through is reported at the store, since the fix belongs to that parameter.
  • A wider alias (new rule covariant-alias). A value written as Sub[], Holder<Sub>, Map<K, Sub> or Ref<Sub> bound to a writable place written with a wider type argument. Returning a list the function made is fine.
  • Loans alive at once (aliased-mut). Calls in one Promise.all that lend the same object, a second loan while the first promise is not yet awaited, and a loan in a map callback that returns the promise.
  • A tag written through a union (new rule union-tag-write). TypeScript accepts unit.kind = "archer" through a Mason | Archer; the object then lies about which member it is.

What this fixes in #116

Type-checking the migrated copy of an adopter's project with its workspace packages resolved, for the first time, showed 339 errors left after safe-ts migrate mut. Two kinds were ours:

  • A member could not be lent where its union is asked. mut(list) with a number[] was refused by a parameter typed Mut<number[] | Int32Array>. A function accepting either kind may do only what both allow, so this is safe; the one unsafe thing, retagging, is what union-tag-write refuses. Mut<A | B> is now Mut<A> | Mut<B> for a known union. Every earlier refusal still holds (Dog[] where Animal[] | Int32Array is asked; a generic Mut<T>).
  • Lending each element cost an array copy. A function that changes a list's elements declares readonly Mut<Unit>[], and the docs said to call it with units.map((u) => mut(u)), which after the transform is a real copy on every call. New mutEach(items) (std and prelude) lends what a list, Map or Set holds; the transform erases it to its argument. The migration writes it and missing-mut offers it.

Lending this: mut(this) cannot compile (the polymorphic this type does not reduce), and the type-level way around it reopens a hole. The spelling is mut<Cart>(this), accepted without a cast finding only inside an instance method of that class.

Cost, measured on an adopter's project

  • Findings on unmigrated code: 76 new no-param-mutation (265 places) and 12 missing-mut, nothing lost. Every one of the 50 places the element model added was read: all are functions changing objects their caller lent to read, one harmless in effect (a diagnostics counter). The new rules mutating-getter, covariant-alias and union-tag-write have no findings there.
  • Getting the migrated copy back to green: 84 parameter declarations; the migration writes the loans (62 files). Left by hand: 7 callback-typed parameters and 3 aliased-mut findings that need a design decision.
  • What tsc still refuses after migration: 201 errors at 52 places, down from 339 at 73.
Kind Places Declarations to change
Mut<A> lent where Mut<B> may write a property A has narrower or optional: a correct refusal 16 4
A value the migration could not follow (an unresolved method, [], a default) 20 0: write the loan there
A function taking Mut in a read-only callback slot 8 one per slot
A fresh object lent where the type has an optional property 4 0: mut<Deps>({...})
A subclass, a wider element type, a generic Mut 3 3
An overload 1 1

That table is in the upgrade section of docs/guide/adoption.md.

  • Whole-program pass on the largest entry: 956 ms before, 961 ms after.
  • Soundness corpus: borrowed-receiver-method-mutation, borrowed-return-escape, covariant-mutable-array-local, covariant-mutable-field, async-toctou-lost-update and mut-readonly-union-field-write are closed, and seven classes were added and closed. 5 of 43 escape on this branch, two of which #120 closes.

What stays unseen

  • A method reached through an interface member. There is no body to read, and the only signature-level spelling TypeScript has (this: Mut<I>) would force mut(x).m() at every call. Not built; a decision for the owner.
  • A subclass override that changes the object where the method it overrides does not.
  • A borrowed value kept outside the object's own fields.
  • Loans alive at once beyond straight-line code and the array forms (loops, timers, listeners): these need the control-flow layer of #120.
  • mut-function-field-replaced stays a listed hole: closing it needs assignability between function types.
  • A covariant alias where one side has no written type, or a generic from a package the checker knows nothing about.

Created with Claude Opus 5.5 (implementation) and Claude Fable 5.2 (review and acceptance tests) in Claude Code.

Based on `nominal-mut` (#116), and it should land with it: this changes two things in that PR's `Mut` type and its migration (see "What this fixes in #116"). 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. This is the top of the chain. **Combined with the pieces below.** The API map's `returns` section (this piece) and `callbacks` section (#121) are held together by a test: `Array.from(xs, mapper)` hands back what the mapper returns, which removes a false positive this piece had alone on `Array.from(xs, (x) => ({ ...x }))`. A `Readonly<Store>` receiver is opened by #123's opener, so a method that changes the store is reported through it. SAFE-TS's ownership rule is Rust's, by convention: a parameter is borrowed, and a function may change it only when it says so with `Mut<T>`. #116 made `Mut` nominal, so TypeScript itself refuses a call that lends without `mut(...)`. What was left is every way a borrowed object is changed with no `Mut` in sight. Each of these passed `tsc` strict, `safe-ts check --deny-warnings` and oxlint: ```ts function tick(order: Order): void { for (const line of order.lines) line.qty += 1; // the elements of a borrowed list } function bumpCounter(c: Counter): void { c.bump(); } // a method that changes `this` function peek(o: Outer): Inner { return o.inner; } // a part handed out, then changed by the caller class Registry { add(item: Inner): void { this.items.push(item); } // a borrowed object kept, zero(): void { for (const item of this.items) item.value = 0; } // and changed later through the copy } const bases: Base[] = subs; bases.push(plainBase); // a Sub[] seen as a writable Base[] await Promise.all([addOne(mut(ledger)), addOne(mut(ledger))]); // two mutable loans alive at once ``` ## The principle **What is reached through a borrowed value is borrowed, however it got there**, and **one mutable loan at a time**. - **Elements.** A container and what it holds are tracked separately. A loop variable, `find` / `at` / `Map.get`, an index and destructuring give an object the container holds. `filter`, `slice`, `toSorted` and a spread give a new container (the function's own) holding the *same* objects. `map` and `structuredClone` give new objects. What each built-in hands back is data in the ECMAScript map. - **Methods and getters that change `this`.** Decided from the method's body, across the class hierarchy, including a method that lends `this` to a helper. Calling one on a borrowed value is `no-param-mutation`. A getter that changes its object is the new rule `mutating-getter`; a memo goes in a `/** @cache */` field. - **A part handed out.** A function whose every `return` gives back a part of the same parameter returns something borrowed. - **A kept copy.** Storing a borrowed parameter in a field that is later changed through is reported at the store, since the fix belongs to that parameter. - **A wider alias** (new rule `covariant-alias`). A value written as `Sub[]`, `Holder<Sub>`, `Map<K, Sub>` or `Ref<Sub>` bound to a writable place written with a wider type argument. Returning a list the function made is fine. - **Loans alive at once** (`aliased-mut`). Calls in one `Promise.all` that lend the same object, a second loan while the first promise is not yet awaited, and a loan in a `map` callback that returns the promise. - **A tag written through a union** (new rule `union-tag-write`). TypeScript accepts `unit.kind = "archer"` through a `Mason | Archer`; the object then lies about which member it is. ## What this fixes in #116 Type-checking the migrated copy of an adopter's project with its workspace packages resolved, for the first time, showed 339 errors left after `safe-ts migrate mut`. Two kinds were ours: - **A member could not be lent where its union is asked.** `mut(list)` with a `number[]` was refused by a parameter typed `Mut<number[] | Int32Array>`. A function accepting either kind may do only what both allow, so this is safe; the one unsafe thing, retagging, is what `union-tag-write` refuses. `Mut<A | B>` is now `Mut<A> | Mut<B>` for a known union. Every earlier refusal still holds (`Dog[]` where `Animal[] | Int32Array` is asked; a generic `Mut<T>`). - **Lending each element cost an array copy.** A function that changes a list's elements declares `readonly Mut<Unit>[]`, and the docs said to call it with `units.map((u) => mut(u))`, which after the transform is a real copy on every call. New **`mutEach(items)`** (std and prelude) lends what a list, `Map` or `Set` holds; the transform erases it to its argument. The migration writes it and `missing-mut` offers it. Lending `this`: `mut(this)` cannot compile (the polymorphic `this` type does not reduce), and the type-level way around it reopens a hole. The spelling is `mut<Cart>(this)`, accepted without a cast finding only inside an instance method of that class. ## Cost, measured on an adopter's project - **Findings on unmigrated code:** 76 new `no-param-mutation` (265 places) and 12 `missing-mut`, nothing lost. Every one of the 50 places the element model added was read: all are functions changing objects their caller lent to read, one harmless in effect (a diagnostics counter). The new rules `mutating-getter`, `covariant-alias` and `union-tag-write` have no findings there. - **Getting the migrated copy back to green:** 84 parameter declarations; the migration writes the loans (62 files). Left by hand: 7 callback-typed parameters and 3 `aliased-mut` findings that need a design decision. - **What `tsc` still refuses after migration:** 201 errors at 52 places, down from 339 at 73. | Kind | Places | Declarations to change | |---|---|---| | `Mut<A>` lent where `Mut<B>` may write a property `A` has narrower or optional: a correct refusal | 16 | 4 | | A value the migration could not follow (an unresolved method, `[]`, a default) | 20 | 0: write the loan there | | A function taking `Mut` in a read-only callback slot | 8 | one per slot | | A fresh object lent where the type has an optional property | 4 | 0: `mut<Deps>({...})` | | A subclass, a wider element type, a generic `Mut` | 3 | 3 | | An overload | 1 | 1 | That table is in the upgrade section of `docs/guide/adoption.md`. - **Whole-program pass** on the largest entry: 956 ms before, 961 ms after. - **Soundness corpus:** `borrowed-receiver-method-mutation`, `borrowed-return-escape`, `covariant-mutable-array-local`, `covariant-mutable-field`, `async-toctou-lost-update` and `mut-readonly-union-field-write` are closed, and seven classes were added and closed. 5 of 43 escape on this branch, two of which #120 closes. ## What stays unseen - **A method reached through an interface member.** There is no body to read, and the only signature-level spelling TypeScript has (`this: Mut<I>`) would force `mut(x).m()` at every call. Not built; a decision for the owner. - A subclass override that changes the object where the method it overrides does not. - A borrowed value kept outside the object's own fields. - Loans alive at once beyond straight-line code and the array forms (loops, timers, listeners): these need the control-flow layer of #120. - `mut-function-field-replaced` stays a listed hole: closing it needs assignability between function types. - A covariant alias where one side has no written type, or a generic from a package the checker knows nothing about. Created with Claude Opus 5.5 (implementation) and Claude Fable 5.2 (review and acceptance tests) in Claude Code.
Open: a borrowed object could still be changed without a `Mut` in sight. A method or getter of
the project's own class that changes `this`, called on a borrowed parameter; a part of a borrowed
parameter handed out by a function and changed by the caller; a borrowed object kept in a field
and changed later through the copy; a `Sub[]` bound to a writable `Base[]` local, field, return
or property; and two `Mut` loans of one object alive at once across an async call. Five classes
of the soundness corpus escaped for these.

Closed:
- no-param-mutation follows a method of a project class that changes its object (Rust's
  `&mut self`), from state.rs's per-class summary (fields assigned, also through locals naming
  a part of `this` and elements of a field, changing methods of fields, `mut(...)` of `this` or
  a part, other methods, up the extends chain), resolved at the call through the receivers the
  whole program already follows. A method named like a collection's is decided by its body.
- A call whose function returns the borrowed argument (or a part of it) on every path, or a
  method returning its object or a part of it, hands out something borrowed: changing it is
  changing the argument (borrow.rs `hands_out`, exact paths only, no copies).
- A borrowed parameter kept in `this` (a field, an element, a constructor parameter property)
  is reported at the store when the class changes what it keeps there later; a platform
  object's handler slot set through the copy doesn't count.
- New rule mutating-getter: a getter that changes its object.
- New rule covariant-alias: a written container type bound to a writable place written with
  the same container of another type argument.
- aliased-mut reports two loans alive at once: calls of one Promise.all, a second loan while a
  promise kept in a const isn't awaited yet, an async callback of map/forEach/flatMap that lends
  a captured object to a call it awaits or returns.
- `mut<C>(this)` in an instance method of `class C` is accepted (no no-unchecked-cast): the
  polymorphic `this` doesn't reduce through the nominal mark, and `this` is a C or a subclass.
- `/** @cache */` on a class field: filling it is no change of the object.

Corpus: borrowed-receiver-method-mutation, borrowed-return-escape, covariant-mutable-array-local,
covariant-mutable-field and async-toctou-lost-update come off escaping.txt; new classes
borrowed-receiver-setter, borrowed-getter-part-escape, borrowed-stored-changed-later and
async-pending-loan are rejected. mut-function-field-replaced and mut-readonly-union-field-write
stay listed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open (review of 07dce04f): no-param-mutation never followed a loop's variable, nor what
`find`, `at` or `get` hand back, nor the elements of a new list holding the same objects
(`filter`, `slice`, a spread), so `for (const line of order.lines) line.qty = 0` passed. A part
handed out was followed only when every `return` gave back the same path. A callback that isn't
`async` but returns the loan's promise inside `Promise.all(xs.map(...))` passed aliased-mut.
failure-contract dropped a finding once a slot's type or the value put into it was wrapped in
`Mut` (`Mut<Deps>`, `mut<Deps>({ ... })`). The union-tag write lent through a `readonly`
property stayed open. covariant-alias reported a function returning its own local under a wider
type, and missed Vue's `Ref` and React's ref objects.

Closed:
- analyze.rs `reach`: what an expression holds of a borrowed parameter, the object itself or a
  new container of its objects, through members, elements, `?:`/`??`, the built-ins as
  ecmascript-api.json's new `returns` section says (element, container, same, fresh), and calls
  that may hand back a part (decided by the whole program, with the built-in's answer as the
  fallback for an unresolved `get`). For-of variables, destructuring (`[first, ...rest]`) and
  element callbacks of such values are bound through it. A new container's own changes are
  the function's; lending or passing it lends its objects, unless the callee's parameter holds
  only primitives (`Mut<number[]>`, `Mut<Int32Array>`). Elements declared `Mut` (lists, maps,
  sets) are owned.
- borrow.rs `hands_out`: a part of the same parameter in every `return`, by any path, through
  other functions (resolved across files) and built-ins; state.rs does the same for a method's
  `this`, noting a new container.
- New quick fix: `readonly Mut<T>[]` for a change to an element of a `T[]` parameter.
- aliased-mut: a non-async `map` callback returning the loan's promise, collected by
  `Promise.all`.
- failure-contract: `Mut<T>` slots are `T`'s, and `mut(value)` is checked as the value.
- New rule union-tag-write (error): a write through a written union to a property its members
  type differently.
- covariant-alias: returning a function's own local isn't an alias; Vue `Ref`/`ShallowRef` and
  React `RefObject`/`MutableRefObject` are writable containers.
- The class method named in a kept-copy message is chosen in source order (was hash order).

Corpus: mut-readonly-union-field-write comes off escaping.txt; new classes
borrowed-element-changed and borrowed-part-several-paths, and two more programs of
async-pending-loan (a non-async map callback, an async map callback), all rejected.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A member is lent where its union is asked; mutEach lends what a list holds without a copy
All checks were successful
Tests / test (pull_request) Successful in 7m29s
Benchmarks / bench (pull_request) Successful in 3m25s
96d8c8d1ce
Open (review of 69090f0c): `Mut<number[]>` was refused where `Mut<number[] | Int32Array>` is
asked, about a third of the tsc errors left on a migrated adopter. The refusal guarded a write
that turns one member into another, which union-tag-write now refuses itself. And a function
that changes a list's elements (`readonly Mut<T>[]`) could only be lent each element with
`items.map((item) => mut(item))`: after the transform, a new array on every call.

Closed:
- std `Mut<T>` distributes over a concrete union: `Mut<A | B>` is `Mut<A> | Mut<B>`, so a member
  lends where its union is asked, each member compared as any loan (a typed array's buffer,
  `Dog[]` still refused as `Animal[] | Int32Array`), and a tag test narrows to the member's
  `Mut`. A generic `Mut<T>` takes neither branch, so it is still refused where `Mut<Entity>` is
  asked, and `mut(this)` still needs the class written. The one-value mark moves to
  `src/mut-loan.ts` so that TypeScript's messages keep saying `Mut<...>`.
- std `mutEach(items)` (and the prelude's): each element of a list, a map's values or a set's
  members lent, typed `readonly Mut<T>[]` / `ReadonlyMap<K, Mut<V>>` / `ReadonlySet<Mut<T>>`,
  the list itself as a read-only view at run time. The transform erases it like `mut(x)`
  (scripts, the prelude, Vue templates). missing-mut asks for it at a parameter with `Mut`
  elements (*Lend each element: mutEach(xs)*; `.map((x) => mut(x))` and array literals of loans
  are accepted), the migration writes it (an `import type { Mut }` rewritten once for `mut` and
  `mutEach`), and aliased-mut, unneeded-mut, no-param-mutation, the concurrency checks and the
  class summaries read it as a loan. `Iterable<Mut<T>>` parameters count as element loans.
- docs/guide/adoption.md: what tsc still refuses after the migration, by kind, with the number
  of declarations each takes, from a migrated adopter.

Corpus: new class mut-union-member-retag (a member lent as its union, retagged by the callee),
rejected by union-tag-write; nothing reopens.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts, kept from both sides: ecmascript-api.json gets `returns` beside `consumes` and
`callbacks` (merged as JSON, each side only added its own key); builtins.rs reads both new
sections (`Hands` / `returns` and `Reads` / `callbacks`, each with its own accessors and
checks that a member it names is in the map); the slot reader keeps the other side's
utility types, `Record` and generic slots, with this side's `Mut<Deps>` read as `Deps`
beside `Option`; cache.rs keeps this side's `Map` values as elements before the other side's
utility and generic shapes; the README's known gaps (union-tag-write refuses the union write;
number-parse-nan follows paths); the sidebar; the CHANGELOG. escaping.txt: neither side's
closed classes (mut-readonly-union-field-write from this side; one-shot-generator-reused and
use-after-consume-arraybuffer from the other).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open after the merge:
- `packages/std/src/mut-loan.ts` (borrow-escapes: the one-value mark of `Mut`) is
  `// @safe-ts std`, and with escape-hatches-2 a marker counts only in a file its package.json
  lists: `unlisted-marker` at the marker, and the module checked as project code (its `null`s
  reported in every fixture importing std's `mut`). Closes: `src/mut-loan.ts` under std's
  `"trustedFiles"`, as unlisted-marker's page says to write.
- null_package_receivers: `copy.put("c", null)` with `copy: Readonly<Store>` is now also
  `no-param-mutation`. The one opener (return-types) reads `Readonly<Store>` as `Store`, and
  borrow-escapes follows `Store.put`, which writes the store's private map: `Readonly` makes
  the fields read-only, not the methods, so the caller's store does change. A finding of the
  two pieces together, right by the rule's page; the expectation is written, with the reason
  in the fixture's comment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: `returns` (borrow-escapes) says `Array.from` hands back a container of its argument's
objects, and the borrow follower took that for every call, while `callbacks` (promise-statics)
says its second argument is a callback whose results are collected. So
`Array.from(order.lines, (l) => ({ ...l }))` was taken to hold the borrowed lines, and a change
to the copies was reported as `no-param-mutation` (borrow-escapes alone reports it). Nothing
held the three sections (`consumes`, `callbacks`, `returns`) to each other.

Closes:
- `Builtins::static_hands(name, args)`: a static whose callback's results are collected and
  that is given that callback hands back new values, as `map` does; both callers (analyze.rs
  `call_reach`, borrow.rs `part_in`) pass the call's argument count. `Array.from(xs)` is a
  container as before. elements fixture: `fromList` (reported) and `fromMapped` (silent),
  in two functions since one parameter's findings in one function are one finding.
- builtins::tests::the_sections_agree: all three sections load; a collected callback means
  fresh values (a static's optional mapper through `static_hands`); a truthiness callback
  picks an element or a container, and its iteration of an iterator may stop early
  (`iterates: some`); an order callback sorts the same items; a static's `returns` and
  `consumes` are about the same argument.
- Receiver table: a slot row for std's `Mut<Port>` lent with `mut<Port>({ ... })`, now that
  failure-contract reads a `Mut` slot as its type (43 rows).
- no-param-mutation's page: `Array.from` with a mapper is with `map` (and an identity mapper
  is the same gap as `lines.map((l) => l)`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Merge the chain below: one finding for a dropped promise that holds a Result
All checks were successful
Benchmarks / bench (pull_request) Successful in 5m6s
Tests / test (pull_request) Successful in 10m2s
95d03c4c0f
Co-Authored-By: Claude Fable 5.2 <[email protected]>
sionzee changed target branch from nominal-mut to main 2026-11-21 23:34:12 +01:00
Merge main
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m47s
Tests / test (pull_request) Successful in 8m22s
bf64f1e577
Co-Authored-By: Claude Fable 5.2 <[email protected]>
sionzee deleted branch borrow-escapes 2026-11-21 23:36:01 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Evobug/Safe-Ts!122
No description provided.