Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

JavaScript · 745 lines · 29.1 KiB · at 2cc04ee

// `tsus migrate <file.ts>`: a codemod from TypeScript to .tsus.//// It runs as a series of passes, each on a fresh parse of the previous// pass's output, so edits inside one pass never have to compose://   1. var -> const/let (only where dropping hoisting changes nothing)//   2. simple classes -> a data type plus functions//   3. T | null / T | undefined returns -> Option<T>//   4. throwing functions -> Result<T, E> with a literal or tagged E//   5. imports for whatever the passes used// Then the strict checker runs on the output, and everything it still// rejects is reported as unconverted, alongside the passes' own notes.import ts from "typescript";import { applyEdits } from "./fix.js";import { createContext } from "./rules/context.js";import { varFix } from "./rules/immutability.js";import { walk, skipParens, hasModifier, collectWrites } from "./rules/analysis.js";import { createSourceMap, lineColOf } from "./rules/sourcemap.js";import { checkSource } from "./check.js";import { preprocess } from "./preprocess.js";const parse = (code, name = "migrate.ts") =>  ts.createSourceFile(name, code, ts.ScriptTarget.ES2022, true, ts.ScriptKind.TS);const edit = (start, end, newText) => ({ start, end, newText });const lowerFirst = (s) => s.charAt(0).toLowerCase() + s.slice(1);const upperFirst = (s) => s.charAt(0).toUpperCase() + s.slice(1);// A pass gets { sf, code, ctx, report } and returns edits.const runPass = (state, pass) => {  const sf = parse(state.code);  const ctx = createContext({ sourceFile: sf, fileName: "migrate.ts", filePath: "" });  // Report positions in the input file, whatever earlier passes rewrote.  const toInput = createSourceMap(state.source, state.code);  const loc = (pos) => {    const inputOffset = toInput.approx(pos);    return { line: lineColOf(state.source, inputOffset).line, inputOffset };  };  const edits = pass({ sf, code: state.code, ctx, state, loc });  if (edits.length > 0) {    state.code = applyEdits(state.code, edits);  }};// The function whose own body directly contains `node` (not a nested one).const ownerFunction = (node) => {  let p = node.parent;  while (p) {    if (      ts.isFunctionDeclaration(p) ||      ts.isFunctionExpression(p) ||      ts.isArrowFunction(p) ||      ts.isMethodDeclaration(p) ||      ts.isConstructorDeclaration(p) ||      ts.isGetAccessorDeclaration(p) ||      ts.isSetAccessorDeclaration(p)    ) {      return p;    }    p = p.parent;  }  return undefined;};const functionName = (fn) => {  if (fn.name && ts.isIdentifier(fn.name)) {    return fn.name.text;  }  if (ts.isVariableDeclaration(fn.parent) && ts.isIdentifier(fn.parent.name)) {    return fn.parent.name.text;  }  if (ts.isPropertyAssignment(fn.parent) && ts.isIdentifier(fn.parent.name)) {    return fn.parent.name.text;  }  return "<anonymous>";};// Identifier naming the function, for finding its call sites.const functionNameNode = (fn) => {  if (fn.name && ts.isIdentifier(fn.name)) {    return fn.name;  }  if (ts.isVariableDeclaration(fn.parent) && ts.isIdentifier(fn.parent.name)) {    return fn.parent.name;  }  return undefined;};const callSitesOf = (ctx, fn) => {  const nameNode = functionNameNode(fn);  if (!nameNode) {    return [];  }  const symbol = ctx.symbolOf(nameNode);  const sites = [];  walk(ctx.sf, (node) => {    if (ts.isCallExpression(node) && ts.isIdentifier(node.expression) && symbol && ctx.symbolOf(node.expression) === symbol) {      sites.push(node);    }  });  return sites;};// --- pass 1: var ------------------------------------------------------------const varPass = ({ sf, ctx, state, loc }) => {  const edits = [];  walk(sf, (node) => {    if (ts.isVariableDeclarationList(node) && (node.flags & (ts.NodeFlags.Let | ts.NodeFlags.Const)) === 0) {      const fix = varFix(ctx, node);      const names = node.declarations.map((d) => d.name.getText(sf)).join(", ");      if (fix) {        edits.push(...fix.edits);        state.converted.push({ kind: "var", name: names, ...loc(node.getStart(sf)), detail: fix.description });      } else {        state.unconverted.push({          kind: "var",          name: names,          ...loc(node.getStart(sf)),          reason: "used before its declaration or outside its block, so var's hoisting matters; restructure by hand",        });      }    }  });  return edits;};// --- pass 2: classes --------------------------------------------------------const MUTATING_METHODS = new Set([  "push", "pop", "shift", "unshift", "splice", "sort", "reverse", "fill", "copyWithin", "set", "add", "delete", "clear",]);const classBlockers = (sf, cls) => {  const reasons = [];  if (cls.heritageClauses?.length) {    reasons.push("extends or implements another type");  }  if (!cls.name) {    reasons.push("anonymous class");  }  if (ts.canHaveDecorators(cls) && ts.getDecorators(cls)?.length) {    reasons.push("decorators");  }  if (hasModifier(cls, ts.SyntaxKind.AbstractKeyword)) {    reasons.push("abstract class");  }  for (const m of cls.members) {    if (hasModifier(m, ts.SyntaxKind.StaticKeyword)) {      reasons.push(`static member ${m.name?.getText(sf) ?? ""}`.trim());    } else if (ts.isGetAccessorDeclaration(m) || ts.isSetAccessorDeclaration(m)) {      reasons.push(`accessor ${m.name.getText(sf)}`);    } else if (m.name && ts.isPrivateIdentifier(m.name)) {      reasons.push(`#private member ${m.name.getText(sf)}`);    } else if (ts.isIndexSignatureDeclaration(m) || ts.isClassStaticBlockDeclaration(m)) {      reasons.push("index signature or static block");    } else if (ts.isMethodDeclaration(m) && m.asteriskToken) {      reasons.push(`generator method ${m.name.getText(sf)}`);    } else if (ts.isPropertyDeclaration(m) && !m.type) {      reasons.push(`field ${m.name.getText(sf)} has no type annotation`);    }  }  // Methods may read this.x but not write it or let `this` escape.  for (const m of cls.members) {    if (!ts.isMethodDeclaration(m) || !m.body) {      continue;    }    for (const w of collectWrites(m.body)) {      const t = skipParens(w.target);      let root = t;      while (ts.isPropertyAccessExpression(root) || ts.isElementAccessExpression(root)) {        root = skipParens(root.expression);      }      if (root.kind === ts.SyntaxKind.ThisKeyword) {        reasons.push(`method ${m.name.getText(sf)} mutates this.${t.name?.getText(sf) ?? "<field>"}`);      }    }    walk(m.body, (n) => {      if (n.kind === ts.SyntaxKind.ThisKeyword && !ts.isPropertyAccessExpression(n.parent)) {        reasons.push(`method ${m.name.getText(sf)} passes this around`);      }      if (ts.isCallExpression(n) && ts.isPropertyAccessExpression(n.expression) && MUTATING_METHODS.has(n.expression.name.text)) {        let root = skipParens(n.expression.expression);        while (ts.isPropertyAccessExpression(root) || ts.isElementAccessExpression(root)) {          root = skipParens(root.expression);        }        if (root.kind === ts.SyntaxKind.ThisKeyword) {          reasons.push(`method ${m.name.getText(sf)} mutates ${n.expression.expression.getText(sf)} with ${n.expression.name.text}()`);        }      }    });  }  const ctor = cls.members.find(ts.isConstructorDeclaration);  if (ctor?.body) {    for (const stmt of ctor.body.statements) {      const ok =        ts.isExpressionStatement(stmt) &&        ts.isBinaryExpression(stmt.expression) &&        stmt.expression.operatorToken.kind === ts.SyntaxKind.EqualsToken &&        ts.isPropertyAccessExpression(stmt.expression.left) &&        stmt.expression.left.expression.kind === ts.SyntaxKind.ThisKeyword;      if (!ok) {        reasons.push("constructor does more than assign fields");        break;      }    }  }  return [...new Set(reasons)];};const indentOf = (code, pos) => {  const lineStart = code.lastIndexOf("\n", pos - 1) + 1;  return code.slice(lineStart, pos).match(/^[ \t]*/)[0].length;};// Shifts every line after the first left by `n` columns (where it can).const dedent = (text, n) =>  text    .split("\n")    .map((line, i) => (i === 0 ? line : line.replace(new RegExp(`^[ \\t]{0,${n}}`), "")))    .join("\n");const paramText = (sf, p) => {  const name = p.name.getText(sf);  const q = p.questionToken ? "?" : "";  const type = p.type ? `: ${p.type.getText(sf)}` : "";  const init = p.initializer ? ` = ${p.initializer.getText(sf)}` : "";  const rest = p.dotDotDotToken ? "..." : "";  return `${rest}${name}${q}${type}${init}`;};const isParamProperty = (p) =>  (ts.getModifiers(p) ?? []).some((m) =>    [ts.SyntaxKind.PublicKeyword, ts.SyntaxKind.PrivateKeyword, ts.SyntaxKind.ProtectedKeyword, ts.SyntaxKind.ReadonlyKeyword].includes(m.kind),  );// Rewrites `this.field` -> `self.field` and `this.m(a)` -> `typeM(self, a)`// inside [start, end) and returns the new text of that span.const rewriteThis = (sf, code, node, methodNames, fnName) => {  const edits = [];  walk(node, (n) => {    const isSelfCall =      ts.isCallExpression(n) &&      ts.isPropertyAccessExpression(n.expression) &&      n.expression.expression.kind === ts.SyntaxKind.ThisKeyword &&      methodNames.has(n.expression.name.text);    if (isSelfCall) {      const open = code.indexOf("(", n.expression.getEnd());      const sep = n.arguments.length > 0 ? ", " : "";      edits.push(edit(n.expression.getStart(sf), open + 1, `${fnName(n.expression.name.text)}(self${sep}`));    } else if (n.kind === ts.SyntaxKind.ThisKeyword && ts.isPropertyAccessExpression(n.parent)) {      const call = n.parent.parent;      const handled = ts.isCallExpression(call) && call.expression === n.parent && methodNames.has(n.parent.name.text);      if (!handled) {        edits.push(edit(n.getStart(sf), n.getEnd(), "self"));      }    }  });  const start = node.getStart(sf);  const local = edits.map((e) => ({ ...e, start: e.start - start, end: e.end - start }));  return applyEdits(code.slice(start, node.getEnd()), local);};const classPass = ({ sf, code, ctx, state, loc }) => {  const edits = [];  for (const cls of sf.statements.filter(ts.isClassDeclaration)) {    const where = loc(cls.getStart(sf));    const blockers = classBlockers(sf, cls);    if (blockers.length > 0) {      state.unconverted.push({ kind: "class", name: cls.name?.text ?? "<anonymous>", ...where, reason: blockers.join("; ") });      continue;    }    const name = cls.name.text;    const exported = hasModifier(cls, ts.SyntaxKind.ExportKeyword) ? "export " : "";    const ctor = cls.members.find(ts.isConstructorDeclaration);    const fields = [];    const values = new Map();    for (const p of ctor?.parameters ?? []) {      if (isParamProperty(p)) {        const ro = hasModifier(p, ts.SyntaxKind.ReadonlyKeyword) ? "readonly " : "";        fields.push(`${ro}${p.name.getText(sf)}${p.questionToken ? "?" : ""}: ${p.type ? p.type.getText(sf) : "unknown"}`);        values.set(p.name.getText(sf), p.name.getText(sf));      }    }    for (const m of cls.members.filter(ts.isPropertyDeclaration)) {      const ro = hasModifier(m, ts.SyntaxKind.ReadonlyKeyword) ? "readonly " : "";      fields.push(`${ro}${m.name.getText(sf)}: ${m.type.getText(sf)}`);      if (m.initializer) {        values.set(m.name.getText(sf), m.initializer.getText(sf));      }    }    for (const stmt of ctor?.body?.statements ?? []) {      const assign = stmt.expression;      values.set(assign.left.name.text, assign.right.getText(sf));    }    const ctorParams = (ctor?.parameters ?? []).map((p) => paramText(sf, p)).join(", ");    const methods = cls.members.filter(ts.isMethodDeclaration);    const methodNames = new Set(methods.map((m) => m.name.getText(sf)));    const fnName = (method) => `${lowerFirst(name)}${upperFirst(method)}`;    const props = [...values.entries()].map(([k, v]) => (k === v ? k : `${k}: ${v}`)).join(", ");    const out = [];    out.push(`${exported}type ${name} = { ${fields.join("; ")} };`);    out.push("");    out.push(`${exported}const create${name} = (${ctorParams}): ${name} => ({ ${props} });`);    for (const m of methods) {      const params = ["self: " + name, ...m.parameters.map((p) => paramText(sf, p))].join(", ");      const ret = m.type ? `: ${m.type.getText(sf)}` : "";      const isAsync = hasModifier(m, ts.SyntaxKind.AsyncKeyword) ? "async " : "";      const body = m.body ? dedent(rewriteThis(sf, code, m.body, methodNames, fnName), indentOf(code, m.getStart(sf))) : "{}";      out.push("");      out.push(`${exported}const ${fnName(m.name.getText(sf))} = ${isAsync}(${params})${ret} => ${body};`);    }    edits.push(edit(cls.getStart(sf), cls.getEnd(), out.join("\n")));    state.converted.push({      kind: "class",      name,      ...where,      detail: `type ${name} plus create${name}${methods.length ? ", " + methods.map((m) => fnName(m.name.getText(sf))).join(", ") : ""}`,    });    // Rewrite uses in this file.    const classSymbol = ctx.symbolOf(cls.name);    const isNamed = (t) => t && ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) && t.typeName.text === name;    const isArrayOfName = (t) =>      t &&      ((ts.isArrayTypeNode(t) && isNamed(t.elementType)) ||        (ts.isTypeOperatorNode(t) && isArrayOfName(t.type)) ||        (ts.isTypeReferenceNode(t) && ["Array", "ReadonlyArray"].includes(t.typeName.getText(sf)) && isNamed(t.typeArguments?.[0])));    const instanceOf = (id) => {      const decl = ctx.symbolOf(id)?.valueDeclaration;      if (!decl) {        return false;      }      // (it) => it.isLow() passed to items.find/map/filter/... where items: Name[]      if (ts.isParameter(decl) && !decl.type && (ts.isArrowFunction(decl.parent) || ts.isFunctionExpression(decl.parent))) {        const call = decl.parent.parent;        if (ts.isCallExpression(call) && call.arguments[0] === decl.parent && ts.isPropertyAccessExpression(call.expression)) {          const recv = skipParens(call.expression.expression);          const recvDecl = ts.isIdentifier(recv) ? ctx.symbolOf(recv)?.valueDeclaration : undefined;          return Boolean(recvDecl && isArrayOfName(recvDecl.type) && decl.parent.parameters[0] === decl);        }        return false;      }      const t = decl.type;      if (t && ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) && t.typeName.text === name) {        return true;      }      const init = ts.isVariableDeclaration(decl) && decl.initializer && skipParens(decl.initializer);      return Boolean(init && ts.isNewExpression(init) && ts.isIdentifier(init.expression) && init.expression.text === name);    };    walk(sf, (n) => {      if (n.pos >= cls.pos && n.end <= cls.end) {        return;      }      if (ts.isNewExpression(n) && ts.isIdentifier(n.expression) && ctx.symbolOf(n.expression) === classSymbol) {        const newKw = n.getStart(sf);        edits.push(edit(newKw, n.expression.getEnd(), `create${name}`));        if (!n.arguments) {          edits.push(edit(n.getEnd(), n.getEnd(), "()"));        }      } else if (ts.isCallExpression(n) && ts.isPropertyAccessExpression(n.expression) && methodNames.has(n.expression.name.text)) {        const recv = skipParens(n.expression.expression);        if (ts.isIdentifier(recv) && instanceOf(recv)) {          const open = code.indexOf("(", n.expression.getEnd());          const sep = n.arguments.length > 0 ? ", " : "";          edits.push(edit(n.expression.getStart(sf), open + 1, `${fnName(n.expression.name.text)}(${recv.text}${sep}`));        } else {          state.unconverted.push({            kind: "class-use",            name: `${n.expression.getText(sf)}()`,            ...loc(n.getStart(sf)),            reason: `looks like a call to ${name}.${n.expression.name.text} on a value whose type is not visible here; rewrite it as ${fnName(n.expression.name.text)}(value, ...)`,          });        }      } else if (ts.isBinaryExpression(n) && n.operatorToken.kind === ts.SyntaxKind.InstanceOfKeyword && n.right.getText(sf) === name) {        state.unconverted.push({ kind: "class-use", name: n.getText(sf), ...loc(n.getStart(sf)), reason: "instanceof has no plain-data equivalent; add a tag field" });      }    });    if (exported) {      state.notes.push(`exported class ${name} became type ${name} plus functions; importers must switch from new ${name}(...) to create${name}(...)`);    }  }  return edits;};// --- pass 3: nullable returns -> Option ---------------------------------------const isNullish = (t) =>  (ts.isLiteralTypeNode(t) && t.literal.kind === ts.SyntaxKind.NullKeyword) || t.kind === ts.SyntaxKind.UndefinedKeyword;// For `T | null` (optionally inside Promise<...>) returns { inner, promise }.const nullableReturn = (sf, typeNode) => {  if (!typeNode) {    return undefined;  }  let t = typeNode;  let promise = false;  if (ts.isTypeReferenceNode(t) && ts.isIdentifier(t.typeName) && t.typeName.text === "Promise" && t.typeArguments?.length === 1) {    promise = true;    t = t.typeArguments[0];  }  while (ts.isParenthesizedTypeNode(t)) {    t = t.type;  }  if (!ts.isUnionTypeNode(t) || !t.types.some(isNullish)) {    return undefined;  }  const rest = t.types.filter((m) => !isNullish(m));  if (rest.length === 0) {    return undefined;  }  return { inner: rest.map((m) => m.getText(sf)).join(" | "), promise };};const isNullishExpr = (e) => {  const x = skipParens(e);  return x.kind === ts.SyntaxKind.NullKeyword || (ts.isIdentifier(x) && x.text === "undefined") || ts.isVoidExpression(x);};const obviouslyPresent = (e) => {  const x = skipParens(e);  return (    ts.isStringLiteral(x) ||    ts.isNumericLiteral(x) ||    ts.isTemplateExpression(x) ||    ts.isNoSubstitutionTemplateLiteral(x) ||    ts.isObjectLiteralExpression(x) ||    ts.isArrayLiteralExpression(x) ||    ts.isNewExpression(x) ||    ts.isArrowFunction(x) ||    ts.isFunctionExpression(x) ||    x.kind === ts.SyntaxKind.TrueKeyword ||    x.kind === ts.SyntaxKind.FalseKeyword ||    ts.isTypeOfExpression(x) ||    ts.isPrefixUnaryExpression(x) ||    (ts.isBinaryExpression(x) &&      ![ts.SyntaxKind.QuestionQuestionToken, ts.SyntaxKind.BarBarToken, ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.CommaToken].includes(x.operatorToken.kind) &&      !ts.isAssignmentExpression?.(x))  );};// For `v === null ? null : v`, `v !== undefined ? v : null`, `v == null ?// undefined : v` and friends, the text of v; otherwise undefined.const nullCheckedOperand = (sf, cond) => {  const c = skipParens(cond.condition);  if (!ts.isBinaryExpression(c)) {    return undefined;  }  const op = c.operatorToken.kind;  const isEq = op === ts.SyntaxKind.EqualsEqualsEqualsToken || op === ts.SyntaxKind.EqualsEqualsToken;  const isNe = op === ts.SyntaxKind.ExclamationEqualsEqualsToken || op === ts.SyntaxKind.ExclamationEqualsToken;  if (!isEq && !isNe) {    return undefined;  }  const operand = isNullishExpr(c.right) ? c.left : isNullishExpr(c.left) ? c.right : undefined;  if (!operand) {    return undefined;  }  const v = operand.getText(sf);  const [absent, present] = isEq ? [cond.whenTrue, cond.whenFalse] : [cond.whenFalse, cond.whenTrue];  return isNullishExpr(absent) && skipParens(present).getText(sf) === v ? v : undefined;};// Edits that turn a nullable expression into an Option expression.const toOptionEdits = (sf, expr, used) => {  const x = skipParens(expr);  if (isNullishExpr(x)) {    used.add("None");    return [edit(expr.getStart(sf), expr.getEnd(), "None")];  }  // a ?? null  ->  fromNullable(a)  if (ts.isBinaryExpression(x) && x.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken && isNullishExpr(x.right)) {    used.add("fromNullable");    return [edit(expr.getStart(sf), expr.getEnd(), `fromNullable(${x.left.getText(sf)})`)];  }  if (ts.isConditionalExpression(x)) {    // v === undefined ? null : v  (and the other spellings)  ->  fromNullable(v)    const checked = nullCheckedOperand(sf, x);    if (checked) {      used.add("fromNullable");      return [edit(expr.getStart(sf), expr.getEnd(), `fromNullable(${checked})`)];    }    return [...toOptionEdits(sf, x.whenTrue, used), ...toOptionEdits(sf, x.whenFalse, used)];  }  const wrapper = obviouslyPresent(x) ? "Some" : "fromNullable";  used.add(wrapper);  return [edit(expr.getStart(sf), expr.getStart(sf), `${wrapper}(`), edit(expr.getEnd(), expr.getEnd(), ")")];};const allFunctions = (sf) => {  const fns = [];  walk(sf, (n) => {    if (ts.isFunctionDeclaration(n) || ts.isFunctionExpression(n) || ts.isArrowFunction(n) || ts.isMethodDeclaration(n)) {      fns.push(n);    }  });  return fns;};const ownReturns = (fn) => {  const out = [];  if (!fn.body) {    return out;  }  walk(fn.body, (n) => {    if (ts.isReturnStatement(n) && ownerFunction(n) === fn) {      out.push(n);    }  });  return out;};const optionPass = ({ sf, ctx, state, loc }) => {  const edits = [];  for (const fn of allFunctions(sf)) {    const nr = nullableReturn(sf, fn.type);    if (!nr) {      continue;    }    state.used.add("Option");    const newType = nr.promise ? `Promise<Option<${nr.inner}>>` : `Option<${nr.inner}>`;    edits.push(edit(fn.type.getStart(sf), fn.type.getEnd(), newType));    if (fn.body && !ts.isBlock(fn.body)) {      edits.push(...toOptionEdits(sf, fn.body, state.used));    } else {      for (const r of ownReturns(fn)) {        if (r.expression) {          edits.push(...toOptionEdits(sf, r.expression, state.used));        } else {          state.used.add("None");          edits.push(edit(r.getStart(sf) + "return".length, r.getStart(sf) + "return".length, " None"));        }      }    }    const name = functionName(fn);    state.converted.push({ kind: "nullable-return", name, ...loc(fn.getStart(sf)), detail: `returns ${newType}` });    for (const call of callSitesOf(ctx, fn)) {      state.unconverted.push({        kind: "caller",        name: `${name}()`,        ...loc(call.getStart(sf)),        reason: `${name} now returns ${newType}; handle it with match, map or unwrapOr`,      });    }  }  return edits;};// --- pass 4: throw -> Result --------------------------------------------------const insideTryBlock = (node, fn) => {  let p = node.parent;  let child = node;  while (p && p !== fn) {    if (ts.isTryStatement(p) && p.tryBlock === child) {      return true;    }    child = p;    p = p.parent;  }  return false;};// { type, value } for one throw statement.const errorOf = (sf, thr) => {  const e = skipParens(thr.expression);  if (ts.isStringLiteral(e) || ts.isNoSubstitutionTemplateLiteral(e)) {    const lit = JSON.stringify(e.text);    return { type: lit, value: lit };  }  if (ts.isNewExpression(e) && ts.isIdentifier(e.expression)) {    const ctorName = e.expression.text;    const arg = e.arguments?.[0];    if (!arg) {      const lit = JSON.stringify(ctorName);      return { type: lit, value: lit };    }    if (ts.isStringLiteral(arg) || ts.isNoSubstitutionTemplateLiteral(arg)) {      const lit = JSON.stringify(arg.text);      return { type: lit, value: lit };    }    return { type: `{ tag: "${ctorName}"; message: string }`, value: `{ tag: "${ctorName}", message: ${arg.getText(sf)} }` };  }  return { type: `{ tag: "Thrown"; value: unknown }`, value: `{ tag: "Thrown", value: ${e.getText(sf)} }` };};const isVoidType = (t) => t && (t.kind === ts.SyntaxKind.VoidKeyword || (ts.isTypeReferenceNode(t) && t.typeName.getText() === "Promise" && t.typeArguments?.[0]?.kind === ts.SyntaxKind.VoidKeyword));const resultPass = ({ sf, code, ctx, state, loc }) => {  const edits = [];  for (const fn of allFunctions(sf)) {    if (!fn.body || !ts.isBlock(fn.body)) {      continue;    }    const throws = [];    walk(fn.body, (n) => {      if (ts.isThrowStatement(n) && ownerFunction(n) === fn) {        throws.push(n);      }    });    if (throws.length === 0) {      continue;    }    const name = functionName(fn);    const where = loc(fn.getStart(sf));    if (throws.some((t) => insideTryBlock(t, fn))) {      state.unconverted.push({ kind: "throw", name, ...where, reason: "throws inside its own try block; untangle the control flow by hand" });      continue;    }    const errors = throws.map((t) => errorOf(sf, t));    const errorType = [...new Set(errors.map((e) => e.type))].join(" | ");    const isAsync = hasModifier(fn, ts.SyntaxKind.AsyncKeyword);    const voidish = isVoidType(fn.type) || (!fn.type && ownReturns(fn).every((r) => !r.expression));    state.used.add("Result");    state.used.add("Err");    let newType;    if (voidish) {      newType = isAsync ? `Promise<Result<true, ${errorType}>>` : `Result<true, ${errorType}>`;    } else if (fn.type) {      const t = fn.type;      const isPromise = ts.isTypeReferenceNode(t) && t.typeName.getText(sf) === "Promise" && t.typeArguments?.length === 1;      newType = isPromise        ? `Promise<Result<${t.typeArguments[0].getText(sf)}, ${errorType}>>`        : `Result<${t.getText(sf)}, ${errorType}>`;    }    if (newType && fn.type) {      edits.push(edit(fn.type.getStart(sf), fn.type.getEnd(), newType));    } else if (newType) {      // no annotation: add one after the parameter list      const close = fn.parameters.end;      const paren = code.indexOf(")", close);      edits.push(edit(paren + 1, paren + 1, `: ${newType}`));    }    errors.forEach((err, i) => {      const t = throws[i];      edits.push(edit(t.getStart(sf), t.getEnd(), `return Err(${err.value});`));    });    state.used.add("Ok");    for (const r of ownReturns(fn)) {      if (r.expression) {        edits.push(edit(r.expression.getStart(sf), r.expression.getStart(sf), "Ok("));        edits.push(edit(r.expression.getEnd(), r.expression.getEnd(), ")"));      } else {        const at = r.getStart(sf) + "return".length;        edits.push(edit(at, at, " Ok(true)"));      }    }    if (voidish) {      const stmts = fn.body.statements;      const last = stmts[stmts.length - 1];      if (!last || !(ts.isReturnStatement(last) || ts.isThrowStatement(last))) {        const closeBrace = fn.body.getEnd() - 1;        const indent = code.slice(code.lastIndexOf("\n", closeBrace) + 1, closeBrace);        edits.push(edit(closeBrace, closeBrace, `  return Ok(true);\n${indent}`));      }    }    state.converted.push({      kind: "throw",      name,      ...where,      detail: newType ? `returns ${newType}` : `throws became Err(...) (add a return type annotation: Result<T, ${errorType}>)`,    });    for (const call of callSitesOf(ctx, fn)) {      state.unconverted.push({        kind: "caller",        name: `${name}()`,        ...loc(call.getStart(sf)),        reason: `${name} now returns a Result instead of throwing; match on it or propagate it`,      });    }  }  return edits;};// --- pass 5: imports ----------------------------------------------------------const importPass = ({ sf, state }) => {  const runtime = ["Some", "None", "Ok", "Err"].filter((n) => state.used.has(n));  const types = ["Option", "Result"].filter((n) => state.used.has(n)).map((n) => `type ${n}`);  const lines = [];  if (runtime.length + types.length > 0) {    lines.push(`import { ${[...runtime, ...types].join(", ")} } from "@tsus/runtime";`);  }  if (state.used.has("fromNullable")) {    lines.push(`import { fromNullable } from "@tsus/runtime/boundary";`);  }  if (lines.length === 0) {    return [];  }  const imports = sf.statements.filter(ts.isImportDeclaration);  if (imports.length > 0) {    const at = imports[imports.length - 1].getEnd();    return [edit(at, at, "\n" + lines.join("\n"))];  }  // after a leading comment block, if any  const first = sf.statements[0];  const at = first ? first.getStart(sf) : 0;  return [edit(at, at, lines.join("\n") + "\n\n")];};// --- driver -------------------------------------------------------------------export const migrateSource = (source, fileName = "input.ts") => {  const state = { source, code: source, converted: [], unconverted: [], notes: [], used: new Set() };  runPass(state, varPass);  runPass(state, classPass);  runPass(state, optionPass);  runPass(state, resultPass);  runPass(state, importPass);  // What the strict checker still rejects in the output.  const outName = fileName.replace(/\.(ts|tsx|mts)$/, ".tsus");  let remaining = [];  try {    const { code } = preprocess(state.code);    remaining = checkSource(outName, code, { original: state.code });  } catch (error) {    remaining = [{ code: "TSUS006", message: error.message, line: 1, col: 1, start: 0 }];  }  const outputToInput = createSourceMap(state.source, state.code);  const inputToOutput = createSourceMap(state.code, state.source);  for (const d of remaining) {    const inputOffset = outputToInput.approx(d.start ?? 0);    state.unconverted.push({      kind: "check",      code: d.code,      line: lineColOf(state.source, inputOffset).line,      outputLine: d.line,      inputOffset,      reason: d.message,      explain: `tsus explain ${d.code}`,    });  }  const finish = (items) =>    items      .map((item) => {        const { inputOffset, ...rest } = item;        return rest.outputLine ? rest : { ...rest, outputLine: lineColOf(state.code, inputToOutput.approx(inputOffset)).line };      })      .sort((a, b) => a.line - b.line || a.outputLine - b.outputLine);  return {    code: state.code,    converted: finish(state.converted),    unconverted: finish(state.unconverted),    notes: state.notes,  };};