Build tsus MVP: runtime, CLI compiler/checker, 26/26 examples passing
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Changed files
14 files changed876 additions0 deletionsagainst dc221d2
- ChangedLEARNINGS.md+9−0
- ChangedREADME.md+2−0
- Changedpackage-lock.json+22−0
- Addedpackages/cli/bin/tsus.js+48−0
- Addedpackages/cli/package.json+11−0
- Addedpackages/cli/src/build.js+106−0
- Addedpackages/cli/src/check.js+88−0
- Addedpackages/cli/src/preprocess.js+335−0
- Addedpackages/runtime/boundary.d.ts+11−0
- Addedpackages/runtime/boundary.js+22−0
- Addedpackages/runtime/index.d.ts+33−0
- Addedpackages/runtime/index.js+79−0
- Addedpackages/runtime/package.json+15−0
- Addedscripts/run-examples.mjs+95−0
ChangedLEARNINGS.md+9−0
| @@ -27,3 +27,12 @@ | ||
| - Bare string-literal patterns (`"/" => ...` in the worker example) mean patterns are not just variant tags; the runtime match needs literal equality patterns plus a `_` wildcard. | ||
| - Circular `.tsus` imports (example 21) are fine as long as the cycle is function-level, because compiled output is ESM and ESM handles cycles with hoisted bindings. The compiler does not need to detect cycles for the MVP. | ||
| - The checker rules (no class, no null, no undefined, no var, no throw) apply to `.tsus` files only. Examples 13 and 22 have `.ts` dependencies that use classes, null, and undefined on purpose; the checker must scope itself by extension or mixed projects are impossible. | ||
| + | ||
| +## Outcome | ||
| + | ||
| +With the MVP in place (`packages/runtime` + `packages/cli`), the harness reports 26/26 examples passing, including the five that pass by being rejected with the expected diagnostic code. Known MVP limitations, in honesty order: | ||
| + | ||
| +1. No semantic type-checking yet: `tsus build` strips types per-module (`ts.transpileModule`), so type errors surface at runtime. The next step is a `ts.createProgram` pass with a virtual file system that maps `.tsus` to preprocessed TS. | ||
| +2. No exhaustiveness checking: a non-exhaustive match throws `TSUS100` at runtime instead of failing at compile time. | ||
| +3. The `await`-in-arm detection is textual, so a string literal containing the word `await` would wrongly make that arm async. | ||
| +4. Regex literals are not tokenized; a regex containing a quote or brace character could confuse the scanner. | ||
ChangedREADME.md+2−0
| @@ -2,6 +2,8 @@ | ||
| This is my proposal for TypeScript-Ultra-Strict: a stricter TypeScript for a world where AI writes most of the code. | ||
| +> **Status: working MVP on the `mvp` branch.** `packages/cli` implements `tsus check` and `tsus build`, `packages/runtime` implements `Option`/`Result`/`match` and the boundary layer, and all 26 projects under `examples/` pass (`npm install && npm run examples`). The 5 `banned-*` examples pass by being rejected with the right diagnostic codes. `LEARNINGS.md` documents what broke before the toolchain existed and how that shaped the design. The compiled output is plain ESM; the worker example (`examples/23-cloudflare-worker`) exports the Cloudflare `{ fetch }` module shape and runs against real `Request`/`Response` objects, so `wrangler` can bundle it as-is. | ||
| + | ||
| TypeScript's early design decisions assumed humans would write and maintain it, so a lot of features exist to make a human's life easier. We valued speed over quality. With AI writing most of our code, we can flip that tradeoff and force the language to be declarative and verifiable, like Rust. | ||
| ## What changes | ||
Changedpackage-lock.json+22−0
| @@ -13,6 +13,14 @@ | ||
| "zod": "^3.23.0" | ||
| } | ||
| }, | ||
| + "node_modules/@tsus/cli": { | ||
| + "resolved": "packages/cli", | ||
| + "link": true | ||
| + }, | ||
| + "node_modules/@tsus/runtime": { | ||
| + "resolved": "packages/runtime", | ||
| + "link": true | ||
| + }, | ||
| "node_modules/typescript": { | ||
| "version": "5.9.3", | ||
| "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", | ||
| @@ -34,6 +42,20 @@ | ||
| "funding": { | ||
| "url": "https://github.com/sponsors/colinhacks" | ||
| } | ||
| + }, | ||
| + "packages/cli": { | ||
| + "name": "@tsus/cli", | ||
| + "version": "0.1.0", | ||
| + "dependencies": { | ||
| + "typescript": "^5.5.0" | ||
| + }, | ||
| + "bin": { | ||
| + "tsus": "bin/tsus.js" | ||
| + } | ||
| + }, | ||
| + "packages/runtime": { | ||
| + "name": "@tsus/runtime", | ||
| + "version": "0.1.0" | ||
| } | ||
| } | ||
| } | ||
Addedpackages/cli/bin/tsus.js+48−0
| @@ -0,0 +1,48 @@ | ||
| +#!/usr/bin/env node | ||
| +// tsus CLI: `tsus check [dir]` and `tsus build [dir]`, both with --json. | ||
| +// Diagnostics are machine-first: stable codes, JSON mode, human text is a | ||
| +// rendering of the same data. | ||
| +import path from "node:path"; | ||
| +import process from "node:process"; | ||
| +import { checkProject, buildProject } from "../src/build.js"; | ||
| + | ||
| +const usage = () => { | ||
| + console.error("usage: tsus <check|build> [dir] [--json]"); | ||
| + process.exit(2); | ||
| +}; | ||
| + | ||
| +const args = process.argv.slice(2); | ||
| +const command = args[0]; | ||
| +const json = args.includes("--json"); | ||
| +const dirArg = args.slice(1).find((a) => !a.startsWith("--")) ?? "."; | ||
| +const rootDir = path.resolve(dirArg); | ||
| + | ||
| +const renderHuman = (diagnostics) => { | ||
| + for (const d of diagnostics) { | ||
| + console.error(`error ${d.code}: ${d.message}`); | ||
| + console.error(` --> ${d.file}:${d.line}:${d.col}`); | ||
| + console.error(` hint: ${d.hint}`); | ||
| + } | ||
| + console.error(`${diagnostics.length} error(s)`); | ||
| +}; | ||
| + | ||
| +const report = (result, extra) => { | ||
| + const ok = result.diagnostics.length === 0; | ||
| + if (json) { | ||
| + console.log(JSON.stringify({ ok, diagnostics: result.diagnostics, ...extra }, null, 2)); | ||
| + } else if (ok) { | ||
| + console.log(extra?.emitted ? `built ${extra.emitted.length} file(s)` : "check passed"); | ||
| + } else { | ||
| + renderHuman(result.diagnostics); | ||
| + } | ||
| + process.exit(ok ? 0 : 1); | ||
| +}; | ||
| + | ||
| +if (command === "check") { | ||
| + report(checkProject(rootDir)); | ||
| +} else if (command === "build") { | ||
| + const result = buildProject(rootDir); | ||
| + report(result, { emitted: result.emitted.map((f) => path.relative(rootDir, f)) }); | ||
| +} else { | ||
| + usage(); | ||
| +} | ||
Addedpackages/cli/package.json+11−0
| @@ -0,0 +1,11 @@ | ||
| +{ | ||
| + "name": "@tsus/cli", | ||
| + "version": "0.1.0", | ||
| + "type": "module", | ||
| + "bin": { | ||
| + "tsus": "./bin/tsus.js" | ||
| + }, | ||
| + "dependencies": { | ||
| + "typescript": "^5.5.0" | ||
| + } | ||
| +} | ||
Addedpackages/cli/src/build.js+106−0
| @@ -0,0 +1,106 @@ | ||
| +// tsus build: src/**/*.{ts,tsus} -> dist/**/*.js (plain ESM). | ||
| +import fs from "node:fs"; | ||
| +import path from "node:path"; | ||
| +import ts from "typescript"; | ||
| +import { preprocess, PreprocessError } from "./preprocess.js"; | ||
| +import { checkSource } from "./check.js"; | ||
| + | ||
| +const walk = (dir) => { | ||
| + const out = []; | ||
| + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { | ||
| + const full = path.join(dir, entry.name); | ||
| + if (entry.isDirectory()) { | ||
| + out.push(...walk(full)); | ||
| + } else { | ||
| + out.push(full); | ||
| + } | ||
| + } | ||
| + return out; | ||
| +}; | ||
| + | ||
| +// Rewrite relative import/export specifiers ending in .tsus or .ts to .js. | ||
| +const rewriteSpecifiers = (code) => | ||
| + code.replace( | ||
| + /(\b(?:from|import)\s*\(?\s*)(["'])(\.{1,2}\/[^"']*?)\.(?:tsus|ts)(\2)/g, | ||
| + (_m, lead, quote, spec) => `${lead}${quote}${spec}.js${quote}`, | ||
| + ); | ||
| + | ||
| +const RUNTIME_IMPORT = `import { __tsus_match } from "@tsus/runtime";\n`; | ||
| + | ||
| +export const collectSources = (rootDir) => { | ||
| + const srcDir = path.join(rootDir, "src"); | ||
| + if (!fs.existsSync(srcDir)) { | ||
| + throw new Error(`no src/ directory in ${rootDir}`); | ||
| + } | ||
| + return { srcDir, files: walk(srcDir) }; | ||
| +}; | ||
| + | ||
| +// Preprocess + check every .tsus file. Returns diagnostics (empty = clean). | ||
| +export const checkProject = (rootDir) => { | ||
| + const { srcDir, files } = collectSources(rootDir); | ||
| + const diagnostics = []; | ||
| + for (const file of files) { | ||
| + if (!file.endsWith(".tsus")) { | ||
| + continue; | ||
| + } | ||
| + const rel = path.relative(rootDir, file); | ||
| + const source = fs.readFileSync(file, "utf8"); | ||
| + try { | ||
| + const { code } = preprocess(source); | ||
| + diagnostics.push(...checkSource(rel, code)); | ||
| + } catch (error) { | ||
| + if (error instanceof PreprocessError) { | ||
| + diagnostics.push({ | ||
| + code: error.code, | ||
| + message: `match macro error: ${error.message}`, | ||
| + hint: "Arms look like: Pattern(binding) => expression, separated by commas.", | ||
| + file: rel, | ||
| + line: 1, | ||
| + col: 1, | ||
| + }); | ||
| + } else { | ||
| + throw error; | ||
| + } | ||
| + } | ||
| + } | ||
| + return { srcDir, files, diagnostics }; | ||
| +}; | ||
| + | ||
| +export const buildProject = (rootDir) => { | ||
| + const { srcDir, files, diagnostics } = checkProject(rootDir); | ||
| + if (diagnostics.length > 0) { | ||
| + return { diagnostics, emitted: [] }; | ||
| + } | ||
| + const distDir = path.join(rootDir, "dist"); | ||
| + const emitted = []; | ||
| + for (const file of files) { | ||
| + const rel = path.relative(srcDir, file); | ||
| + const isTsus = file.endsWith(".tsus"); | ||
| + const isTs = file.endsWith(".ts") && !file.endsWith(".d.ts"); | ||
| + if (!isTsus && !isTs) { | ||
| + // Asset (data files, etc.): copy through so runtime-relative reads work. | ||
| + const dest = path.join(distDir, rel); | ||
| + fs.mkdirSync(path.dirname(dest), { recursive: true }); | ||
| + fs.copyFileSync(file, dest); | ||
| + emitted.push(dest); | ||
| + continue; | ||
| + } | ||
| + let tsCode = fs.readFileSync(file, "utf8"); | ||
| + if (isTsus) { | ||
| + const { code, changed } = preprocess(tsCode); | ||
| + tsCode = changed ? RUNTIME_IMPORT + code : code; | ||
| + } | ||
| + tsCode = rewriteSpecifiers(tsCode); | ||
| + const output = ts.transpileModule(tsCode, { | ||
| + compilerOptions: { | ||
| + module: ts.ModuleKind.ESNext, | ||
| + target: ts.ScriptTarget.ES2022, | ||
| + }, | ||
| + }).outputText; | ||
| + const dest = path.join(distDir, rel.replace(/\.(tsus|ts)$/, ".js")); | ||
| + fs.mkdirSync(path.dirname(dest), { recursive: true }); | ||
| + fs.writeFileSync(dest, output); | ||
| + emitted.push(dest); | ||
| + } | ||
| + return { diagnostics: [], emitted }; | ||
| +}; | ||
Addedpackages/cli/src/check.js+88−0
| @@ -0,0 +1,88 @@ | ||
| +// The strictness checker. Runs on preprocessed (valid-TS) source of .tsus | ||
| +// files only; plain .ts dependencies are exempt by design. | ||
| +import ts from "typescript"; | ||
| + | ||
| +const RULES = { | ||
| + TSUS001: { | ||
| + message: "class declarations are banned in .tsus files", | ||
| + hint: "Use plain object types and functions.", | ||
| + }, | ||
| + TSUS002: { | ||
| + message: "null is banned in .tsus files", | ||
| + hint: "Use Option<T> from @tsus/runtime, or fromNullable at the boundary.", | ||
| + }, | ||
| + TSUS003: { | ||
| + message: "undefined is banned in .tsus files", | ||
| + hint: "Use Option<T> from @tsus/runtime, or fromNullable at the boundary.", | ||
| + }, | ||
| + TSUS004: { | ||
| + message: "var is banned in .tsus files", | ||
| + hint: "Use const (preferred) or let.", | ||
| + }, | ||
| + TSUS005: { | ||
| + message: "throw is banned in .tsus files", | ||
| + hint: "Return Result<T, E> from @tsus/runtime, or wrapSync/wrapAsync at the boundary.", | ||
| + }, | ||
| +}; | ||
| + | ||
| +export const checkSource = (fileName, code) => { | ||
| + const sourceFile = ts.createSourceFile( | ||
| + fileName, | ||
| + code, | ||
| + ts.ScriptTarget.ES2022, | ||
| + true, | ||
| + ts.ScriptKind.TS, | ||
| + ); | ||
| + const diagnostics = []; | ||
| + | ||
| + const add = (node, code) => { | ||
| + const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)); | ||
| + diagnostics.push({ | ||
| + code, | ||
| + message: RULES[code].message, | ||
| + hint: RULES[code].hint, | ||
| + file: fileName, | ||
| + line: line + 1, | ||
| + col: character + 1, | ||
| + }); | ||
| + }; | ||
| + | ||
| + const visit = (node) => { | ||
| + if (ts.isClassDeclaration(node) || ts.isClassExpression(node)) { | ||
| + add(node, "TSUS001"); | ||
| + } | ||
| + if (node.kind === ts.SyntaxKind.NullKeyword) { | ||
| + add(node, "TSUS002"); | ||
| + } | ||
| + if (ts.isIdentifier(node) && node.text === "undefined") { | ||
| + add(node, "TSUS003"); | ||
| + } | ||
| + if ( | ||
| + ts.isVariableDeclarationList(node) && | ||
| + (node.flags & (ts.NodeFlags.Let | ts.NodeFlags.Const)) === 0 | ||
| + ) { | ||
| + add(node, "TSUS004"); | ||
| + } | ||
| + if (ts.isThrowStatement(node)) { | ||
| + add(node, "TSUS005"); | ||
| + } | ||
| + ts.forEachChild(node, visit); | ||
| + }; | ||
| + visit(sourceFile); | ||
| + | ||
| + const parseErrors = sourceFile.parseDiagnostics ?? []; | ||
| + for (const d of parseErrors) { | ||
| + const { line, character } = sourceFile.getLineAndCharacterOfPosition(d.start ?? 0); | ||
| + diagnostics.push({ | ||
| + code: "TSUS000", | ||
| + message: `syntax error: ${ts.flattenDiagnosticMessageText(d.messageText, " ")}`, | ||
| + hint: "The file does not parse as TypeScript after macro expansion.", | ||
| + file: fileName, | ||
| + line: line + 1, | ||
| + col: character + 1, | ||
| + }); | ||
| + } | ||
| + | ||
| + diagnostics.sort((a, b) => a.line - b.line || a.col - b.col); | ||
| + return diagnostics; | ||
| +}; | ||
Addedpackages/cli/src/preprocess.js+335−0
| @@ -0,0 +1,335 @@ | ||
| +// Rewrites `match (expr) { Pattern(x) => body, ... }` blocks into | ||
| +// `__tsus_match((expr), [[pattern, handler], ...])` calls, producing valid | ||
| +// TypeScript. Runs before the TypeScript parser ever sees the file, so it has | ||
| +// to tokenize strings, template literals (with nested ${}), and comments | ||
| +// itself instead of trusting a regex. | ||
| + | ||
| +export class PreprocessError extends Error { | ||
| + constructor(message, index) { | ||
| + super(message); | ||
| + this.code = "TSUS006"; | ||
| + this.index = index; | ||
| + } | ||
| +} | ||
| + | ||
| +const isIdentStart = (ch) => /[A-Za-z_$]/.test(ch); | ||
| +const isIdentChar = (ch) => /[A-Za-z0-9_$]/.test(ch); | ||
| + | ||
| +// --- low-level skippers: each returns the index just past the construct --- | ||
| + | ||
| +const skipLineComment = (src, i) => { | ||
| + const end = src.indexOf("\n", i); | ||
| + return end === -1 ? src.length : end; | ||
| +}; | ||
| + | ||
| +const skipBlockComment = (src, i) => { | ||
| + const end = src.indexOf("*/", i + 2); | ||
| + return end === -1 ? src.length : end + 2; | ||
| +}; | ||
| + | ||
| +const skipString = (src, i) => { | ||
| + const quote = src[i]; | ||
| + i += 1; | ||
| + while (i < src.length) { | ||
| + if (src[i] === "\\") { | ||
| + i += 2; | ||
| + continue; | ||
| + } | ||
| + if (src[i] === quote) { | ||
| + return i + 1; | ||
| + } | ||
| + i += 1; | ||
| + } | ||
| + return i; | ||
| +}; | ||
| + | ||
| +const skipTemplate = (src, i) => { | ||
| + i += 1; // past the opening backtick | ||
| + while (i < src.length) { | ||
| + if (src[i] === "\\") { | ||
| + i += 2; | ||
| + continue; | ||
| + } | ||
| + if (src[i] === "`") { | ||
| + return i + 1; | ||
| + } | ||
| + if (src[i] === "$" && src[i + 1] === "{") { | ||
| + i = skipBalanced(src, i + 1); | ||
| + continue; | ||
| + } | ||
| + i += 1; | ||
| + } | ||
| + return i; | ||
| +}; | ||
| + | ||
| +// src[i] must be one of ( [ {. Returns index past the matching closer, | ||
| +// skipping strings, templates, and comments along the way. | ||
| +const skipBalanced = (src, i) => { | ||
| + const open = src[i]; | ||
| + const close = open === "(" ? ")" : open === "[" ? "]" : "}"; | ||
| + let depth = 0; | ||
| + while (i < src.length) { | ||
| + const ch = src[i]; | ||
| + if (ch === "/" && src[i + 1] === "/") { | ||
| + i = skipLineComment(src, i); | ||
| + continue; | ||
| + } | ||
| + if (ch === "/" && src[i + 1] === "*") { | ||
| + i = skipBlockComment(src, i); | ||
| + continue; | ||
| + } | ||
| + if (ch === '"' || ch === "'") { | ||
| + i = skipString(src, i); | ||
| + continue; | ||
| + } | ||
| + if (ch === "`") { | ||
| + i = skipTemplate(src, i); | ||
| + continue; | ||
| + } | ||
| + if (ch === open) { | ||
| + depth += 1; | ||
| + } else if (ch === close) { | ||
| + depth -= 1; | ||
| + if (depth === 0) { | ||
| + return i + 1; | ||
| + } | ||
| + } | ||
| + i += 1; | ||
| + } | ||
| + throw new PreprocessError(`unclosed ${open} in match expression`, i); | ||
| +}; | ||
| + | ||
| +const skipWsAndComments = (src, i) => { | ||
| + while (i < src.length) { | ||
| + if (/\s/.test(src[i])) { | ||
| + i += 1; | ||
| + } else if (src[i] === "/" && src[i + 1] === "/") { | ||
| + i = skipLineComment(src, i); | ||
| + } else if (src[i] === "/" && src[i + 1] === "*") { | ||
| + i = skipBlockComment(src, i); | ||
| + } else { | ||
| + break; | ||
| + } | ||
| + } | ||
| + return i; | ||
| +}; | ||
| + | ||
| +// --- arm parsing --- | ||
| + | ||
| +// Scans an arm body starting at i, stopping at a top-level comma or the end. | ||
| +const scanArmBody = (src, i) => { | ||
| + while (i < src.length) { | ||
| + const ch = src[i]; | ||
| + if (ch === "/" && src[i + 1] === "/") { | ||
| + i = skipLineComment(src, i); | ||
| + continue; | ||
| + } | ||
| + if (ch === "/" && src[i + 1] === "*") { | ||
| + i = skipBlockComment(src, i); | ||
| + continue; | ||
| + } | ||
| + if (ch === '"' || ch === "'") { | ||
| + i = skipString(src, i); | ||
| + continue; | ||
| + } | ||
| + if (ch === "`") { | ||
| + i = skipTemplate(src, i); | ||
| + continue; | ||
| + } | ||
| + if (ch === "(" || ch === "[" || ch === "{") { | ||
| + i = skipBalanced(src, i); | ||
| + continue; | ||
| + } | ||
| + if (ch === ",") { | ||
| + return i; | ||
| + } | ||
| + i += 1; | ||
| + } | ||
| + return i; | ||
| +}; | ||
| + | ||
| +const parseArms = (body, transformFn) => { | ||
| + const arms = []; | ||
| + let i = 0; | ||
| + while (true) { | ||
| + i = skipWsAndComments(body, i); | ||
| + if (i >= body.length) { | ||
| + break; | ||
| + } | ||
| + const arm = {}; | ||
| + const ch = body[i]; | ||
| + if (ch === '"' || ch === "'") { | ||
| + const end = skipString(body, i); | ||
| + arm.kind = "lit"; | ||
| + arm.text = body.slice(i, end); | ||
| + i = end; | ||
| + } else if (/[0-9]/.test(ch) || (ch === "-" && /[0-9]/.test(body[i + 1]))) { | ||
| + let end = i + 1; | ||
| + while (end < body.length && /[0-9._]/.test(body[end])) { | ||
| + end += 1; | ||
| + } | ||
| + arm.kind = "lit"; | ||
| + arm.text = body.slice(i, end); | ||
| + i = end; | ||
| + } else if (isIdentStart(ch)) { | ||
| + let end = i; | ||
| + while (end < body.length && isIdentChar(body[end])) { | ||
| + end += 1; | ||
| + } | ||
| + const name = body.slice(i, end); | ||
| + i = end; | ||
| + if (name === "_") { | ||
| + arm.kind = "wildcard"; | ||
| + } else { | ||
| + arm.kind = "variant"; | ||
| + arm.name = name; | ||
| + i = skipWsAndComments(body, i); | ||
| + if (body[i] === "(") { | ||
| + const closeEnd = skipBalanced(body, i); | ||
| + arm.binding = body.slice(i + 1, closeEnd - 1).trim(); | ||
| + i = closeEnd; | ||
| + } | ||
| + } | ||
| + } else { | ||
| + throw new PreprocessError(`unexpected character "${ch}" in match pattern`, i); | ||
| + } | ||
| + i = skipWsAndComments(body, i); | ||
| + if (body.slice(i, i + 2) !== "=>") { | ||
| + throw new PreprocessError(`expected => after match pattern`, i); | ||
| + } | ||
| + i += 2; | ||
| + i = skipWsAndComments(body, i); | ||
| + const bodyEnd = scanArmBody(body, i); | ||
| + const rawBody = body.slice(i, bodyEnd).trim(); | ||
| + if (rawBody === "") { | ||
| + throw new PreprocessError("empty match arm body", i); | ||
| + } | ||
| + arm.body = transformFn(rawBody); | ||
| + arms.push(arm); | ||
| + i = bodyEnd; | ||
| + if (body[i] === ",") { | ||
| + i += 1; | ||
| + } | ||
| + } | ||
| + if (arms.length === 0) { | ||
| + throw new PreprocessError("match expression has no arms", 0); | ||
| + } | ||
| + return arms; | ||
| +}; | ||
| + | ||
| +const emitMatch = (subject, arms) => { | ||
| + const parts = arms.map((arm) => { | ||
| + // An arm whose body awaits becomes an async handler; __tsus_match then | ||
| + // returns a promise and the caller writes `await match (...)`. | ||
| + const asyncKw = /\bawait\b/.test(arm.body) ? "async " : ""; | ||
| + if (arm.kind === "wildcard") { | ||
| + return `["_", ${asyncKw}() => (${arm.body})]`; | ||
| + } | ||
| + if (arm.kind === "lit") { | ||
| + return `[{ lit: ${arm.text} }, ${asyncKw}() => (${arm.body})]`; | ||
| + } | ||
| + if (arm.binding !== undefined && arm.binding !== "") { | ||
| + return `["${arm.name}", ${asyncKw}(${arm.binding}) => (${arm.body})]`; | ||
| + } | ||
| + return `["${arm.name}", ${asyncKw}() => (${arm.body})]`; | ||
| + }); | ||
| + return `__tsus_match((${subject}), [${parts.join(", ")}])`; | ||
| +}; | ||
| + | ||
| +// --- main transform --- | ||
| + | ||
| +export const preprocess = (source) => { | ||
| + const state = { changed: false }; | ||
| + const code = transform(source, state); | ||
| + return { code, changed: state.changed }; | ||
| +}; | ||
| + | ||
| +const transform = (src, state) => { | ||
| + let out = ""; | ||
| + let i = 0; | ||
| + const n = src.length; | ||
| + while (i < n) { | ||
| + const ch = src[i]; | ||
| + if (ch === "/" && src[i + 1] === "/") { | ||
| + const end = skipLineComment(src, i); | ||
| + out += src.slice(i, end); | ||
| + i = end; | ||
| + continue; | ||
| + } | ||
| + if (ch === "/" && src[i + 1] === "*") { | ||
| + const end = skipBlockComment(src, i); | ||
| + out += src.slice(i, end); | ||
| + i = end; | ||
| + continue; | ||
| + } | ||
| + if (ch === '"' || ch === "'") { | ||
| + const end = skipString(src, i); | ||
| + out += src.slice(i, end); | ||
| + i = end; | ||
| + continue; | ||
| + } | ||
| + if (ch === "`") { | ||
| + // Walk the template so match blocks inside ${...} still get rewritten. | ||
| + out += "`"; | ||
| + i += 1; | ||
| + while (i < n) { | ||
| + if (src[i] === "\\") { | ||
| + out += src.slice(i, i + 2); | ||
| + i += 2; | ||
| + continue; | ||
| + } | ||
| + if (src[i] === "`") { | ||
| + out += "`"; | ||
| + i += 1; | ||
| + break; | ||
| + } | ||
| + if (src[i] === "$" && src[i + 1] === "{") { | ||
| + const end = skipBalanced(src, i + 1); | ||
| + const inner = src.slice(i + 2, end - 1); | ||
| + out += "${" + transform(inner, state) + "}"; | ||
| + i = end; | ||
| + continue; | ||
| + } | ||
| + out += src[i]; | ||
| + i += 1; | ||
| + } | ||
| + continue; | ||
| + } | ||
| + if (isIdentStart(ch)) { | ||
| + const start = i; | ||
| + while (i < n && isIdentChar(src[i])) { | ||
| + i += 1; | ||
| + } | ||
| + const word = src.slice(start, i); | ||
| + const prev = start > 0 ? src[start - 1] : ""; | ||
| + if (word === "match" && prev !== ".") { | ||
| + let j = i; | ||
| + while (j < n && /\s/.test(src[j])) { | ||
| + j += 1; | ||
| + } | ||
| + if (src[j] === "(") { | ||
| + const parenEnd = skipBalanced(src, j); | ||
| + let k = parenEnd; | ||
| + while (k < n && /\s/.test(src[k])) { | ||
| + k += 1; | ||
| + } | ||
| + if (src[k] === "{") { | ||
| + const braceEnd = skipBalanced(src, k); | ||
| + const subject = src.slice(j + 1, parenEnd - 1); | ||
| + const armsSrc = src.slice(k + 1, braceEnd - 1); | ||
| + const arms = parseArms(armsSrc, (text) => transform(text, state)); | ||
| + out += emitMatch(transform(subject, state), arms); | ||
| + state.changed = true; | ||
| + i = braceEnd; | ||
| + continue; | ||
| + } | ||
| + } | ||
| + } | ||
| + out += word; | ||
| + continue; | ||
| + } | ||
| + out += ch; | ||
| + i += 1; | ||
| + } | ||
| + return out; | ||
| +}; | ||
Addedpackages/runtime/boundary.d.ts+11−0
| @@ -0,0 +1,11 @@ | ||
| +import type { Option, Result } from "./index.js"; | ||
| + | ||
| +export declare const fromNullable: <T>(value: T | null | undefined) => Option<T>; | ||
| + | ||
| +export declare const wrapSync: <A extends unknown[], R>( | ||
| + fn: (...args: A) => R, | ||
| +) => (...args: A) => Result<R, Error>; | ||
| + | ||
| +export declare const wrapAsync: <A extends unknown[], R>( | ||
| + fn: (...args: A) => R | Promise<R>, | ||
| +) => (...args: A) => Promise<Result<Awaited<R>, Error>>; | ||
Addedpackages/runtime/boundary.js+22−0
| @@ -0,0 +1,22 @@ | ||
| +// The interop boundary: converts the outside world's nulls, undefineds, and | ||
| +// throws into Option and Result at the edge of tsus code. | ||
| +import { Some, None, Ok, Err } from "./index.js"; | ||
| + | ||
| +export const fromNullable = (value) => | ||
| + value === null || value === undefined ? None : Some(value); | ||
| + | ||
| +export const wrapSync = (fn) => (...args) => { | ||
| + try { | ||
| + return Ok(fn(...args)); | ||
| + } catch (error) { | ||
| + return Err(error); | ||
| + } | ||
| +}; | ||
| + | ||
| +export const wrapAsync = (fn) => async (...args) => { | ||
| + try { | ||
| + return Ok(await fn(...args)); | ||
| + } catch (error) { | ||
| + return Err(error); | ||
| + } | ||
| +}; | ||
Addedpackages/runtime/index.d.ts+33−0
| @@ -0,0 +1,33 @@ | ||
| +export interface Option<T> { | ||
| + readonly tag: "Some" | "None"; | ||
| + isSome(): boolean; | ||
| + isNone(): boolean; | ||
| + map<U>(f: (value: T) => U): Option<U>; | ||
| + andThen<U>(f: (value: T) => Option<U>): Option<U>; | ||
| + unwrapOr(fallback: T): T; | ||
| + okOr<E>(error: E): Result<T, E>; | ||
| +} | ||
| + | ||
| +export interface Result<T, E> { | ||
| + readonly tag: "Ok" | "Err"; | ||
| + isOk(): boolean; | ||
| + isErr(): boolean; | ||
| + map<U>(f: (value: T) => U): Result<U, E>; | ||
| + mapErr<F>(f: (error: E) => F): Result<T, F>; | ||
| + andThen<U>(f: (value: T) => Result<U, E>): Result<U, E>; | ||
| + unwrapOr(fallback: T): T; | ||
| + ok(): Option<T>; | ||
| +} | ||
| + | ||
| +export declare const Some: <T>(value: T) => Option<T>; | ||
| +export declare const None: Option<never>; | ||
| +export declare const Ok: <T, E = never>(value: T) => Result<T, E>; | ||
| +export declare const Err: <E, T = never>(error: E) => Result<T, E>; | ||
| + | ||
| +export type Tagged<K extends string, V> = { readonly tag: K; readonly value: V }; | ||
| +export declare const tag: <K extends string, V>(t: K, value: V) => Tagged<K, V>; | ||
| + | ||
| +export declare const __tsus_match: ( | ||
| + value: unknown, | ||
| + arms: Array<[unknown, (...args: never[]) => unknown]>, | ||
| +) => never; | ||
Addedpackages/runtime/index.js+79−0
| @@ -0,0 +1,79 @@ | ||
| +// The tsus runtime. Plain ESM, no classes, usable from Node and Cloudflare Workers. | ||
| + | ||
| +export const Some = (value) => ({ | ||
| + tag: "Some", | ||
| + value, | ||
| + isSome: () => true, | ||
| + isNone: () => false, | ||
| + map: (f) => Some(f(value)), | ||
| + andThen: (f) => f(value), | ||
| + unwrapOr: () => value, | ||
| + okOr: () => Ok(value), | ||
| +}); | ||
| + | ||
| +export const None = Object.freeze({ | ||
| + tag: "None", | ||
| + isSome: () => false, | ||
| + isNone: () => true, | ||
| + map: () => None, | ||
| + andThen: () => None, | ||
| + unwrapOr: (fallback) => fallback, | ||
| + okOr: (error) => Err(error), | ||
| +}); | ||
| + | ||
| +export const Ok = (value) => ({ | ||
| + tag: "Ok", | ||
| + value, | ||
| + isOk: () => true, | ||
| + isErr: () => false, | ||
| + map: (f) => Ok(f(value)), | ||
| + mapErr: () => Ok(value), | ||
| + andThen: (f) => f(value), | ||
| + unwrapOr: () => value, | ||
| + ok: () => Some(value), | ||
| +}); | ||
| + | ||
| +export const Err = (error) => ({ | ||
| + tag: "Err", | ||
| + error, | ||
| + isOk: () => false, | ||
| + isErr: () => true, | ||
| + map: () => Err(error), | ||
| + mapErr: (f) => Err(f(error)), | ||
| + andThen: () => Err(error), | ||
| + unwrapOr: (fallback) => fallback, | ||
| + ok: () => None, | ||
| +}); | ||
| + | ||
| +export const tag = (t, value) => ({ tag: t, value }); | ||
| + | ||
| +// Compiled form of the match macro. Arms are [pattern, handler] pairs where | ||
| +// pattern is a variant tag string, "_" for wildcard, or { lit: value }. | ||
| +export const __tsus_match = (value, arms) => { | ||
| + for (const [pattern, handler] of arms) { | ||
| + if (pattern === "_") { | ||
| + return handler(value); | ||
| + } | ||
| + if (typeof pattern === "object" && pattern !== null && "lit" in pattern) { | ||
| + if (value === pattern.lit) { | ||
| + return handler(value); | ||
| + } | ||
| + continue; | ||
| + } | ||
| + if (value !== null && typeof value === "object" && value.tag === pattern) { | ||
| + if (pattern === "None") { | ||
| + return handler(); | ||
| + } | ||
| + if (pattern === "Err") { | ||
| + return handler(value.error); | ||
| + } | ||
| + if ("value" in value) { | ||
| + return handler(value.value); | ||
| + } | ||
| + return handler(value); | ||
| + } | ||
| + } | ||
| + throw new Error( | ||
| + `TSUS100: non-exhaustive match, no arm matched ${JSON.stringify(value)}. Add a _ arm.`, | ||
| + ); | ||
| +}; | ||
Addedpackages/runtime/package.json+15−0
| @@ -0,0 +1,15 @@ | ||
| +{ | ||
| + "name": "@tsus/runtime", | ||
| + "version": "0.1.0", | ||
| + "type": "module", | ||
| + "exports": { | ||
| + ".": { | ||
| + "types": "./index.d.ts", | ||
| + "default": "./index.js" | ||
| + }, | ||
| + "./boundary": { | ||
| + "types": "./boundary.d.ts", | ||
| + "default": "./boundary.js" | ||
| + } | ||
| + } | ||
| +} | ||
Addedscripts/run-examples.mjs+95−0
| @@ -0,0 +1,95 @@ | ||
| +// Runs every example against the tsus toolchain and verifies the outcome | ||
| +// declared in each example's example.json. | ||
| +import fs from "node:fs"; | ||
| +import path from "node:path"; | ||
| +import { fileURLToPath, pathToFileURL } from "node:url"; | ||
| +import { spawnSync } from "node:child_process"; | ||
| + | ||
| +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); | ||
| +const cliBin = path.join(repoRoot, "packages/cli/bin/tsus.js"); | ||
| +const examplesDir = path.join(repoRoot, "examples"); | ||
| + | ||
| +const results = []; | ||
| + | ||
| +const runNode = (args, cwd) => | ||
| + spawnSync(process.execPath, args, { cwd, encoding: "utf8", timeout: 30_000 }); | ||
| + | ||
| +const checkLines = (stdout, expected) => { | ||
| + const lines = stdout.trim().split("\n").map((l) => l.trim()); | ||
| + if (lines.length !== expected.length) { | ||
| + return `expected ${expected.length} lines, got ${lines.length}: ${JSON.stringify(lines)}`; | ||
| + } | ||
| + for (let i = 0; i < expected.length; i += 1) { | ||
| + if (lines[i] !== expected[i]) { | ||
| + return `line ${i + 1}: expected ${JSON.stringify(expected[i])}, got ${JSON.stringify(lines[i])}`; | ||
| + } | ||
| + } | ||
| + return ""; | ||
| +}; | ||
| + | ||
| +for (const name of fs.readdirSync(examplesDir).sort()) { | ||
| + const dir = path.join(examplesDir, name); | ||
| + const manifestPath = path.join(dir, "example.json"); | ||
| + if (!fs.existsSync(manifestPath)) { | ||
| + continue; | ||
| + } | ||
| + const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")); | ||
| + let failure = ""; | ||
| + | ||
| + if (manifest.expect === "check-fail") { | ||
| + const r = runNode([cliBin, "check", dir, "--json"], repoRoot); | ||
| + if (r.status === 0) { | ||
| + failure = "check unexpectedly passed"; | ||
| + } else { | ||
| + const parsed = JSON.parse(r.stdout || "{}"); | ||
| + const seen = new Set((parsed.diagnostics ?? []).map((d) => d.code)); | ||
| + const missing = (manifest.codes ?? []).filter((c) => !seen.has(c)); | ||
| + if (missing.length > 0) { | ||
| + failure = `missing expected codes ${missing.join(", ")}; saw ${[...seen].join(", ") || "none"}`; | ||
| + } | ||
| + } | ||
| + } else { | ||
| + const rb = runNode([cliBin, "build", dir], repoRoot); | ||
| + if (rb.status !== 0) { | ||
| + failure = `build failed:\n${(rb.stderr || rb.stdout || "").trim()}`; | ||
| + } else if (manifest.expect === "run") { | ||
| + const rr = runNode([path.join(dir, "dist/main.js")], dir); | ||
| + if (rr.status !== 0) { | ||
| + failure = `run failed:\n${(rr.stderr || "").trim()}`; | ||
| + } else { | ||
| + failure = checkLines(rr.stdout, manifest.output); | ||
| + } | ||
| + } else if (manifest.expect === "worker") { | ||
| + const entry = pathToFileURL(path.join(dir, "dist", manifest.entry)).href; | ||
| + try { | ||
| + const mod = await import(entry); | ||
| + for (const req of manifest.requests) { | ||
| + const res = await mod.default.fetch(new Request(`http://worker.local${req.path}`)); | ||
| + const body = await res.text(); | ||
| + if (res.status !== req.status || body !== req.body) { | ||
| + failure = `${req.path}: expected ${req.status} ${JSON.stringify(req.body)}, got ${res.status} ${JSON.stringify(body)}`; | ||
| + break; | ||
| + } | ||
| + } | ||
| + } catch (error) { | ||
| + failure = `worker import failed: ${error.message}`; | ||
| + } | ||
| + } else { | ||
| + failure = `unknown expectation ${manifest.expect}`; | ||
| + } | ||
| + } | ||
| + | ||
| + results.push({ name, ok: failure === "", failure }); | ||
| +} | ||
| + | ||
| +let passed = 0; | ||
| +for (const r of results) { | ||
| + if (r.ok) { | ||
| + passed += 1; | ||
| + console.log(`PASS ${r.name}`); | ||
| + } else { | ||
| + console.log(`FAIL ${r.name}\n ${r.failure.replaceAll("\n", "\n ")}`); | ||
| + } | ||
| +} | ||
| +console.log(`\n${passed}/${results.length} examples passed`); | ||
| +process.exit(passed === results.length ? 0 : 1); | ||
Checks
No checks reported for this commit.
Runs
No runs for this commit.