Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Registry covers the compiler codes (TSUS000, 006, 200-203, 300-303) from codes.js; AGENTS.md teaches typed match, ?, and the narrowing helpers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
b0c0c214ae626ab6cd3863e8aa69dd7f5abf580c
Parent 358de06 Browse filesHistory

Changed files

6 files changed430 additions48 deletionsagainst 358de06

  1. ChangedAGENTS.md+35−12
  2. ChangedREADME.md+1−1
  3. Changeddocs/rules.md+224−5
  4. Changedpackages/cli/src/explain.js+1−1
  5. Changedpackages/cli/src/rules/registry.js+134−17
  6. Changedpackages/cli/templates/AGENTS.md+35−12
ChangedAGENTS.md+35−12
@@ -8,7 +8,7 @@
2. Run `tsus check --json`. Each diagnostic has a stable `code`, a position, a `hint`, and usually a `fix` with exact text edits.
3. Run `tsus fix` to apply every safe fix (`--unsafe` adds fixes that can change behavior; review those). Or apply a diagnostic's `fix.edits` yourself: each edit replaces `[start, end)` (UTF-16 offsets into the original file) with `newText`.
4. For anything left, run `tsus explain <CODE>` and change the code. Do not work around a rule: there is no suppression comment, and `as`, `any` and `!` are themselves errors.
-5. Repeat until `tsus check` passes, then `tsus build` emits plain ESM into `dist/`.
+5. Repeat until `tsus check` passes, then `tsus build` emits plain ESM into `dist/`. `tsus check` also type-checks the project in strict mode; a TypeScript error comes back as `TSUS200` with the original code in `tsCode`.
To port a `.ts` file, run `tsus migrate src/file.ts`. It writes `src/file.tsus` next to it and lists what it could not convert.
@@ -26,11 +26,13 @@
const ada: User = { name: "ada", email: Some("ada@example.com") };
const nobody: Option<string> = None;
-// Errors are a closed set the caller can match on.
-type LoadError = "empty id" | Tagged<"NotFound", string> | { tag: "Timeout"; ms: number };
+// Errors are a closed set the caller can match on: all string literals,
+// or all tagged variants. Never string, Error or a mix of the two kinds.
+type ParseError = "empty" | "not a number";
+type LoadError = Tagged<"EmptyId", string> | Tagged<"NotFound", string> | { tag: "Timeout"; ms: number };
const load = (id: string): Result<User, LoadError> =>
- id === "" ? Err("empty id") : Err(tag("NotFound", id));
+ id === "" ? Err(tag("EmptyId", id)) : Err(tag("NotFound", id));
```
- `Option<T>`: `Some(value)` or `None`. Methods: `map`, `andThen`, `unwrapOr(fallback)`, `okOr(error)`, `isSome()`, `isNone()`.
@@ -38,6 +40,7 @@
- `Tagged<"Name", V>` and `tag("Name", value)` build tagged variants; any object type with a literal `tag` field works too.
- Behavior lives in functions that take data and return new data: `const rename = (u: User, name: string): User => ({ ...u, name });`.
- A `void` operation that can fail returns `Result<true, E>` and ends with `return Ok(true);`.
+- A string literal passed to a generic widens to `string` (`okOr("empty")` is `Result<T, string>`). Give the type argument (`okOr<ParseError>("empty")`) or return through a function whose return type names the error.
## match
@@ -52,19 +55,26 @@
const explain = (e: LoadError): string =>
match (e) {
- "empty id" => "no id given", // literal pattern
- NotFound(id) => `no user ${id}`, // Tagged variant: binds its value
- _ => "timed out", // wildcard
+ NotFound(id) => `no user ${id}`, // Tagged variant: binds its value
+ Timeout(t) => `timed out after ${t.ms}ms`, // plain tagged object: binds the object
+ _ => "no id given", // wildcard
};
+
+const describe = (e: ParseError): string =>
+ match (e) {
+ "empty" => "nothing to parse", // literal patterns
+ "not a number" => "digits only", // a finite union needs no _
+ };
```
-- Patterns: `Some(x)`, `None`, `Ok(x)`, `Err(e)`, any tag name `Variant(x)` (binds `.value` for `Tagged`, the whole object otherwise), string or number literals, and `_`.
-- Arms are expressions, not blocks. Put multi-step logic in a named function and call it from the arm.
+- Variant patterns: `Some(x)`, `None`, `Ok(x)`, `Err(e)`, and any tag `Variant(x)` of a union with a literal `tag` field (binds `.value` for `Tagged`, the whole object otherwise). Literal patterns: string, number or boolean literals. One match uses one kind, not both; either kind may end with `_`.
+- Matches are checked at compile time: a missing variant is TSUS201, an arm the subject cannot hold is TSUS202. A literal match over a plain `string` needs `_`.
+- Arms are expressions, not blocks. Put multi-step logic in a named function and call it from the arm. Build tagged values in arms with `tag(...)`, not raw object literals (the `tag` field would widen to `string`).
- Matches nest. An arm may `await`; then write `await match (...) { ... }`.
## The ? operator
-`?` after a `Result` or `Option` expression returns early with its `Err` or `None`, and otherwise yields the inner value. It only works inside a function whose declared return type is a `Result` or `Option` (or a `Promise` of one), and the error types must line up (use `mapErr` first if not). In async code, await first: `const user = (await load(id))?;`.
+`?` after a `Result` or `Option` expression returns early with its `Err` or `None`, and otherwise yields the inner value. It only works inside a function whose declared return type is a `Result` or `Option` (or a `Promise` of one), never at top level or inside a match arm (TSUS300). Error types must line up: convert with `mapErr`, or turn an Option into a Result with `okOr` (TSUS302). In async code `?` applies to the awaited value: `const user = await load(id)?;`. `?` binds loosely, so wrap it in parentheses inside larger expressions (`(a?) + (b?)`), and keep it out of `?:` branches, the right side of `&&` `||` `??`, and loop conditions (TSUS303).
```ts
const total = (rawA: string, rawB: string): Result<number, ParseError> => {
@@ -72,6 +82,11 @@
const b = parse(rawB)?;
return Ok(a + b);
};
+
+const portOf = (env: Map<string, string>): Result<number, ParseError> => {
+ const raw = fromNullable(env.get("PORT")).okOr<ParseError>("empty")?;
+ return parse(raw);
+};
```
## The boundary
@@ -80,7 +95,7 @@
```ts
import { tag, type Tagged } from "@tsus/runtime";
-import { fromNullable, wrapSync, wrapAsync } from "@tsus/runtime/boundary";
+import { fromNullable, wrapSync, wrapAsync, isRecord, asRecord, field } from "@tsus/runtime/boundary";
import { readFile } from "node:fs/promises";
const first = fromNullable([1, 2].find((n) => n > 1)); // T | null | undefined -> Option<T>
@@ -91,7 +106,7 @@
const text = (await read("a.txt", "utf8")).mapErr((e): ReadError => tag("ReadFailed", e.message));
```
-Map `Error` into your own tagged error type right away with `mapErr`. A file named `*.boundary.tsus` may use `as` casts (after a runtime check) and default exports (for hosts such as Cloudflare Workers that require `export default`). All other rules still apply there. Keep boundary files small; validate untrusted data with a schema library such as zod and return a `Result`.
+For `unknown` data use `isRecord(v)` (a type guard: plain object, not null, not an array), `asRecord(v)` (`Option<Record<string, unknown>>`) and `field(v, "key")` (an own property as `Option<unknown>`) instead of casts. Map `Error` into your own tagged error type right away with `mapErr`. A file named `*.boundary.tsus` may use `as` casts (after a runtime check) and default exports (for hosts such as Cloudflare Workers that require `export default`). All other rules still apply there. Keep boundary files small; validate untrusted data with a schema library such as zod and return a `Result`.
## Diagnostic codes
@@ -106,6 +121,14 @@
| TSUS005 | throw is banned | none |
| TSUS006 | Malformed match expression | none |
| TSUS100 | Non-exhaustive match (runtime) | none |
+| TSUS200 | Type error | none |
+| TSUS201 | Non-exhaustive match | none |
+| TSUS202 | Match arm does not fit the subject | none |
+| TSUS203 | Match subject is not matchable | none |
+| TSUS300 | ? outside a function returning Result or Option | none |
+| TSUS301 | ? applied to something that is not a Result or Option | none |
+| TSUS302 | ? propagates a value the function cannot return | none |
+| TSUS303 | ? in a position that may not run | none |
| TSUS401 | any is banned | safe |
| TSUS402 | as casts are banned outside boundary files | none |
| TSUS403 | Non-null assertions are banned | none |
View file
ChangedREADME.md+1−1
@@ -139,7 +139,7 @@
|---|---|
| `tsus check [dir] --json` | Every diagnostic has a stable `code`, `start`/`end` offsets and line/col ranges in the original `.tsus` file, a `hint`, an `explain` pointer, and a `fix` (or `null`) |
| `tsus fix [dir]` | Applies every safe fix, re-checking between passes. `--unsafe` adds fixes that can change behavior, `--code TSUS405` limits it to one rule, `--dry-run` reports without writing |
-| `tsus explain <CODE>` | The rule, why it exists, a rejected and an accepted example. `--list` prints every code, `--json` the raw entry |
+| `tsus explain <CODE>` | The rule, why it exists, a rejected and an accepted example, for every code: the strictness rules, the macro and type-check codes (TSUS000, TSUS006, TSUS200 to TSUS203) and the `?` codes (TSUS300 to TSUS303). `--list` prints every code, `--json` the raw entry |
| `tsus init [dir]` | Scaffolds `AGENTS.md` (plus a `CLAUDE.md` that imports it), a strict `tsconfig.json`, `package.json` and a starter `src/main.tsus`. Never overwrites; `--force` refreshes only `AGENTS.md` |
| `tsus migrate <file.ts>` | Codemod: `T \| null` and `T \| undefined` returns become `Option<T>`, throwing functions return `Result<T, E>` with a literal or tagged `E`, simple classes become a data type plus functions, `var` becomes `const` or `let`. Writes `<file>.tsus` next to the input and reports, with line numbers, everything it did not convert (including whatever the checker still rejects in the output) |
View file
Changeddocs/rules.md+224−5
@@ -12,6 +12,14 @@
| TSUS005 | throw is banned | none |
| TSUS006 | Malformed match expression | none |
| TSUS100 | Non-exhaustive match (runtime) | none |
+| TSUS200 | Type error | none |
+| TSUS201 | Non-exhaustive match | none |
+| TSUS202 | Match arm does not fit the subject | none |
+| TSUS203 | Match subject is not matchable | none |
+| TSUS300 | ? outside a function returning Result or Option | none |
+| TSUS301 | ? applied to something that is not a Result or Option | none |
+| TSUS302 | ? propagates a value the function cannot return | none |
+| TSUS303 | ? in a position that may not run | none |
| TSUS401 | any is banned | safe |
| TSUS402 | as casts are banned outside boundary files | none |
| TSUS403 | Non-null assertions are banned | none |
@@ -171,7 +179,7 @@
## TSUS006 match-syntax
-**Malformed match expression.** The match macro is expanded before TypeScript parses the file, so a malformed match has to be reported by the macro itself.
+**Malformed match expression.** The match macro is expanded before TypeScript parses the file, so a malformed match has to be reported by the macro itself. One match uses either variant patterns or literal patterns, never both.
Rejected:
@@ -190,34 +198,245 @@
};
```
-Hint: Arms look like: Pattern(binding) => expression, separated by commas.
+Hint: Arms look like: Variant(binding) => expression, "literal" => expression, or _ => expression, separated by commas.
Fix: No automatic fix: the right change depends on intent.
-## TSUS100 non-exhaustive-match
+## TSUS100 non-exhaustive-match-runtime
-**Non-exhaustive match (runtime).** A match that falls through has no value to return. Raised at runtime by __tsus_match until exhaustiveness is checked at compile time.
+**Non-exhaustive match (runtime).** Thrown by the runtime if a value reaches a match that has no arm for it, which type-checked code only allows when outside data lies about its type. The compile-time check is TSUS201.
Rejected:
```ts
+// data from JSON claims to be a Shape but has tag "Hexagon"
const name = (s: Shape): string =>
match (s) {
Circle(c) => "circle",
+ Rect(r) => "rect",
};
```
Accepted:
```ts
+// validate outside data at the boundary before it becomes a Shape
const name = (s: Shape): string =>
match (s) {
Circle(c) => "circle",
- _ => "other",
+ Rect(r) => "rect",
};
```
Hint: Add an arm for every variant, or a _ arm.
+
+Fix: No automatic fix: the right change depends on intent.
+
+## TSUS200 type-error
+
+**Type error.** The whole project is type-checked by TypeScript in strict mode after macro expansion. Each TypeScript error is reported at its .tsus position with the TypeScript code in tsCode.
+
+Rejected:
+
+```ts
+const port: number = "8080";
+```
+
+Accepted:
+
+```ts
+const port: number = 8080;
+```
+
+Hint: The original TypeScript diagnostic is in tsCode and the message.
+
+Fix: No automatic fix: the right change depends on intent.
+
+## TSUS201 non-exhaustive-match
+
+**Non-exhaustive match.** A match has to produce a value for every case. Missing a variant is the bug match exists to prevent, so it fails at compile time.
+
+Rejected:
+
+```ts
+type Shape = Tagged<"Circle", number> | Tagged<"Square", number>;
+
+const area = (s: Shape): number =>
+ match (s) {
+ Circle(r) => Math.PI * r * r,
+ };
+```
+
+Accepted:
+
+```ts
+const area = (s: Shape): number =>
+ match (s) {
+ Circle(r) => Math.PI * r * r,
+ Square(side) => side * side,
+ };
+```
+
+Hint: Add an arm for every missing variant, or a _ arm to cover the rest.
+
+Fix: No automatic fix: the right change depends on intent.
+
+## TSUS202 match-arm-mismatch
+
+**Match arm does not fit the subject.** An arm for a variant the subject cannot hold is dead code, and usually a typo for a variant it can hold.
+
+Rejected:
+
+```ts
+const area = (s: Shape): number =>
+ match (s) {
+ Circle(r) => Math.PI * r * r,
+ Sqaure(side) => side * side,
+ };
+```
+
+Accepted:
+
+```ts
+const area = (s: Shape): number =>
+ match (s) {
+ Circle(r) => Math.PI * r * r,
+ Square(side) => side * side,
+ };
+```
+
+Hint: Each pattern must be a variant tag (or literal value) the subject's type can actually hold.
+
+Fix: No automatic fix: the right change depends on intent.
+
+## TSUS203 match-subject
+
+**Match subject is not matchable.** Variant patterns read the subject's tag field and literal patterns compare primitive values, so the subject must be a tagged union or a primitive.
+
+Rejected:
+
+```ts
+const describe = (d: Date): string =>
+ match (d) {
+ Some(x) => "some",
+ None => "none",
+ };
+```
+
+Accepted:
+
+```ts
+const describe = (d: Option<Date>): string =>
+ match (d) {
+ Some(x) => x.toISOString(),
+ None => "none",
+ };
+```
+
+Hint: Variant patterns need a tagged union (a `tag` field); literal patterns need a string, number, bigint, or boolean subject.
+
+Fix: No automatic fix: the right change depends on intent.
+
+## TSUS300 try-outside-result-function
+
+**? outside a function returning Result or Option.** ? returns early with the Err or None, so the enclosing function must be able to return one. Match arms are closures, and the top level has nothing to return from.
+
+Rejected:
+
+```ts
+const total = (raw: string): number => {
+ const n = parse(raw)?;
+ return n;
+};
+```
+
+Accepted:
+
+```ts
+const total = (raw: string): Result<number, ParseError> => {
+ const n = parse(raw)?;
+ return Ok(n);
+};
+```
+
+Hint: Declare the enclosing function's return type as Result<T, E>, Option<T>, or Promise<...> of one; ? cannot be used at top level or inside match arms, which are closures.
+
+Fix: No automatic fix: the right change depends on intent.
+
+## TSUS301 try-on-non-result
+
+**? applied to something that is not a Result or Option.** Only Result and Option have an Err or None to propagate.
+
+Rejected:
+
+```ts
+const shout = (raw: string): Result<string, "empty"> => {
+ const text = raw?;
+ return Ok(text.toUpperCase());
+};
+```
+
+Accepted:
+
+```ts
+const shout = (raw: string): Result<string, "empty"> =>
+ raw === "" ? Err("empty") : Ok(raw.toUpperCase());
+```
+
+Hint: Only Result and Option values can be propagated with ?. In async code, await first: `const x = await load()?;`.
+
+Fix: No automatic fix: the right change depends on intent.
+
+## TSUS302 try-incompatible-error
+
+**? propagates a value the function cannot return.** The early return has to fit the function's declared return type: the error types must line up, and None cannot leave a function that returns Result.
+
+Rejected:
+
+```ts
+const port = (env: Option<string>): Result<number, "bad port"> => {
+ const raw = env?;
+ return parsePort(raw);
+};
+```
+
+Accepted:
+
+```ts
+const port = (env: Option<string>): Result<number, "bad port"> => {
+ const raw = env.okOr<"bad port">("bad port")?;
+ return parsePort(raw);
+};
+```
+
+Hint: An Err must match the function's error type, and None can only propagate out of a function returning Option. Convert first (mapErr, okOr).
+
+Fix: No automatic fix: the right change depends on intent.
+
+## TSUS303 try-conditional-position
+
+**? in a position that may not run.** ? becomes an early return before its statement, so it cannot sit in code that might not run: a ?: branch, the right side of && || ??, or a loop condition.
+
+Rejected:
+
+```ts
+const check = (raw: string): Result<boolean, ParseError> =>
+ Ok(raw.length > 0 && (parse(raw)?) > 1);
+```
+
+Accepted:
+
+```ts
+const check = (raw: string): Result<boolean, ParseError> => {
+ if (raw.length === 0) {
+ return Ok(false);
+ }
+ const n = parse(raw)?;
+ return Ok(n > 1);
+};
+```
+
+Hint: ? is lowered to an early return before the statement, so it cannot sit in a ?: branch, the right side of && || ??, or a loop condition. Move it into its own statement.
Fix: No automatic fix: the right change depends on intent.
View file
Changedpackages/cli/src/explain.js+1−1
@@ -34,7 +34,7 @@
].join("\n");
export const renderList = () =>
- REGISTRY.map((r) => `${r.code} ${r.name.padEnd(24)} ${r.title}`).join("\n");
+ REGISTRY.map((r) => `${r.code} ${r.name.padEnd(30)} ${r.title}`).join("\n");
export const explain = (code) => ruleFor(code);
View file
Changedpackages/cli/src/rules/registry.js+134−17
@@ -6,18 +6,21 @@
// "unsafe" -> a fix exists but can change behavior; `tsus fix --unsafe`
// "none" -> a human (or agent) has to decide
-export const REGISTRY = [
- {
- code: "TSUS000",
+import { CODES } from "../codes.js";
+
+// Compiler codes (macro, type-check, ?) take message and hint from codes.js,
+// which the compiler itself reports with; the registry adds the docs.
+const compiler = (code, docs) => ({ code, ...CODES[code], ...docs });
+
+const ENTRIES = [
+ compiler("TSUS000", {
name: "syntax-error",
title: "Syntax error",
- message: "syntax error",
- hint: "The file does not parse as TypeScript after macro expansion.",
why: "Every other rule runs on the parsed tree, so nothing else can be checked until the file parses.",
bad: `const total = (a: number, b: number): number => a + ;`,
good: `const total = (a: number, b: number): number => a + b;`,
fix: "none",
- },
+ }),
{
code: "TSUS001",
name: "no-class",
@@ -96,13 +99,10 @@
};`,
fix: "none",
},
- {
- code: "TSUS006",
+ compiler("TSUS006", {
name: "match-syntax",
title: "Malformed match expression",
- message: "match macro error",
- hint: "Arms look like: Pattern(binding) => expression, separated by commas.",
- why: "The match macro is expanded before TypeScript parses the file, so a malformed match has to be reported by the macro itself.",
+ why: "The match macro is expanded before TypeScript parses the file, so a malformed match has to be reported by the macro itself. One match uses either variant patterns or literal patterns, never both.",
bad: `const label = match (opt) {
Some(x) -> x,
};`,
@@ -111,25 +111,140 @@
None => "none",
};`,
fix: "none",
- },
+ }),
{
code: "TSUS100",
- name: "non-exhaustive-match",
+ name: "non-exhaustive-match-runtime",
title: "Non-exhaustive match (runtime)",
message: "non-exhaustive match, no arm matched",
hint: "Add an arm for every variant, or a _ arm.",
- why: "A match that falls through has no value to return. Raised at runtime by __tsus_match until exhaustiveness is checked at compile time.",
- bad: `const name = (s: Shape): string =>
+ why: "Thrown by the runtime if a value reaches a match that has no arm for it, which type-checked code only allows when outside data lies about its type. The compile-time check is TSUS201.",
+ bad: `// data from JSON claims to be a Shape but has tag "Hexagon"
+const name = (s: Shape): string =>
match (s) {
Circle(c) => "circle",
+ Rect(r) => "rect",
};`,
- good: `const name = (s: Shape): string =>
+ good: `// validate outside data at the boundary before it becomes a Shape
+const name = (s: Shape): string =>
match (s) {
Circle(c) => "circle",
- _ => "other",
+ Rect(r) => "rect",
};`,
fix: "none",
},
+ compiler("TSUS200", {
+ name: "type-error",
+ title: "Type error",
+ why: "The whole project is type-checked by TypeScript in strict mode after macro expansion. Each TypeScript error is reported at its .tsus position with the TypeScript code in tsCode.",
+ bad: `const port: number = "8080";`,
+ good: `const port: number = 8080;`,
+ fix: "none",
+ }),
+ compiler("TSUS201", {
+ name: "non-exhaustive-match",
+ title: "Non-exhaustive match",
+ why: "A match has to produce a value for every case. Missing a variant is the bug match exists to prevent, so it fails at compile time.",
+ bad: `type Shape = Tagged<"Circle", number> | Tagged<"Square", number>;
+
+const area = (s: Shape): number =>
+ match (s) {
+ Circle(r) => Math.PI * r * r,
+ };`,
+ good: `const area = (s: Shape): number =>
+ match (s) {
+ Circle(r) => Math.PI * r * r,
+ Square(side) => side * side,
+ };`,
+ fix: "none",
+ }),
+ compiler("TSUS202", {
+ name: "match-arm-mismatch",
+ title: "Match arm does not fit the subject",
+ why: "An arm for a variant the subject cannot hold is dead code, and usually a typo for a variant it can hold.",
+ bad: `const area = (s: Shape): number =>
+ match (s) {
+ Circle(r) => Math.PI * r * r,
+ Sqaure(side) => side * side,
+ };`,
+ good: `const area = (s: Shape): number =>
+ match (s) {
+ Circle(r) => Math.PI * r * r,
+ Square(side) => side * side,
+ };`,
+ fix: "none",
+ }),
+ compiler("TSUS203", {
+ name: "match-subject",
+ title: "Match subject is not matchable",
+ why: "Variant patterns read the subject's tag field and literal patterns compare primitive values, so the subject must be a tagged union or a primitive.",
+ bad: `const describe = (d: Date): string =>
+ match (d) {
+ Some(x) => "some",
+ None => "none",
+ };`,
+ good: `const describe = (d: Option<Date>): string =>
+ match (d) {
+ Some(x) => x.toISOString(),
+ None => "none",
+ };`,
+ fix: "none",
+ }),
+ compiler("TSUS300", {
+ name: "try-outside-result-function",
+ title: "? outside a function returning Result or Option",
+ why: "? returns early with the Err or None, so the enclosing function must be able to return one. Match arms are closures, and the top level has nothing to return from.",
+ bad: `const total = (raw: string): number => {
+ const n = parse(raw)?;
+ return n;
+};`,
+ good: `const total = (raw: string): Result<number, ParseError> => {
+ const n = parse(raw)?;
+ return Ok(n);
+};`,
+ fix: "none",
+ }),
+ compiler("TSUS301", {
+ name: "try-on-non-result",
+ title: "? applied to something that is not a Result or Option",
+ why: "Only Result and Option have an Err or None to propagate.",
+ bad: `const shout = (raw: string): Result<string, "empty"> => {
+ const text = raw?;
+ return Ok(text.toUpperCase());
+};`,
+ good: `const shout = (raw: string): Result<string, "empty"> =>
+ raw === "" ? Err("empty") : Ok(raw.toUpperCase());`,
+ fix: "none",
+ }),
+ compiler("TSUS302", {
+ name: "try-incompatible-error",
+ title: "? propagates a value the function cannot return",
+ why: "The early return has to fit the function's declared return type: the error types must line up, and None cannot leave a function that returns Result.",
+ bad: `const port = (env: Option<string>): Result<number, "bad port"> => {
+ const raw = env?;
+ return parsePort(raw);
+};`,
+ good: `const port = (env: Option<string>): Result<number, "bad port"> => {
+ const raw = env.okOr<"bad port">("bad port")?;
+ return parsePort(raw);
+};`,
+ fix: "none",
+ }),
+ compiler("TSUS303", {
+ name: "try-conditional-position",
+ title: "? in a position that may not run",
+ why: "? becomes an early return before its statement, so it cannot sit in code that might not run: a ?: branch, the right side of && || ??, or a loop condition.",
+ bad: `const check = (raw: string): Result<boolean, ParseError> =>
+ Ok(raw.length > 0 && (parse(raw)?) > 1);`,
+ good: `const check = (raw: string): Result<boolean, ParseError> => {
+ if (raw.length === 0) {
+ return Ok(false);
+ }
+ const n = parse(raw)?;
+ return Ok(n > 1);
+};`,
+ fix: "none",
+ }),
{
code: "TSUS401",
name: "no-any",
@@ -334,6 +449,8 @@
fix: "safe",
},
];
+
+export const REGISTRY = ENTRIES;
export const RULES_BY_CODE = new Map(REGISTRY.map((r) => [r.code, r]));
View file
Changedpackages/cli/templates/AGENTS.md+35−12
@@ -8,7 +8,7 @@
2. Run `tsus check --json`. Each diagnostic has a stable `code`, a position, a `hint`, and usually a `fix` with exact text edits.
3. Run `tsus fix` to apply every safe fix (`--unsafe` adds fixes that can change behavior; review those). Or apply a diagnostic's `fix.edits` yourself: each edit replaces `[start, end)` (UTF-16 offsets into the original file) with `newText`.
4. For anything left, run `tsus explain <CODE>` and change the code. Do not work around a rule: there is no suppression comment, and `as`, `any` and `!` are themselves errors.
-5. Repeat until `tsus check` passes, then `tsus build` emits plain ESM into `dist/`.
+5. Repeat until `tsus check` passes, then `tsus build` emits plain ESM into `dist/`. `tsus check` also type-checks the project in strict mode; a TypeScript error comes back as `TSUS200` with the original code in `tsCode`.
To port a `.ts` file, run `tsus migrate src/file.ts`. It writes `src/file.tsus` next to it and lists what it could not convert.
@@ -26,11 +26,13 @@
const ada: User = { name: "ada", email: Some("ada@example.com") };
const nobody: Option<string> = None;
-// Errors are a closed set the caller can match on.
-type LoadError = "empty id" | Tagged<"NotFound", string> | { tag: "Timeout"; ms: number };
+// Errors are a closed set the caller can match on: all string literals,
+// or all tagged variants. Never string, Error or a mix of the two kinds.
+type ParseError = "empty" | "not a number";
+type LoadError = Tagged<"EmptyId", string> | Tagged<"NotFound", string> | { tag: "Timeout"; ms: number };
const load = (id: string): Result<User, LoadError> =>
- id === "" ? Err("empty id") : Err(tag("NotFound", id));
+ id === "" ? Err(tag("EmptyId", id)) : Err(tag("NotFound", id));
```
- `Option<T>`: `Some(value)` or `None`. Methods: `map`, `andThen`, `unwrapOr(fallback)`, `okOr(error)`, `isSome()`, `isNone()`.
@@ -38,6 +40,7 @@
- `Tagged<"Name", V>` and `tag("Name", value)` build tagged variants; any object type with a literal `tag` field works too.
- Behavior lives in functions that take data and return new data: `const rename = (u: User, name: string): User => ({ ...u, name });`.
- A `void` operation that can fail returns `Result<true, E>` and ends with `return Ok(true);`.
+- A string literal passed to a generic widens to `string` (`okOr("empty")` is `Result<T, string>`). Give the type argument (`okOr<ParseError>("empty")`) or return through a function whose return type names the error.
## match
@@ -52,19 +55,26 @@
const explain = (e: LoadError): string =>
match (e) {
- "empty id" => "no id given", // literal pattern
- NotFound(id) => `no user ${id}`, // Tagged variant: binds its value
- _ => "timed out", // wildcard
+ NotFound(id) => `no user ${id}`, // Tagged variant: binds its value
+ Timeout(t) => `timed out after ${t.ms}ms`, // plain tagged object: binds the object
+ _ => "no id given", // wildcard
};
+
+const describe = (e: ParseError): string =>
+ match (e) {
+ "empty" => "nothing to parse", // literal patterns
+ "not a number" => "digits only", // a finite union needs no _
+ };
```
-- Patterns: `Some(x)`, `None`, `Ok(x)`, `Err(e)`, any tag name `Variant(x)` (binds `.value` for `Tagged`, the whole object otherwise), string or number literals, and `_`.
-- Arms are expressions, not blocks. Put multi-step logic in a named function and call it from the arm.
+- Variant patterns: `Some(x)`, `None`, `Ok(x)`, `Err(e)`, and any tag `Variant(x)` of a union with a literal `tag` field (binds `.value` for `Tagged`, the whole object otherwise). Literal patterns: string, number or boolean literals. One match uses one kind, not both; either kind may end with `_`.
+- Matches are checked at compile time: a missing variant is TSUS201, an arm the subject cannot hold is TSUS202. A literal match over a plain `string` needs `_`.
+- Arms are expressions, not blocks. Put multi-step logic in a named function and call it from the arm. Build tagged values in arms with `tag(...)`, not raw object literals (the `tag` field would widen to `string`).
- Matches nest. An arm may `await`; then write `await match (...) { ... }`.
## The ? operator
-`?` after a `Result` or `Option` expression returns early with its `Err` or `None`, and otherwise yields the inner value. It only works inside a function whose declared return type is a `Result` or `Option` (or a `Promise` of one), and the error types must line up (use `mapErr` first if not). In async code, await first: `const user = (await load(id))?;`.
+`?` after a `Result` or `Option` expression returns early with its `Err` or `None`, and otherwise yields the inner value. It only works inside a function whose declared return type is a `Result` or `Option` (or a `Promise` of one), never at top level or inside a match arm (TSUS300). Error types must line up: convert with `mapErr`, or turn an Option into a Result with `okOr` (TSUS302). In async code `?` applies to the awaited value: `const user = await load(id)?;`. `?` binds loosely, so wrap it in parentheses inside larger expressions (`(a?) + (b?)`), and keep it out of `?:` branches, the right side of `&&` `||` `??`, and loop conditions (TSUS303).
```ts
const total = (rawA: string, rawB: string): Result<number, ParseError> => {
@@ -72,6 +82,11 @@
const b = parse(rawB)?;
return Ok(a + b);
};
+
+const portOf = (env: Map<string, string>): Result<number, ParseError> => {
+ const raw = fromNullable(env.get("PORT")).okOr<ParseError>("empty")?;
+ return parse(raw);
+};
```
## The boundary
@@ -80,7 +95,7 @@
```ts
import { tag, type Tagged } from "@tsus/runtime";
-import { fromNullable, wrapSync, wrapAsync } from "@tsus/runtime/boundary";
+import { fromNullable, wrapSync, wrapAsync, isRecord, asRecord, field } from "@tsus/runtime/boundary";
import { readFile } from "node:fs/promises";
const first = fromNullable([1, 2].find((n) => n > 1)); // T | null | undefined -> Option<T>
@@ -91,7 +106,7 @@
const text = (await read("a.txt", "utf8")).mapErr((e): ReadError => tag("ReadFailed", e.message));
```
-Map `Error` into your own tagged error type right away with `mapErr`. A file named `*.boundary.tsus` may use `as` casts (after a runtime check) and default exports (for hosts such as Cloudflare Workers that require `export default`). All other rules still apply there. Keep boundary files small; validate untrusted data with a schema library such as zod and return a `Result`.
+For `unknown` data use `isRecord(v)` (a type guard: plain object, not null, not an array), `asRecord(v)` (`Option<Record<string, unknown>>`) and `field(v, "key")` (an own property as `Option<unknown>`) instead of casts. Map `Error` into your own tagged error type right away with `mapErr`. A file named `*.boundary.tsus` may use `as` casts (after a runtime check) and default exports (for hosts such as Cloudflare Workers that require `export default`). All other rules still apply there. Keep boundary files small; validate untrusted data with a schema library such as zod and return a `Result`.
## Diagnostic codes
@@ -106,6 +121,14 @@
| TSUS005 | throw is banned | none |
| TSUS006 | Malformed match expression | none |
| TSUS100 | Non-exhaustive match (runtime) | none |
+| TSUS200 | Type error | none |
+| TSUS201 | Non-exhaustive match | none |
+| TSUS202 | Match arm does not fit the subject | none |
+| TSUS203 | Match subject is not matchable | none |
+| TSUS300 | ? outside a function returning Result or Option | none |
+| TSUS301 | ? applied to something that is not a Result or Option | none |
+| TSUS302 | ? propagates a value the function cannot return | none |
+| TSUS303 | ? in a position that may not run | none |
| TSUS401 | any is banned | safe |
| TSUS402 | as casts are banned outside boundary files | none |
| TSUS403 | Non-null assertions are banned | none |
View file

Checks

No checks reported for this commit.

Runs

No runs for this commit.