Functions on an enum: UploadError.describe(error) with constructors<E>().impl({...}) #149

Merged
sionzee merged 2 commits from enum-impl into main 2026-11-24 12:52:24 +01:00
Owner

Enums had no place for the functions that belong to them: describing an error, the next state after a retry. They ended up as loose functions in some module. Now they go on the enum's table, like Rust's impl block:

export const UploadError = constructors<UploadError>().impl({
  MAX_ATTEMPTS: 3,
  describe: (error: UploadError) => match(error, { ... }),
});

UploadError.describe(error);

Why on the table and not on the values (error.describe()): values stay plain objects, so JSON.parse, validate<T>, spreads and structuredClone keep everything they had. Putting methods on the values would need a prototype on each value, and a value from any of those would silently lack its methods while the type still claims them. The build can't safely rewrite error.describe() into the static call either, because it has no types for the receiver. The benchmark added here (npm run bench:enum-methods) also measured the cost: methods on the values were 1.3–3× slower to call once an enum has more than about four variants, a match elsewhere up to 1.7× slower, and JSON.stringify 1.5× slower on Node.

No state on the table. Members are functions or constants (strings, numbers, booleans, bigints). An object, array or Map doesn't compile, because it would be one global shared by every value. State that belongs to a value goes in its variant (Retrying: { attempt }). The table refuses writes.

Build: the build now reads the member names from .impl({...}) and leaves those calls alone; before this, any Table.x(...) call was rewritten into { tag: "x", ... }. When the names can't be listed (.impl(members)), only a declared variant is rewritten. impl and then are never variants.

Also changed: a plain constructors<E>() table now refuses writes too (before, a write went into its hidden target and was never read). This is in the CHANGELOG under Changed.

Docs:

  • Enums guide: new section "Functions on an enum".
  • Migration path:
    • the adoption guide's throw-to-result step: an error class's methods become .impl members;
    • errors.md "Give errors names": a message shown in several places is one function on the enum;
    • the migration skill's architecture rules, patterns and review checklist.
  • CHANGELOG.

Tests (fast profile): cargo nextest run --workspace 415/415, npm run test:std 458/458, npm run typecheck (including the emitted enum.check.ts), node scripts/docs-typecheck.mjs (1,118 examples), npm run test:soundness (escapes unchanged: 16 of 110).

Not wired into bench:check: the bench spawns a process per case and takes minutes, so it's a manual benchmark like bench:loops.

Created with Claude Opus 5.5 in Claude Code.

Enums had no place for the functions that belong to them: describing an error, the next state after a retry. They ended up as loose functions in some module. Now they go on the enum's table, like Rust's `impl` block: ```ts export const UploadError = constructors<UploadError>().impl({ MAX_ATTEMPTS: 3, describe: (error: UploadError) => match(error, { ... }), }); UploadError.describe(error); ``` **Why on the table and not on the values (`error.describe()`):** values stay plain objects, so `JSON.parse`, `validate<T>`, spreads and `structuredClone` keep everything they had. Putting methods on the values would need a prototype on each value, and a value from any of those would silently lack its methods while the type still claims them. The build can't safely rewrite `error.describe()` into the static call either, because it has no types for the receiver. The benchmark added here (`npm run bench:enum-methods`) also measured the cost: methods on the values were 1.3–3× slower to call once an enum has more than about four variants, a `match` elsewhere up to 1.7× slower, and `JSON.stringify` 1.5× slower on Node. **No state on the table.** Members are functions or constants (strings, numbers, booleans, bigints). An object, array or `Map` doesn't compile, because it would be one global shared by every value. State that belongs to a value goes in its variant (`Retrying: { attempt }`). The table refuses writes. **Build:** the build now reads the member names from `.impl({...})` and leaves those calls alone; before this, any `Table.x(...)` call was rewritten into `{ tag: "x", ... }`. When the names can't be listed (`.impl(members)`), only a declared variant is rewritten. `impl` and `then` are never variants. **Also changed:** a plain `constructors<E>()` table now refuses writes too (before, a write went into its hidden target and was never read). This is in the CHANGELOG under Changed. **Docs:** - Enums guide: new section "Functions on an enum". - Migration path: - the adoption guide's `throw-to-result` step: an error class's methods become `.impl` members; - errors.md "Give errors names": a message shown in several places is one function on the enum; - the migration skill's architecture rules, patterns and review checklist. - CHANGELOG. Tests (fast profile): `cargo nextest run --workspace` 415/415, `npm run test:std` 458/458, `npm run typecheck` (including the emitted `enum.check.ts`), `node scripts/docs-typecheck.mjs` (1,118 examples), `npm run test:soundness` (escapes unchanged: 16 of 110). Not wired into `bench:check`: the bench spawns a process per case and takes minutes, so it's a manual benchmark like `bench:loops`. Created with Claude Opus 5.5 in Claude Code.
Functions on an enum: constructors<E>().impl({...}) puts functions and constants on the table
Some checks failed
Benchmarks / bench (pull_request) Successful in 3m32s
Tests / test (pull_request) Has been cancelled
c47cd07e03
`UploadError.describe(error)`, like Rust's `impl UploadError { ... }`. Members are functions
or constants (strings, numbers, booleans, bigints): objects, arrays and maps don't compile,
since state on the table would be one global. A member named like a variant, `impl` or `then`
doesn't compile either. Values stay plain objects, and the table is read-only.

The build reads the member names from `.impl({...})` and leaves those calls alone (before,
any `Table.x(...)` was rewritten into `{ tag: "x", ... }`). Where it can't list them
(`.impl(members)`), only a declared variant is rewritten.

packages/std/bench/enum-methods.bench.ts measures why the functions live on the table and not
on the values: methods on a prototype were 1.3-3x slower to call once an enum has more than
about four variants, and 1.5x slower to JSON.stringify on Node.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Migration docs point to functions on an enum
All checks were successful
Benchmarks / bench (pull_request) Successful in 5m10s
Tests / test (pull_request) Successful in 27m13s
3f78ad86a9
The adoption guide's throw-to-result step (an error class's methods become `.impl` members),
errors.md "Give errors names" (a message shown in several places is one function on the
enum), and the migration skill's architecture rules and review checklist.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee force-pushed enum-impl from 3f78ad86a9
All checks were successful
Benchmarks / bench (pull_request) Successful in 5m10s
Tests / test (pull_request) Successful in 27m13s
to bad5219357
Some checks failed
Tests / test (pull_request) Has been cancelled
Benchmarks / bench (pull_request) Has been cancelled
2026-11-24 12:52:07 +01:00
Compare
sionzee deleted branch enum-impl 2026-11-24 12:52:24 +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!149
No description provided.