Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

match: arms are contextually typed by the match's declared type; evals primer and route-match reference updated for the typed checker

The union-of-arms typing rejected Err({ kind: "missing" }) in a function
returning Result<T, QueryError>, which the eval references hit in 6 tasks.
R is now inferred from the contextual type only (NoInfer in the arms'
constraint) and falls back to the union of the arms when there is none, so
object-literal arms keep their literal tags and a wrong arm is reported on
the arm itself.

evals/LANGUAGE.md now teaches the typed match and the ? operator, as its
header asks; route-match/reference.tsus annotates a map callback whose
literal return type made unwrapOr(1) a real type error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
f30ac6384492b92a7f52a1f893cec460c64b6d70
Parent 9472e3c Browse filesHistory

Changed files

9 files changed94 additions36 deletionsagainst 9472e3c

  1. ChangedLEARNINGS.md+11−8
  2. ChangedREADME.md+3−4
  3. Changedevals/LANGUAGE.md+26−5
  4. Changedevals/tasks/route-match/reference.tsus+1−1
  5. Changedexamples/31-wrong-arm-type/example.json+1−1
  6. Changedexamples/36-literal-patterns/example.json+1−1
  7. Changedexamples/36-literal-patterns/src/main.tsus+20−0
  8. Changedpackages/cli/src/preprocess.js+6−3
  9. Changedpackages/runtime/index.d.ts+25−13
ChangedLEARNINGS.md+11−8
@@ -45,14 +45,18 @@
`ts.createScanner` already knows strings, comments, numbers, and every operator, including the ones that matter for `?`: it emits `?.` and `??` as their own tokens, so telling them apart from a bare `?` costs nothing. What it cannot know is parser context. Two tokens need a rescan: `/` (division or regex) and `}` (end of a block or the resume of a template after `${`). Regexes are decided by a one-token lookbehind (after an identifier, literal, `)`, `]`, or `}` it is division), and templates by remembering the brace depth at each `TemplateHead`. Example 32 is the regex `/["'`]/g`, which the old hand-written scanner read as the start of a string and a template.
-## Typing match took three tries
+## Typing match took four tries
The obvious signature, `<V, R>(value: V, arms: { [K in TagOf<V>]: (p: Payload<V, K>) => R }) => R`, type-checks the arms but infers `R` as `unknown`: TypeScript cannot infer through a mapped type whose keys are a conditional type of another type parameter. Every match silently became `unknown`.
-Currying fixes inference. `__tsus_match(value)(arms)` fixes `V` in the first call, so in the second the mapped type has concrete keys. Then there was a choice about the result type. A single `R` is Rust-like (arms must agree, errors land on the offending arm), but it rejects the most common tagged-union code: `Idle => tag("Running", ...)`, `Running => tag("Done", ...)` returns two different variant types, and TypeScript will not unify them into the declared union. So the arms object is inferred as a type parameter `A extends MatchArms<V>`, and the match's type is the union of the arms' return types. Exhaustiveness comes from the constraint, unknown arms from an extra mapped type that maps foreign keys to `never`.
+Currying fixes inference. `__tsus_match(value)(arms)` fixes `V` in the first call, so in the second the mapped type has concrete keys. A single inferred `R` then works, but it is too strict in a TypeScript way: `Idle => tag("Running", ...)` and `Running => tag("Done", ...)` return two different variant types, and TypeScript picks the first as `R` and rejects the second even when the function declares the union as its return type.
-One more wrinkle: when the constraint fails (the real error), TypeScript falls back to it, and if the constraint's arms return `unknown`, every use of the match reports a second, misleading error. The constraint returns `any`, which only ever surfaces after a match is already reported broken.
+The third version inferred the arms object as a type parameter `A extends MatchArms<V>` and typed the match as the union of the arms' return types. That handled variants, and examples 1 to 36 passed, but the eval harness's reference solutions (merged while this work was in flight) failed on the most common error-handling line there is: `None => Err({ kind: "missing" })` inside a function returning `Result<T, QueryError>`. With no contextual type reaching the arm, `Err` infers `{ kind: string }` and the union no longer fits. Plain TypeScript gets this right in a ternary because the return type flows into both branches.
+The version that shipped takes the result type from context when there is one and from the arms when there is not. `R` appears in the match's return type and, wrapped in `NoInfer`, in the arms' constraint, so it is inferred only from the contextual type. When a context exists, every arm is contextually typed by it (so `Err({ kind: "missing" })` infers `QueryError`) and must be assignable to it, which also moves a wrong-arm error from the whole match onto the offending arm. When there is no context, `R` stays `unknown`, and a conditional type switches the result to the union of the arms. Exhaustiveness comes from the constraint, unknown arms from an extra mapped type that maps foreign keys to `never`.
+
+One more wrinkle: when the constraint fails (the real error), TypeScript falls back to it, and if the constraint's arms return `unknown`, every use of the match reports a second, misleading error. Without a context the constraint returns `any`, which only ever surfaces after a match is already reported broken.
+
`_` cannot be a key in the same object without turning the mapped type into a union, which breaks contextual typing for the arm parameters, so a wildcard match lowers to a separate `__tsus_match_or(value)(arms, otherwise)`.
## Literal patterns are a different shape
@@ -75,9 +79,9 @@
The runtime import is prepended on line 1 with no newline, so line numbers in the lowered code, the emitted JS, and stack traces without source maps still match the `.tsus` file.
-## Semantic checking found a real bug immediately
+## Semantic checking found real bugs immediately
-Example 16 had passed since the MVP, but `wrapAsync(readFile)` infers from `readFile`'s last overload, so the `Ok` payload was `string | Buffer`, and `text.trim()` was a type error that only worked at runtime because the call happened to pass `"utf8"`. The first `ts.createProgram` run flagged it. The fix pins the overload: `wrapAsync((file: string) => readFile(file, "utf8"))`.
+Example 16 had passed since the MVP, but `wrapAsync(readFile)` infers from `readFile`'s last overload, so the `Ok` payload was `string | Buffer`, and `text.trim()` was a type error that only worked at runtime because the call happened to pass `"utf8"`. The first `ts.createProgram` run flagged it. The fix pins the overload: `wrapAsync((file: string) => readFile(file, "utf8"))`. The eval harness's `route-match` reference had the same kind of latent error: `.map((s) => (s.kind === "static" ? 3 : 0)).unwrapOr(1)` infers `Option<3 | 0>`, so the fallback `1` does not fit. It now annotates the callback's return as `number`.
The virtual compiler host serves each `.tsus` file as `<file>.tsus.ts` and resolves `./x.tsus` specifiers itself; everything else goes through TypeScript's normal bundler resolution, so `.ts` files importing `.tsus` (example 14) and `.tsus` importing `.ts` (example 13) both type-check as one program.
@@ -90,6 +94,5 @@
1. The bundler plugins transform one file at a time and only run the syntactic rules; type errors surface in `tsus check`, not in the framework build.
2. `tsus check` uses fixed compiler options and ignores `tsconfig.json`.
3. `?` binds like `?:`, so it needs parentheses inside larger expressions; its return-type check is syntactic and does not see through type aliases.
-4. Match arms are typed as a union, and raw object literals in arms are not contextually typed by the declared return type (`tag` widens to `string`); use `tag(...)`.
-5. The regex lookbehind treats `/` after `)` or `}` as division, commas in type arguments inside an arm body rely on a merge heuristic, and an arm body cannot be a statement block.
-6. If any arm awaits, every arm of that match becomes async.
+4. The regex lookbehind treats `/` after `)` or `}` as division, commas in type arguments inside an arm body rely on a merge heuristic, and an arm body cannot be a statement block.
+5. If any arm awaits, every arm of that match becomes async.
View file
ChangedREADME.md+3−4
@@ -65,7 +65,7 @@
match (path) { "/" => a, _ => b } // -> __tsus_match_lit(path)([["/", () => (a)]], () => (b))
```
-`@tsus/runtime` types that object with a mapped type over the subject union's `tag` field, so TypeScript itself requires every variant (unless there is a `_` arm), rejects arms the union cannot hold, and narrows each arm's binding to its variant's payload. This works for `Option`, `Result`, and any user union with a string `tag`. Literal patterns lower to a list of `[literal, handler]` pairs; each literal must be a value of the subject's type, and `_` is required unless the literals cover a finite union like `"GET" | "POST"`. The match's type is the union of its arms' types. If any arm awaits, every arm becomes async and the match is a Promise; `await` inside a string or comment does not count.
+`@tsus/runtime` types that object with a mapped type over the subject union's `tag` field, so TypeScript itself requires every variant (unless there is a `_` arm), rejects arms the union cannot hold, and narrows each arm's binding to its variant's payload. This works for `Option`, `Result`, and any user union with a string `tag`. Literal patterns lower to a list of `[literal, handler]` pairs; each literal must be a value of the subject's type, and `_` is required unless the literals cover a finite union like `"GET" | "POST"`. When the match has a contextual type (a declared return type, an annotated `const`, a typed parameter), every arm is checked against it, so `Err({ kind: "missing" })` infers the declared error union and a wrong arm is reported on that arm; with no context, the match's type is the union of its arms. If any arm awaits, every arm becomes async and the match is a Promise; `await` inside a string or comment does not count.
`expr?` works like Rust's: on an `Err` or `None` it returns that value from the enclosing function, otherwise it unwraps.
@@ -125,8 +125,7 @@
1. The bundler plugins (`@tsus/plugin/*`) transform one file at a time and only run the syntactic rules. Type errors surface in `tsus check`, not in `next build` or `vite build`.
2. `tsus check` uses fixed compiler options (strict, ES2022, bundler resolution, DOM and Node types) and ignores any `tsconfig.json`.
3. `?` binds like the conditional operator, so `a()? + 1` is a syntax error; write `(a()?) + 1`. It cannot appear in a match arm (arms are closures), a `?:` branch, the right side of `&&`/`||`/`??`, or a loop condition. Its return-type check is syntactic: the declared type must be spelled `Result<...>`, `Option<...>`, or `Promise<...>` of one, not an alias.
-4. Match arms are typed as a union, not required to agree. Raw object literals in arms are not contextually typed by the function's return type, so `{ tag: "Circle" }` widens to `tag: string`; build variants with `tag(...)` or annotate.
-5. Regex detection is a one-token lookbehind: after `)` or `}` a `/` is read as division, so `if (x) /re/.test(s)` misparses. Commas in an arm body's type arguments are handled by a heuristic, and an arm body cannot be a statement block.
+4. Regex detection is a one-token lookbehind: after `)` or `}` a `/` is read as division, so `if (x) /re/.test(s)` misparses. Commas in an arm body's type arguments are handled by a heuristic, and an arm body cannot be a statement block.
## The examples
@@ -144,7 +143,7 @@
| `32-regex-literals` | Regex literals containing braces, quotes, a backtick, and a fake match block |
| `33-await-in-string` | `await` inside a string in an arm stays synchronous; a real `await` makes the match async |
| `34-try-operator` | `?` on Result and Option, several per expression, in async functions, next to `?.`, `??`, and ternaries |
-| `36-literal-patterns` | Literal arms over string, number, and boolean subjects; finite unions need no `_` |
+| `36-literal-patterns` | Literal arms over string, number, and boolean subjects; finite unions need no `_`; arms typed by the declared return type |
**Rejected on purpose** (these pass by failing the checker with the right code)
View file
Changedevals/LANGUAGE.md+26−5
@@ -1,6 +1,6 @@
# TypeScript-Ultra-Strict (tsus) primer
-This is the language reference the eval harness gives the model for the `.tsus` side. It describes the compiler as it exists in this repository (`packages/cli`, `packages/runtime`), not the full proposal. If the compiler changes (typed `match`, a `?` operator), update this file in the same commit so the primer never teaches a language the checker does not implement.
+This is the language reference the eval harness gives the model for the `.tsus` side. It describes the compiler as it exists in this repository (`packages/cli`, `packages/runtime`), not the full proposal. If the compiler changes (new syntax, new bans, different checking), update this file in the same commit so the primer never teaches a language the checker does not implement.
## What a .tsus file is
@@ -49,14 +49,35 @@
Rules:
-- Patterns: `Some(x)`, `None`, `Ok(x)`, `Err(e)`, any tag of a `Tagged` union (`Circle(c)` binds the payload), string or number literals (`"GET" => ...`, `404 => ...`), and the wildcard `_`.
+- Patterns: `Some(x)`, `None`, `Ok(x)`, `Err(e)`, any tag of a tagged union (`Circle(c)` binds the payload: the `value` field if the variant has one, else `error`, else the whole variant), string, number, or boolean literals (`"GET" => ...`, `404 => ...`, `true => ...`), and the wildcard `_`. Do not mix variant and literal patterns in one match.
- Each arm body is a single expression. Do not write `Pattern(x) => { statements }`; braces are parsed as an object literal. When an arm needs several steps, call a helper function, or use a ternary.
-- Arms are tried top to bottom. A match with no matching arm crashes at runtime (`TSUS100`), so cover every variant or end with `_`.
-- If an arm body uses `await`, the whole match becomes a promise: write `await match (x) { ... }`.
+- The match is checked at compile time. Every variant needs an arm unless there is a `_` arm (a missing one is `TSUS201`), an arm for a variant the type does not have is `TSUS202`, and each arm's binding is typed as that variant's payload. Literal arms over a finite union (`"GET" | "POST"`) need no `_` once every member is listed; over a plain `string` or `number` they always need `_`.
+- When the match has a declared type (a function return type, an annotated `const`), every arm is checked against it, so `Err({ kind: "missing" })` gets the declared error type. Otherwise the match's type is the union of the arms.
+- If an arm body uses `await`, every arm becomes async and the match is a promise: write `await match (x) { ... }`.
- `match` only fires as `match (expr) {`. A method call like `str.match(/re/)` is untouched.
You do not have to use `match`; `if (opt.isSome())` plus `unwrapOr` or `map` is fine too. Use whatever is clearest.
+## The ? operator
+
+Inside a function whose declared return type is `Result<T, E>`, `Option<T>`, or `Promise` of one, `expr?` unwraps an `Ok`/`Some` and returns an `Err`/`None` from the function early:
+
+```ts
+const loadPort = (raw: string): Result<number, ConfigError> => {
+ const n = parseNumber(raw)?; // returns the Err if parsing failed
+ return n > 0 ? Ok(n) : Err({ kind: "out_of_range", value: n });
+};
+
+const fetchName = async (id: string): Promise<Result<string, ApiError>> => {
+ const user = await getUser(id)?; // ? applies to the awaited Result
+ return Ok(user.name);
+};
+```
+
+- The error type must fit: an `Err<string>` cannot propagate out of a function returning `Result<T, number>`, and `None` can only propagate out of a function returning `Option` (`TSUS302`). Convert first with `mapErr` or `okOr`.
+- `?` covers everything to its left, like the `?:` operator. Inside a larger expression, parenthesize: `Ok((a()?) + (b()?))`.
+- Not allowed at top level, in a function without a declared `Result`/`Option` return type, or inside a match arm (`TSUS300`); not on a value that is not a `Result`/`Option` (`TSUS301`); not in a `?:` branch, on the right of `&&`/`||`/`??`, or in a loop condition (`TSUS303`).
+
## The boundary: talking to JavaScript APIs
Built-in and npm APIs still return `undefined`/`null` and still throw. Convert at the edge:
@@ -94,4 +115,4 @@
## Checker status
-`tsus check` enforces the five bans and the macro syntax. At the time this primer was written it did not yet run full semantic type-checking, so type errors in a `.tsus` file show up when the hidden tests run rather than at compile time. Write well-typed code anyway.
+`tsus check` enforces the bans and the macro syntax, then type-checks the whole file with TypeScript in strict mode. Type errors are reported at their `.tsus` line and column as `TSUS200`, with the TypeScript code in `tsCode`, so fix them the way you would fix a `tsc` error.
View file
Changedevals/tasks/route-match/reference.tsus+1−1
@@ -50,7 +50,7 @@
);
const rank = (segs: Seg[], i: number): number =>
- fromNullable(segs[i]).map((s) => (s.kind === "static" ? 3 : s.kind === "param" ? 2 : 0)).unwrapOr(1);
+ fromNullable(segs[i]).map((s): number => (s.kind === "static" ? 3 : s.kind === "param" ? 2 : 0)).unwrapOr(1);
const compare = (a: Seg[], b: Seg[]): number => {
for (let i = 0; i < Math.max(a.length, b.length); i += 1) {
View file
Changedexamples/31-wrong-arm-type/example.json+1−1
@@ -2,7 +2,7 @@
"expect": "check-fail",
"codes": ["TSUS200", "TSUS202"],
"diagnostics": [
- { "code": "TSUS200", "file": "src/main.tsus", "line": 8, "tsCode": 2322 },
+ { "code": "TSUS200", "file": "src/main.tsus", "line": 9, "col": 14, "tsCode": 2322 },
{ "code": "TSUS200", "file": "src/main.tsus", "line": 17, "col": 23, "tsCode": 2339 },
{ "code": "TSUS202", "file": "src/main.tsus", "line": 23, "col": 5 }
]
View file
Changedexamples/36-literal-patterns/example.json+1−1
@@ -1 +1 @@
-{ "expect": "run", "output": ["write negative off missing other"] }
+{ "expect": "run", "output": ["write negative off missing other", "fine not_found teapot"] }
View file
Changedexamples/36-literal-patterns/src/main.tsus+20−0
@@ -1,3 +1,5 @@
+import { Ok, Err, type Result } from "@tsus/runtime";
+
type Method = "GET" | "POST" | "DELETE";
// Literal arms that cover a finite union need no _ arm.
@@ -29,4 +31,22 @@
_ => "other",
};
+// The declared return type flows into every arm, so the raw object literals
+// below are checked against HttpError instead of widening to { kind: string }.
+type HttpError = { kind: "not_found" } | { kind: "teapot"; code: number };
+
+const fetchStatus = (code: number): Result<string, HttpError> =>
+ match (code) {
+ 404 => Err({ kind: "not_found" }),
+ 418 => Err({ kind: "teapot", code }),
+ _ => Ok("fine"),
+ };
+
+const explain = (r: Result<string, HttpError>): string =>
+ match (r) {
+ Ok(body) => body,
+ Err(e) => e.kind,
+ };
+
console.log(verb("POST"), sign(-1), toggle(false), status(404), status(500));
+console.log(explain(fetchStatus(200)), explain(fetchStatus(404)), explain(fetchStatus(418)));
View file
Changedpackages/cli/src/preprocess.js+6−3
@@ -347,7 +347,8 @@
if (a.binding) {
em.copy(text.slice(a.binding.start, a.binding.end), a.binding.start);
}
- em.synth(") => (", a.arrow.start);
+ em.synth(") => ", a.arrow.start);
+ em.synth("(", tokens[a.bodyLo].start);
em.append(a.em);
em.synth("),", tokens[a.bodyHi - 1].end);
patterns.push({ name: a.name, start: a.first.start });
@@ -363,7 +364,8 @@
}
em.synth("[", a.first.start);
em.copy(text.slice(a.literal.start, a.literal.end), a.literal.start);
- em.synth(`, ${asyncKw}() => (`, a.arrow.start);
+ em.synth(`, ${asyncKw}() => `, a.arrow.start);
+ em.synth("(", tokens[a.bodyLo].start);
em.append(a.em);
em.synth(")],", tokens[a.bodyHi - 1].end);
patterns.push({ name: a.value, start: a.first.start });
@@ -372,7 +374,8 @@
em.synth("]", closeTok.start);
}
if (wildcard) {
- em.synth(`, ${asyncKw}() => (`, wildcard.arrow.start);
+ em.synth(`, ${asyncKw}() => `, wildcard.arrow.start);
+ em.synth("(", tokens[wildcard.bodyLo].start);
em.append(wildcard.em);
em.synth(")", tokens[wildcard.bodyHi - 1].end);
}
View file
Changedpackages/runtime/index.d.ts+25−13
@@ -57,8 +57,16 @@
// the union's `tag` field makes every variant a required key (that is the
// exhaustiveness check), rejects keys the union cannot hold, and types each
// arm's parameter as that variant's payload. Works for Option, Result, and
-// any user union with a string `tag` field. The match's type is the union of
-// the arms' types.
+// any user union with a string `tag` field.
+//
+// The match's type depends on where it sits:
+// - With a contextual type (a declared return type, an annotated const, an
+// argument), R is inferred from that context alone (NoInfer keeps the arms
+// out of it). Every arm is contextually typed by R and must be assignable
+// to it, so `Err({ kind: "missing" })` infers the declared error union and
+// a wrong arm is reported on that arm.
+// - With no context, R stays unknown and the match's type is the union of
+// what the arms return.
/** The tag values of a tagged union. */
export type TagOf<V> = V extends { readonly tag: infer K extends string } ? K : never;
@@ -71,24 +79,28 @@
? E
: V;
-// The arm results here are `any` only so that a match which fails this
-// constraint (the real error) does not also report an `unknown` result
-// everywhere the match is used. A match that type-checks takes its type from
-// the arms actually written, through ArmResult.
-export type MatchArms<V> = { [K in TagOf<V>]: (payload: Payload<VariantOf<V, K>>) => any };
+export type MatchArms<V, R> = { [K in TagOf<V>]: (payload: Payload<VariantOf<V, K>>) => R };
type NoExtraArms<V, A> = { [K in Exclude<keyof A, TagOf<V>>]: never };
type ArmResult<A> = A[keyof A] extends infer F ? (F extends (...args: never[]) => infer R ? R : never) : never;
+/** True when no contextual type reached R. */
+type NoContext<R> = [unknown] extends [R] ? true : false;
+// Without a context the arms' constraint is `any` rather than `unknown`, so a
+// match that fails the constraint (the real error) does not also turn into
+// an `unknown` that errors everywhere it is used.
+type ArmContext<R> = NoContext<R> extends true ? any : NoInfer<R>;
export declare const __tsus_match: <V extends { readonly tag: string }>(
value: V,
-) => <A extends MatchArms<V>>(arms: A & NoExtraArms<V, A>) => ArmResult<A>;
+) => <R, A extends MatchArms<V, ArmContext<R>>>(
+ arms: A & NoExtraArms<V, A>,
+) => NoContext<R> extends true ? ArmResult<A> : R;
export declare const __tsus_match_or: <V extends { readonly tag: string }>(
value: V,
-) => <A extends Partial<MatchArms<V>>, W>(
+) => <R, A extends Partial<MatchArms<V, ArmContext<R>>>, W extends ArmContext<R>>(
arms: A & NoExtraArms<V, A>,
otherwise: (value: V) => W,
-) => ArmResult<A> | W;
+) => NoContext<R> extends true ? ArmResult<A> | W : R;
// Literal patterns (`"/" => ...`) cannot key an object without colliding
// with `_` and losing number/string distinctions, so they lower to a list of
@@ -100,14 +112,14 @@
export declare const __tsus_match_lit: <V extends Literal>(
value: V,
-) => <const C extends readonly (readonly [V, () => unknown])[], W = never>(
+) => <R, const C extends readonly (readonly [V, () => ArmContext<R>])[], W extends ArmContext<R> = never>(
cases: C,
...otherwise: [Exclude<V, CaseLiterals<C>>] extends [never] ? [] : [otherwise: (value: V) => W]
-) => CaseResult<C> | W;
+) => NoContext<R> extends true ? CaseResult<C> | W : R;
// --- the ? operator ---
-// `any` for the same reason as MatchArms: when ? is applied to a non-Result
+// `any` for the same reason as ArmContext: when ? is applied to a non-Result
// (TSUS301), the unwrapped value should not cascade into more errors.
type Tryable = Result<any, any> | Option<any>;
type Bail = { readonly tag: "Err" } | { readonly tag: "None" };
View file

Checks

No checks reported for this commit.

Runs

No runs for this commit.