exhaustive-dispatch, string-dispatch; exhaustive-switch on any closed set #91

Merged
sionzee merged 1 commit from closed-set-dispatch into main 2026-11-20 16:40:43 +01:00
Owner

Problem

A bug reached production in an adopter's game. Phase is codesOf(PHASES), a frozen object of numeric codes, not an Enum. The code dispatched on it with if/else and ?: chains (u.phase === Phase.WALK ? … : u.phase === Phase.RUN ? … : 0). A TEND phase landed together with its branch in rebasePhase. Two other chains (rescheduleAbility, an invariant's carryMax) quietly fell through to : 0 for it. Nothing reported this: exhaustive-switch only looked at switch (x.tag). If-chains, ternaries, literal unions (which the enums guide recommends for plain names) and code objects were never checked for completeness.

Feedback #6: on type El = { tag: string }, switch (e.tag) { case 'svg': … } got an exhaustive-switch error and a prefer-is-over-tag warning. The adopter had to rename the field.

Solution

This is the first of two stacked PRs: the rules. The second adds match on a string literal union.

  • exhaustive-dispatch (new, error). It reports an if / else if chain, a run of if (...) return ...;, or a ?: chain that tests two or more members of a closed set and doesn't handle the others, unless it ends in unreachable(x). A closed set is one of:

    • an enum's tag (x.tag === "A", and is(x, "A"));
    • a union of string or number literals;
    • the constants of an as const / frozen code object, including a codesOf(...) table.

    The set comes from the value's declared type. When the value is typed number (the adopter's carryMax case), it comes from the one object every tested constant is read from. It also covers a switch on a number whose cases are such constants, where unreachable(x) can't compile.

    • What counts as a dispatch: two or more branches, each testing members of one value with === / == (a || b in one branch counts as one branch). One test with an else is not a dispatch: there the others really are "everything else" (is, _), as the guide's "Which one?" paragraph says. Any other test in the chain (x === A && ready, !==, a variable) means it isn't a dispatch.
    • The final else itself doesn't matter. A neutral default, a computed value and no else at all each hide the member added later.
  • exhaustive-switch now covers a switch on any closed set, by its declared type (a literal union, a code type such as (typeof Phase)[keyof typeof Phase]), not only .tag. The message names the members without a case. A switch (x.tag) whose type can't be found is reported as before. A .tag typed as plain string is skipped, and so is prefer-is-over-tag on it, through a new Want::PlainString type site.

  • string-dispatch (new, idiomatic). It reports one plain string compared with three or more distinct literals in one function (ifs, ||, switch cases).

    • Not counted: "", literals with no letter in them, and typeof x === "...".
    • Not reported in a function declared to return a literal union, an Enum, or an Option / Result / Promise of one. That function is the boundary parser.
    • The message says: parse once into a closed type (a table, aliases included), then dispatch on it.
    • The motivating dev-launcher code is a test fixture.

How it works: dispatch.rs collects the sites per file: the subject's Shape, and each tested value as a TypeExpr ("open", typeof Phase.WALK). The whole-program pass answers them with the JSON type model. The new functions are json::value::closed, literal, codes and names_closed_set, so types and code objects declared in other files count. exhaustive-switch moved out of analyze.rs into the same module, and keeps its quick fix.

False positives, measured on this repo

  • Fixtures (every fixture directory, which fail on any unexpected finding): no new findings outside the two new fixtures.

  • Docs and skill code blocks (728 checked blocks): 4 new findings, each a real instance of the pattern. I changed the blocks:

    • guide/adoption.md union-to-enum, before and after: progress tested 2 kinds of 4 and left the rest to the last branch. Since the block must be the codemod's exact output, the example is now a one-test reason().
    • guide/json.md: switch (problem.kind) handled 2 of 6 kinds plus a default. All kinds are now listed, with default: unreachable(...).
    • The skill's patterns-core.md "A closed set of states": the "bad" block now names exhaustive-dispatch.
  • Examples (examples/demo, vue, react, with --idiomatic): 0 new findings.

  • Package and script sources (67 files, most are // @safe-ts std and not checked): 3 exhaustive-dispatch findings in packages/pack-kit/generate.ts. All 3 are the "last member as the else" shape:

    • kind === "method" ? … : kind === "new" ? … : kind === "static" ? … : <function>
    • option === "value" ? … : option === "promise" ? … : []

    That is the same bug shape as the adopter's, so I count them as intended. string-dispatch first flagged a bracket scanner there (c === "(", "[", "{"). That's why literals without a letter don't count; it's quiet now.

  • The other dispatch criterion I tried: "one test plus a neutral default". It matched 3 sites in generate.ts and 1 in the fixture (kind === "static" ? "static " : "", x === A ? true : false). All 4 are one-member tests, not dispatches. So the rule requires two branches.

Tests

  • cargo nextest run -p safe_ts_core: 254 passed. New fixtures:
    • closed_set_dispatch: the adopter's codesOf code set, with rebasePhase / rescheduleAbility / carryMax, a number-typed field, a switch on the set, enums, is chains, literal unions, typeof chains, and { tag: string }.
    • string_dispatch (idiomatic): the dev launcher, a switch, a parser returning Option<Command>, "", punctuation, and a .tag: string that gets neither rule.
  • cargo test -p safe_ts_core --test docs and --test migrate: pass.
  • npm run test:std: 367 passed. node scripts/docs-typecheck.mjs: 617 examples compile. npm run build -w docs: builds.

Docs

  • New pages rules/exhaustive-dispatch.md and rules/string-dispatch.md.
  • exhaustive-switch.md: covers any closed set, with a literal-union example and a "What counts" section.
  • guide/enums.md: the tip, "Which one?", the switch section, and a new "A dispatch on a union or a code object" section.
  • Rule tables in README, docs/README.md and adoption.md, the sidebar, and CHANGELOG.
  • Skill: patterns-core.md "A closed set of states" (numeric code sets, strings parsed once), the string-if-chain row in census.md, final-pass.md and tool-gaps.md.

Left out

  • match on a string literal union: the stacked follow-up PR.
  • skills/safe-ts-migrate/scripts/census.mjs is unchanged (another lane edits it). Its rule-to-anchor map (~line 235) could add exhaustive-dispatch / string-dispatch → patterns-core.md#a-closed-set-of-states.
  • Vue template v-if chains stay with vue-exhaustive-v-if (enum tags only).
  • x !== A chains, [A, B].includes(x) and comparisons with variables are not read as dispatches.

Created with Claude Opus 5.5 in Claude Code.

## Problem A bug reached production in an adopter's game. `Phase` is `codesOf(PHASES)`, a frozen object of numeric codes, not an `Enum`. The code dispatched on it with if/else and `?:` chains (`u.phase === Phase.WALK ? … : u.phase === Phase.RUN ? … : 0`). A `TEND` phase landed together with its branch in `rebasePhase`. Two other chains (`rescheduleAbility`, an invariant's `carryMax`) quietly fell through to `: 0` for it. Nothing reported this: `exhaustive-switch` only looked at `switch (x.tag)`. If-chains, ternaries, literal unions (which the enums guide recommends for plain names) and code objects were never checked for completeness. Feedback #6: on `type El = { tag: string }`, `switch (e.tag) { case 'svg': … }` got an `exhaustive-switch` error and a `prefer-is-over-tag` warning. The adopter had to rename the field. ## Solution This is the first of two stacked PRs: the rules. The second adds `match` on a string literal union. - **`exhaustive-dispatch`** (new, error). It reports an `if` / `else if` chain, a run of `if (...) return ...;`, or a `?:` chain that tests **two or more members** of a closed set and doesn't handle the others, unless it ends in `unreachable(x)`. A closed set is one of: - an enum's tag (`x.tag === "A"`, and `is(x, "A")`); - a union of string or number literals; - the constants of an `as const` / frozen code object, including a `codesOf(...)` table. The set comes from the value's declared type. When the value is typed `number` (the adopter's `carryMax` case), it comes from the one object every tested constant is read from. It also covers a `switch` on a `number` whose cases are such constants, where `unreachable(x)` can't compile. - **What counts as a dispatch:** two or more branches, each testing members of one value with `===` / `==` (`a || b` in one branch counts as one branch). One test with an `else` is not a dispatch: there the others really are "everything else" (`is`, `_`), as the guide's "Which one?" paragraph says. Any other test in the chain (`x === A && ready`, `!==`, a variable) means it isn't a dispatch. - The final `else` itself doesn't matter. A neutral default, a computed value and no `else` at all each hide the member added later. - **`exhaustive-switch`** now covers a `switch` on any closed set, by its declared type (a literal union, a code type such as `(typeof Phase)[keyof typeof Phase]`), not only `.tag`. The message names the members without a `case`. A `switch (x.tag)` whose type can't be found is reported as before. **A `.tag` typed as plain `string` is skipped**, and so is `prefer-is-over-tag` on it, through a new `Want::PlainString` type site. - **`string-dispatch`** (new, idiomatic). It reports one plain `string` compared with three or more distinct literals in one function (`if`s, `||`, `switch` cases). - Not counted: `""`, literals with no letter in them, and `typeof x === "..."`. - Not reported in a function declared to return a literal union, an `Enum`, or an `Option` / `Result` / `Promise` of one. That function is the boundary parser. - The message says: parse once into a closed type (a table, aliases included), then dispatch on it. - The motivating dev-launcher code is a test fixture. How it works: `dispatch.rs` collects the sites per file: the subject's `Shape`, and each tested value as a `TypeExpr` (`"open"`, `typeof Phase.WALK`). The whole-program pass answers them with the JSON type model. The new functions are `json::value::closed`, `literal`, `codes` and `names_closed_set`, so types and code objects declared in other files count. `exhaustive-switch` moved out of `analyze.rs` into the same module, and keeps its quick fix. ### False positives, measured on this repo - **Fixtures** (every fixture directory, which fail on any unexpected finding): no new findings outside the two new fixtures. - **Docs and skill code blocks** (728 checked blocks): 4 new findings, each a real instance of the pattern. I changed the blocks: - `guide/adoption.md` `union-to-enum`, before and after: `progress` tested 2 kinds of 4 and left the rest to the last branch. Since the block must be the codemod's exact output, the example is now a one-test `reason()`. - `guide/json.md`: `switch (problem.kind)` handled 2 of 6 kinds plus a `default`. All kinds are now listed, with `default: unreachable(...)`. - The skill's `patterns-core.md` "A closed set of states": the "bad" block now names `exhaustive-dispatch`. - **Examples** (`examples/demo`, `vue`, `react`, with `--idiomatic`): 0 new findings. - **Package and script sources** (67 files, most are `// @safe-ts std` and not checked): 3 `exhaustive-dispatch` findings in `packages/pack-kit/generate.ts`. All 3 are the "last member as the `else`" shape: - `kind === "method" ? … : kind === "new" ? … : kind === "static" ? … : <function>` - `option === "value" ? … : option === "promise" ? … : []` That is the same bug shape as the adopter's, so I count them as intended. `string-dispatch` first flagged a bracket scanner there (`c === "("`, `"["`, `"{"`). That's why literals without a letter don't count; it's quiet now. - **The other dispatch criterion I tried:** "one test plus a neutral default". It matched 3 sites in `generate.ts` and 1 in the fixture (`kind === "static" ? "static " : ""`, `x === A ? true : false`). All 4 are one-member tests, not dispatches. So the rule requires two branches. ## Tests - `cargo nextest run -p safe_ts_core`: 254 passed. New fixtures: - `closed_set_dispatch`: the adopter's `codesOf` code set, with `rebasePhase` / `rescheduleAbility` / `carryMax`, a `number`-typed field, a switch on the set, enums, `is` chains, literal unions, `typeof` chains, and `{ tag: string }`. - `string_dispatch` (idiomatic): the dev launcher, a `switch`, a parser returning `Option<Command>`, `""`, punctuation, and a `.tag: string` that gets neither rule. - `cargo test -p safe_ts_core --test docs` and `--test migrate`: pass. - `npm run test:std`: 367 passed. `node scripts/docs-typecheck.mjs`: 617 examples compile. `npm run build -w docs`: builds. ## Docs - New pages `rules/exhaustive-dispatch.md` and `rules/string-dispatch.md`. - `exhaustive-switch.md`: covers any closed set, with a literal-union example and a "What counts" section. - `guide/enums.md`: the tip, "Which one?", the `switch` section, and a new "A dispatch on a union or a code object" section. - Rule tables in README, `docs/README.md` and `adoption.md`, the sidebar, and CHANGELOG. - Skill: `patterns-core.md` "A closed set of states" (numeric code sets, strings parsed once), the `string-if-chain` row in `census.md`, `final-pass.md` and `tool-gaps.md`. ## Left out - `match` on a string literal union: the stacked follow-up PR. - `skills/safe-ts-migrate/scripts/census.mjs` is unchanged (another lane edits it). Its rule-to-anchor map (~line 235) could add `exhaustive-dispatch` / `string-dispatch` → `patterns-core.md#a-closed-set-of-states`. - Vue template `v-if` chains stay with `vue-exhaustive-v-if` (enum tags only). - `x !== A` chains, `[A, B].includes(x)` and comparisons with variables are not read as dispatches. Created with Claude Opus 5.5 in Claude Code.
exhaustive-dispatch, string-dispatch; exhaustive-switch on any closed set
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m47s
1460bd3f4a
A dispatch on a closed set by hand (an if/else chain, a run of `if (...) return`, a `?:`
chain) handled the members it named and left the rest to its last branch. A phase added
to an adopter's code set (`codesOf(...)`, numeric codes) got its branch in one chain and
fell through to `: 0` in two others, and nothing reported it: exhaustive-switch only
looked at `switch (x.tag)`.

- exhaustive-dispatch (error): a chain that tests two or more members of a closed set
  (an Enum tag, also through `is`; a union of string or number literals; the constants
  of an `as const` / frozen code object) must handle every member or end in
  `unreachable(x)`. The set comes from the value's declared type, or from the object
  every tested constant is read from when the value is a plain number. One test with an
  else is not a dispatch.
- exhaustive-switch covers a switch on any closed set by its declared type, names the
  members without a case, and skips a `.tag` typed as a plain string (so does
  prefer-is-over-tag).
- string-dispatch (idiomatic): one plain string compared with three or more words in a
  function; not in a function declared to return a closed set (the parser).

The sites are collected per file (dispatch.rs) and answered in the whole-program pass
with the JSON type model (json::value::closed / literal / codes).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee force-pushed closed-set-dispatch from 1460bd3f4a
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m47s
to 58b488e43d
Some checks failed
Benchmarks / bench (pull_request) Failing after 1m10s
2026-11-20 16:37:49 +01:00
Compare
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!91
No description provided.