Methods on an enum's values: error.describe(), turned into calls of the table and checked #151

Merged
sionzee merged 9 commits from enum-instance-methods into main 2026-11-24 12:52:49 +01:00
Owner

You wanted to call an enum's functions on its values (error.describe()), not on the table. This PR adds that, stacked on #149.

export type UploadError = Enum<
  { Invalid: { problem: CheckError }; Retrying: { attempt: number }; StoreFull: {} },
  { readonly describe: () => string; readonly nextAttempt: () => UploadError }
>;
export const UploadError = constructors<UploadError>().impl({
  describe: (error) => match(error, { ... }),            // value typed from the declaration
  nextAttempt: (error): UploadError => match(error, { ... }),
});

error.nextAttempt().describe();   // the build writes UploadError.describe(UploadError.nextAttempt(error))

How it works. The values stay plain objects, so there's no runtime cost and JSON, validate<T>, spreads and structuredClone keep working. The build follows the value through what the source declares and turns each call into a call of the table: parameters, locals, fields, # fields and parameter properties, items of declared lists and maps (for...of, forEach/map, map.get(k)?.m()), declared return types, constructor results, match handlers (destructured too), variant(...), and the value impl's own functions get. That covers the ten receiver forms plus the enum-specific forms in the fixture. x?.m() is supported, and f()?.m() goes through std's new callIfPresent. When only the type is imported, the table gets imported under an alias. Legacy files get the rewrite too.

What can't be rewritten is refused. Four rules, all errors and on by default:

  • enum-method-receiver: the receiver's type isn't declared anywhere the checker follows, the call has an unsupported form (m?.(), a longer optional chain), the call is in a Vue template, or the method is read off its value (.m, ["m"], const { m } = x).
  • enum-method-escape: the value is passed where a type naming one of its methods is declared.
  • enum-method-name: a method named like a built-in's or a library's (get, next, map, update, toString, valueOf, toJSON, then). The list is fixed, built from the ECMAScript inventory and the node, browser, ws, vue-router and zod maps, never from the program. Without it, an unresolved x.get() couldn't be told apart from the enum's.
  • enum-as-text: any enum's value turned into text (${x}, String(x), x + "...", xs.join(), x.toString()), which gives "[object Object]". Values whose type the checker can't follow aren't checked: they print "[object Object]" too, but never crash.

toString can't be a method, because the language calls it out of sight of the build.

Adopter check (a scratch copy of the adopter, with a probe enum added): 0 reports from all four rules with distinctive method names (describe, label, nextAttempt, isRetryable, summary), and 0 enum-as-text on its existing enums. With get, next and toString, there are 3 enum-method-name errors at the declaration and nothing at the call sites. (Before the name rule, get alone gave 836 receiver errors.)

Tests (fast profile):

  • cargo nextest run --workspace: 424/424, including the new fixtures enum_methods and vue_enum_methods, 7 transform tests, the spelling harness (no new misses) and the work ceilings (unchanged, after two cheap fixes);
  • npm run test:std: 460/460, with runtime tests through the transform;
  • npm run typecheck: passes, including the emitted enum.check.ts;
  • node scripts/docs-typecheck.mjs: 1,126 examples compile;
  • crates/safe_ts_core/tests/docs.rs: passes;
  • npm run test:soundness: unchanged, 16 of 110 classes escape.

Known gaps:

  • A method that builds variants through its own table needs its return type written (otherwise TypeScript reports TS7022).
  • enum-method-escape doesn't see generic constraints (<T extends Describable>), fields or return positions.
  • A method passed to a library that formats it isn't checked by enum-as-text.

Created with Claude Opus 5.5 in Claude Code.

You wanted to call an enum's functions on its values (`error.describe()`), not on the table. This PR adds that, stacked on #149. ```ts export type UploadError = Enum< { Invalid: { problem: CheckError }; Retrying: { attempt: number }; StoreFull: {} }, { readonly describe: () => string; readonly nextAttempt: () => UploadError } >; export const UploadError = constructors<UploadError>().impl({ describe: (error) => match(error, { ... }), // value typed from the declaration nextAttempt: (error): UploadError => match(error, { ... }), }); error.nextAttempt().describe(); // the build writes UploadError.describe(UploadError.nextAttempt(error)) ``` **How it works.** The values stay plain objects, so there's no runtime cost and JSON, `validate<T>`, spreads and `structuredClone` keep working. The build follows the value through what the source declares and turns each call into a call of the table: parameters, locals, fields, `#` fields and parameter properties, items of declared lists and maps (`for...of`, `forEach`/`map`, `map.get(k)?.m()`), declared return types, constructor results, `match` handlers (destructured too), `variant(...)`, and the value `impl`'s own functions get. That covers the ten receiver forms plus the enum-specific forms in the fixture. `x?.m()` is supported, and `f()?.m()` goes through std's new `callIfPresent`. When only the type is imported, the table gets imported under an alias. Legacy files get the rewrite too. **What can't be rewritten is refused.** Four rules, all errors and on by default: - `enum-method-receiver`: the receiver's type isn't declared anywhere the checker follows, the call has an unsupported form (`m?.()`, a longer optional chain), the call is in a Vue template, or the method is read off its value (`.m`, `["m"]`, `const { m } = x`). - `enum-method-escape`: the value is passed where a type naming one of its methods is declared. - `enum-method-name`: a method named like a built-in's or a library's (`get`, `next`, `map`, `update`, `toString`, `valueOf`, `toJSON`, `then`). The list is fixed, built from the ECMAScript inventory and the node, browser, ws, vue-router and zod maps, never from the program. Without it, an unresolved `x.get()` couldn't be told apart from the enum's. - `enum-as-text`: any enum's value turned into text (`${x}`, `String(x)`, `x + "..."`, `xs.join()`, `x.toString()`), which gives "[object Object]". Values whose type the checker can't follow aren't checked: they print "[object Object]" too, but never crash. `toString` can't be a method, because the language calls it out of sight of the build. **Adopter check** (a scratch copy of the adopter, with a probe enum added): 0 reports from all four rules with distinctive method names (`describe`, `label`, `nextAttempt`, `isRetryable`, `summary`), and 0 `enum-as-text` on its existing enums. With `get`, `next` and `toString`, there are 3 `enum-method-name` errors at the declaration and nothing at the call sites. (Before the name rule, `get` alone gave 836 receiver errors.) **Tests** (fast profile): - `cargo nextest run --workspace`: 424/424, including the new fixtures `enum_methods` and `vue_enum_methods`, 7 transform tests, the spelling harness (no new misses) and the work ceilings (unchanged, after two cheap fixes); - `npm run test:std`: 460/460, with runtime tests through the transform; - `npm run typecheck`: passes, including the emitted `enum.check.ts`; - `node scripts/docs-typecheck.mjs`: 1,126 examples compile; - `crates/safe_ts_core/tests/docs.rs`: passes; - `npm run test:soundness`: unchanged, 16 of 110 classes escape. **Known gaps:** - A method that builds variants through its own table needs its return type written (otherwise TypeScript reports TS7022). - `enum-method-escape` doesn't see generic constraints (`<T extends Describable>`), fields or return positions. - A method passed to a library that formats it isn't checked by `enum-as-text`. Created with Claude Opus 5.5 in Claude Code.
`Enum<V, M>` declares methods every value has (`{ readonly describe: () => string }`);
`constructors<E>().impl({ describe: (error) => ... })` implements each, the value first and
typed from the declaration, next to the table's own functions and constants. Values stay
plain objects: the build turns `error.describe()` into `UploadError.describe(error)`.
`Fields` excludes the methods; `Data<E>` is a value without them (what the build checks its
literals against); `callIfPresent` is what it writes for `f()?.m()`. `Object.prototype`'s
names, `toJSON`, `then`, `impl` and `tag` can't be methods.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The build follows the receiver through what the source declares (parameters, locals, fields,
declared lists and maps, return types, constructor results, match handlers, variant(...),
the value impl's functions get) and writes `error.describe()` as `UploadError.describe(error)`,
`x?.m()` guarded, the table imported where only the type is. Legacy files get it too. In
TypeScript output, literals of an enum with methods are checked against `Data<E>`, and impl's
functions get their declared return types (a call of the table in a body would make the type
circular).

Rules, on by default as errors:
- enum-method-name: a method named like a built-in's or a feature pack library's method
  (`get`, `next`, `toString`); a fixed list from the ECMAScript inventory and the node,
  browser, ws, vue-router and zod maps.
- enum-method-receiver: a call whose receiver the declarations don't name, a form the
  rewrite doesn't take, a call in a Vue template, a method taken off its value.
- enum-method-escape: a value given where a type naming one of its methods is declared.
- enum-as-text: any enum's value turned into text (`${x}`, `String(x)`, `+`, `join`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Docs: methods on an enum, instance first
Some checks failed
Benchmarks / bench (pull_request) Successful in 4m3s
Tests / test (pull_request) Has been cancelled
f001d899b6
Enums guide "Methods on an enum" replaces "Functions on an enum"; the errors and adoption
guides, the migration skill, the transforms guide and the CHANGELOG say `error.describe()`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
enum-method-receiver: help that can be followed
Some checks failed
Benchmarks / bench (pull_request) Successful in 2m49s
Tests / test (pull_request) Failing after 13m41s
1bc15376b2
An expression receiver (`(await load())`) gets "keep it in a local declared with its type",
not `(await load()): E`; a name shared by several enums lists every table; a call inside a
longer optional chain says to keep the value in a local and check it, instead of passing a
possibly missing value to the table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee changed target branch from enum-impl to main 2026-11-24 12:52:07 +01:00
sionzee force-pushed enum-instance-methods from 1bc15376b2
Some checks failed
Benchmarks / bench (pull_request) Successful in 2m49s
Tests / test (pull_request) Failing after 13m41s
to c226202f03
Some checks failed
Tests / test (pull_request) Has been cancelled
Benchmarks / bench (pull_request) Has been cancelled
2026-11-24 12:52:34 +01:00
Compare
sionzee deleted branch enum-instance-methods 2026-11-24 12:52:49 +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!151
No description provided.