Borrowed stays borrowed: elements, methods that change this, parts handed out, kept copies, wider aliases, loans alive at once #122
Loading…
Reference in a new issue
No description provided.
Delete branch "borrow-escapes"
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
nominal-mut(#116), and it should land with it: this changes two things in that PR'sMuttype 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
returnssection (this piece) andcallbackssection (#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 onArray.from(xs, (x) => ({ ...x })). AReadonly<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 madeMutnominal, so TypeScript itself refuses a call that lends withoutmut(...). What was left is every way a borrowed object is changed with noMutin sight. Each of these passedtscstrict,safe-ts check --deny-warningsand oxlint:The principle
What is reached through a borrowed value is borrowed, however it got there, and one mutable loan at a time.
find/at/Map.get, an index and destructuring give an object the container holds.filter,slice,toSortedand a spread give a new container (the function's own) holding the same objects.mapandstructuredClonegive new objects. What each built-in hands back is data in the ECMAScript map.this. Decided from the method's body, across the class hierarchy, including a method that lendsthisto a helper. Calling one on a borrowed value isno-param-mutation. A getter that changes its object is the new rulemutating-getter; a memo goes in a/** @cache */field.returngives back a part of the same parameter returns something borrowed.covariant-alias). A value written asSub[],Holder<Sub>,Map<K, Sub>orRef<Sub>bound to a writable place written with a wider type argument. Returning a list the function made is fine.aliased-mut). Calls in onePromise.allthat lend the same object, a second loan while the first promise is not yet awaited, and a loan in amapcallback that returns the promise.union-tag-write). TypeScript acceptsunit.kind = "archer"through aMason | 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:mut(list)with anumber[]was refused by a parameter typedMut<number[] | Int32Array>. A function accepting either kind may do only what both allow, so this is safe; the one unsafe thing, retagging, is whatunion-tag-writerefuses.Mut<A | B>is nowMut<A> | Mut<B>for a known union. Every earlier refusal still holds (Dog[]whereAnimal[] | Int32Arrayis asked; a genericMut<T>).readonly Mut<Unit>[], and the docs said to call it withunits.map((u) => mut(u)), which after the transform is a real copy on every call. NewmutEach(items)(std and prelude) lends what a list,MaporSetholds; the transform erases it to its argument. The migration writes it andmissing-mutoffers it.Lending
this:mut(this)cannot compile (the polymorphicthistype does not reduce), and the type-level way around it reopens a hole. The spelling ismut<Cart>(this), accepted without a cast finding only inside an instance method of that class.Cost, measured on an adopter's project
no-param-mutation(265 places) and 12missing-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 rulesmutating-getter,covariant-aliasandunion-tag-writehave no findings there.aliased-mutfindings that need a design decision.tscstill refuses after migration: 201 errors at 52 places, down from 339 at 73.Mut<A>lent whereMut<B>may write a propertyAhas narrower or optional: a correct refusal[], a default)Mutin a read-only callback slotmut<Deps>({...})MutThat table is in the upgrade section of
docs/guide/adoption.md.borrowed-receiver-method-mutation,borrowed-return-escape,covariant-mutable-array-local,covariant-mutable-field,async-toctou-lost-updateandmut-readonly-union-field-writeare closed, and seven classes were added and closed. 5 of 43 escape on this branch, two of which #120 closes.What stays unseen
this: Mut<I>) would forcemut(x).m()at every call. Not built; a decision for the owner.mut-function-field-replacedstays a listed hole: closing it needs assignability between function types.Created with Claude Opus 5.5 (implementation) and Claude Fable 5.2 (review and acceptance tests) in Claude Code.
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]>declareis a cast #119Resultkept in a local #120promise-as-value,floating-promise#121