exhaustive-dispatch, string-dispatch; exhaustive-switch on any closed set #91
Loading…
Reference in a new issue
No description provided.
Delete branch "closed-set-dispatch"
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?
Problem
A bug reached production in an adopter's game.
PhaseiscodesOf(PHASES), a frozen object of numeric codes, not anEnum. The code dispatched on it with if/else and?:chains (u.phase === Phase.WALK ? … : u.phase === Phase.RUN ? … : 0). ATENDphase landed together with its branch inrebasePhase. Two other chains (rescheduleAbility, an invariant'scarryMax) quietly fell through to: 0for it. Nothing reported this:exhaustive-switchonly looked atswitch (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 anexhaustive-switcherror and aprefer-is-over-tagwarning. The adopter had to rename the field.Solution
This is the first of two stacked PRs: the rules. The second adds
matchon a string literal union.exhaustive-dispatch(new, error). It reports anif/else ifchain, a run ofif (...) return ...;, or a?:chain that tests two or more members of a closed set and doesn't handle the others, unless it ends inunreachable(x). A closed set is one of:x.tag === "A", andis(x, "A"));as const/ frozen code object, including acodesOf(...)table.The set comes from the value's declared type. When the value is typed
number(the adopter'scarryMaxcase), it comes from the one object every tested constant is read from. It also covers aswitchon anumberwhose cases are such constants, whereunreachable(x)can't compile.===/==(a || bin one branch counts as one branch). One test with anelseis 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.elseitself doesn't matter. A neutral default, a computed value and noelseat all each hide the member added later.exhaustive-switchnow covers aswitchon 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 acase. Aswitch (x.tag)whose type can't be found is reported as before. A.tagtyped as plainstringis skipped, and so isprefer-is-over-tagon it, through a newWant::PlainStringtype site.string-dispatch(new, idiomatic). It reports one plainstringcompared with three or more distinct literals in one function (ifs,||,switchcases)."", literals with no letter in them, andtypeof x === "...".Enum, or anOption/Result/Promiseof one. That function is the boundary parser.How it works:
dispatch.rscollects the sites per file: the subject'sShape, and each tested value as aTypeExpr("open",typeof Phase.WALK). The whole-program pass answers them with the JSON type model. The new functions arejson::value::closed,literal,codesandnames_closed_set, so types and code objects declared in other files count.exhaustive-switchmoved out ofanalyze.rsinto 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.mdunion-to-enum, before and after:progresstested 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-testreason().guide/json.md:switch (problem.kind)handled 2 of 6 kinds plus adefault. All kinds are now listed, withdefault: unreachable(...).patterns-core.md"A closed set of states": the "bad" block now namesexhaustive-dispatch.Examples (
examples/demo,vue,react, with--idiomatic): 0 new findings.Package and script sources (67 files, most are
// @safe-ts stdand not checked): 3exhaustive-dispatchfindings inpackages/pack-kit/generate.ts. All 3 are the "last member as theelse" 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-dispatchfirst 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.tsand 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'scodesOfcode set, withrebasePhase/rescheduleAbility/carryMax, anumber-typed field, a switch on the set, enums,ischains, literal unions,typeofchains, and{ tag: string }.string_dispatch(idiomatic): the dev launcher, aswitch, a parser returningOption<Command>,"", punctuation, and a.tag: stringthat gets neither rule.cargo test -p safe_ts_core --test docsand--test migrate: pass.npm run test:std: 367 passed.node scripts/docs-typecheck.mjs: 617 examples compile.npm run build -w docs: builds.Docs
rules/exhaustive-dispatch.mdandrules/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?", theswitchsection, and a new "A dispatch on a union or a code object" section.docs/README.mdandadoption.md, the sidebar, and CHANGELOG.patterns-core.md"A closed set of states" (numeric code sets, strings parsed once), thestring-if-chainrow incensus.md,final-pass.mdandtool-gaps.md.Left out
matchon a string literal union: the stacked follow-up PR.skills/safe-ts-migrate/scripts/census.mjsis unchanged (another lane edits it). Its rule-to-anchor map (~line 235) could addexhaustive-dispatch/string-dispatch→patterns-core.md#a-closed-set-of-states.v-ifchains stay withvue-exhaustive-v-if(enum tags only).x !== Achains,[A, B].includes(x)and comparisons with variables are not read as dispatches.Created with Claude Opus 5.5 in Claude Code.
1460bd3f4a58b488e43d