exhaustive-switch / exhaustive-dispatch: a member of a union takes its set from the union's members; Mut<Class> members; panic spellings #166

Merged
sionzee merged 2 commits from dispatch-union-members into main 2026-11-24 14:22:33 +01:00
Owner

From an adopter's feedback on 0.5.1: a dispatch on p.op of a packet union asked for every constant of the code table.

1. The set of a member of a union is the union's members

export const Op = Object.freeze({ Hello: 1, Welcome: 2, Ping: 3, Pong: 4 });
type OpCode = (typeof Op)[keyof typeof Op];
const PACKETS = {
  [Op.Hello]: { dir: "c2s" }, [Op.Welcome]: { dir: "s2c" },
  [Op.Ping]: { dir: "c2s" }, [Op.Pong]: { dir: "s2c" },
} as const;
type ClientOp = { [O in OpCode]: (typeof PACKETS)[O]["dir"] extends "c2s" ? O : never }[OpCode];
type PacketOf<O extends OpCode> = O extends OpCode ? { op: O } : never;

export function answer(p: PacketOf<ClientOp>): string {
  switch (p.op) {
    case Op.Ping: return "pong";
    default: return "";
  }
}

main: exhaustive-dispatch: "doesn't handle Op.Hello, Op.Welcome and Op.Pong". Op.Welcome and Op.Pong can't come (a case for one is TS2678). The rule already takes the set from the value's type when it can read the type; here it couldn't, so it fell back to the table every tested constant is read from. The type evaluator couldn't read:

  • a mapped type over numeric keys ({ [O in OpCode]: ... } with numeric codes). It took only string literals as keys. Under the new number_keys setting (the value evaluators set it; JSON validators still refuse number keys), an integer key names the field by its text, and the parameter is bound to the number;
  • a spread in an as const array (fields: [...SEQ_TICK, ["good", "u8"]]), now a tuple rest;
  • arithmetic on number literals (64 * 1024), now number.

(These three came from an earlier attempt at this piece. I reviewed them and kept them, with one change: string-keyed mapped types bind the key exactly as before.)

Now: exhaustive-switch: "switch (p.op) doesn't handle Op.Hello". A typed switch is exhaustive-switch's, which can ask for default: unreachable(p.op). An if/?: chain says "tests some of the constants of Op its type allows" when the type allows fewer constants than the table has.

2. A member of a class instance declared Mut<C>

switch (w.mode) with w: Mut<Walker> (a class) wasn't reported; with w: Walker, Readonly<Walker> or Mut<Holder> (an object alias) it was. program_member took a declared type as a class instance only when it was a bare class name. It now looks through Mut / Readonly (also Mut<Readonly<C>>). This is the evaluator every type-reading rule shares, so the same gap closes for strict-truthiness (if (w.count) with w: Mut<Counter> wasn't reported on main), and for unreachable-code and the rest of json::value's users. The rules with their own type walk (declared_keys.rs, loans.rs, spread_args.rs, ...) already unwrap Mut.

3. panic / unreachable in other spellings never return

dispatch.rs is_std_never now reads the import declaration (as is_std_lend does), not imports.imported (one local per imported name, so a renamed import was missed on the normalised tree). The narrowing (never_returns) follows .call / .apply and const copies. Also a member of a std namespace import (result.panic(...), also through a const copy) and panic["call"](...). A panic imported from another module still isn't taken as never returning: it may be another function that returns, and taking it for std's would narrow the members asked for. That stays on the safe side: more members are listed.

Still reported (fixtures)

tests/fixtures/union_dispatch (checked by messages.rs for the exact lists):

  • a member not handled is still named (receiveSome: Msg.Book), and so is a member whose packets come in the other direction when the union allows it (AnyMessage, MsgCode: every constant);
  • a value typed number still gets the table's constants (exhaustive-dispatch);
  • earlier returns still narrow on a union member (answerAfterLeave);
  • Mut<C> from another file and from this one, Readonly<C>, Mut<Readonly<C>>, Mut<alias>, if chains, and strict-truthiness through Mut<C>.

tests/fixtures/narrowed_dispatch/never.ts: renamed, .call, .apply, const copy narrow; panic from ./log (which returns) doesn't.

Adopter tree (before export with the workspace packages linked)

main this branch
all diagnostics 3207 3257
exhaustive-* 184 197

The five switches on packet codes (market.ts:199, world-host.ts:1246, online.ts:982, a test fake server, a bot script) dropped 19 or 45 Op constants each. I checked every dropped constant against the table's dir: each is a packet of the other direction. online.ts:982 handles every server packet and ends in default: break, so it is now "without default: unreachable(...)". Other changes come from types the evaluator can now read: 11 new exhaustive-dispatch and 8 exhaustive-switch lines, including the five above (new dispatch reports on an event enum and string unions) (spot-checked: grief.ts:125 really sends "sibling" to the default), 39 strict-truthiness (numbers tested for truth), 2 inline-member-set, and 4 undeclared-return-type gone (their results can now be read).

Not done: world-host.ts:1246 still lists the Cmd* codes, which if (isCommandPacket(p)) { ...; continue; } narrowed away (p is CommandPacket). Following a type predicate is new analysis in narrowing.rs, and type predicates are what no-type-predicate bans. main lists them too (and the server packets as well).

Tests

  • cargo nextest run --workspace (fast profile): 416 of 416 pass.
  • npm run test:rewrites (full mode): passes with misses.txt updated:
    • gone: the four text exhaustive-dispatch lines for panic spelled .apply, .call, as a const copy, and as a renamed import (item 3).
    • new fixture sites in gaps the file already names: ternary-to-if 6→14, hoist-const (new exhaustive-switch) 10→13, decl-to-arrow (far, both rules) 2→3.
    • text exhaustive-dispatch re-export / re-export-star 1→3: panic imported through a project module that re-exports it isn't taken for std's in the file pass (on purpose, see above). The normalised tree imports it from std.
    • text exhaustive-dispatch namespace-import 1: as parsed, a table keyed by [ns.Msg.Join] isn't read by the evaluator, so the set falls back to the whole table (more listed). The normalised tree reads it.
    • used hatch:panic / hatch:trust apply / call: the rewriter wraps the fixture's panic.call(...) / result.panic(...) again (panic.call.call(panic, ...)). As parsed, the panic or namespace given as an argument counts as a hatch handed on (fail closed).
  • npm run test:soundness: passes (16 of 110 classes escape, the ones in escaping.txt).
  • npm run test:docs: passes. The new exhaustive-switch example is reported on main as exhaustive-dispatch listing Op.Welcome and Op.Pong; on this branch it lists Op.Hello only.

🤖 Generated with Claude Code

From an adopter's feedback on 0.5.1: a dispatch on `p.op` of a packet union asked for every constant of the code table. ## 1. The set of a member of a union is the union's members ```ts export const Op = Object.freeze({ Hello: 1, Welcome: 2, Ping: 3, Pong: 4 }); type OpCode = (typeof Op)[keyof typeof Op]; const PACKETS = { [Op.Hello]: { dir: "c2s" }, [Op.Welcome]: { dir: "s2c" }, [Op.Ping]: { dir: "c2s" }, [Op.Pong]: { dir: "s2c" }, } as const; type ClientOp = { [O in OpCode]: (typeof PACKETS)[O]["dir"] extends "c2s" ? O : never }[OpCode]; type PacketOf<O extends OpCode> = O extends OpCode ? { op: O } : never; export function answer(p: PacketOf<ClientOp>): string { switch (p.op) { case Op.Ping: return "pong"; default: return ""; } } ``` main: `exhaustive-dispatch`: "doesn't handle Op.Hello, Op.Welcome and Op.Pong". `Op.Welcome` and `Op.Pong` can't come (a `case` for one is TS2678). The rule already takes the set from the value's type when it can read the type; here it couldn't, so it fell back to the table every tested constant is read from. The type evaluator couldn't read: - a mapped type over **numeric** keys (`{ [O in OpCode]: ... }` with numeric codes). It took only string literals as keys. Under the new `number_keys` setting (the value evaluators set it; JSON validators still refuse number keys), an integer key names the field by its text, and the parameter is bound to the number; - a spread in an `as const` array (`fields: [...SEQ_TICK, ["good", "u8"]]`), now a tuple rest; - arithmetic on number literals (`64 * 1024`), now `number`. (These three came from an earlier attempt at this piece. I reviewed them and kept them, with one change: string-keyed mapped types bind the key exactly as before.) Now: `exhaustive-switch`: "`switch (p.op)` doesn't handle Op.Hello". A typed switch is `exhaustive-switch`'s, which can ask for `default: unreachable(p.op)`. An `if`/`?:` chain says "tests some of the constants of `Op` its type allows" when the type allows fewer constants than the table has. ## 2. A member of a class instance declared `Mut<C>` `switch (w.mode)` with `w: Mut<Walker>` (a class) wasn't reported; with `w: Walker`, `Readonly<Walker>` or `Mut<Holder>` (an object alias) it was. `program_member` took a declared type as a class instance only when it was a bare class name. It now looks through `Mut` / `Readonly` (also `Mut<Readonly<C>>`). This is the evaluator every type-reading rule shares, so the same gap closes for `strict-truthiness` (`if (w.count)` with `w: Mut<Counter>` wasn't reported on main), and for `unreachable-code` and the rest of `json::value`'s users. The rules with their own type walk (`declared_keys.rs`, `loans.rs`, `spread_args.rs`, ...) already unwrap `Mut`. ## 3. `panic` / `unreachable` in other spellings never return `dispatch.rs` `is_std_never` now reads the import declaration (as `is_std_lend` does), not `imports.imported` (one local per imported name, so a renamed import was missed on the normalised tree). The narrowing (`never_returns`) follows `.call` / `.apply` and `const` copies. Also a member of a std namespace import (`result.panic(...)`, also through a `const` copy) and `panic["call"](...)`. A `panic` imported from another module still isn't taken as never returning: it may be another function that returns, and taking it for std's would narrow the members asked for. That stays on the safe side: more members are listed. ## Still reported (fixtures) `tests/fixtures/union_dispatch` (checked by `messages.rs` for the exact lists): - a member not handled is still named (`receiveSome`: `Msg.Book`), and so is a member whose packets come in the other direction when the union allows it (`AnyMessage`, `MsgCode`: every constant); - a value typed `number` still gets the table's constants (`exhaustive-dispatch`); - earlier returns still narrow on a union member (`answerAfterLeave`); - `Mut<C>` from another file and from this one, `Readonly<C>`, `Mut<Readonly<C>>`, `Mut<alias>`, `if` chains, and `strict-truthiness` through `Mut<C>`. `tests/fixtures/narrowed_dispatch/never.ts`: renamed, `.call`, `.apply`, `const` copy narrow; `panic` from `./log` (which returns) doesn't. ## Adopter tree (before export with the workspace packages linked) | | main | this branch | |---|---|---| | all diagnostics | 3207 | 3257 | | `exhaustive-*` | 184 | 197 | The five switches on packet codes (`market.ts:199`, `world-host.ts:1246`, `online.ts:982`, a test fake server, a bot script) dropped 19 or 45 `Op` constants each. I checked every dropped constant against the table's `dir`: each is a packet of the other direction. `online.ts:982` handles every server packet and ends in `default: break`, so it is now "without `default: unreachable(...)`". Other changes come from types the evaluator can now read: 11 new `exhaustive-dispatch` and 8 `exhaustive-switch` lines, including the five above (new dispatch reports on an event enum and string unions) (spot-checked: `grief.ts:125` really sends `"sibling"` to the `default`), 39 `strict-truthiness` (numbers tested for truth), 2 `inline-member-set`, and 4 `undeclared-return-type` gone (their results can now be read). Not done: `world-host.ts:1246` still lists the `Cmd*` codes, which `if (isCommandPacket(p)) { ...; continue; }` narrowed away (`p is CommandPacket`). Following a type predicate is new analysis in `narrowing.rs`, and type predicates are what `no-type-predicate` bans. main lists them too (and the server packets as well). ## Tests - `cargo nextest run --workspace` (fast profile): 416 of 416 pass. - `npm run test:rewrites` (full mode): passes with `misses.txt` updated: - **gone:** the four `text exhaustive-dispatch` lines for `panic` spelled `.apply`, `.call`, as a `const` copy, and as a renamed import (item 3). - **new fixture sites in gaps the file already names:** `ternary-to-if` 6→14, `hoist-const` (`new exhaustive-switch`) 10→13, `decl-to-arrow` (`far`, both rules) 2→3. - **`text exhaustive-dispatch re-export` / `re-export-star` 1→3:** `panic` imported through a project module that re-exports it isn't taken for std's in the file pass (on purpose, see above). The normalised tree imports it from std. - **`text exhaustive-dispatch namespace-import 1`:** as parsed, a table keyed by `[ns.Msg.Join]` isn't read by the evaluator, so the set falls back to the whole table (more listed). The normalised tree reads it. - **`used hatch:panic` / `hatch:trust` `apply` / `call`:** the rewriter wraps the fixture's `panic.call(...)` / `result.panic(...)` again (`panic.call.call(panic, ...)`). As parsed, the `panic` or namespace given as an argument counts as a hatch handed on (fail closed). - `npm run test:soundness`: passes (16 of 110 classes escape, the ones in `escaping.txt`). - `npm run test:docs`: passes. The new `exhaustive-switch` example is reported on main as `exhaustive-dispatch` listing `Op.Welcome` and `Op.Pong`; on this branch it lists `Op.Hello` only. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
exhaustive-switch / exhaustive-dispatch: a member of a union takes its set from the union's members
Some checks failed
Benchmarks / bench (pull_request) Successful in 6m44s
Tests / test (pull_request) Has been cancelled
4cf9bff30b
`switch (p.op)` on a union of packet types derived from a table of packets (a mapped type over
numeric codes, field lists that spread a shared head, limits written as arithmetic) asked for
every constant of the code table: the type evaluator couldn't read the union, so the rule fell
back to the table. It now reads mapped types over integer keys (value evaluators only; JSON
validators still refuse number keys), array spreads in `as const` values, and arithmetic on
number literals, so only the codes the union allows are asked for.

A member of a class instance declared `Mut<C>` (also `Mut<Readonly<C>>`) now has its declared
type in the evaluator every type-reading rule shares (`exhaustive-switch`, `exhaustive-dispatch`,
`strict-truthiness`, ...).

std's `panic` / `unreachable` never return for the narrowing in more spellings: a renamed
import (read from the import declaration), `.call` / `.apply`, a `const` copy, a std namespace
member. A `panic` of another module still doesn't count.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee force-pushed dispatch-union-members from 4cf9bff30b
Some checks failed
Benchmarks / bench (pull_request) Successful in 6m44s
Tests / test (pull_request) Has been cancelled
to 52ca8d0fd6
All checks were successful
Benchmarks / bench (pull_request) Successful in 3m24s
Tests / test (pull_request) Successful in 27m7s
2026-11-24 13:48:02 +01:00
Compare
Merge main into dispatch-union-members
Some checks failed
Tests / test (pull_request) Has been cancelled
Benchmarks / bench (pull_request) Has been cancelled
915c2009c6
Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee deleted branch dispatch-union-members 2026-11-24 14:22:33 +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!166
No description provided.