diff --git a/CHANGELOG.md b/CHANGELOG.md index fc485b4..2ae113d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] - reject a fallback when the handler map already covers the universe +- allow boolean, null and undefined in the matcher universe ## [0.4.0] - 2026-09-20 diff --git a/backlog.tasks b/backlog.tasks index e409cd7..e17212f 100644 --- a/backlog.tasks +++ b/backlog.tasks @@ -52,8 +52,9 @@ Bugs: → `handleExit` returns `io.EOF`, cancelling the background context while `Session.updateWatches` is still in flight; the bare error is flushed to stderr and the server exits 1 → close stdin after `shutdown` instead of sending `exit`; the server exits cleanly (code 0, no output), kill kept as a fallback Enhancements: -☐ Allow boolean literals in primitive union patterns (e.g. `true: () => "yes"`) @medium -☐ Are there other primitive types that should be supported in union patterns? (e.g. `bigint`, `symbol`) @medium +✔ Allow boolean literals in primitive union patterns (e.g. `true: () => "yes"`) @medium @done + ✔ Are there other primitive types that should be supported in union patterns? (e.g. `bigint`, `symbol`) @medium @done + → added boolean, null and undefined; rejected `symbol` (compile-time brand, nothing at runtime) and `bigint` (not a property key) Documentation: ☐ Bring README.md back to its previous form — synopsis and examples restored, in the correct place diff --git a/development/library.md b/development/library.md index f8650b9..9f31e15 100644 --- a/development/library.md +++ b/development/library.md @@ -91,3 +91,36 @@ Each factory is two overloads whose order is load-bearing: - `Parameters[0]` resolves only the **last** overload, so it is not a sound "rejected" oracle for a factory. Factory-negative tests use `@ts-expect-error` call sites (the test file only — the general ban stands). + +## Primitive universe + +#### Decision (2026-09) + +The universe (`Matchable`) is `string | number | boolean | null | undefined`, +with `boolean` admitted as `true | false`. `symbol` and `bigint` are not. + +`boolean`/`null`/`undefined` are not property keys, so handler-map keys are a +projection (`PatternKey`: each member stringified) and `PatternParam` inverts +it, so callbacks receive the real member (`true`, not `"true"`). The popup +offers `true`, `false`, `null`, `undefined` by name (verified over LSP). + +#### Why + +- Runtime dispatch is unchanged in effect: `handlers[true]` already coerces to + `"true"`. `dispatch` wraps the index in `String()` only because TypeScript + forbids indexing with `boolean`/`null`/`undefined` (`TS2538`). + +#### Rejected + +- **`symbol`.** A brand is a compile-time phantom — nothing to match at + runtime; the popup cannot offer symbol keys anyway. +- **`bigint`.** Not a valid property key; a stringified key (`"1"`) collides + with numeric `1`. +- **`NaN` / `-0`.** No literal type exists; they stay one `number`. + +#### Known issue + +- A universe mixing a member with its stringification (`1 | "1"`, + `true | "true"`, `null | "null"`) collapses to one handler key and routes + both members to it. Pre-existing for `1 | "1"`; now reachable for the new + members. Not guarded at the type level. diff --git a/src/primitive.test.ts b/src/primitive.test.ts index 2953883..4ccfc12 100644 --- a/src/primitive.test.ts +++ b/src/primitive.test.ts @@ -95,6 +95,50 @@ test("getMatcher: dispatches on mixed string and numeric keys", () => { assert.equal(matcher(2), 20); }); +test("getMatcher: dispatches on boolean literals", () => { + // Arrange + const factory = getMatcher(); + + // Act + const matcher = factory({ + true: (s) => { + expectTypeOf(s).toEqualTypeOf(); + return 1; + }, + false: (s) => { + expectTypeOf(s).toEqualTypeOf(); + return 2; + }, + }); + + // Assert + expectTypeOf(matcher).toEqualTypeOf<(shape: boolean) => number>(); + assert.equal(matcher(true), 1); + assert.equal(matcher(false), 2); +}); + +test("getMatcher: dispatches on null and undefined", () => { + // Arrange + const factory = getMatcher(); + + // Act + const matcher = factory({ + null: (s) => { + expectTypeOf(s).toEqualTypeOf(); + return "null"; + }, + undefined: (s) => { + expectTypeOf(s).toEqualTypeOf(); + return "undefined"; + }, + }); + + // Assert + expectTypeOf(matcher).toEqualTypeOf<(shape: null | undefined) => string>(); + assert.equal(matcher(null), "null"); + assert.equal(matcher(undefined), "undefined"); +}); + // ============================================================================ // API: getMatcher — ❌ Exhaustive (fallback) / ✔️ ReturnsStrict // ============================================================================ @@ -157,6 +201,41 @@ test("getMatcher: a `_` fallback routes mixed string and numeric gaps", () => { assert.equal(matcher(2), "fallback"); }); +test("getMatcher: a `_` fallback receives unhandled boolean and nullish keys", () => { + // Arrange + const factory = getMatcher<"a" | true | false | null | undefined>(); + + // Act + const matcher = factory( + { + a: (s) => { + expectTypeOf(s).toEqualTypeOf<"a">(); + return 1 as const; + }, + null: (s) => { + expectTypeOf(s).toEqualTypeOf(); + return 2 as const; + }, + }, + (s) => { + // `true` and `false` are keyed as `"true"`/`"false"` but the + // fallback still sees them as booleans. + expectTypeOf(s).toEqualTypeOf(); + return 3 as const; + }, + ); + + // Assert + expectTypeOf(matcher).toEqualTypeOf< + (shape: "a" | true | false | null | undefined) => 1 | 2 | 3 + >(); + assert.equal(matcher("a"), 1); + assert.equal(matcher(true), 3); + assert.equal(matcher(false), 3); + assert.equal(matcher(null), 2); + assert.equal(matcher(undefined), 3); +}); + // ============================================================================ // API: getMatcherW — ✔️ Exhaustive / ❌ ReturnsStrict // ============================================================================ @@ -220,6 +299,40 @@ test("getMatcherW: dispatches on mixed string and numeric keys", () => { assert.equal(matcher(2), 20); }); +test("getMatcherW: exhaustive boolean and nullish widen to the union", () => { + // Arrange + const factory = getMatcherW(); + + // Act + const matcher = factory({ + true: (s) => { + expectTypeOf(s).toEqualTypeOf(); + return "yes" as const; + }, + false: (s) => { + expectTypeOf(s).toEqualTypeOf(); + return "no" as const; + }, + null: (s) => { + expectTypeOf(s).toEqualTypeOf(); + return 0 as const; + }, + undefined: (s) => { + expectTypeOf(s).toEqualTypeOf(); + return 1 as const; + }, + }); + + // Assert + expectTypeOf(matcher).toEqualTypeOf< + (shape: boolean | null | undefined) => "yes" | "no" | 0 | 1 + >(); + assert.equal(matcher(true), "yes"); + assert.equal(matcher(false), "no"); + assert.equal(matcher(null), 0); + assert.equal(matcher(undefined), 1); +}); + // ============================================================================ // API: getMatcherW — ❌ Exhaustive (fallback) / ❌ ReturnsStrict // ============================================================================ @@ -313,6 +426,27 @@ test("getMatcher factory rejects patterns outside its contract", () => { factory({ a: () => 1, b: () => 2 }, () => 0); }); +test("getMatcher factory rejects non-exhaustive boolean and nullish maps", () => { + // Arrange + const factory = getMatcher(); + + // Act / Assert — the calls below must not compile + // @ts-expect-error only `true` is handled; `false`, `null`, `undefined` are not + factory({ true: () => 1 }); + // @ts-expect-error `null` and `undefined` are not handled + factory({ true: () => 1, false: () => 2 }); + factory( + // @ts-expect-error a fallback is redundant once the map covers the universe + { + true: () => 1, + false: () => 2, + null: () => 3, + undefined: () => 4, + }, + () => 0, + ); +}); + test("getMatcher: an open universe keeps the fallback's remainder open", () => { // Arrange const factory = getMatcher(); @@ -363,6 +497,17 @@ test("getMatcher: an unhandled shape throws without a fallback", () => { assert.throws(() => matcher("b"), /Unhandled shape: b/); }); +test("getMatcher: an unhandled boolean shape throws without a fallback", () => { + // Arrange — an `string | boolean` universe widens its handler map to an + // index signature, so the runtime map's exhaustiveness is not provable. + const handlers: Record number> = { true: () => 1 }; + const matcher = getMatcher()(handlers); + + // Act / Assert + assert.equal(matcher(true), 1); + assert.throws(() => matcher(false), /Unhandled shape: false/); +}); + // ============================================================================ // Autocomplete — the language server is the oracle, not the type system // ============================================================================ @@ -381,6 +526,7 @@ interface LabelsProbe { readonly name: string; readonly factory: "getMatcher" | "getMatcherW"; readonly body: string; + readonly universe?: string; readonly tail?: string; } @@ -388,6 +534,7 @@ const labelsFor = ({ name, factory, body, + universe = UNIVERSE, tail = "", }: LabelsProbe): Promise => { const session = new LspSession(REPO_ROOT); @@ -395,7 +542,7 @@ const labelsFor = ({ file: `src/__autocomplete_${name}.ts`, source: [ `import { ${factory} } from "./index.ts";`, - `const m = ${factory}<${UNIVERSE}>()({`, + `const m = ${factory}<${universe}>()({`, body, `}${tail});`, "", @@ -511,3 +658,39 @@ test("autocomplete: `getMatcherW` also offers optional keys with a fallback", () assert.deepEqual([...result], ["a?", "b?", "c?"]); }); }); + +test("autocomplete: boolean and nullish keys are offered by name", () => { + // Arrange + const name = "getMatcher_boolean_nullish"; + + // Act + const labels = labelsFor({ + name, + factory: "getMatcher", + universe: "boolean | null | undefined", + body: " /*COMPLETE*/", + }); + + // Assert + return labels.then((result) => { + assert.deepEqual([...result], ["false", "null", "true", "undefined"]); + }); +}); + +test("autocomplete: a handled boolean literal drops out of the popup", () => { + // Arrange + const name = "getMatcher_boolean_after_key"; + + // Act + const labels = labelsFor({ + name, + factory: "getMatcher", + universe: "boolean | null | undefined", + body: " true: () => 1,\n /*COMPLETE*/", + }); + + // Assert + return labels.then((result) => { + assert.deepEqual([...result], ["false", "null", "undefined"]); + }); +}); diff --git a/src/primitive.ts b/src/primitive.ts index b23c5c3..78a1477 100644 --- a/src/primitive.ts +++ b/src/primitive.ts @@ -2,13 +2,45 @@ import type { Exact, ValueOf } from "type-fest"; type UnaryFn = (shape: T) => R; +// The primitive universe a matcher can discriminate. `boolean` is admitted as +// the pair `true | false`; `symbol` is deliberately absent (a brand is a +// compile-time phantom, so there is nothing to match at runtime). +type Matchable = string | number | boolean | null | undefined; + +// `boolean`, `null` and `undefined` cannot be property keys, so a mapped type +// over the universe keys each non-key member by its stringification. `Param` +// inverts that projection, so a handler callback still receives the *real* +// member (`true`, not `"true"`). A universe mixing a member with the string it +// stringifies to (e.g. `true | "true"`) collapses to one key and is not +// representable — see development/library.md. +type PatternKey = T extends boolean + ? T extends true + ? "true" + : "false" + : T extends null + ? "null" + : T extends undefined + ? "undefined" + : T; +type PatternParam = K extends "true" + ? true + : K extends "false" + ? false + : K extends "null" + ? null + : K extends "undefined" + ? undefined + : K; + // `Extract` drops optional handlers (`undefined`) so `PatternReturns` also works // when `P`'s constraint has optional keys. type PatternReturns

= ReturnType< Extract, (...args: never[]) => unknown> >; -type Handlers = { [K in T]: UnaryFn }; +type Handlers = { + [K in PatternKey]: UnaryFn, R>; +}; // The fallback is a *second argument*, not a property of the handler map, // because its parameter is the remainder `Exclude` and TypeScript @@ -16,8 +48,8 @@ type Handlers = { [K in T]: UnaryFn }; // argument, by contrast, is contextually typed from inference on an earlier // one, so the split is what makes the remainder expressible at all. // See development/library.md. -type Fallback = UnaryFn< - Exclude, +type Fallback = UnaryFn< + Exclude>, R >; @@ -32,9 +64,8 @@ type Fallback = UnaryFn< interface RedundantFallback { readonly "every case is already handled, so the fallback is redundant": never; } -type MustBePartial = T extends keyof Handled - ? RedundantFallback - : unknown; +type MustBePartial = + PatternKey extends keyof Handled ? RedundantFallback : unknown; // TypeScript does not apply the excess-property check to a generic constraint, // so `Exact` restores it for the generic forms: a handler map can otherwise @@ -44,7 +75,7 @@ type MustBePartial = T extends keyof Handled // Strict returns: one common `R`. Overload order is load-bearing: // #1 Handlers (first) -> the exhaustive form and the autocomplete popup // #2 Fallback (last) -> accepts a partial handler map plus a fallback -interface MatcherStrict { +interface MatcherStrict { (handlers: Handlers): UnaryFn; < R, @@ -61,7 +92,7 @@ interface MatcherStrict { // from the whole handler map, whose closed constraint supplies the // contextual/autocomplete type. // oxlint-disable typescript/unified-signatures -interface MatcherWidening { +interface MatcherWidening {

, P>>( handlers: P, ): UnaryFn>; @@ -80,19 +111,21 @@ type HandlerMap = Record | undefined>; const dispatch = (handlers: HandlerMap, fallback?: UnaryFn) => - (shape: string | number): unknown => + (shape: Matchable): unknown => + // `handlers[true]` already coerces to the `"true"` property at + // runtime; `String` is here only because TypeScript forbids + // indexing with `boolean`/`null`/`undefined` (TS2538). ( - handlers[shape] ?? + handlers[String(shape)] ?? fallback ?? (() => { - throw new Error(`Unhandled shape: ${shape}`); + throw new Error(`Unhandled shape: ${String(shape)}`); }) )( // oxlint-disable-next-line typescript/no-unsafe-type-assertion shape as never, ); -export const getMatcher = (): MatcherStrict => - dispatch; -export const getMatcherW = (): MatcherWidening => +export const getMatcher = (): MatcherStrict => dispatch; +export const getMatcherW = (): MatcherWidening => dispatch;