// 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;};