Code nothing refers to, branches already decided, event names that match at neither end: five rules from the whole program #130

Merged
sionzee merged 131 commits from whole-program-reach into main 2026-11-22 17:33:00 +01:00
Owner

Based on sinks-and-brands (#129), and contains it and #128: the diff shown is this piece alone.

Some defects are in no single file. An agent that writes a new function rarely deletes the old one; a listener waits for a name the other end stopped emitting; a branch stays behind after its case was handled. Each of these passed tsc strict, safe-ts check --deny-warnings and oxlint with the preset:

export function discount(n: number): number { return roundDown(n * 0.9); }   // nobody imports it
function roundDown(n: number): number { return Math.floor(n); }               // used only by `discount`

bus.on("item-added", refresh);        bus.emit("itemAdded", item);            // never heard, nothing fails
button.addEventListener("clik", save);                                        // not an event of the element
server.on("lisening", ready);                                                 // not an event of a Server

if (shape.kind === "circle") { ... } else if (shape.kind === "square") { ... } else { fallback(); }   // every member handled
panic("unsupported"); cleanup();                                              // never runs

Five rules

Rule Level Reports
unused-code idiomatic, warning a function, class, type, interface, constant or enum nothing used refers to: an export no file of the program imports and the program does not offer outside, or a declaration only such code uses
unused-private idiomatic, warning a private or # member nothing in its class uses, a private field written and never read, a private member read only by unused private members
unreachable-code error statements after a call that never returns (panic, unreachable, process.exit(), a function declared never, imported ones too); a branch the subject's closed type has already decided, also after typeof, instanceof, === undefined, Array.isArray and in tests that take every kind the written type has
unknown-event error a listener for a name its platform class never dispatches and nothing in the program does
unmatched-event error a listener for a name nothing emits on that emitter, and an emit nobody listens for; a near miss between the two ends is named at both sites

What counts as used is what a file's module code refers to, and every export the outside can reach: an entry named on the command line, a file nothing imports, one loaded by import(), a worker or import.meta.glob, what a package.json's main / exports / bin name, tool config files, Vue components, and what a test or script of the same package imports. It stands on a per-file index of resolved references (from oxc's scope analysis) joined once in the whole-program pass. safe-ts fix unused-code <dirs> deletes what nothing refers to at all; run it again for what a deletion leaves.

Event names are data. The browser pack lists lib.dom.d.ts's event maps and the Node pack @types/node's, each checked against the installed version by a test. An emitter of the program's own (a module-level one, a class extending EventEmitter or EventTarget, a field holding one) is matched end to end; the listener side is reported only where nothing outside the program can emit on it.

The oxlint preset now names what one file shows of dead code (no-unused-vars, no-unreachable, no-constant-condition, no-duplicate-case, no-dupe-else-if): they were on only through oxlint's default category, so a project that set its own categories lost them without a word.

Evidence

  • Held-out cases (a project of my own, kept from the implementer): 25 expected findings, all reported, nothing else. Unused exports behind a barrel and a namespace import; a helper used only by dead code; an export kept alive by a test; # and private members; a listener on an emitter nothing else can reach against one that is handed out; typeof / instanceof / === undefined chains with a dead fallback; misspelt Node event names on a Server, a stream and process. The first round missed the listener side, # members, type tests and Node's events; all four were added.
  • An adopter's project: 58 unused-code findings checking its directories (46 from its entries) and one unused-private, every one read and dead: copies of functions a shared package had taken over, constants and helpers nothing calls any more, and the chains only those used. unreachable-code, unknown-event and unmatched-event: none, with 62 listeners on Node objects checked. No count of any other rule changes there or on the three example projects (the demo gains 4 unused-code, all real).
  • Soundness corpus: one class added and closed (a listener and an emit that disagree on the name). 2 of 74 escape.
  • Cost on that project's largest entry (minimum of 18 interleaved runs, both binaries built the same way): the whole-program pass goes from 497 ms to 531 ms with unused-code on, of which about 30 ms is the reference index and a scan of 175 files around the program; with the rule off, 5 ms. These are the implementer's numbers; my own rerun was on a loaded machine and showed no difference outside its noise. The scan runs only when the rule is on for some file, parses each file once per content, and has a ceiling in the work-count test (outside_files_parsed).

What turns red on upgrade

  • unreachable-code, unknown-event and unmatched-event are errors. Write unreachable(x) for a fallback after every member of a closed type; delete code after panic(...); use one constant for an event name at both ends.
  • Four of the five oxlint rules above are errors where they were warnings; no-unused-vars stays a warning.
  • With idiomatic rules on, unused-code and unused-private add warnings; the baseline holds their count.

What stays unseen

  • unused-code: importers outside the program and its packages; a name looked up at run time (window[name], a route table built from strings); templates other than Vue's; public and protected class members, Enum members nothing constructs, parameters no caller passes.
  • unreachable-code: an imported never function called in both branches of an if; a function that never returns without being declared never; narrowing that happened before the chain.
  • unknown-event: a receiver whose class is not written down; other libraries' emitters, which have no event list. Found after filing: the receiver's class is read only where it is a parameter or a local typed with the class. A loop variable over a typed list, an element taken by index, a destructured parameter, a field of this and a callback's parameter get no class yet, so a misspelt name there is not reported (1 of 10 written forms in a probe of mine). Nothing is reported wrongly; the fix, through the receiver resolution the call rules already use, is in the piece stacked above this one.
  • unmatched-event: an emitter passed around untyped or kept in a collection; once(emitter, name) from node:events.

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

Based on `sinks-and-brands` (#129), and contains it and #128: the diff shown is this piece alone. Some defects are in no single file. An agent that writes a new function rarely deletes the old one; a listener waits for a name the other end stopped emitting; a branch stays behind after its case was handled. Each of these passed `tsc` strict, `safe-ts check --deny-warnings` and oxlint with the preset: ```ts export function discount(n: number): number { return roundDown(n * 0.9); } // nobody imports it function roundDown(n: number): number { return Math.floor(n); } // used only by `discount` bus.on("item-added", refresh); bus.emit("itemAdded", item); // never heard, nothing fails button.addEventListener("clik", save); // not an event of the element server.on("lisening", ready); // not an event of a Server if (shape.kind === "circle") { ... } else if (shape.kind === "square") { ... } else { fallback(); } // every member handled panic("unsupported"); cleanup(); // never runs ``` ## Five rules | Rule | Level | Reports | |---|---|---| | `unused-code` | idiomatic, warning | a function, class, type, interface, constant or enum nothing used refers to: an export no file of the program imports and the program does not offer outside, or a declaration only such code uses | | `unused-private` | idiomatic, warning | a `private` or `#` member nothing in its class uses, a private field written and never read, a private member read only by unused private members | | `unreachable-code` | error | statements after a call that never returns (`panic`, `unreachable`, `process.exit()`, a function declared `never`, imported ones too); a branch the subject's closed type has already decided, also after `typeof`, `instanceof`, `=== undefined`, `Array.isArray` and `in` tests that take every kind the written type has | | `unknown-event` | error | a listener for a name its platform class never dispatches and nothing in the program does | | `unmatched-event` | error | a listener for a name nothing emits on that emitter, and an emit nobody listens for; a near miss between the two ends is named at both sites | **What counts as used** is what a file's module code refers to, and every export the outside can reach: an entry named on the command line, a file nothing imports, one loaded by `import()`, a worker or `import.meta.glob`, what a package.json's `main` / `exports` / `bin` name, tool config files, Vue components, and what a test or script of the same package imports. It stands on a per-file index of resolved references (from oxc's scope analysis) joined once in the whole-program pass. `safe-ts fix unused-code <dirs>` deletes what nothing refers to at all; run it again for what a deletion leaves. **Event names are data.** The browser pack lists `lib.dom.d.ts`'s event maps and the Node pack `@types/node`'s, each checked against the installed version by a test. An emitter of the program's own (a module-level one, a class extending `EventEmitter` or `EventTarget`, a field holding one) is matched end to end; the listener side is reported only where nothing outside the program can emit on it. **The oxlint preset now names what one file shows of dead code** (`no-unused-vars`, `no-unreachable`, `no-constant-condition`, `no-duplicate-case`, `no-dupe-else-if`): they were on only through oxlint's default category, so a project that set its own categories lost them without a word. ## Evidence - **Held-out cases** (a project of my own, kept from the implementer): 25 expected findings, all reported, nothing else. Unused exports behind a barrel and a namespace import; a helper used only by dead code; an export kept alive by a test; `#` and `private` members; a listener on an emitter nothing else can reach against one that is handed out; `typeof` / `instanceof` / `=== undefined` chains with a dead fallback; misspelt Node event names on a `Server`, a stream and `process`. The first round missed the listener side, `#` members, type tests and Node's events; all four were added. - **An adopter's project:** 58 `unused-code` findings checking its directories (46 from its entries) and one `unused-private`, every one read and dead: copies of functions a shared package had taken over, constants and helpers nothing calls any more, and the chains only those used. `unreachable-code`, `unknown-event` and `unmatched-event`: none, with 62 listeners on Node objects checked. No count of any other rule changes there or on the three example projects (the demo gains 4 `unused-code`, all real). - **Soundness corpus:** one class added and closed (a listener and an emit that disagree on the name). 2 of 74 escape. - **Cost on that project's largest entry** (minimum of 18 interleaved runs, both binaries built the same way): the whole-program pass goes from 497 ms to 531 ms with `unused-code` on, of which about 30 ms is the reference index and a scan of 175 files around the program; with the rule off, 5 ms. These are the implementer's numbers; my own rerun was on a loaded machine and showed no difference outside its noise. The scan runs only when the rule is on for some file, parses each file once per content, and has a ceiling in the work-count test (`outside_files_parsed`). ## What turns red on upgrade - `unreachable-code`, `unknown-event` and `unmatched-event` are errors. Write `unreachable(x)` for a fallback after every member of a closed type; delete code after `panic(...)`; use one constant for an event name at both ends. - Four of the five oxlint rules above are errors where they were warnings; `no-unused-vars` stays a warning. - With idiomatic rules on, `unused-code` and `unused-private` add warnings; the baseline holds their count. ## What stays unseen - `unused-code`: importers outside the program and its packages; a name looked up at run time (`window[name]`, a route table built from strings); templates other than Vue's; public and `protected` class members, `Enum` members nothing constructs, parameters no caller passes. - `unreachable-code`: an imported `never` function called in both branches of an `if`; a function that never returns without being declared `never`; narrowing that happened before the chain. - `unknown-event`: a receiver whose class is not written down; other libraries' emitters, which have no event list. **Found after filing:** the receiver's class is read only where it is a parameter or a local typed with the class. A loop variable over a typed list, an element taken by index, a destructured parameter, a field of `this` and a callback's parameter get no class yet, so a misspelt name there is not reported (1 of 10 written forms in a probe of mine). Nothing is reported wrongly; the fix, through the receiver resolution the call rules already use, is in the piece stacked above this one. - `unmatched-event`: an emitter passed around untyped or kept in a collection; `once(emitter, name)` from `node:events`. Created with Claude Opus 5.5 (implementation and the merge) and Claude Fable 5.2 (review and acceptance tests) in Claude Code.
What was open: `safe-ts check` sees the whole program but never asked who uses
what. An export nobody imports (and the helpers only it calls), a private
member nothing reads, a fallback after every member of a closed type is
handled, code after `panic()`, and an event listened for under one name and
emitted under another all passed tsc strict, `check --idiomatic
--deny-warnings` and oxlint.

What closes it:
- A reference index per file (reach.rs, cached with the summary): every
  resolved reference of a top-level symbol from oxc's scope analysis, by the
  declaration it is written in. The whole-program pass joins the files once
  through their imports and walks from module code and from what the outside
  can use (named entries, files nothing imports, import()/worker/glob loads,
  package.json main/types/exports/bin, config files, Vue components; imports of
  same-package files the run doesn't reach). `unused-code` (idiomatic, warning,
  check only) reports the rest; its delete fix is applied in bulk by
  `safe-ts fix unused-code <dirs>`, which now runs the whole program for
  PROGRAM_RULES.
- `unused-private` (idiomatic, warning, both paths): private / # members
  nothing uses, written-never-read fields, members only unused privates read.
- `unreachable-code` (error, both paths): statements after a call that never
  returns, on the flow layer (Graph::reachable_starts with a cut), and the rest
  of a dispatch whose tests handle every member of an exactly closed type.
- `unknown-event` / `unmatched-event` (errors, check only): DOM listeners for a
  name the class doesn't dispatch (browser pack: lib.dom event maps, new
  `events` section with a manifest test), and listeners/emits with no other end
  on the same emitter (module-level or local instance, emitter class, emitter
  field, the DOM), near misses named at both sites.
- Soundness corpus: new class event-name-mismatch, escaping at the start
  commit, rejected now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What was open after the first round:
- unmatched-event was quiet on the listener side whenever any other site,
  on any emitter, used the name, or any site anywhere computed one; a near
  miss was looked for only among unmatched names.
- unused-private left `#` members to oxlint.
- unreachable-code decided only literal dispatches, not typeof / instanceof /
  undefined / Array.isArray / in.
- no-unused-vars and no-unreachable were on only through oxlint's default
  category, so a project setting its own lost them unseen.
- unused-code built its index and scanned the files around the program on
  every run, rule on or off.
- Node's emitters had no event list.

What closes it:
- Emitters handed to code the checker can't see (a binding or local passed,
  returned or stored, here or in an importer; a field read as a value
  anywhere; exported to the outside unless private) stay silent at both
  ends; others are judged on their own sites only (a class's instances still
  count sites nothing keys). Near misses against every name the other end
  uses.
- `#` and static private members reported like `private` ones.
- Type-test chains (KindSite in dispatch.rs, json_value::type_kinds,
  TypeLookup::class_chain) report the rest when the tests take every kind
  the written type has.
- The preset names no-unused-vars (warn), no-unreachable,
  no-constant-condition, no-duplicate-case, no-dupe-else-if (errors), with a
  test that fails if one is missing; turning one off is a weakened setting.
- The index and the scan run only where unused-code is on; the scan keeps
  each file's imports by content in the Project; CheckReport counts the files
  parsed and reused (tests/reach_work.rs).
- Node pack: events from @types/node's event maps (test/events.ts, manifest
  test), with `creates` for what module functions return; unknown-event
  checks Node objects the source names.
- Corpus: two more event-name-mismatch variants (two emitters; a near miss
  by `once`), escaping at the start commit, rejected now.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts resolved by keeping both sides: the API maps carry events, sinks and acquires (both
safe-ts.json regenerated by their generators), the preset, RULES / PROGRAM_RULES /
IDIOMATIC_RULES, Run's fields, TypeLookup (their Arc<TypeDecl>, my class_chain), json_value
(their names(), my closed_exactly and type_kinds), meaning.rs's WRITTEN, the sidebar, README's
known gaps, the CHANGELOG by section, flow.md (their table gets an unreachable-code row, my
section sits before "What it costs"), the corpus index.

The reference index is renamed from `reach` to `references` (references.rs,
project/references.rs, LocalAnalysis::references): `reach` is the sink piece's word for what
outside input reaches (`sinks::Reach`, `Run::reach`). unused-code's scan is counted in
tests/work.rs (outside_files_parsed: 24 from the entry, 0 as a directory; no other count moved);
reach_work.rs becomes unused_code_work.rs. The sinks fixture's helper files turn unused-code off
(as the nine fixtures before); event_names hands its worker a constant URL instead of a
parameter (code-sink).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
After the merge: platform events worked out once per class in a pass; path-sink in the list of program-only rules
All checks were successful
Benchmarks / bench (pull_request) Successful in 3m17s
Tests / test (pull_request) Successful in 10m42s
4a4ec70f0e
Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee changed target branch from sinks-and-brands to main 2026-11-22 17:32:23 +01:00
Merge main: the piece below has landed
Some checks failed
Benchmarks / bench (pull_request) Failing after 3s
Tests / test (pull_request) Has been cancelled
6bcfe15061
Co-Authored-By: Claude Fable 5.2 <[email protected]>
sionzee deleted branch whole-program-reach 2026-11-22 17:33:00 +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!130
No description provided.