Module state handed out on some path: a static method, one branch of a ?:, a local helper, one of two returns #144

Merged
sionzee merged 26 commits from module-state-paths into main 2026-11-23 20:42:05 +01:00
Owner

#143 taught no-mutable-global to follow module state through a function that hands it out, and listed three forms it still missed. This closes them, and a fourth found while reviewing. Each of these passed tsc strict, safe-ts check --idiomatic --deny-warnings and oxlint on main:

export class Registry {
  private static readonly items: string[] = [];
  static all(): string[] { return Registry.items; }
}
Registry.all().push("d");                       // a static method hands out a static list

export function maybe(on: boolean): Option<Config> {
  return on ? hidden : undefined;
}
const cfg = maybe(on);
if (cfg !== undefined) cfg.retries = 0;         // module state on one branch of a `?:`

const again = (): Config => getHidden();
again().label = "y";                            // passed on through a helper kept in a local

function orFresh(useShared: boolean): Config {
  if (useShared) return getHidden();
  return fresh();
}
orFresh(true).hosts.push("x");                  // module state on one of two `return`s

What changes

  • A top-level class's static fields count as module state through its static methods, as they already did written out (Registry.items.push(x)).
  • For module state, one path handing it back is enough: a caller cannot tell which object it got. A part of a parameter must still be handed back on every path, as before.
  • A helper with no parameters declared inside the calling function (an arrow, a function expression, a declaration that is one return) is read where it is called.
  • A call given only primitives is asked whether it hands back module state; before, it was asked only about its arguments.
  • The same part changed again through what one call hands back is one finding, at the first.
  • Whether a function hands back what it is given is remembered per function and parameter for the pass.

Evidence

  • Held-out cases, written by the reviewer and not shown to the implementer: 42 forms that change module state another way are reported. main reports 32 of them; the ten new ones are the forms above in several spellings, a switch with module state on one case, and a try. 12 fine forms are silent: reads, a function whose every return is a new object, a copy made by a static method.
  • Two rounds. The first version dropped a finding #143 reports: a part of handed-out state lent, deepen(mut(getHidden().inner)). Merging findings per call let the pass to mut itself take the call's slot. Fixed, and pinned in the fixture in three spellings.
  • On an adopter's project (about 760 files): output identical to main, entries and directories.
  • Soundness corpus: unchanged, 16 of 110 escape.
  • Cost: about 0.4 to 0.5% fewer instructions than main for a whole check of that project's largest entry (18.70 to 18.61 billion, one thread, callgrind, mean of two runs each; runs of one binary differ by up to 0.6%). The memo of hand-outs takes back part of what #143 added; it does not take back all of it.

What turns red on upgrade

Code that changes module state through one of the forms above. On the code measured, nothing.

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

#143 taught `no-mutable-global` to follow module state through a function that hands it out, and listed three forms it still missed. This closes them, and a fourth found while reviewing. Each of these passed `tsc` strict, `safe-ts check --idiomatic --deny-warnings` and oxlint on `main`: ```ts export class Registry { private static readonly items: string[] = []; static all(): string[] { return Registry.items; } } Registry.all().push("d"); // a static method hands out a static list export function maybe(on: boolean): Option<Config> { return on ? hidden : undefined; } const cfg = maybe(on); if (cfg !== undefined) cfg.retries = 0; // module state on one branch of a `?:` const again = (): Config => getHidden(); again().label = "y"; // passed on through a helper kept in a local function orFresh(useShared: boolean): Config { if (useShared) return getHidden(); return fresh(); } orFresh(true).hosts.push("x"); // module state on one of two `return`s ``` ## What changes - A top-level class's static fields count as module state through its static methods, as they already did written out (`Registry.items.push(x)`). - For module state, **one path handing it back is enough**: a caller cannot tell which object it got. A part of a *parameter* must still be handed back on every path, as before. - A helper with no parameters declared inside the calling function (an arrow, a function expression, a declaration that is one `return`) is read where it is called. - A call given only primitives is asked whether it hands back module state; before, it was asked only about its arguments. - The same part changed again through what one call hands back is one finding, at the first. - Whether a function hands back what it is given is remembered per function and parameter for the pass. ## Evidence - **Held-out cases, written by the reviewer and not shown to the implementer:** 42 forms that change module state another way are reported. `main` reports 32 of them; the ten new ones are the forms above in several spellings, a `switch` with module state on one case, and a `try`. 12 fine forms are silent: reads, a function whose every `return` is a new object, a copy made by a static method. - **Two rounds.** The first version dropped a finding #143 reports: a part of handed-out state lent, `deepen(mut(getHidden().inner))`. Merging findings per call let the pass to `mut` itself take the call's slot. Fixed, and pinned in the fixture in three spellings. - **On an adopter's project (about 760 files):** output identical to `main`, entries and directories. - **Soundness corpus:** unchanged, 16 of 110 escape. - **Cost:** about 0.4 to 0.5% fewer instructions than `main` for a whole check of that project's largest entry (18.70 to 18.61 billion, one thread, callgrind, mean of two runs each; runs of one binary differ by up to 0.6%). The memo of hand-outs takes back part of what #143 added; it does not take back all of it. ## What turns red on upgrade Code that changes module state through one of the forms above. On the code measured, nothing. Created with Claude Opus 5.5 (implementation) and Claude Fable 5.2 (review and acceptance tests) in Claude Code.
What was open: `unreleased-resource` and `unbalanced-update` took no synchronous call to be a
way out, so an interval set before `check(n)` (a function that throws a PropagateError) and
cleared after it leaked whenever a caller caught the throw; and four sites read std's `q` by its
text, so `const v = ask(parse(n))` with `q as ask` returned the error early unseen.

What closes it:
- The flow layer takes the calls an analysis names (`flow::Calls`): std's `q` by its import, and
  calls that may throw. `unreleased-resource` solves again with those calls throwing for what the
  first solve left open, and lists them as candidates; `unbalanced-update` gets an `Ev::Raise`
  after each such call. The whole-program pass decides (`Project::call_can_throw`): a project
  function that lets a failure out synchronously (through a `Throwing` slot too), a built-in that
  throws (`throwing_builtins`), a library member a pack marks as throwing. A call it can't resolve
  doesn't throw: measured on an adopter (1,128 of 5,813 calls asked about, nearly all built-in
  methods on receivers of no known class) the other choice changes no finding there, on the
  examples or on the fixtures.
- `spelling::renamed_imports`: a SAFE-TS export imported under another name is read by the name it
  is exported as; fixes and messages keep the written name. The harness's new transformation
  `import-rename` found 205 sites across 42 rules before, 0 after (5 `text` lines where the tree as
  parsed reads less). `superseded-task-write` and `failure-contract` no longer read `Mut<` and
  `PropagateError` from the source text.

On an adopter (entries and directories, --idiomatic): no finding changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was open: `q` gives TypeScript the value, so `const n = q(parse(text))` with `parse`
returning `Result<number, "bad-number">`, in a function declaring `Result<number, "other">`,
passed tsc and `safe-ts check` (which only asked that the function return some Result); a
caller's exhaustive match over the declared error met one it had no arm for. Only `safe-ts emit`
followed by tsc found it.

What closes it: the file's analysis records, per `q(...)` in a function with a declared return
type, the call its Result comes from (in place, awaited, a `const` read once, a `?.` chain) or the
mapper's declared return type, and the function's own declared type (`LocalAnalysis::q_errors`;
`FnInfo::declared_return`, and `err_returned` for a function with no declared return type). The
whole-program pass resolves the call as every rule does, opens both sides to their error types
through aliases and promises (`written::result_error_of`) and compares what can be decided
without guessing (`written::atoms`, `written::fits`): literals, primitives, Enums and classes by
identity (a subclass fits), other named types by identity, the language's error classes by name.
Silent on type parameters, generics, object types written in place, a pack's safe version.

Soundness corpus: `q-passes-undeclared-error` escapes on the starting commit and is rejected now
(16 of 101 classes escape). On an adopter: 300 `q` sites, 155 with both sides compared, no
finding; the examples unchanged. Spelling harness: two sites by design (`inline-const` makes the
`q` one `q-position` refuses; a `const` returned hides an undeclared function's errors), one
`text` line for the release fix around a copied callee; messages of `brand-constructor` and
`must-use-result` name a std export as the file writes it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was open (review of adb8cbbf): a callee in another file of the project didn't answer
whether it throws: `check(n)` imported, `new Reader(3).guard(n)`, `reader.guard(n)` on a local
made with `new`. A call of a function imported from a project file is also listed among the
package calls, and `call_can_throw` returned that list's "nothing known" before asking the
project's function. And a callback a built-in runs right away (`ns.forEach((n) => check(n))`,
`ns.forEach(check)`) let its throw out unseen.

What closes it: the package answer counts only when a pack describes the member; otherwise the
project's function is resolved (every written form of the receiver: a parameter, `new` in place
or in a local, a field, a field of a parameter, an element, a call's result, a static method, a
namespace import, a re-export, a default export, all through the shared resolution). A call that
runs callbacks right away (the analyzer's `sync_callbacks`) carries the calls written in them,
and a function passed by name, as its own (`left_behind::run_now_calls`); the first that can
throw is named. Both rules, fixtures for each form.

Soundness corpus: `sync-throw-skips-release` and `sync-throw-skips-undo` escape on the starting
commit (its CLI and its native addon for oxlint) and are rejected now (16 of 103 escape). On an
adopter: no finding changes. Work guard: `memo_questions` +144 (the imported callees resolved),
allocations +0.5%; ceilings regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was open (review of 7b2d3f74's parent): with `import { q as ask }` and `import * as R` of
the same module in one file, `renamed_imports` made the first `q`, so the namespace member
`R.q` was no longer read as a name (a binding called `q` existed) and the leak past
`R.q(parse(n))` went silent, where the starting commit reported it. Findings also quoted the call
as `R(...)`.

What closes it: a namespace member of a SAFE-TS module that the file also imports by that name is
read as that binding (no import added), and a copy of it (`const take = R.q`) names that binding
too; messages quote the callee as written, dots included. The harness rewrites one site at a time
and can't write the two imports together: fixtures for it in `unreleased_resource` and
`q_undeclared_error`. Two by-design lines for `R?.q(...)` and `const RCopy1 = R; RCopy1.q(...)`,
which the transform doesn't rewrite (checked with `safe-ts emit`); `miss no-mutable-global
callee-const` closes as a side effect.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
q-undeclared-error reads std's helpers, safe versions, declared slots and mappers
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m50s
Tests / test (pull_request) Successful in 10m59s
622d764aab
What was open (review of adb8cbbf): the forms where the bug is most likely were silent.
`q(unsafe(...))` and `q(await unsafeAsync(...))` pass on `unknown`, `q(parseJson<T>(...))` a
`JsonError`, a pack's safe version an error object, `q(hooks.parse(text))` the error of a declared
function type, and a function with no declared return type with two returns gave nothing; most
mappers (by name, or an arrow written in place without a return type) weren't read.

What closes it: std's helpers by a table of their error types (`written::STD_ERRORS`), checked
against std's sources by a test so it can't drift; a pack's safe version as an error object of a
type not read (decided against literals and primitives only: the maps describe the failure, not
its type); a call through a declared function type by its contract's return type; an undeclared
function's errors from each `return` (a `const` read once followed, `.length` / `.size` a value);
a mapper by its declared return type, the function it names, or what an arrow written there
plainly returns; `unknown` passed on fits only `unknown`; std's types by name, installed or not.

On an adopter: 300 `q` sites, 238 compared (155 before), 5 findings, each a safe `fs` function's
error object passed on by a function declaring `Result<..., string>`: real, the declared type is
false for every caller. The rule's page says how far it reaches, by kind. Spelling harness: closes
`far q-undeclared-error hoist-const`, `new bounded-concurrency callee-const` and one `new
uncaught-propagation callee-const`; the new fixtures add sites of existing reasons, and two by-design
lines for `R?.q` and a copied namespace (not rewritten by the transform, checked with emit).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Borrowed data through a copy or a looser type: shallow copies share their parts, readonly dropped by an annotation
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m15s
Tests / test (pull_request) Successful in 10m31s
836835ff61
Two ways to change data that is not the function's to change passed every gate.

A shallow copy of a borrowed parameter (`{ ...order }`, `Object.assign({}, order)`, a rest, a
list with a spread among other elements, a copy a helper hands back) is a new object whose
parts are still the caller's. `no-param-mutation` followed only a list made of one spread. It
now follows the others: a change of a part through the copy is reported, and so is lending the
part. A whole copy lent to a `Mut` parameter is reported where the callee could write
something the copy still shares: a field the copy took, that something can be written through
as far as its type is written, that the callee's parameter type has, and that the callee
names (a function, a static method, or a method no override can replace).

TypeScript lets `readonly` be dropped by any annotation, so a frozen object can be handed
around as writable and a write to it throws when it runs. New rule `readonly-dropped` (error,
with a quick fix): a value whose written type has a `readonly` property given a place that
can write it, with types opened across files.

Soundness corpus: `shallow-copy-shares-object` and `spread-list-shares-elements` added and
closed. Contains the ways-out piece it was merged with: the rewrite list and the work
ceilings are those of the merged tree.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Open: q(...), match(...), parseJson<T>/validate<T> and arbitrary<T>() added the
std names they need (Err, mapErr, unreachable, the JSON and generator
runtimes) by appending ", X as __x" to the text of the import specifier they
found std in. That is right only inside a braced list: with std reached
through a namespace (`import * as R from ".../result"; R.q(...)`), the
specifier is the one spelling::normalize adds, written nowhere, at the end of
the namespace import, and the build wrote `import * as R from "...";, Err as
__qErr`, which doesn't parse.

Closed: each rewrite writes an import of its own (`ImportSite::import`) in
front of the declaration it found std in, on the same line; for a declaration
normalize added, in front of the namespace import it stands for. A test
transforms each shape (namespace with and without a semicolon, with a
mapper, match and parseJson and arbitrary through a namespace, a default and
braces, import type next to a value import, two imports of one module, an
inline type specifier, and with the prelude: no import, import type only,
empty brace lists, a namespace) and gives the programs to tsc, strict. The
other rewrites (enum constructors, loops, @inline, dev checks) add no import:
dev checks name __qErr, which q's rewrite imports. Expected outputs in
tests/transform.rs that pinned the appended names now pin the new statement.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: tsconfig.rs looked at noUncheckedIndexedAccess only, so a project with
"strict": false (or strictNullChecks, strictFunctionTypes, ... off on their
own) checked clean, while every one of those lets a program through tsc that
the rules assume tsc refuses.

Closed: tsconfig::flag_warnings, through extends and a solution file's
projects (one having the flag is enough, as for strict-lib): strict off is one
warning naming the members it leaves off (TypeScript 6+ turns strict on when
unset; the version is read from the typescript package installed above the
entry, and nothing is said when none is), a member off on its own is one
warning, and exactOptionalPropertyTypes, verbatimModuleSyntax and
erasableSyntaxOnly left off are one each. Each says what goes wrong. Computed
once per tsconfig (a directory's every file is an entry; the work guard saw
the repeated reads). tests/tsconfig_flags.rs shows each flag with a program
tsc accepts with it off and refuses with it on, which the checker reports
nothing in. Left out, with reasons on the docs page: skipLibCheck (a real
hole, but turning it off reports errors in third-party declarations),
noImplicitOverride (no rule finds an override by its keyword),
noFallthroughCasesInSwitch, noPropertyAccessFromIndexSignature, alwaysStrict.

The examples, the corpus's projects and the migration skill's template set
the two module flags; the corpus still has 16 of 105 classes escaping. The CLI
test's tsconfig gains the documented flags, and the resolution tests filter
every tsconfig flag warning, not only noUncheckedIndexedAccess's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: Object.getPrototypeOf, Reflect.construct of arguments that don't fit, a
property descriptor's value and Object.assign of four sources compiled with an
any under the documented setup, and no-hidden-any said nothing. Those four were
found by reading; nothing found the rest.

Closed: tests/lib_any.rs reads the declarations of the documented setup
(lib.esnext.full.d.ts and every lib it references; @types/node) with oxc and
lists each member with any where code receives it (a return, a property, a
callback's parameter, a type parameter defaulting to any), read with polarity
so an any a member only accepts isn't listed. Each must be retyped in
strict-lib, known to no-hidden-any (hidden_any::members), or listed in
tests/lib-any/allowed.txt with the reason; the test fails otherwise, and on a
stale line. 962 members: 26 retyped, 31 reported, 905 allowed.

strict-lib now retypes Object.getPrototypeOf / setPrototypeOf / Object(value),
Object.assign of four sources, Object.values / entries of a type without an
index, the descriptor methods (Object.getOwnPropertyDescriptor(s),
Reflect.getOwnPropertyDescriptor), Reflect.apply / construct, the JSON.stringify
replacer's values, the replace / replaceAll callback's captures and
PromiseLike.then's reason; strict-lib.check.ts proves each. no-hidden-any
reports PropertyDescriptor value/get, AbortSignal.reason, AggregateError.errors,
SuppressedError error/suppressed, Window.opener of annotated bindings and
window.opener (a type may have several such properties now).

std's json-tables.test.ts read Object.values of a union of tables as any: it
gives the table a record type now. Soundness corpus: lib-any-reaches-code, all
six programs escaping before, rejected by tsc now. On an adopter and the
examples: no finding changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: a regex with the g or y flag kept in a class field or a local and tested
again (in a method, a loop over other strings, a callback) starts where the
last match ended: test answers true, false, true for one text. Only a
module-level one was reported (no-mutable-global).

Closed: the rule regex-last-index (regex_state.rs, per file), an error. The
regex is known by how it is made (a literal, new RegExp(x, "g") with the flags
written) and kept (a const or let of a function, a parameter's default, a
class field or this.x assigned in the constructor, and a const copy of one).
Reported where nothing sets lastIndex between: a loop over a value it changes,
a callback on what it is given, a field's in a method, a second straight-line
call on another string. Not the idiom: a loop or callback reading one string
(walking its matches), a loop decided by the call and run to its end (it
leaves lastIndex at 0, so what runs it again starts afresh), matchAll,
replace, split, match, a regex made where it is used. Quick fix "Drop the `g`
flag: each test starts at the beginning" where test is every use of a literal
without y (meaning.rs runs it).

Measured: nothing on an adopter (both ways) and the examples; on the installed
packages' JavaScript with a local g regex used by test / exec (11 files), two
findings at first, both the idiom (a tokenizer closure, a substitution loop
adjusting lastIndex), taken as such now, so nothing. Soundness corpus:
regex-last-index-reused, escaping before (3 of 3) and rejected by this rule.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: new Date(n).toISOString() with n a number that may be NaN or out of
range, and d.toISOString() with d a parameter or a field, aren't reported
(DateState::Number and DateState::Unseen are skipped).

Measured on an adopter (about 760 files) and the examples, by where the date
comes from: 5 toISOString receivers and 3 Intl.DateTimeFormat format(date)
arguments not judged. 1 is Date.now() plus arithmetic (valid), 2 a number
parameter, 1 a number field, 1 a Date property; the arguments a parameter, a
destructured binding and a ?:. Every one is a time from a clock. A number
parsed from text is already reported (and number-parse-nan's); what is left
is who made the number or the date, which a brand could answer and a rule
reading the function can't. So no new report: docs/guide/builtins.md lists
the measurement and the members it covers (toISOString, toTemporalInstant,
the four format methods), the builtins fixture pins the silent forms, and the
soundness corpus gains date-from-unchecked-number, escaping (17 of 108 now).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The message named the regex where it is made (`this.digits`), also when the
call reads it through parentheses or a const copy; it quotes the receiver
the call writes now (`(re).test(...)`, `digitsCopy1.test(...)`), as other
rules do. The full rewrite harness lists the two transformations whose
message text differs from the fixture's, with the reason.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: verbatimModuleSyntax and erasableSyntaxOnly were warned about and added
to the documented setup. What they prevent is a module that fails to load
under Node's own type stripping, loudly and at once, never under Vite or Bun;
the other flags each let a wrong value through in silence. With
--deny-warnings they turned every project on the earlier documented setup
red, and the docs' own examples use parameter properties.

Closed: flag_warnings warns for strict, its members and
exactOptionalPropertyTypes only. The flags are out of adoption.md's setup and
table, the migration skill's template, examples/demo, examples/react and the
corpus project (which Node runs through the loader, but whose programs gave
the same results with and without them, and which keeps to the documented
setup). adoption.md's Node section recommends them for code Node runs itself,
and lists them among the flags not warned about, with why. On an adopter: no
setup warning about its tsconfigs now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: the property table (ANY_PROPERTIES) reported a read only on a binding
annotated with the type, so signals[0]?.reason, this.signal.reason (a field)
and ctl.signal.reason (the commonest way an AbortSignal's reason is read)
were silent, for the new entries and the old ones alike.

Closed: a read of a table property on a receiver the file can't tell the type
of is a pending read (hidden_any::PendingRead). analyze.rs asks the file's
shapes for the receiver (list.at(i) as an element of the list) and adds the
diagnostic with a TypeSite, Want::NoAnyProperty(property); the whole program
evaluates the shape to a global type (json_value's global_type: a type the
program doesn't declare, through `| undefined`, and a member of a global type
lib declares with one, hidden_any::GLOBAL_MEMBERS: AbortController#signal,
Request#signal), keeps the report naming lib's `Type.property`, and drops it
otherwise, so a project type with a field of that name stays silent. Forms
given: a parameter, a class field (declared or assigned in the constructor), a
getter, an element (index, at, for-of, a callback's), a const, a function's or
method's declared return type (across files), await, ?. and controller.signal.
Not given: narrowing by a test (status === "rejected", instanceof), a lib
function's return (AbortSignal.timeout), a package's value.

Fixtures: twelve reported forms and four silent twins. The rewrite ratchet
loses a miss (no-hidden-any inline-const). On an adopter: no finding changes
(its 174 .reason reads are of its own types).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The whole program's answer for a pending read (Want::NoAnyProperty) now names
the type where the annotated path does (`x.reason` is typed `any`
(`AbortSignal.reason`): ...), with the same help, so a spelling the
normaliser opens (a local alias, Readonly<T>) reads the same either way. The
full rewrite harness lists the one spelling whose message differs, a const
copy of the receiver, quoted as written. The fixture's second function named
`popped` is `poppedAll`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The pending reads asked shape.rs for their receivers in a walk of their own,
which cost +1.66% of a check on an adopter's largest entry (4,185 reads of
`state` off its own types, 811 `map.get(key)` calls). Now the sink sites'
shapes and these are found in one walk; a read that is a call's callee isn't
a pending read; and a name declared with a written type that isn't one of the
table's (`game: Mut<Game>`) is judged by the name, as an annotated binding is.
+0.58 to +0.84% over the reference now. A binding typed `AbortSignal |
undefined` is still followed (a fixture pins it).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A binding declared with a local alias of a union (`type Signal = AbortSignal |
undefined`, or a generic alias given AbortSignal) went silent: `unaliased`
follows only an alias whose body is a name, an array or a tuple, and the
written-type shortcut took the alias's name for a type of the program. Now
the shortcut leaves a binding typed with a top-level alias that may name a
table type (generic, or its body mentions one) to the whole program, and
`global_type` opens a union alias through its arguments (`written::open`),
with the one type lookup it already makes for the global check. The full
rewrite run lists nothing new for the rule; +0.60% instructions over the
reference on an adopter's largest entry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: `task.signal?.reason` with `signal: Option<AbortSignal>`, an
`Option<AbortSignal>` parameter after its check and an
`Option<AbortController>` field were silent, though the same written
`AbortSignal | undefined` were reported. Two causes, both needed: opening
aliases stops at std's own types (`written.rs` knows them by name), so the
evaluation got `Option<AbortSignal>` back unopened; and the written-type
shortcut took `Option<...>` for a type of the program.

Closed: `global_of` (json_value.rs) reads std's `Option<T>` (found in std, or
the prelude's global) as `T | undefined`, and an element of a list whose
element type is a union through the list's written type, flattening the
nested union `noUncheckedIndexedAccess` makes; the shortcut looks inside
`Option<...>` as inside `Mut<...>`. Fixtures: an Option property, parameter,
field and element, a list of `T | undefined`, `const [first] = e.errors`, with
std imported and (a new fixture directory) with the prelude; silent twins with
an Option of a project type. The two generic events are reported where their
type is written (a field's annotation too), which the rule page now says.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
no-hidden-any: an element of a list of unions read through the flattened union alone
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m17s
Tests / test (pull_request) Successful in 10m39s
ab7781add1
The element fallback added in the previous commit evaluated the list again
for every element read the first evaluation didn't settle (+0.25% on an
adopter's largest entry); with nested unions flattened, the evaluation's own
answer already gives `Option<AbortSignal>[]` and `(AbortSignal |
undefined)[]` elements, so it goes. A generic alias of such a list
(`type G<T> = readonly (T | undefined)[]`) isn't opened: the rewrite ratchet
lists it, with the reason.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: aliased-mut over time followed a loan to its await and asked where the function ended
normally only. A loan of the function's own Mut parameter still pending where a throw, a call that
throws, an await that rejects or another member of its Promise.all rejecting first leaves the
function outlived the call the same way as one left by a return, and its caller lent the object
again; docs/guide/flow.md listed it as the one analysis on the flow layer with that gap.

Closed: for each loan no normal way out reports (the parameter's, or a place outliving a method or
a listener), lent.rs solves the function again on a graph where an await may reject and its own
calls may throw (Options::awaits_throw, Calls::throwing; not std's calls, not a loan's holder),
with a fact per loan and point an exception may start from; an await of Promise.all keeps its
members' loans pending on the throw edge, through a const too. A throw, a yield or an await of
something not a call is reported as it is; a way out through calls goes to the whole-program pass
with them, which keeps it when one can fail (call_can_throw / awaited_can_fail, as for
unreleased-resource) and names it. The normal ways out keep the graph they came from.

Soundness corpus: async-loan-exception (three programs), escaping before, rejected now. On an
adopter, as is and migrated with `safe-ts migrate mut`: no new finding. The work guard's loans
(24 functions keeping a loan across an await that may reject) add 72 memo questions and up to 1%
allocations: ceilings regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: `{ onEvent: (a: Animal) => string }` lent as `Mut<{ onEvent: (d: Dog) => string }>` passed
every gate: TypeScript checks a function property one way, and Mut can't tell such a property
from a method (methods must be compared one way so subclasses lend). The callee installed a
handler needing a dog, the owner called it with any animal. docs/guide/state.md listed it as a
hole of Mut; the corpus class mut-function-field-replaced escaped.

Closed: the checker reads the syntax, which tells them apart. cache::Shape::Function now carries
the written signature (cache::Sig: each parameter's and the result's shape and span); each file
lists the values it lends (`mut(x)`, a Mut value passed on, a const holding either) with their
written type (readonly::Lend, from covariance.rs's value types), and each function's Mut
parameters keep the shape they lend (loans::Signature::lent_shapes). The whole-program pass,
where missing-mut already resolves the call, compares a writable function property of the
callee's type with the value's (readonly.rs, through aliases, interfaces, intersections and
Mut<...>, across files): a narrower parameter or a wider result is covariant-alias. A readonly
property, a method written as a method and a class's method aren't replaced through the loan;
what either side can't be read as is silent.

A rule of covariant-alias's: the hazard (a write through a differently typed writable view lands
where readers expect the other type) and the fix (readonly on the callee's side, or the same type)
are its own. Corpus: mut-function-field-replaced closed by this rule alone. On an adopter, as is
and migrated: nothing new. Work guard: +2 memo questions, +0.4% allocations (the lends each
file lists): ceilings regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: no-mutable-global followed a member of module state and a part kept in a local only. A
change through destructuring (`const { inner } = CONFIG; inner.depth = 9`), a loop or a callback
over a part, a list or an object made in the function holding the state, a shallow copy's shared
parts, or what a function hands back of it (`current().retries = 7`, the way most code reaches a
singleton) passed every gate, while the borrow rules answered the same questions for a parameter.

Closed with that machinery, not a second one: module state (a module's let / var / const, or an
import of another module's binding) is a root of no-param-mutation's reach() from a function
(Borrowed::module), so bind_reach, element callbacks, for...of, copies and calls follow it as
they follow a borrowed parameter, and the sites go through the same ParamSite decisions with the
rule no-mutable-global. A function's hand-out summary (borrow::HandsOut via part_in, decided
across files by handed_out) counts module state as a parameter (mutation::STATE), methods of
top-level classes too (Summary::state_methods); a call of a project function, a namespace's
function or a method of module state is asked whether it hands state back. Where the two could
not be joined: a `let` given another value later and a container made in the function lent
whole are not followed (both reported false findings on an adopter), nor a copy of a
namespace's function (the ratchet lists it).

Soundness corpus: module-state-reached (destructured, a getter, a list made of it), escaping
before, rejected now. On an adopter, as is and migrated: 2 new findings, both real by the rule's
definition (a benchmark's module-level table written through an element). Rewrite ratchet: the
destructure miss of no-mutable-global comes off; a callee-const miss is listed. Work guard: +0.1%
allocations, ceilings regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: the full mode of the rewrite harness (npm run test:rewrites) found what the fast mode
doesn't: aliased-mut took `const ready = Promise.resolve(); await ready` for an await that may
reject (a way out by an exception), and the new fixtures' spellings moved counts the ratchet
lists.

Closed: lent.rs asks Values what the awaited name stands for before deciding it can't reject.
The other lines are spellings the shared tree treats as it did before, each with its reason: an
alias of Mut<...> (plain or generic) isn't read as Mut, so a lend through it has no type for
covariant-alias to compare (the same cause unneeded-mut's line gives); Promise?.all isn't
Promise.all as parsed; a namespace name, a re-export, a copy of a name and parentheses are named
as written in the messages of no-mutable-global's new findings; the rest are the fixtures' own
counts of kinds already listed (missing-mut at a hoisted loan, prefer-option for an optional
parameter).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: three forms of module state handed out stayed silent. `Registry.all().push(x)`, where a
static method returns a static list (a class wasn't a root of module state, though
`Registry.items.push(x)` written out was reported); `const cfg = maybe(on); cfg.retries = 0`
with `maybe` returning the state on one side of a `?:`, where the call was asked only whether
it hands back the parameter `on`; and `const again = (): Config => getHidden(); again().x = 1`,
a helper of the calling function's own, which has no summary in the whole program.

Closed: a top-level class's static fields are module state (reach's module_root, borrow's
state_root); a primitive argument isn't asked about (it can't be handed back as an object); a
parameterless helper declared in the function (an arrow, a function expression or declaration
with one `return`) is read where it is called, its returned expression reached there.

Also in this commit, made before the piece was accepted as it stands: `handed_out` is
remembered per function and parameter in the pass (`Run::handed`; with module state counted as
a parameter, chains of functions returning each other's results were followed again for every
question); a package's function is not asked whether it hands back module state; and the
changes through what one call hands back are one finding, at the first, built only once.

Fixture state_reached gains the three forms and their silent twins (a copy from a static
method, a fresh object on the other branch, a helper building a new object).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Open: f1f35bc2 lost two findings 94ba6dba made: a part of what a call hands back of module
state, lent (`deepen(mut(getHidden().inner))`, also through `const cfg = getHidden()`). The cause
was its one-finding-per-call change: `mut(...)` also passes its argument to `mut` itself, a site
the pass keeps only if that callee declares the parameter `Mut`; it came first, took the call's
slot, and the loan site after it was skipped, so the call's only finding was dropped. And a
function handing back module state on one `return` of two (`if (shared) return getHidden();
return fresh();`) was taken to hand back nothing, as for a parameter's part, which must be handed
back on every path.

Closed: changes through one call's result are one site only where the pass decides them by the
call alone (an assignment, an update, a `delete`, a loan) and they change the same members; a
pass to a parameter and a method call neither take the slot nor are skipped. For module state a
function's summary keeps each `return` that hands it back with the calls it goes through
(borrow::StateOut, FnBorrow::hands_state, the methods' too), and the pass takes one that holds
(handed_out for mutation::STATE). The per-function memo of handed_out and the package filter are
unchanged.

Fixture state_reached pins both lends of a part, the whole lent, a method change and an
assignment through one call's result (both stand), and the form on one `return` with a twin
where every `return` is a new object.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merge main: the piece below has landed
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m33s
Tests / test (pull_request) Successful in 12m33s
d53cbefffa
Co-Authored-By: Claude Fable 5.2 <[email protected]>
sionzee deleted branch module-state-paths 2026-11-23 20:42:05 +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!144
No description provided.