eutaxy 0.17.1 → 0.17.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/dist/bin.mjs +1 -1
- package/dist/{cli-CxbXc1j2.mjs → cli-B0Gs2mhT.mjs} +790 -440
- package/dist/cli-B0Gs2mhT.mjs.map +1 -0
- package/dist/cli.d.mts.map +1 -1
- package/dist/cli.mjs +1 -1
- package/package.json +1 -1
- package/dist/cli-CxbXc1j2.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli-B0Gs2mhT.mjs","names":["join","ident","fail","env","term","emitFunction","binderType","arrowTerm","installHint","run","ident","engineName","engineAssumptions","proven","unknown","prepare","proveModule","ident","str","strings","send","toPosix","text"],"sources":["../../prover/src/pool.ts","../../cli/src/args.ts","../../prover/src/reader/compiler.ts","../../prover/src/reader/expressions.ts","../../prover/src/reader/types.ts","../../prover/src/reader/subset.ts","../../prover/src/reader/specs.ts","../../prover/src/toolchain.ts","../../prover-lean/src/elan.ts","../../prover-lean/src/emit.ts","../../prover-lean/src/lean.ts","../../prover-lean/src/supplied.ts","../../prover-lean/src/goals.ts","../../prover-lean/src/prove.ts","../../prover-smt/src/emit.ts","../../prover-smt/src/z3.ts","../../prover-smt/src/prove.ts","../../cli/src/resolve.ts","../../cli/src/wrangler.ts","../../cli/src/callees.ts","../../cli/src/vitest-failure.ts","../../cli/src/generate.ts","../../cli/src/specs.ts","../../cli/src/check.ts","../../cli/src/draft.ts","../../cli/src/archive.ts","../../cli/src/install.ts","../../cli/src/held-output.ts","../../cli/src/report.ts","../../cli/src/version.ts","../../cli/src/mcp.ts","../../cli/src/main.ts"],"sourcesContent":["/**\n * Independent jobs run a few at a time, with their results in the order of\n * the items whatever order the jobs finish in: what an engine needs to run\n * one solver process per property, or the report one process per module,\n * without the answer depending on which finished first. A job that throws\n * rejects the pool, and no job is started after it.\n */\n\n/** `work` on every item, at most `limit` at once; the results in item order. */\nexport async function inPool<T, R>(\n items: readonly T[],\n limit: number,\n work: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n let next = 0;\n // Once a job has thrown, the pool's answer is that error: no further job is started.\n let failed = false;\n const worker = async (): Promise<void> => {\n while (next < items.length && !failed) {\n const i = next++;\n try {\n results[i] = await work(items[i] as T, i);\n } catch (err) {\n failed = true;\n throw err;\n }\n }\n };\n const workers = Math.max(1, Math.min(Math.floor(limit), items.length));\n await Promise.all(Array.from({ length: workers }, worker));\n return results;\n}\n\n/**\n * `inPool`, and no item starts `size` or more places past the earliest one\n * not yet finished: when an early job is slow, the jobs behind it wait\n * rather than run ahead, so whatever the finished ones hold for their turn\n * (the report's held output) is never more than `size - 1` items' worth.\n */\nexport async function inWindow<T, R>(\n items: readonly T[],\n size: number,\n work: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const n = Math.max(1, Math.floor(size));\n const finished = items.map(() => false);\n let earliest = 0;\n let failed = false;\n const waiting = new Map<number, () => void>();\n return inPool(items, n, async (item, i) => {\n if (i >= earliest + n) await new Promise<void>((go) => waiting.set(i, go));\n if (failed) throw new Error(\"an earlier job failed\");\n try {\n return await work(item, i);\n } catch (err) {\n failed = true;\n throw err;\n } finally {\n finished[i] = true;\n while (finished[earliest]) earliest++;\n for (const [j, go] of waiting)\n if (j < earliest + n) {\n waiting.delete(j);\n go();\n }\n }\n });\n}\n","/** A small argument parser: positionals, `--flag value`, `--flag=value` and boolean `--flag`. */\n\nexport interface ParsedArgs {\n readonly positionals: readonly string[];\n readonly flags: Readonly<Record<string, string | true>>;\n}\n\nexport function parseArgs(argv: readonly string[], booleans: readonly string[] = []): ParsedArgs {\n const positionals: string[] = [];\n const flags: Record<string, string | true> = {};\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i] as string;\n if (!a.startsWith(\"--\")) {\n positionals.push(a);\n continue;\n }\n const eq = a.indexOf(\"=\");\n if (eq !== -1) {\n flags[a.slice(2, eq)] = a.slice(eq + 1);\n continue;\n }\n const name = a.slice(2);\n const next = argv[i + 1];\n if (booleans.includes(name) || next === undefined || next.startsWith(\"--\")) {\n flags[name] = true;\n } else {\n flags[name] = next;\n i++;\n }\n }\n return { positionals, flags };\n}\n","/**\n * The TypeScript compiler, through its API (7.1): one compiler process per\n * Node process, started on first use; a program per read, over an\n * in-memory layer holding the files being read on top of the host's own\n * files, so imports resolve as the user's compiler resolves them; a\n * standalone source file for text that is not a module (a spec file's\n * arrow, read back from its text). Every handle the compiler process\n * holds for a read is released when the read ends. Nothing else in Eutaxy\n * imports the compiler API: a change to it lands here.\n */\n\nimport {\n type FunctionLikeBase,\n type Identifier,\n ModifierFlags,\n type ModifiersBase,\n type Node,\n NodeFlags,\n type SourceFile,\n SyntaxKind,\n type VariableDeclarationList,\n} from \"typescript/ast\";\nimport { createFileSystemLayer } from \"typescript/fs\";\nimport { API, type Checker, DiagnosticCategory, type Program } from \"typescript/sync\";\n\nlet api: API | undefined;\n\nfunction compiler(): API {\n api ??= new API({});\n return api;\n}\n\n/** Stop the compiler process; the next read starts another. */\nexport function closeCompiler(): void {\n api?.close();\n api = undefined;\n}\n\n/**\n * The options every read compiles under: strict, the latest language\n * level, bundler-style resolution with `.ts` imports allowed, and the\n * standard library alone (`types: []`), so a module's own types resolve\n * and nothing is emitted. The user's configuration is not read: a type\n * Eutaxy cannot resolve under these options is reported unknown, never\n * guessed.\n */\nconst options = {\n strict: true,\n target: 99, // ScriptTarget.ESNext\n module: 99, // ModuleKind.ESNext\n moduleResolution: 100, // ModuleResolutionKind.Bundler\n allowImportingTsExtensions: true,\n noEmit: true,\n skipLibCheck: true,\n types: [] as string[],\n lib: [\"es2023\"],\n};\n\n/** A file given to a read: its path, under which imports resolve, and its text, which stands in for the file on disk. */\nexport interface InputFile {\n readonly path: string;\n readonly text: string;\n}\n\n/** A program over the input files, with its checker. */\nexport interface Opened {\n readonly program: Program;\n readonly checker: Checker;\n /** The source file of an input path. */\n readonly file: (path: string) => SourceFile;\n /** The first parse error of an input file, if any. */\n readonly parseError: (path: string) => { line: number; message: string } | undefined;\n /** The compiler's errors in a file of the program: text ranges (offsets into the file), with the message and its line. */\n readonly typeErrors: (path: string) => readonly CompilerError[];\n /**\n * Whether an identifier names the global of its name: the compiler\n * resolves it to a symbol declared in its default library alone\n * (`lib.*.d.ts`). A declaration, import or block-scoped shadow of the\n * name in scope, a global declared by the project's own declaration\n * files, or a name the compiler cannot resolve is not; a type-only\n * import of the name is, since the compiler resolves a value past it,\n * and so is an interface augmentation of its type (`declare global {\n * interface Number { … } }`), which changes no value.\n */\n readonly standardGlobal: (id: Identifier) => boolean;\n}\n\n/** One compiler error in a file: its text range, message and 1-based line. */\nexport interface CompilerError {\n readonly pos: number;\n readonly end: number;\n readonly message: string;\n readonly line: number;\n}\n\n/** Run `fn` over a program whose root files are the inputs, released afterwards. */\nexport function withProgram<T>(files: readonly InputFile[], fn: (opened: Opened) => T): T {\n const snapshot = compiler().createSnapshot({\n fileSystem: createFileSystemLayer(files.map((f) => [f.path, f.text] as const)),\n createPrograms: [{ rootFiles: files.map((f) => f.path), compilerOptions: options }],\n });\n try {\n const program = snapshot.operation.createdPrograms[0];\n const checker = program.getProject().checker;\n const file = (path: string): SourceFile => {\n const sf = program.getSourceFile(path);\n if (!sf) throw new Error(`the compiler holds no source file for ${path}`);\n return sf;\n };\n const parseError = (path: string) => {\n const first = program.getSyntacticDiagnostics(path)[0];\n return first\n ? { line: (first.startPosition?.line ?? 0) + 1, message: first.text }\n : undefined;\n };\n const errors = new Map<string, readonly CompilerError[]>();\n const typeErrors = (path: string) => {\n let found = errors.get(path);\n if (!found) {\n found = program\n .getSemanticDiagnostics(path)\n .filter((d) => d.category === DiagnosticCategory.Error)\n .map((d) => ({\n pos: d.pos,\n end: d.end,\n message: d.text,\n line: (d.startPosition?.line ?? 0) + 1,\n }));\n errors.set(path, found);\n }\n return found;\n };\n // Answers by symbol: the global `Math` is one symbol however often it is named. Interface and\n // type alias declarations merge into a symbol without touching its value, so only the others decide.\n const standard = new Map<number, boolean>();\n const typeOnly = new Set([SyntaxKind.InterfaceDeclaration, SyntaxKind.TypeAliasDeclaration]);\n const standardGlobal = (id: Identifier): boolean => {\n const symbol = checker.getSymbolAtLocation(id);\n if (!symbol) return false;\n let known = standard.get(symbol.id);\n if (known === undefined) {\n const values = symbol.declarations.filter((d) => !typeOnly.has(d.kind));\n known =\n values.length > 0 &&\n values.every((d) => {\n const sf = d.resolve()?.getSourceFile();\n return sf !== undefined && program.isSourceFileDefaultLibrary(sf);\n });\n standard.set(symbol.id, known);\n }\n return known;\n };\n return fn({ program, checker, file, parseError, typeErrors, standardGlobal });\n } finally {\n snapshot.dispose();\n }\n}\n\n/** Run `fn` over a source file parsed from `text` alone (no program, no checker), released afterwards. */\nexport function withSourceFile<T>(text: string, fn: (sf: SourceFile) => T): T {\n const lease = compiler().createSourceFile(\"/eutaxy/reader/fragment.ts\", text);\n try {\n return fn(lease.sourceFile);\n } finally {\n lease.dispose();\n }\n}\n\n/** 1-based line of a node's first token. */\nexport function lineAt(sf: SourceFile, node: Node): number {\n return sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;\n}\n\n/** A node's text, leading trivia excluded. */\nexport function textOf(sf: SourceFile, node: Node): string {\n return sf.text.slice(node.getStart(sf), node.end);\n}\n\nexport function isExported(node: ModifiersBase): boolean {\n return (node.modifierFlags & ModifierFlags.Export) !== 0;\n}\n\nexport function isAsync(node: ModifiersBase): boolean {\n return (node.modifierFlags & ModifierFlags.Async) !== 0;\n}\n\nexport function isConst(list: VariableDeclarationList): boolean {\n return (list.flags & NodeFlags.Const) !== 0;\n}\n\n/**\n * The offset of the `(` opening a function's parameter list: the\n * declaration's identity, as the spec reader and the subset reader both\n * record it. Undefined for an arrow written without parentheses.\n */\nexport function openParen(sf: SourceFile, fn: FunctionLikeBase): number | undefined {\n const at = fn.parameters.pos - 1;\n return sf.text[at] === \"(\" ? at : undefined;\n}\n\n/** The name of a syntax kind, for messages. */\nexport function kindName(kind: SyntaxKind): string {\n return SyntaxKind[kind] ?? String(kind);\n}\n","/**\n * Function bodies and spec arrows read from the compiler's syntax tree\n * into the subset's `Expr`: `const` bindings, `if` with early returns,\n * `return`, and expressions from arithmetic, comparisons, `&& || !`, the\n * conditional operator, record and array literals, field reads, list\n * methods and calls to the module's own functions. What a name stands\n * for comes from the scope (parameters and consts) and from `Names`: the\n * module's own functions when the text is the module, the spec file's\n * imports when it is an arrow. Anything else is `OutsideSubset` with the\n * construct named and its line.\n */\n\nimport {\n type ArrowFunction,\n type BinaryExpression,\n type Block,\n type CallExpression,\n type Expression,\n type Identifier,\n type Node,\n type ObjectLiteralExpression,\n type ReturnStatement,\n type SourceFile,\n type Statement,\n SyntaxKind,\n type TypeNode,\n} from \"typescript/ast\";\nimport * as is from \"typescript/ast/is\";\nimport { isAsync, isConst, kindName, lineAt, textOf } from \"./compiler.ts\";\nimport {\n type BinaryOp,\n type Expr,\n hasLoneSurrogate,\n insertNarrows,\n OutsideSubset,\n type SubsetType,\n type TypeContext,\n tagOf,\n typeOf,\n} from \"./subset.ts\";\nimport type { Refuse } from \"./types.ts\";\n\n/**\n * A call to a function the text cannot call by name (a generic one, or one\n * imported from another file) read as that function's body, bound to the\n * arguments: undefined when the callee is no such function, so the call is\n * refused as before. `readArgs` reads the arguments in the caller's scope,\n * a record literal argument typed as the parameter it is passed for when\n * that type is given; `fail` refuses at the call.\n */\nexport type Inline = (\n call: CallExpression,\n callee: Identifier,\n scope: Scope,\n readArgs: (types: readonly (SubsetType | undefined)[]) => Expr[],\n fail: (what: string) => never,\n) => Expr | undefined;\n\n/**\n * A name the text reads that is neither in scope nor a function: a\n * module-level `const` of the text's file or one it imports, read as its\n * initializer (a `const` holding a pure value is that value wherever it is\n * read). Undefined when the name is no such constant, so it is refused as\n * before; `fail` refuses at the name.\n */\nexport type Constant = (name: Identifier, fail: (what: string) => never) => Expr | undefined;\n\n/** What the bare names of the text being read stand for, outside any local scope. */\nexport interface Names {\n /** A function the subset may call under this name. */\n readonly callable: (name: string) => boolean;\n /** The module function a callable name stands for (a spec file's local name resolves to the module's). */\n readonly target: (name: string) => string;\n /** A function the text may name at all, in the subset or not: for messages. */\n readonly declared: (name: string) => boolean;\n /** Whether the text is a spec file's, whose names are its imports, never the module's. */\n readonly spec: boolean;\n /**\n * Whether an identifier is the global of its name (`Math`, `Number`):\n * for a module, the compiler resolves it to its standard library; for a\n * spec file's arrow, read from its text alone, every built-in it names\n * has been checked so by the spec reader, so any is.\n */\n readonly global: (id: Identifier) => boolean;\n}\n\n/** Where the types a body mentions come from: the compiler for the module, the module's own declared types for an arrow. */\nexport interface TypeSource {\n /** The subset type a `const` annotation names. */\n readonly annotation: (node: TypeNode, refuse: Refuse) => SubsetType;\n /** The type the context gives a record literal, when the compiler knows one the subset takes. */\n readonly contextual: (node: ObjectLiteralExpression) => SubsetType | undefined;\n}\n\nexport type Scope = ReadonlyMap<string, SubsetType>;\n\nconst binaryOps: Partial<Record<SyntaxKind, BinaryOp>> = {\n [SyntaxKind.PlusToken]: \"+\",\n [SyntaxKind.MinusToken]: \"-\",\n [SyntaxKind.AsteriskToken]: \"*\",\n [SyntaxKind.SlashToken]: \"/\",\n [SyntaxKind.LessThanToken]: \"<\",\n [SyntaxKind.LessThanEqualsToken]: \"<=\",\n [SyntaxKind.GreaterThanToken]: \">\",\n [SyntaxKind.GreaterThanEqualsToken]: \">=\",\n [SyntaxKind.EqualsEqualsEqualsToken]: \"===\",\n [SyntaxKind.ExclamationEqualsEqualsToken]: \"!==\",\n [SyntaxKind.AmpersandAmpersandToken]: \"&&\",\n [SyntaxKind.BarBarToken]: \"||\",\n};\n\nconst methods = new Set([\"slice\", \"map\", \"flatMap\", \"every\", \"some\", \"reduce\"]);\n\n/** The reader of one text: a function body, or an arrow of the spec file. */\nexport class ExprReader {\n readonly sf: SourceFile;\n readonly names: Names;\n readonly types: TypeSource;\n readonly ctx: TypeContext;\n /** The line a refusal reports for a node: the file's, or none for text whose position the caller knows. */\n private readonly lineOf: (node: Node) => number;\n private readonly inline: Inline | undefined;\n private readonly constant: Constant | undefined;\n /** Record literals typed by the call they are passed to, in place of the compiler's contextual type. */\n private readonly typedAs = new Map<Node, SubsetType>();\n\n constructor(\n sf: SourceFile,\n names: Names,\n types: TypeSource,\n ctx: TypeContext,\n lineOf: (node: Node) => number = (node) => lineAt(sf, node),\n inline?: Inline,\n constant?: Constant,\n ) {\n this.sf = sf;\n this.names = names;\n this.types = types;\n this.ctx = ctx;\n this.lineOf = lineOf;\n this.inline = inline;\n this.constant = constant;\n }\n\n /** Whether an identifier is the global of its name here: no scope or function shadows it, and the names confirm it. */\n private global(id: Identifier, scope: Scope): boolean {\n return !scope.has(id.text) && !this.names.declared(id.text) && this.names.global(id);\n }\n\n fail(what: string, at: Node): never {\n throw new OutsideSubset(what, this.lineOf(at));\n }\n\n /** `OutsideSubset` at a node, for a type read there. */\n refuseAt(at: Node): Refuse {\n return (what) => this.fail(what, at);\n }\n\n text(node: Node): string {\n return textOf(this.sf, node);\n }\n\n /** The expression with `narrow` nodes inserted where a null check guards a nullable name. */\n narrowed(e: Expr, scope: Scope, at: Node): Expr {\n return insertNarrows(e, scope, this.ctx, (m) => this.fail(m, at));\n }\n\n typeOfExpr(e: Expr, scope: Scope, at: Node, expected?: SubsetType): SubsetType {\n return typeOf(e, scope, this.ctx, (m) => this.fail(m, at), expected);\n }\n\n /**\n * A block's statements as one expression: `const` becomes `let`, `if (c)\n * return a; rest` a conditional, and the last statement must return:\n * every path ends in a `return`.\n */\n block(statements: readonly Statement[], scope: Scope, end: Node): Expr {\n return this.statements(statements, 0, scope, end);\n }\n\n private statements(statements: readonly Statement[], i: number, scope: Scope, end: Node): Expr {\n const s = statements[i];\n if (!s) this.fail(\"a path that does not return\", end);\n if (is.isEmptyStatement(s)) return this.statements(statements, i + 1, scope, end);\n if (is.isVariableStatement(s)) {\n const list = s.declarationList;\n if (!isConst(list)) this.fail(\"a mutable binding (use const)\", s);\n const [decl, second] = list.declarations;\n if (!decl || second) this.fail(\"several bindings in one const\", s);\n if (!is.isIdentifier(decl.name)) this.fail(\"a destructured const\", decl.name);\n const name = decl.name.text;\n // A const shadows a module function throughout its block, from before its own line (the temporal\n // dead zone): a call above it would throw where the reader would see the function. Refused outright.\n if (this.names.declared(name))\n this.fail(`const ${name} shadows the module's function ${name} in its block`, decl.name);\n if (scope.has(name))\n this.fail(`const ${name} redeclares a name already bound here`, decl.name);\n const annotated = decl.type\n ? this.types.annotation(decl.type, this.refuseAt(decl.type))\n : undefined;\n if (!decl.initializer) this.fail(`const ${name} without a value`, decl);\n const value = this.expression(decl.initializer, scope);\n // While reading, the scope carries names; types come from `typeOf` once null checks have narrowed\n // the tree, so an initializer under a guard is typed as the guard allows. The annotation is the\n // binding's type (a null initializer is then a nullable, not null); `typeOf` checks it fits.\n const inner = new Map(scope);\n inner.set(name, annotated ?? { kind: \"null\" });\n const body = this.statements(statements, i + 1, inner, end);\n return { kind: \"let\", name, value, body, ...(annotated ? { type: annotated } : {}) };\n }\n if (is.isIfStatement(s)) {\n const test = this.expression(s.expression, scope);\n const then = this.branch(s.thenStatement, scope);\n if (s.elseStatement) {\n const otherwise = this.branch(s.elseStatement, scope);\n const after = statements[i + 1];\n if (after) this.fail(\"statements after an if/else that both return\", after);\n return { kind: \"cond\", test, ifTrue: then, ifFalse: otherwise };\n }\n return {\n kind: \"cond\",\n test,\n ifTrue: then,\n ifFalse: this.statements(statements, i + 1, scope, end),\n };\n }\n if (is.isReturnStatement(s)) {\n const after = statements[i + 1];\n // `return` then a line break: JavaScript inserts a semicolon and returns undefined.\n if (!s.expression && after) {\n const gap = this.sf.text.slice(\n s.getStart(this.sf) + \"return\".length,\n after.getStart(this.sf),\n );\n if (/[\\n\\r\\u2028\\u2029]/.test(gap))\n this.fail(\n \"a line break after return (JavaScript inserts a semicolon and returns undefined)\",\n s,\n );\n }\n const value = this.returned(s, scope);\n if (after) this.fail(\"statements after a return\", after);\n return value;\n }\n if (\n is.isForStatement(s) ||\n is.isForOfStatement(s) ||\n is.isForInStatement(s) ||\n is.isWhileStatement(s) ||\n is.isDoStatement(s)\n )\n this.fail(\"a loop\", s);\n if (is.isThrowStatement(s)) this.fail(\"throw\", s);\n if (is.isSwitchStatement(s)) this.fail(\"switch\", s);\n if (is.isTryStatement(s)) this.fail(\"try\", s);\n if (is.isFunctionDeclaration(s)) this.fail(\"a nested function\", s);\n this.fail(`statement starting with ${this.text(s).split(/\\s/)[0] ?? kindName(s.kind)}`, s);\n }\n\n /** An `if` branch: `return e;` or `{ ...statements ending in return }`. */\n private branch(s: Statement, scope: Scope): Expr {\n if (is.isBlock(s)) return this.block(s.statements, scope, s);\n if (is.isReturnStatement(s)) return this.returned(s, scope);\n this.fail(\"an if branch that does not return\", s);\n }\n\n /** `return e;`. A line break after `return` makes JavaScript return undefined: no value, refused. */\n private returned(s: ReturnStatement, scope: Scope): Expr {\n if (!s.expression) this.fail(\"a return without a value\", s);\n return this.expression(s.expression, scope);\n }\n\n expression(node: Expression, scope: Scope): Expr {\n if (is.isParenthesizedExpression(node)) return this.expression(node.expression, scope);\n if (is.isIdentifier(node)) return this.identifier(node, scope);\n if (is.isNumericLiteral(node)) {\n const raw = this.text(node);\n if (!/^[0-9](_?[0-9])*$/.test(raw))\n this.fail(`the numeric literal ${raw} (integers in decimal only)`, node);\n return { kind: \"int\", value: raw.replace(/_/g, \"\") };\n }\n if (is.isBigIntLiteral(node)) this.fail(`the bigint literal ${this.text(node)}`, node);\n if (is.isStringLiteral(node)) {\n if (hasLoneSurrogate(node.text))\n this.fail(\"a string literal with a lone surrogate, which Lean's strings cannot hold\", node);\n return { kind: \"string\", value: node.text };\n }\n if (is.isNoSubstitutionTemplateLiteral(node) || is.isTemplateExpression(node))\n this.fail(\"a template literal\", node);\n if (is.isRegularExpressionLiteral(node)) this.fail(\"a regular expression\", node);\n if (node.kind === SyntaxKind.TrueKeyword) return { kind: \"bool\", value: true };\n if (node.kind === SyntaxKind.FalseKeyword) return { kind: \"bool\", value: false };\n if (node.kind === SyntaxKind.NullKeyword) return { kind: \"null\" };\n if (is.isPrefixUnaryExpression(node)) {\n if (node.operator === SyntaxKind.ExclamationToken)\n return { kind: \"not\", operand: this.expression(node.operand, scope) };\n if (node.operator === SyntaxKind.MinusToken) {\n const operand = this.expression(node.operand, scope);\n // A negated literal stays a literal with its sign flipped, so -(-1) is 1, never the text `--1`.\n return operand.kind === \"int\"\n ? {\n kind: \"int\",\n value: operand.value.startsWith(\"-\") ? operand.value.slice(1) : `-${operand.value}`,\n }\n : { kind: \"neg\", operand };\n }\n if (node.operator === SyntaxKind.PlusToken) this.fail(\"unary plus\", node);\n this.fail(`the ${this.text(node).slice(0, 2)} operator`, node);\n }\n if (is.isPostfixUnaryExpression(node))\n this.fail(`the ${this.text(node).slice(-2)} operator`, node);\n if (is.isTypeOfExpression(node)) this.fail(\"the typeof operator\", node);\n if (is.isVoidExpression(node)) this.fail(\"the void operator\", node);\n if (is.isAwaitExpression(node)) this.fail(\"the await operator\", node);\n if (is.isNewExpression(node)) this.fail(\"the new operator\", node);\n if (is.isDeleteExpression(node)) this.fail(\"the delete operator\", node);\n if (is.isBinaryExpression(node)) return this.binary(node, scope);\n if (is.isConditionalExpression(node))\n return {\n kind: \"cond\",\n test: this.expression(node.condition, scope),\n ifTrue: this.expression(node.whenTrue, scope),\n ifFalse: this.expression(node.whenFalse, scope),\n };\n if (is.isCallExpression(node)) return this.call(node, scope);\n if (is.isPropertyAccessExpression(node)) {\n if (node.questionDotToken) this.fail(\"optional chaining\", node);\n if (!is.isIdentifier(node.name)) this.fail(\"a private field\", node.name);\n return {\n kind: \"field\",\n object: this.expression(node.expression, scope),\n field: node.name.text,\n };\n }\n if (is.isElementAccessExpression(node)) {\n if (this.isHead(node))\n this.fail(\"xs[0] without ?? fallback (it is undefined on an empty list)\", node);\n this.fail(\"index access other than xs[0] ?? fallback\", node);\n }\n if (is.isObjectLiteralExpression(node)) return this.record(node, scope);\n if (is.isArrayLiteralExpression(node)) {\n const items: Expr[] = [];\n let rest: Expr | undefined;\n for (const item of node.elements) {\n if (rest) this.fail(\"a spread that is not last in an array literal\", item);\n if (is.isSpreadElement(item)) rest = this.expression(item.expression, scope);\n else if (is.isOmittedExpression(item)) this.fail(\"a hole in an array literal\", item);\n else items.push(this.expression(item, scope));\n }\n return { kind: \"list\", items, ...(rest ? { rest } : {}) };\n }\n if (is.isArrowFunction(node) || is.isFunctionExpression(node))\n this.fail(\"a function expression (the subset has callbacks of list methods only)\", node);\n if (is.isAsExpression(node)) this.fail(\"the as operator\", node);\n if (is.isSatisfiesExpression(node)) this.fail(\"the satisfies operator\", node);\n if (is.isNonNullExpression(node)) this.fail(\"the ! assertion\", node);\n if (is.isTypeAssertion(node)) this.fail(\"a type assertion\", node);\n if (node.kind === SyntaxKind.ThisKeyword) this.fail(\"this\", node);\n this.fail(`unexpected ${this.text(node) || kindName(node.kind)}`, node);\n }\n\n private identifier(node: Identifier, scope: Scope): Expr {\n const name = node.text;\n if (name === \"undefined\") this.fail(\"undefined (the subset has null)\", node);\n if (scope.has(name) || this.names.declared(name)) return { kind: \"var\", name };\n const constant = this.constant?.(node, (what) => this.fail(what, node));\n if (constant) return constant;\n // A built-in the compiler resolves to something other than its standard library: an import of the\n // name, say. (`Math.abs` reaches here too, as the global: its method is what the subset lacks.)\n if ((name === \"Math\" || name === \"Number\") && !this.names.global(node))\n this.fail(\n `${name}, which is not the standard ${name} here: a declaration of it other than the compiler's is in scope`,\n node,\n );\n this.fail(\n this.names.spec\n ? `${name}, which is neither a parameter, a const nor a function imported from the module beside the spec file`\n : `${name}, which is neither a parameter, a const nor a function of this module`,\n node,\n );\n }\n\n /** Whether an element access is `xs[0]`. */\n private isHead(node: Node): boolean {\n return (\n is.isElementAccessExpression(node) &&\n is.isNumericLiteral(node.argumentExpression) &&\n this.text(node.argumentExpression) === \"0\"\n );\n }\n\n private binary(node: BinaryExpression, scope: Scope): Expr {\n const kind = node.operatorToken.kind;\n const op = binaryOps[kind];\n if (op) {\n return {\n kind: \"binary\",\n op,\n left: this.expression(node.left, scope),\n right: this.expression(node.right, scope),\n };\n }\n if (kind === SyntaxKind.QuestionQuestionToken) {\n // `xs[0] ?? fallback` only: any other index may be past the end, which is undefined.\n if (is.isBinaryExpression(node.left) && node.left.operatorToken.kind === kind)\n this.fail(\"a chain of ??\", node);\n if (is.isElementAccessExpression(node.left) && !this.isHead(node.left))\n this.fail(\"index access other than xs[0] ?? fallback\", node.left);\n if (!is.isElementAccessExpression(node.left))\n this.fail(\n \"?? after anything but xs[0] (write xs[0] ?? fallback, parenthesized where it meets other operators)\",\n node,\n );\n if (node.left.questionDotToken) this.fail(\"optional chaining\", node.left);\n return {\n kind: \"headOr\",\n list: this.expression(node.left.expression, scope),\n fallback: this.expression(node.right, scope),\n };\n }\n if (kind >= SyntaxKind.FirstAssignment && kind <= SyntaxKind.LastAssignment)\n this.fail(\"an assignment\", node);\n if (kind === SyntaxKind.CommaToken) this.fail(\"the comma operator\", node);\n if (kind === SyntaxKind.InKeyword || kind === SyntaxKind.InstanceOfKeyword)\n this.fail(`the ${this.text(node.operatorToken)} operator`, node);\n this.fail(`the ${this.text(node.operatorToken)} operator`, node);\n }\n\n private call(node: CallExpression, scope: Scope): Expr {\n if (node.questionDotToken) this.fail(\"optional chaining\", node);\n let callee = node.expression;\n while (is.isParenthesizedExpression(callee)) callee = callee.expression;\n if (is.isPropertyAccessExpression(callee)) {\n if (callee.questionDotToken) this.fail(\"optional chaining\", callee);\n if (!is.isIdentifier(callee.name)) this.fail(\"a private method\", callee.name);\n const method = callee.name.text;\n const receiver = callee.expression;\n if (\n is.isIdentifier(receiver) &&\n receiver.text === \"Number\" &&\n method === \"isInteger\" &&\n this.global(receiver, scope)\n ) {\n const [arg, extra] = node.arguments;\n if (!arg || extra) this.fail(\"Number.isInteger takes one argument\", node);\n return { kind: \"isInteger\", operand: this.expression(arg, scope) };\n }\n if (\n is.isIdentifier(receiver) &&\n receiver.text === \"Math\" &&\n method === \"floor\" &&\n this.global(receiver, scope)\n ) {\n const [arg, extra] = node.arguments;\n if (!arg || extra) this.fail(\"Math.floor takes one argument\", node);\n return { kind: \"floor\", operand: this.expression(arg, scope) };\n }\n // The receiver first: `Math.abs` fails on `Math`, a name of nothing here, before its method.\n const list = this.expression(receiver, scope);\n if (!methods.has(method))\n this.fail(\n `the method ${method} (the subset has slice(1), map, flatMap, every, some and reduce)`,\n callee.name,\n );\n return this.method(node, list, method, scope);\n }\n if (!is.isIdentifier(callee)) this.fail(\"a call to a computed callee\", callee);\n const name = callee.text;\n // A binder or local named like a function shadows it: the call is to a number, which throws.\n if (scope.has(name))\n this.fail(`a call to ${name}, which names a value here, not the module's function`, callee);\n if (!this.names.callable(name) && this.inline) {\n const readArgs = (types: readonly (SubsetType | undefined)[]): Expr[] =>\n node.arguments.map((a, i) => {\n if (is.isSpreadElement(a)) this.fail(\"a spread argument\", a);\n const type = types[i];\n if (!type) return this.expression(a, scope);\n // The literals the argument evaluates to: itself, or a conditional's branches.\n const literals: Node[] = [];\n const collect = (e: Expression): void => {\n if (is.isParenthesizedExpression(e)) collect(e.expression);\n else if (is.isConditionalExpression(e)) {\n collect(e.whenTrue);\n collect(e.whenFalse);\n } else if (is.isObjectLiteralExpression(e)) literals.push(e);\n };\n collect(a);\n for (const l of literals) this.typedAs.set(l, type);\n try {\n return this.expression(a, scope);\n } finally {\n for (const l of literals) this.typedAs.delete(l);\n }\n });\n const inlined = this.inline(node, callee, scope, readArgs, (what) => this.fail(what, node));\n if (inlined) return inlined;\n }\n if (!this.names.declared(name)) this.identifier(callee, scope); // names nothing here: its message\n if (!this.names.callable(name))\n this.fail(`a call to ${name}, which is outside the subset`, callee);\n return {\n kind: \"call\",\n callee: this.names.target(name),\n args: node.arguments.map((a) => {\n if (is.isSpreadElement(a)) this.fail(\"a spread argument\", a);\n return this.expression(a, scope);\n }),\n };\n }\n\n /** `(a, b) => body` or `a => body`, an expression body only; the names it binds go into scope. */\n private callback(\n node: Expression,\n scope: Scope,\n arity: number,\n what: string,\n ): { names: string[]; body: Expr } {\n if (!is.isArrowFunction(node)) this.fail(`${what} takes an arrow function`, node);\n const arrow: ArrowFunction = node;\n // An async callback returns a promise, truthy whatever the body computes.\n if (isAsync(arrow)) this.fail(`an async callback in ${what}`, arrow);\n const names: string[] = [];\n for (const p of arrow.parameters) {\n if (!is.isIdentifier(p.name)) this.fail(`a destructured parameter of ${what}'s callback`, p);\n if (p.type) this.fail(`a type annotation on ${what}'s parameter`, p.type);\n if (p.initializer) this.fail(`a default value on ${what}'s parameter`, p);\n if (p.dotDotDotToken) this.fail(`a rest parameter on ${what}'s callback`, p);\n names.push(p.name.text);\n }\n if (names.length === 0 || names.length > arity)\n this.fail(\n `${what} takes a callback of 1 to ${arity} parameter(s), given ${names.length}`,\n arrow,\n );\n for (const n of names)\n if (scope.has(n) || this.names.declared(n))\n this.fail(`${what}'s parameter ${n} shadows a name already bound here`, arrow);\n if (new Set(names).size !== names.length)\n this.fail(`${what}'s parameters repeat a name`, arrow);\n if (is.isBlock(arrow.body))\n this.fail(`a block body in ${what}'s callback (write an expression)`, arrow.body);\n const inner = new Map(scope);\n for (const n of names) inner.set(n, { kind: \"null\" });\n return { names, body: this.expression(arrow.body, inner) };\n }\n\n /** A method call on a list: slice(1), map, flatMap, every, some, reduce. */\n private method(node: CallExpression, list: Expr, name: string, scope: Scope): Expr {\n const args = node.arguments;\n if (name === \"slice\") {\n const [one, extra] = args;\n if (!one || extra || !is.isNumericLiteral(one) || this.text(one) !== \"1\")\n this.fail(\"slice with an argument other than 1\", one ?? node);\n return { kind: \"tail\", list };\n }\n if (name === \"reduce\") {\n const [cb, init, extra] = args;\n if (!cb || !init || extra) this.fail(\"reduce takes a callback and an initial value\", node);\n const { names, body } = this.callback(cb, scope, 2, \"reduce\");\n if (names.length !== 2) this.fail(\"reduce takes a callback of (accumulator, item)\", cb);\n return {\n kind: \"fold\",\n list,\n acc: names[0] as string,\n item: names[1] as string,\n body,\n init: this.expression(init, scope),\n };\n }\n const [cb, extra] = args;\n if (!cb || extra) this.fail(`${name} takes one callback`, node);\n const { names, body } = this.callback(cb, scope, 2, name);\n return {\n kind: \"iterate\",\n op: name as \"map\" | \"flatMap\" | \"every\" | \"some\",\n list,\n item: names[0] as string,\n ...(names[1] === undefined ? {} : { index: names[1] }),\n body,\n };\n }\n\n private record(node: ObjectLiteralExpression, scope: Scope): Expr {\n const fields: { name: string; value: Expr }[] = [];\n for (const p of node.properties) {\n if (is.isSpreadAssignment(p)) this.fail(\"spread in a record literal\", p);\n if (is.isShorthandPropertyAssignment(p)) {\n if (!is.isIdentifier(p.name))\n this.fail(`a key that is not a name: ${this.text(p.name)}`, p.name);\n const name = p.name.text;\n if (name === \"__proto__\")\n this.fail(\"a __proto__ key, which sets the prototype, not a field\", p);\n if (!scope.has(name)) this.fail(`shorthand ${name} names nothing in scope`, p);\n fields.push({ name, value: { kind: \"var\", name } });\n continue;\n }\n if (!is.isPropertyAssignment(p)) this.fail(`a method ${this.text(p).split(\"(\")[0] ?? \"\"}`, p);\n if (is.isComputedPropertyName(p.name)) this.fail(\"a computed key\", p.name);\n if (!is.isIdentifier(p.name))\n this.fail(`a key that is not a name: ${this.text(p.name)}`, p.name);\n if (p.name.text === \"__proto__\")\n this.fail(\"a __proto__ key, which sets the prototype, not a field\", p.name);\n fields.push({ name: p.name.text, value: this.expression(p.initializer, scope) });\n }\n const type = this.typedAs.get(node) ?? this.types.contextual(node);\n const literal = (fs: typeof fields): Expr => ({\n kind: \"record\",\n fields: fs,\n ...(type ? { type } : {}),\n });\n // A member of a union picked by a conditional tag (`{ type: c ? \"a\" : \"b\", at }`) is one literal\n // per branch: the conditional moves out, the other fields go into each as written. The fields\n // are pure, so evaluating the test first computes the same value.\n const tag = type?.kind === \"union\" ? tagOf(type.name, this.ctx) : undefined;\n const chosen = tag === undefined ? undefined : fields.find((f) => f.name === tag);\n if (chosen?.value.kind === \"cond\") {\n const split = (value: Expr): Expr =>\n value.kind === \"cond\"\n ? {\n kind: \"cond\",\n test: value.test,\n ifTrue: split(value.ifTrue),\n ifFalse: split(value.ifFalse),\n }\n : literal(fields.map((f) => (f === chosen ? { name: f.name, value } : f)));\n return split(chosen.value);\n }\n return literal(fields);\n }\n}\n\n/**\n * A `const` annotation inside a spec arrow, read from its syntax against\n * the module's declared types: no compiler stands behind an arrow's\n * text, so a name must be a record or union the module reads, and the\n * forms are the primitives, `null`, literals, unions of those and arrays.\n */\nexport function syntacticType(\n sf: SourceFile,\n node: TypeNode,\n records: ReadonlySet<string>,\n unions: ReadonlySet<string>,\n refuse: Refuse,\n): SubsetType {\n const go = (n: TypeNode): SubsetType => syntacticType(sf, n, records, unions, refuse);\n if (is.isParenthesizedTypeNode(node)) return go(node.type);\n if (is.isTypeOperatorNode(node) && node.operator === SyntaxKind.ReadonlyKeyword) {\n if (!is.isArrayTypeNode(node.type))\n return refuse(\"readonly before a type that is not an array\");\n return go(node.type);\n }\n if (is.isArrayTypeNode(node)) return { kind: \"list\", element: go(node.elementType) };\n if (node.kind === SyntaxKind.NumberKeyword) return { kind: \"int\" };\n if (node.kind === SyntaxKind.BooleanKeyword) return { kind: \"bool\" };\n if (node.kind === SyntaxKind.StringKeyword) return { kind: \"string\" };\n if (node.kind === SyntaxKind.UndefinedKeyword)\n return refuse(\"undefined in a type (the subset has null)\");\n if (is.isLiteralTypeNode(node)) {\n const lit = node.literal;\n if (lit.kind === SyntaxKind.NullKeyword) return { kind: \"null\" };\n if (lit.kind === SyntaxKind.TrueKeyword || lit.kind === SyntaxKind.FalseKeyword)\n return { kind: \"bool\" };\n if (is.isStringLiteral(lit)) return { kind: \"string\" };\n return refuse(`the literal type ${textOf(sf, node)}`);\n }\n if (is.isTypeReferenceNode(node)) {\n if (node.typeArguments)\n return refuse(`type ${textOf(sf, node)} (a generic type in an arrow's const)`);\n if (!is.isIdentifier(node.typeName)) return refuse(`type ${textOf(sf, node)}`);\n const name = node.typeName.text;\n if (records.has(name)) return { kind: \"record\", name };\n if (unions.has(name)) return { kind: \"union\", name };\n return refuse(\n `type ${name} (the subset has number, boolean, string, null, and the module's own record types and unions)`,\n );\n }\n if (is.isUnionTypeNode(node)) {\n const members = node.types.map(go);\n const nulls = members.filter((m) => m.kind === \"null\");\n const rest = members.filter((m) => m.kind !== \"null\");\n const first = rest[0];\n if (!first) return refuse(\"null alone is not a type the subset takes\");\n if (!rest.every((m) => JSON.stringify(m) === JSON.stringify(first)))\n return refuse(\"a union of several types (declare it as a type alias in the module)\");\n if (nulls.length === 0) return first;\n return first.kind === \"nullable\" ? first : { kind: \"nullable\", inner: first };\n }\n return refuse(`type ${textOf(sf, node)}`);\n}\n\n/**\n * The block body of an arrow read from a parsed fragment: the statements\n * between the braces, every path returning.\n */\nexport function blockOf(sf: SourceFile): Block | undefined {\n const [first, second] = sf.statements;\n return first && !second && is.isBlock(first) ? first : undefined;\n}\n","/**\n * The compiler's types read two ways. `specTypeOf` reads a type into\n * `SpecType` as far as the spec surface describes it (primitives,\n * literals, records, unions, arrays), marking the rest `unknown` with its\n * text: binder domains for the simulator's rungs. `SubsetTypes` reads a\n * type into the subset's own types (integers, booleans, strings, records,\n * nullable types, tagged unions, lists), naming every record and union it\n * meets so the engines can declare them: a declared type by its name, an\n * instantiated generic or an inline object type as the compiler prints\n * it, a union member declared inline by its union and its tag. Both read\n * what the compiler resolved, so a type declared later in the file, in\n * another file, or through a generic alias reads as its structure.\n */\n\nimport type { SpecType } from \"@eutaxy/spec\";\nimport { SyntaxKind } from \"typescript/ast\";\nimport * as is from \"typescript/ast/is\";\nimport {\n type Checker,\n SymbolFlags,\n type Type,\n TypeFlags,\n TypeFormatFlags,\n type TypeReference,\n} from \"typescript/sync\";\nimport type { Field, RecordType, SubsetType, UnionType } from \"./subset.ts\";\n\n/** Levels of records and lists inside one another a type may hold before it is cut (a generic instantiating itself anew at each level never repeats). */\nconst maxDepth = 16;\n\n/**\n * Why an object type is not plain data, or undefined when it is: a class\n * (an instance is more than its fields: nominal, with private ones), or an\n * interface over a base the compiler could not resolve (it then shows the\n * interface's own fields alone) or over a class.\n */\nexport function notPlain(\n checker: Checker,\n type: Type,\n seen: Set<number> = new Set(),\n): string | undefined {\n const symbol = type.getSymbol();\n if (!symbol || seen.has(type.id)) return undefined;\n seen.add(type.id);\n if ((symbol.flags & SymbolFlags.Class) !== 0)\n return \"a class (an instance is more than a record of its fields)\";\n if ((symbol.flags & SymbolFlags.Interface) === 0) return undefined;\n for (const handle of symbol.declarations) {\n if (handle.kind !== SyntaxKind.InterfaceDeclaration) continue;\n const decl = handle.resolve();\n if (!decl || !is.isInterfaceDeclaration(decl)) continue;\n for (const clause of decl.heritageClauses ?? [])\n for (const base of clause.types) {\n const baseType = checker.getTypeAtLocation(base);\n if (baseType.isErrorType()) return `extends ${base.getText()}, which does not resolve`;\n // The whole ancestry: a class anywhere up makes the interface nominal.\n const why = notPlain(checker, baseType, seen);\n if (why !== undefined) return `extends ${base.getText()}: ${why}`;\n }\n }\n return undefined;\n}\n\n/** A type as the compiler prints it, in full. */\nexport function printType(checker: Checker, type: Type): string {\n return checker.typeToString(type, undefined, TypeFormatFlags.NoTruncation);\n}\n\n/**\n * The name a record or union goes by: its alias or interface name when\n * declared without type arguments, otherwise the type as the compiler\n * prints it (`Result<true, Locked>`, `{ readonly ok: boolean; }`).\n */\nexport function nameOfType(checker: Checker, type: Type): string {\n const alias = type.getAliasSymbol();\n if (alias)\n return type.getAliasTypeArguments().length === 0 ? alias.name : printType(checker, type);\n const symbol = type.getSymbol();\n if (\n symbol &&\n (symbol.flags & (SymbolFlags.Interface | SymbolFlags.Class)) !== 0 &&\n !(type.isTypeReference() && checker.getTypeArguments(type).length > 0)\n )\n return symbol.name;\n return printType(checker, type);\n}\n\n/** A union's members with `true | false` folded back into `boolean`, which the compiler keeps apart. */\nfunction foldBooleans(members: readonly Type[]): (Type | \"boolean\")[] {\n const isTrue = (t: Type) => t.isBooleanLiteralType() && t.value === true;\n const isFalse = (t: Type) => t.isBooleanLiteralType() && t.value === false;\n if (!members.some(isTrue) || !members.some(isFalse)) return [...members];\n const out: (Type | \"boolean\")[] = [];\n let folded = false;\n for (const m of members) {\n if (isTrue(m) || isFalse(m)) {\n if (!folded) out.push(\"boolean\");\n folded = true;\n } else out.push(m);\n }\n return out;\n}\n\n/** The members of a union as one type: flattened, deduplicated, one member alone. */\nexport function unionOf(members: readonly SpecType[]): SpecType {\n const flat = members.flatMap((m) => (m.kind === \"union\" ? m.members : [m]));\n const seen = new Set<string>();\n const unique = flat.filter((m) => {\n const key = JSON.stringify(m);\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n return unique.length === 1 ? (unique[0] as SpecType) : { kind: \"union\", members: unique };\n}\n\n/** A type into `SpecType`; what the spec surface does not describe is `unknown` with the type's text. */\nexport function specTypeOf(\n checker: Checker,\n type: Type,\n seen: ReadonlySet<number> = new Set(),\n): SpecType {\n const unknown = (): SpecType => ({ kind: \"unknown\", text: printType(checker, type) });\n const flags = type.flags;\n if (type.isErrorType()) return unknown();\n if (flags & TypeFlags.Number) return { kind: \"number\" };\n if (flags & TypeFlags.String) return { kind: \"string\" };\n if (flags & TypeFlags.Boolean) return { kind: \"boolean\" };\n if (flags & TypeFlags.BigInt) return { kind: \"bigint\" };\n if (type.isStringLiteralType() || type.isNumberLiteralType() || type.isBooleanLiteralType())\n return { kind: \"literal\", value: type.value };\n if (flags & TypeFlags.Null) return { kind: \"null\" };\n if (flags & (TypeFlags.Undefined | TypeFlags.Void)) return { kind: \"undefined\" };\n if (type.isUnionType())\n return unionOf(\n foldBooleans(type.getTypes()).map((m) =>\n m === \"boolean\" ? { kind: \"boolean\" } : specTypeOf(checker, m, seen),\n ),\n );\n if (!type.isObjectType()) return unknown();\n // A type reaching itself through a field or an element: the cycle is cut with the type's name;\n // one that nests without repeating is cut at a depth.\n if (seen.has(type.id) || seen.size >= maxDepth) return unknown();\n const inner = new Set(seen).add(type.id);\n if (checker.isArrayType(type)) {\n const element = checker.getTypeArguments(type as TypeReference)[0];\n return element ? { kind: \"array\", element: specTypeOf(checker, element, inner) } : unknown();\n }\n if (\n type.isTupleType() ||\n type.getCallSignatures().length > 0 ||\n type.getConstructSignatures().length > 0 ||\n type.getIndexInfos().length > 0\n )\n return unknown();\n if (notPlain(checker, type) !== undefined) return unknown();\n const properties = type.getProperties();\n // An object with a method or an accessor is no record of plain data (a Map, a class instance), and\n // neither is one keyed by a symbol (the compiler names it `__@key@…`, which no string names).\n const computed = SymbolFlags.Method | SymbolFlags.GetAccessor | SymbolFlags.SetAccessor;\n if (properties.some((p) => (p.flags & computed) !== 0 || isSymbolKey(p.name))) return unknown();\n const fields = properties.map((p) => ({\n name: p.name,\n type: specTypeOf(checker, checker.getTypeOfSymbol(p), inner),\n }));\n return { kind: \"record\", name: nameOfType(checker, type), fields };\n}\n\n/** Whether a property's name is the compiler's spelling of a symbol key, which no string names. */\nconst isSymbolKey = (name: string): boolean => name.startsWith(\"__@\");\n\n/** Names a Lean structure declaration generates itself, which a field cannot take. */\nconst structureNames = new Set([\n \"mk\",\n \"rec\",\n \"recOn\",\n \"casesOn\",\n \"noConfusion\",\n \"noConfusionType\",\n \"injEq\",\n]);\n\n/** `OutsideSubset` at the type being read, by the reader that asked. */\nexport type Refuse = (what: string) => never;\n\n/**\n * The subset's types read from the compiler's, with every record and\n * union met along the way kept by name, in the order met, for the engines\n * to declare. One type is read once: a second meeting gives the same\n * record, and so does another compiler type of the same name and the\n * same fields (an inline type written twice). A type the subset does not\n * take is refused with the construct named, and a read that is refused\n * leaves nothing behind: whatever it registered on the way is taken back,\n * so no record belongs to a union that was never declared.\n */\nexport class SubsetTypes {\n readonly records = new Map<string, RecordType>();\n readonly unions: UnionType[] = [];\n private readonly checker: Checker;\n /** By the compiler's type id. */\n private readonly byId = new Map<number, SubsetType>();\n private readonly idOfName = new Map<string, number>();\n /** Types being read now, to refuse a type that holds itself. */\n private readonly reading = new Set<number>();\n\n constructor(checker: Checker) {\n this.checker = checker;\n }\n\n /** The subset type of a compiler type, or a refusal, after which nothing of the read remains. */\n of(type: Type, refuse: Refuse): SubsetType {\n const cached = this.byId.get(type.id);\n if (cached) return cached;\n if (this.reading.size > 0) return this.enter(type, refuse);\n // The outermost read of a type: all or nothing.\n const saved = {\n records: new Map(this.records),\n idOfName: new Map(this.idOfName),\n byId: new Map(this.byId),\n unions: this.unions.length,\n };\n try {\n return this.enter(type, refuse);\n } catch (err) {\n this.records.clear();\n for (const [k, v] of saved.records) this.records.set(k, v);\n this.idOfName.clear();\n for (const [k, v] of saved.idOfName) this.idOfName.set(k, v);\n this.byId.clear();\n for (const [k, v] of saved.byId) this.byId.set(k, v);\n this.unions.length = saved.unions;\n throw err;\n }\n }\n\n /** A type read under the recursion guard. */\n private enter(type: Type, refuse: Refuse): SubsetType {\n // A type reaching itself, through a field or an element, is refused rather than followed.\n if (this.reading.has(type.id))\n return refuse(`${nameOfType(this.checker, type)} holds itself (a recursive type)`);\n if (this.reading.size >= maxDepth)\n return refuse(\n `${nameOfType(this.checker, type)} is nested too deep (more than ${maxDepth} levels)`,\n );\n this.reading.add(type.id);\n try {\n const out = this.read(type, refuse);\n this.byId.set(type.id, out);\n return out;\n } finally {\n this.reading.delete(type.id);\n }\n }\n\n private read(type: Type, refuse: Refuse): SubsetType {\n const checker = this.checker;\n const text = () => printType(checker, type);\n const flags = type.flags;\n if (type.isErrorType()) return refuse(`type ${text()}, which does not resolve`);\n if (flags & TypeFlags.Number) return { kind: \"int\" };\n if (flags & (TypeFlags.String | TypeFlags.StringLiteral)) return { kind: \"string\" };\n if (flags & (TypeFlags.Boolean | TypeFlags.BooleanLiteral)) return { kind: \"bool\" };\n if (flags & TypeFlags.Null) return refuse(\"null alone is not a type the subset takes\");\n if (flags & (TypeFlags.Undefined | TypeFlags.Void))\n return refuse(\"undefined in a type (the subset has null)\");\n if (flags & TypeFlags.NumberLiteral)\n return refuse(`the numeric literal type ${text()} (the subset has number)`);\n if (flags & TypeFlags.BigInt) return refuse(\"bigint (the subset has number)\");\n if (flags & TypeFlags.TypeParameter) return refuse(\"type parameters\");\n if (type.isUnionType()) return this.union(type, refuse);\n if (type.isIntersectionType()) return refuse(\"an intersection type\");\n if (!type.isObjectType())\n return refuse(\n `type ${text()} (the subset has number, boolean, string, null, and record types, unions and arrays of them)`,\n );\n if (checker.isArrayType(type)) {\n const element = checker.getTypeArguments(type as TypeReference)[0];\n if (!element) return refuse(`type ${text()}`);\n return { kind: \"list\", element: this.of(element, refuse) };\n }\n if (type.isTupleType()) return refuse(\"a tuple type\");\n if (type.getCallSignatures().length > 0 || type.getConstructSignatures().length > 0)\n return refuse(\"a function type\");\n if (type.getIndexInfos().length > 0) return refuse(\"an index signature\");\n const why = notPlain(checker, type);\n if (why !== undefined) return refuse(`type ${text()} is outside the subset: ${why}`);\n const record = this.record(type, nameOfType(checker, type), refuse);\n return { kind: \"record\", name: record.name };\n }\n\n /** A union: `T | null` a nullable, literals their base type, several records a tagged union. */\n private union(type: Type, refuse: Refuse): SubsetType {\n const members = type.isUnionType() ? type.getTypes() : [type];\n if (members.some((m) => (m.flags & (TypeFlags.Undefined | TypeFlags.Void)) !== 0))\n return refuse(\"undefined in a type (the subset has null)\");\n const nulls = members.filter((m) => (m.flags & TypeFlags.Null) !== 0);\n const rest = members.filter((m) => (m.flags & TypeFlags.Null) === 0);\n const bare = nulls.length === 0 ? type : type.getNonNullableType();\n let base: SubsetType;\n if (rest.length === 0) return refuse(\"null alone is not a type the subset takes\");\n else if (rest.every((m) => (m.flags & (TypeFlags.String | TypeFlags.StringLiteral)) !== 0))\n base = { kind: \"string\" };\n else if (rest.every((m) => (m.flags & (TypeFlags.Boolean | TypeFlags.BooleanLiteral)) !== 0))\n base = { kind: \"bool\" };\n else if (rest.length === 1) base = this.of(rest[0] as Type, refuse);\n else if (rest.every((m) => m.isObjectType() && !this.checker.isArrayType(m)))\n base = this.taggedUnion(bare, rest, refuse);\n else if (rest.some((m) => m.isObjectType()))\n return refuse(\"a union mixing records with other types\");\n else if (rest.every((m) => (m.flags & TypeFlags.NumberLiteral) !== 0))\n return refuse(\n `the numeric literal type ${printType(this.checker, type)} (the subset has number)`,\n );\n else\n return refuse(\n `a union of several types (${printType(this.checker, type)}): the subset has a union of literals of one kind, a tagged union of records, and either with null`,\n );\n if (nulls.length === 0) return base;\n if (base.kind === \"nullable\") return base;\n return { kind: \"nullable\", inner: base };\n }\n\n /**\n * A union of records, told apart by a tag: a literal-typed field every\n * member has, holding a different literal in each. Members declared\n * inline are named by the union and their tag (`Outcome.true`); a\n * record declared on its own keeps its name, and may be a member of several unions.\n */\n private taggedUnion(type: Type, members: readonly Type[], refuse: Refuse): SubsetType {\n const cached = this.byId.get(type.id);\n if (cached) return cached;\n const checker = this.checker;\n const name = nameOfType(checker, type);\n // One name, one type: a second union of the name, or a record of it, is a clash.\n const taken = this.idOfName.get(name);\n if (taken !== undefined && taken !== type.id) return refuse(`two types named ${name}`);\n if (taken === undefined && (this.records.has(name) || this.unions.some((u) => u.name === name)))\n return refuse(`two types named ${name}`);\n const literalFields = (m: Type): Map<string, string | boolean> => {\n const out = new Map<string, string | boolean>();\n for (const p of m.getProperties()) {\n const t = checker.getTypeOfSymbol(p);\n if (t.isStringLiteralType() || t.isBooleanLiteralType()) out.set(p.name, t.value);\n }\n return out;\n };\n const literals = members.map(literalFields);\n const tag = [...(literals[0] as Map<string, string | boolean>).keys()].find(\n (field) =>\n literals.every((l) => l.has(field)) &&\n new Set(literals.map((l) => JSON.stringify(l.get(field)))).size === literals.length,\n );\n if (tag === undefined)\n return refuse(\n `${name}: a union of records without a tag (a literal-typed field every member has, different in each)`,\n );\n const isAnonymous = (m: Type) =>\n !m.getAliasSymbol() &&\n ((m.getSymbol()?.flags ?? 0) & (SymbolFlags.Interface | SymbolFlags.Class)) === 0;\n const read = members.map((m, i) => {\n const value = (literals[i] as Map<string, string | boolean>).get(tag) as string | boolean;\n const memberName = isAnonymous(m) ? `${name}.${String(value)}` : nameOfType(checker, m);\n const record = this.record(m, memberName, refuse, name);\n return { tag: value, record: record.name };\n });\n const union: UnionType = { name, tag, members: read };\n this.unions.push(union);\n this.idOfName.set(name, type.id);\n const out: SubsetType = { kind: \"union\", name };\n this.byId.set(type.id, out);\n return out;\n }\n\n /** A record under `name`: its fields read, the record kept; a member of `union` when given. */\n private record(type: Type, name: string, refuse: Refuse, union?: string): RecordType {\n let known = this.records.get(name);\n // A union of the name is a clash: one name, one type.\n if (!known && this.unions.some((u) => u.name === name))\n return refuse(`two types named ${name}`);\n if (known && this.idOfName.get(name) !== type.id) {\n // Another compiler type of the same name (an inline type written twice, say) is the same\n // record when it has the same fields, and a clash otherwise.\n const fields = this.fieldsOf(type, name, refuse);\n if (JSON.stringify(fields) !== JSON.stringify(known.fields))\n return refuse(`two types named ${name}`);\n this.byId.set(type.id, { kind: \"record\", name });\n }\n if (known) {\n if (union !== undefined && !known.unions?.includes(union)) {\n known = { ...known, unions: [...(known.unions ?? []), union] };\n this.records.set(name, known);\n }\n return known;\n }\n const fields = this.fieldsOf(type, name, refuse);\n const record: RecordType = {\n name,\n fields,\n ...(union === undefined ? {} : { unions: [union] }),\n };\n this.records.set(name, record);\n this.idOfName.set(name, type.id);\n this.byId.set(type.id, { kind: \"record\", name });\n return record;\n }\n\n /** The fields of a record type, each a stored value the subset takes. */\n private fieldsOf(type: Type, name: string, refuse: Refuse): Field[] {\n // A member read straight from its union is guarded here; one read through `of` already is.\n const guard = !this.reading.has(type.id);\n if (guard) this.reading.add(type.id);\n try {\n const checker = this.checker;\n const fields: Field[] = [];\n const outside: Refuse = (what) => refuse(`type ${name} is outside the subset: ${what}`);\n for (const p of type.getProperties()) {\n if (isSymbolKey(p.name)) return outside(\"a field keyed by a symbol\");\n if ((p.flags & SymbolFlags.Optional) !== 0) return outside(`optional field ${p.name}`);\n if ((p.flags & SymbolFlags.Method) !== 0) return outside(`a method ${p.name}`);\n // A getter computes; a stored field it is not.\n if ((p.flags & (SymbolFlags.GetAccessor | SymbolFlags.SetAccessor)) !== 0)\n return outside(`an accessor ${p.name}`);\n if (structureNames.has(p.name))\n return outside(`field ${p.name} takes a name Lean's structures reserve`);\n if (p.name === \"__proto__\")\n return outside(\"a field named __proto__, which JavaScript treats specially\");\n const fieldType = checker.getTypeOfSymbol(p);\n const read = this.of(fieldType, (what) => outside(`field ${p.name}: ${what}`));\n const literal = fieldType.isStringLiteralType()\n ? fieldType.value\n : fieldType.isBooleanLiteralType()\n ? fieldType.value\n : undefined;\n fields.push({ name: p.name, type: read, ...(literal === undefined ? {} : { literal }) });\n }\n return fields;\n } finally {\n if (guard) this.reading.delete(type.id);\n }\n }\n}\n","/**\n * The pure TypeScript subset the first-party engines accept, read into a\n * small tree: exported functions (declarations, and arrows a module-level\n * `const` holds) over `number`, `boolean` and `string`,\n * record types, nullable types (`T | null`) and tagged unions of records,\n * lists of any of those, returning any of those; bodies made of `const`\n * bindings, `if` with early returns, `return`, and expressions from\n * arithmetic (`+ - *`), comparisons, `=== !==` (`null` included, which\n * narrows a nullable name in the branch it guards), `&& || !`, the\n * conditional operator, record and array literals, field reads (on a\n * union, only a field every member has), list methods and calls to the\n * module's own functions. Types are whatever the compiler resolves them\n * to: declared anywhere in the file, imported from another file, or an\n * instantiated generic. Anything else is `OutsideSubset`, with the\n * construct named: the subset is specified by the contract corpus and\n * widens one characterised class at a time. What each engine takes of it\n * is the engine's business (`restrictModule`). This module holds the\n * subset's meaning: its types and tree, typing, narrowing, renaming and\n * the three passes over a module; `expressions.ts` reads the syntax and\n * `types.ts` the compiler's types.\n */\n\nimport type { Arrow } from \"@eutaxy/spec\";\nimport {\n type ArrowFunction,\n type AsExpression,\n type Expression,\n type FunctionDeclaration,\n type FunctionExpression,\n forEachLeadingCommentRange,\n forEachTrailingCommentRange,\n type Identifier,\n InternalSymbolName,\n type Node,\n type NonNullExpression,\n type ObjectLiteralExpression,\n type ParenthesizedExpression,\n type SatisfiesExpression,\n type SourceFile,\n SyntaxKind,\n type TypeAssertion,\n} from \"typescript/ast\";\nimport * as is from \"typescript/ast/is\";\nimport { type Checker, SymbolFlags, type Type } from \"typescript/sync\";\nimport {\n type CompilerError,\n type InputFile,\n isAsync,\n isConst,\n lineAt,\n openParen,\n textOf,\n withProgram,\n withSourceFile,\n} from \"./compiler.ts\";\nimport {\n blockOf,\n type Constant,\n ExprReader,\n type Inline,\n type Names,\n syntacticType,\n type TypeSource,\n} from \"./expressions.ts\";\nimport { SubsetTypes } from \"./types.ts\";\n\nexport class OutsideSubset extends Error {\n readonly line: number;\n constructor(message: string, line: number) {\n super(message);\n this.line = line;\n }\n}\n\nexport type SubsetType =\n | { readonly kind: \"int\" }\n | { readonly kind: \"bool\" }\n | { readonly kind: \"string\" }\n | { readonly kind: \"record\"; readonly name: string }\n /** `T | null`. */\n | { readonly kind: \"nullable\"; readonly inner: SubsetType }\n /** A tagged union of records declared as a type alias; its members are records of the module. */\n | { readonly kind: \"union\"; readonly name: string }\n /** The type of the literal `null` itself, which only a nullable type accepts. */\n | { readonly kind: \"null\" }\n /** `readonly T[]` or `T[]`: a list of values of one type (Lean's `List`). */\n | { readonly kind: \"list\"; readonly element: SubsetType }\n /** The element type of `[]`, which fits in a list of any type. */\n | { readonly kind: \"nothing\" };\n\nexport interface Field {\n readonly name: string;\n readonly type: SubsetType;\n /** The one value a literal-typed field holds (`ok: true`, `type: \"locked\"`): a union member's tag. */\n readonly literal?: string | boolean;\n}\n\nexport interface RecordType {\n readonly name: string;\n readonly fields: readonly Field[];\n /**\n * The tagged unions this record is a member of, in the order they were\n * read: `Err<E>` is one in `Result<A, E>` and in `Result<B, E>`. A member\n * written inline in a union is named `<union>.<tag>` after the first.\n */\n readonly unions?: readonly string[];\n}\n\n/** Whether a record is a member of a union. */\nexport function isMember(record: RecordType | undefined, union: string): boolean {\n return record?.unions?.includes(union) ?? false;\n}\n\n/** A union's members among the records known, in the order they were read. */\nfunction membersIn(union: string, ctx: TypeContext): RecordType[] {\n return [...ctx.records.values()].filter((rec) => isMember(rec, union));\n}\n\n/** A tagged union: records told apart by one field, the tag, which holds a different literal in each. */\nexport interface UnionType {\n readonly name: string;\n readonly tag: string;\n /** The member records, in declaration order, by their tag's value. */\n readonly members: readonly { readonly tag: string | boolean; readonly record: string }[];\n}\n\nexport type BinaryOp =\n | \"+\"\n | \"-\"\n | \"*\"\n | \"/\"\n | \"<\"\n | \"<=\"\n | \">\"\n | \">=\"\n | \"===\"\n | \"!==\"\n | \"&&\"\n | \"||\";\n\nexport type Expr =\n | { readonly kind: \"int\"; readonly value: string }\n | { readonly kind: \"bool\"; readonly value: boolean }\n | { readonly kind: \"string\"; readonly value: string }\n | { readonly kind: \"null\" }\n | { readonly kind: \"var\"; readonly name: string }\n /** In `body`, `name` (a nullable in scope) stands for its non-null value: inserted where a null check guards. */\n | { readonly kind: \"narrow\"; readonly name: string; readonly body: Expr }\n /** In `body`, `name` (a union in scope) is its member `member`: inserted where a test of the union's tag guards. */\n | {\n readonly kind: \"narrowTag\";\n readonly name: string;\n readonly member: string;\n readonly body: Expr;\n }\n | { readonly kind: \"neg\"; readonly operand: Expr }\n | { readonly kind: \"not\"; readonly operand: Expr }\n /** `Number.isInteger(e)`: always true of an integer in the engines' integer model, the real predicate on doubles. */\n | { readonly kind: \"isInteger\"; readonly operand: Expr }\n /** `Math.floor(e)`: rounding toward negative infinity on doubles; the identity on the integers. */\n | { readonly kind: \"floor\"; readonly operand: Expr }\n | { readonly kind: \"binary\"; readonly op: BinaryOp; readonly left: Expr; readonly right: Expr }\n | { readonly kind: \"cond\"; readonly test: Expr; readonly ifTrue: Expr; readonly ifFalse: Expr }\n | { readonly kind: \"call\"; readonly callee: string; readonly args: readonly Expr[] }\n | { readonly kind: \"field\"; readonly object: Expr; readonly field: string }\n | {\n readonly kind: \"record\";\n readonly fields: readonly { readonly name: string; readonly value: Expr }[];\n /** The type its context gives the literal (a declared return type, a const annotation, a parameter), as the compiler sees it: a record, or the union a member is picked from. */\n readonly type?: SubsetType;\n }\n | {\n readonly kind: \"let\";\n readonly name: string;\n readonly value: Expr;\n readonly body: Expr;\n /** The `const`'s annotation, when it has one: the binding's type, whatever the initializer's. */\n readonly type?: SubsetType;\n }\n /** `[a, b]`, or `[a, b, ...rest]` with the spread last. `xs.length` is a `field` read on a list. */\n | { readonly kind: \"list\"; readonly items: readonly Expr[]; readonly rest?: Expr }\n /** `xs.slice(1)`: every element but the first. */\n | { readonly kind: \"tail\"; readonly list: Expr }\n /** `xs[0] ?? fallback`: the first element, or the fallback for an empty list. */\n | { readonly kind: \"headOr\"; readonly list: Expr; readonly fallback: Expr }\n /** `xs.map`, `xs.flatMap`, `xs.every` or `xs.some` with `(item, index?) => body`. */\n | {\n readonly kind: \"iterate\";\n readonly op: \"map\" | \"flatMap\" | \"every\" | \"some\";\n readonly list: Expr;\n readonly item: string;\n readonly index?: string;\n readonly body: Expr;\n }\n /** `xs.reduce((acc, item) => body, init)`: a left fold. */\n | {\n readonly kind: \"fold\";\n readonly list: Expr;\n readonly acc: string;\n readonly item: string;\n readonly body: Expr;\n readonly init: Expr;\n };\n\nexport interface Param {\n readonly name: string;\n readonly type: SubsetType;\n}\n\nexport interface SubsetFunction {\n readonly name: string;\n readonly params: readonly Param[];\n readonly returns: SubsetType;\n readonly body: Expr;\n /** 1-based line of the declaration. */\n readonly line: number;\n /** Offset of the `(` opening its parameters: the declaration's identity, as the spec extractor records it. */\n readonly offset: number;\n /**\n * For a recursive function, the list parameter it recurses on (its\n * index): the body tests that list's length against 0 first, and every\n * call to itself, in the other branch, passes that list's slice(1).\n */\n readonly structural?: number;\n}\n\n/** A function the subset does not take, and why. */\nexport interface OutsideFunction {\n readonly name: string;\n readonly line: number;\n readonly message: string;\n}\n\nexport interface SubsetModule {\n readonly records: readonly RecordType[];\n readonly unions: readonly UnionType[];\n /** The functions in the subset, in source order, callees before callers. */\n readonly functions: readonly SubsetFunction[];\n /** The module's other functions: outside the subset themselves, or calling one that is. */\n readonly outside: readonly OutsideFunction[];\n}\n\n/** Whether a string holds a surrogate code unit without its pair: no Lean character corresponds to it. */\nexport function hasLoneSurrogate(s: string): boolean {\n return /[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]/.test(s);\n}\n\n/** A type, for messages. */\nexport function describe(t: SubsetType): string {\n switch (t.kind) {\n case \"record\":\n case \"union\":\n return t.name;\n case \"nullable\":\n return `${describe(t.inner)} | null`;\n case \"list\":\n return t.element.kind === \"nullable\"\n ? `(${describe(t.element)})[]`\n : `${describe(t.element)}[]`;\n default:\n return t.kind;\n }\n}\n\nconst sameType = (a: SubsetType, b: SubsetType): boolean => JSON.stringify(a) === JSON.stringify(b);\n\n/**\n * Whether a value of one type may stand where another is expected: the\n * same type; a member record where its union is; `null`, or the inner\n * type, where a nullable is.\n */\nexport function fits(actual: SubsetType, expected: SubsetType, ctx: TypeContext): boolean {\n if (sameType(actual, expected)) return true;\n // The element of `[]` is no value at all, so it stands for any; a list fits where its elements do.\n if (actual.kind === \"nothing\") return true;\n if (actual.kind === \"list\" && expected.kind === \"list\")\n return fits(actual.element, expected.element, ctx);\n if (expected.kind === \"union\")\n return actual.kind === \"record\" && isMember(ctx.records.get(actual.name), expected.name);\n if (expected.kind === \"nullable\")\n return (\n actual.kind === \"null\" ||\n (actual.kind === \"nullable\"\n ? fits(actual.inner, expected.inner, ctx)\n : fits(actual, expected.inner, ctx))\n );\n return false;\n}\n\n/** The type two branches share, or undefined when they share none. */\nfunction join(a: SubsetType, b: SubsetType, ctx: TypeContext): SubsetType | undefined {\n if (fits(a, b, ctx)) return b;\n if (fits(b, a, ctx)) return a;\n if (a.kind === \"list\" && b.kind === \"list\") {\n const element = join(a.element, b.element, ctx);\n return element && { kind: \"list\", element };\n }\n if (a.kind === \"record\" && b.kind === \"record\") {\n // Two members of one union join to it; members of several unions in common join to none,\n // since nothing says which (an expected type, where one is given, decides instead).\n const ub = ctx.records.get(b.name)?.unions ?? [];\n const common = (ctx.records.get(a.name)?.unions ?? []).filter((u) => ub.includes(u));\n if (common.length === 1) return { kind: \"union\", name: common[0] as string };\n }\n if (a.kind === \"nullable\" && b.kind === \"nullable\") {\n const inner = join(a.inner, b.inner, ctx);\n return inner && { kind: \"nullable\", inner };\n }\n if (a.kind === \"null\" && b.kind !== \"null\") return { kind: \"nullable\", inner: b };\n if (b.kind === \"null\" && a.kind !== \"null\") return { kind: \"nullable\", inner: a };\n if (a.kind === \"nullable\" && b.kind !== \"null\" && b.kind !== \"nullable\") {\n const inner = join(a.inner, b, ctx);\n return inner && { kind: \"nullable\", inner };\n }\n if (b.kind === \"nullable\" && a.kind !== \"null\" && a.kind !== \"nullable\") {\n const inner = join(a, b.inner, ctx);\n return inner && { kind: \"nullable\", inner };\n }\n return undefined;\n}\n\n/** Whether `===` between the two types is in the subset, and on records (references in JavaScript) it is not. */\nfunction comparable(l: SubsetType, r: SubsetType): boolean {\n const base = (t: SubsetType): SubsetType => (t.kind === \"nullable\" ? t.inner : t);\n if (l.kind === \"null\" && r.kind === \"null\") return false;\n if (l.kind === \"null\") return r.kind === \"nullable\";\n if (r.kind === \"null\") return l.kind === \"nullable\";\n return sameType(base(l), base(r)) && !isReference(base(l));\n}\n\nconst isReference = (t: SubsetType): boolean =>\n t.kind === \"record\" || t.kind === \"union\" || t.kind === \"list\";\n\n/**\n * The names a test, holding or failing, shows to be non-null: `x !== null`\n * holding, `x === null` failing, through `!`, `&&` (holding) and `||`\n * (failing).\n */\nexport function narrowsOf(test: Expr, holds: boolean): string[] {\n // A narrowing already inserted around an operand (the right side of `&&`) hides nothing.\n if (test.kind === \"narrow\" || test.kind === \"narrowTag\") return narrowsOf(test.body, holds);\n const isNull = (e: Expr) => e.kind === \"null\";\n if (test.kind === \"binary\" && (test.op === \"===\" || test.op === \"!==\")) {\n const other = isNull(test.right) ? test.left : isNull(test.left) ? test.right : undefined;\n if (other?.kind !== \"var\") return [];\n return (test.op === \"!==\") === holds ? [other.name] : [];\n }\n if (test.kind === \"not\") return narrowsOf(test.operand, !holds);\n if (test.kind === \"binary\" && test.op === \"&&\" && holds)\n return [...narrowsOf(test.left, true), ...narrowsOf(test.right, true)];\n if (test.kind === \"binary\" && test.op === \"||\" && !holds)\n return [...narrowsOf(test.left, false), ...narrowsOf(test.right, false)];\n return [];\n}\n\n/**\n * The field that tells a union's members apart, as the union names it: the\n * one the types read chose (`UnionType.tag`), which the engines encode by.\n * Re-deriving it from the member records could pick another field where two\n * discriminate, and the reader would then refuse the test the engines take.\n */\nexport function tagOf(union: string, ctx: TypeContext): string | undefined {\n return ctx.unions.find((u) => u.name === union)?.tag;\n}\n\n/**\n * The names a test, holding or failing, shows to be one member of their\n * union, with that member: `x.tag === \"a\"` holding (or `!==` failing)\n * names the member tagged `\"a\"`; failing, the other member when the\n * union has two; `x.ok` alone is the test of a boolean tag; through `!`,\n * `&&` (holding) and `||` (failing) as null checks are.\n */\nexport function tagNarrowsOf(\n test: Expr,\n holds: boolean,\n scope: ReadonlyMap<string, SubsetType>,\n ctx: TypeContext,\n): { name: string; member: string }[] {\n // The union a `x.tag` read is the tag of, with its members by tag value.\n const tagged = (e: Expr): { name: string; members: readonly RecordType[] } | undefined => {\n if (e.kind !== \"field\" || e.object.kind !== \"var\") return undefined;\n const t = scope.get(e.object.name);\n if (t?.kind !== \"union\" || tagOf(t.name, ctx) !== e.field) return undefined;\n return {\n name: e.object.name,\n members: membersIn(t.name, ctx),\n };\n };\n const byTag = (\n read: { name: string; members: readonly RecordType[] },\n tag: string,\n value: string | boolean,\n isIt: boolean,\n ): { name: string; member: string }[] => {\n const same = read.members.filter(\n (m) => m.fields.find((f) => f.name === tag)?.literal === value,\n );\n const chosen = isIt ? same : read.members.filter((m) => !same.includes(m));\n return chosen.length === 1 ? [{ name: read.name, member: (chosen[0] as RecordType).name }] : [];\n };\n if (test.kind === \"narrow\" || test.kind === \"narrowTag\")\n return tagNarrowsOf(test.body, holds, scope, ctx);\n if (test.kind === \"binary\" && (test.op === \"===\" || test.op === \"!==\")) {\n const literal = (e: Expr) => (e.kind === \"string\" || e.kind === \"bool\" ? e.value : undefined);\n const [field, value] =\n literal(test.right) !== undefined\n ? [test.left, literal(test.right)]\n : [test.right, literal(test.left)];\n if (value === undefined || field.kind !== \"field\") return [];\n const read = tagged(field);\n if (!read) return [];\n return byTag(read, field.field, value, (test.op === \"===\") === holds);\n }\n if (test.kind === \"field\") {\n const read = tagged(test);\n return read ? byTag(read, test.field, holds, true) : [];\n }\n if (test.kind === \"not\") return tagNarrowsOf(test.operand, !holds, scope, ctx);\n if (test.kind === \"binary\" && test.op === \"&&\" && holds)\n return [\n ...tagNarrowsOf(test.left, true, scope, ctx),\n ...tagNarrowsOf(test.right, true, scope, ctx),\n ];\n if (test.kind === \"binary\" && test.op === \"||\" && !holds)\n return [\n ...tagNarrowsOf(test.left, false, scope, ctx),\n ...tagNarrowsOf(test.right, false, scope, ctx),\n ];\n return [];\n}\n\n/**\n * `narrow` and `narrowTag` nodes inserted where a test guards: in a\n * conditional's branches, and in the right operand of `&&` and `||`, for\n * each nullable name the test shows to be non-null there and each union\n * name it shows to be one member there.\n */\nexport function insertNarrows(\n e: Expr,\n scope: ReadonlyMap<string, SubsetType>,\n ctx: TypeContext,\n fail: (message: string) => never,\n): Expr {\n const go = (x: Expr, sc: ReadonlyMap<string, SubsetType>): Expr =>\n insertNarrows(x, sc, ctx, fail);\n // Where JavaScript tests truthiness (a condition, the operand of `!`), a nullable record or union\n // is falsy exactly when it is null, since an object is always truthy: `c` there is `c !== null`,\n // which then narrows as a null check does. A nullable number or string is no object, and stays.\n const probe = Symbol(\"untyped\");\n const condition = (x: Expr, sc: ReadonlyMap<string, SubsetType>): Expr => {\n if (x.kind === \"binary\" && (x.op === \"&&\" || x.op === \"||\"))\n return { ...x, left: condition(x.left, sc), right: condition(x.right, sc) };\n if (x.kind === \"not\") return { kind: \"not\", operand: condition(x.operand, sc) };\n let t: SubsetType;\n try {\n t = typeOf(x, sc, ctx, () => {\n throw probe;\n });\n } catch (err) {\n if (err === probe) return x;\n throw err;\n }\n if (t.kind === \"nullable\" && (t.inner.kind === \"record\" || t.inner.kind === \"union\"))\n return { kind: \"binary\", op: \"!==\", left: x, right: { kind: \"null\" } };\n return x;\n };\n const wrap = (\n body: Expr,\n test: Expr,\n holds: boolean,\n sc: ReadonlyMap<string, SubsetType>,\n ): Expr => {\n const inner = new Map(sc);\n let out = body;\n const nullable = [...new Set(narrowsOf(test, holds))].filter(\n (n) => sc.get(n)?.kind === \"nullable\",\n );\n for (const n of nullable) inner.set(n, (sc.get(n) as { inner: SubsetType }).inner);\n // Tag tests are read in the scope null checks leave: `x !== null && x.ok` narrows x twice.\n const tags: { name: string; member: string }[] = [];\n for (const t of tagNarrowsOf(test, holds, inner, ctx))\n if (!tags.some((x) => x.name === t.name)) {\n tags.push(t);\n inner.set(t.name, { kind: \"record\", name: t.member });\n }\n out = go(out, inner);\n for (const t of tags.reverse())\n out = { kind: \"narrowTag\", name: t.name, member: t.member, body: out };\n for (const n of nullable.reverse()) out = { kind: \"narrow\", name: n, body: out };\n return out;\n };\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n case \"var\":\n return e;\n case \"not\":\n return { kind: \"not\", operand: go(condition(e.operand, scope), scope) };\n case \"neg\":\n case \"isInteger\":\n case \"floor\":\n return { kind: e.kind, operand: go(e.operand, scope) };\n case \"narrow\":\n case \"narrowTag\":\n return e;\n case \"binary\": {\n const left = go(e.left, scope);\n if (e.op === \"&&\")\n return { kind: \"binary\", op: e.op, left, right: wrap(e.right, left, true, scope) };\n if (e.op === \"||\")\n return { kind: \"binary\", op: e.op, left, right: wrap(e.right, left, false, scope) };\n return { kind: \"binary\", op: e.op, left, right: go(e.right, scope) };\n }\n case \"cond\": {\n const test = go(condition(e.test, scope), scope);\n return {\n kind: \"cond\",\n test,\n ifTrue: wrap(e.ifTrue, test, true, scope),\n ifFalse: wrap(e.ifFalse, test, false, scope),\n };\n }\n case \"call\":\n return { kind: \"call\", callee: e.callee, args: e.args.map((a) => go(a, scope)) };\n case \"field\":\n return { kind: \"field\", object: go(e.object, scope), field: e.field };\n case \"record\":\n return { ...e, fields: e.fields.map((f) => ({ name: f.name, value: go(f.value, scope) })) };\n case \"let\": {\n const value = go(e.value, scope);\n const inner = new Map(scope);\n inner.set(e.name, e.type ?? typeOf(value, scope, ctx, fail));\n return { ...e, value, body: go(e.body, inner) };\n }\n case \"list\":\n return {\n kind: \"list\",\n items: e.items.map((x) => go(x, scope)),\n ...(e.rest ? { rest: go(e.rest, scope) } : {}),\n };\n case \"tail\":\n return { kind: \"tail\", list: go(e.list, scope) };\n case \"headOr\":\n return { kind: \"headOr\", list: go(e.list, scope), fallback: go(e.fallback, scope) };\n case \"iterate\": {\n const list = go(e.list, scope);\n return { ...e, list, body: go(e.body, iterateScope(e, list, scope, ctx, fail)) };\n }\n case \"fold\": {\n const list = go(e.list, scope);\n const init = go(e.init, scope);\n // The callback's names before its body is typed: its null checks narrow first, as in map.\n const inner = new Map(scope);\n inner.set(e.acc, typeOf(init, scope, ctx, fail));\n inner.set(e.item, elementOf(typeOf(list, scope, ctx, fail), \"reduce\", fail));\n return { ...e, list, init, body: go(e.body, inner) };\n }\n }\n}\n\n/**\n * The element type of a list expression's type. An operation on an empty\n * array no type is given for (`[].length`, `[].slice(1)`) is refused: an\n * engine could only guess the element type, and such code has a plain\n * value to write instead; `const xs: T[] = []` gives one.\n */\nfunction elementOf(t: SubsetType, what: string, fail: (message: string) => never): SubsetType {\n if (t.kind !== \"list\") fail(`${what} on a ${describe(t)}, not a list`);\n if (holdsNothing(t))\n fail(`${what} on an empty array of no declared type (annotate it: const xs: T[] = [])`);\n return t.element;\n}\n\n/** Whether a type holds the element type of an empty array literal anywhere in it (`[[]]` does). */\nfunction holdsNothing(t: SubsetType): boolean {\n if (t.kind === \"nothing\") return true;\n if (t.kind === \"list\") return holdsNothing(t.element);\n if (t.kind === \"nullable\") return holdsNothing(t.inner);\n return false;\n}\n\n/** The scope inside an iteration's callback: the item an element, the index an integer. */\nfunction iterateScope(\n e: Extract<Expr, { kind: \"iterate\" }>,\n list: Expr,\n scope: ReadonlyMap<string, SubsetType>,\n ctx: TypeContext,\n fail: (message: string) => never,\n): Map<string, SubsetType> {\n const inner = new Map(scope);\n inner.set(e.item, elementOf(typeOf(list, scope, ctx, fail), e.op, fail));\n if (e.index !== undefined) inner.set(e.index, { kind: \"int\" });\n return inner;\n}\n\n/**\n * The scope inside a fold's callback and the accumulator's type: the\n * initial value's, widened once to the body's when the body's holds it.\n * A callback that takes the accumulator apart as a list needs the initial\n * value typed (`xs.reduce((acc, x) => [x, ...acc], [])` does not\n * type-check in TypeScript either).\n */\nfunction foldScope(\n e: Extract<Expr, { kind: \"fold\" }>,\n list: Expr,\n init: Expr,\n scope: ReadonlyMap<string, SubsetType>,\n ctx: TypeContext,\n fail: (message: string) => never,\n): { scope: Map<string, SubsetType>; acc: SubsetType } {\n const item = elementOf(typeOf(list, scope, ctx, fail), \"reduce\", fail);\n const at = (acc: SubsetType) => new Map([...scope, [e.acc, acc], [e.item, item]]);\n const start = typeOf(init, scope, ctx, fail);\n const body = typeOf(e.body, at(start), ctx, fail);\n if (fits(body, start, ctx)) return { scope: at(start), acc: start };\n if (fits(start, body, ctx) && fits(typeOf(e.body, at(body), ctx, fail), body, ctx))\n return { scope: at(body), acc: body };\n fail(`reduce's callback makes a ${describe(body)} from an accumulator of ${describe(start)}`);\n}\n\n/** A function's parameters and return type, for typing calls. */\nexport interface CalleeSignature {\n readonly params: readonly Param[];\n readonly returns: SubsetType;\n}\n\n/** What typing an expression needs to know about its module. */\nexport interface TypeContext {\n readonly records: ReadonlyMap<string, RecordType>;\n /** The unions read so far, each naming its tag; a live list while a module is being read. */\n readonly unions: readonly UnionType[];\n readonly signatures: ReadonlyMap<string, CalleeSignature>;\n}\n\n/** The type of an expression in a scope; records are matched by their fields' names. */\nexport function typeOf(\n e: Expr,\n scope: ReadonlyMap<string, SubsetType>,\n ctx: TypeContext,\n fail: (message: string) => never,\n /**\n * The type the context declares for `e` (a return type, a const's\n * annotation, a parameter): it decides a conditional whose branches are\n * members of several unions in common, where they alone join to none.\n */\n expected?: SubsetType,\n): SubsetType {\n switch (e.kind) {\n case \"int\":\n return { kind: \"int\" };\n case \"bool\":\n return { kind: \"bool\" };\n case \"string\":\n return { kind: \"string\" };\n case \"null\":\n return { kind: \"null\" };\n case \"var\": {\n const t = scope.get(e.name);\n if (!t) fail(`${e.name} is not in scope`);\n return t;\n }\n case \"narrow\": {\n const t = scope.get(e.name);\n if (!t) fail(`${e.name} is not in scope`);\n if (t.kind !== \"nullable\")\n fail(`${e.name} is narrowed but is a ${describe(t)}, not a nullable`);\n return typeOf(e.body, new Map([...scope, [e.name, t.inner]]), ctx, fail, expected);\n }\n case \"narrowTag\": {\n const t = scope.get(e.name);\n if (!t) fail(`${e.name} is not in scope`);\n if (t.kind !== \"union\")\n fail(`${e.name} is narrowed by a tag but is a ${describe(t)}, not a union`);\n if (!isMember(ctx.records.get(e.member), t.name))\n fail(`${e.member} is not a member of ${t.name}`);\n return typeOf(\n e.body,\n new Map([...scope, [e.name, { kind: \"record\", name: e.member }]]),\n ctx,\n fail,\n expected,\n );\n }\n case \"binary\": {\n const l = typeOf(e.left, scope, ctx, fail);\n const r = typeOf(e.right, scope, ctx, fail);\n // `+` joins two strings; every other arithmetic or ordering operator is on integers only\n // (ordering strings compares UTF-16 code units in JavaScript and characters in Lean: not the same).\n if (e.op === \"+\" && l.kind === \"string\" && r.kind === \"string\") return { kind: \"string\" };\n const arithmetic = [\"+\", \"-\", \"*\", \"/\", \"<\", \"<=\", \">\", \">=\"].includes(e.op);\n if (arithmetic && (l.kind !== \"int\" || r.kind !== \"int\"))\n fail(\n `${e.op} on a ${l.kind} and a ${r.kind} (the subset has it on integers${e.op === \"+\" ? \", and + on two strings\" : \"\"})`,\n );\n if ((e.op === \"&&\" || e.op === \"||\") && (l.kind !== \"bool\" || r.kind !== \"bool\"))\n fail(`${e.op} on a ${l.kind} and a ${r.kind} (the subset has it on booleans)`);\n if (e.op === \"===\" || e.op === \"!==\") {\n // Against null, any nullable; otherwise records and unions are references in JavaScript.\n const againstNull = l.kind === \"null\" || r.kind === \"null\";\n const base = (t: SubsetType): SubsetType => (t.kind === \"nullable\" ? t.inner : t);\n if (!againstNull && (isReference(base(l)) || isReference(base(r))))\n fail(\n `${e.op} on records compares references in JavaScript; compare their fields instead`,\n );\n if (!comparable(l, r)) fail(`${e.op} between a ${describe(l)} and a ${describe(r)}`);\n }\n return [\"+\", \"-\", \"*\", \"/\"].includes(e.op) ? { kind: \"int\" } : { kind: \"bool\" };\n }\n case \"neg\": {\n const t = typeOf(e.operand, scope, ctx, fail);\n if (t.kind !== \"int\") fail(`unary minus on a ${t.kind}`);\n return { kind: \"int\" };\n }\n case \"not\": {\n const t = typeOf(e.operand, scope, ctx, fail);\n if (t.kind !== \"bool\") fail(`! on a ${t.kind}`);\n return { kind: \"bool\" };\n }\n case \"isInteger\": {\n const t = typeOf(e.operand, scope, ctx, fail);\n if (t.kind !== \"int\") fail(`Number.isInteger on a ${t.kind}`);\n return { kind: \"bool\" };\n }\n case \"floor\": {\n const t = typeOf(e.operand, scope, ctx, fail);\n if (t.kind !== \"int\") fail(`Math.floor on a ${t.kind}`);\n return { kind: \"int\" };\n }\n case \"cond\": {\n const test = typeOf(e.test, scope, ctx, fail);\n if (test.kind !== \"bool\")\n fail(\n `a condition that is a ${describe(test)} (truthiness is not in the subset; compare it)`,\n );\n const a = typeOf(e.ifTrue, scope, ctx, fail, expected);\n const b = typeOf(e.ifFalse, scope, ctx, fail, expected);\n const joined = join(a, b, ctx);\n if (joined) return joined;\n if (expected && fits(a, expected, ctx) && fits(b, expected, ctx)) return expected;\n return fail(\n `the branches of a conditional have different types (${describe(a)} and ${describe(b)})`,\n );\n }\n case \"let\": {\n const inferred = typeOf(e.value, scope, ctx, fail, e.type);\n if (e.type && !fits(inferred, e.type, ctx))\n fail(`const ${e.name} is annotated ${describe(e.type)} but holds a ${describe(inferred)}`);\n if (!e.type && holdsNothing(inferred))\n fail(\n `const ${e.name} holds an empty array of no declared type (annotate it: const ${e.name}: T[] = [])`,\n );\n return typeOf(e.body, new Map([...scope, [e.name, e.type ?? inferred]]), ctx, fail, expected);\n }\n case \"call\": {\n const sig = ctx.signatures.get(e.callee);\n if (!sig) fail(`the signature of ${e.callee} is not known`);\n if (sig.params.length !== e.args.length)\n fail(`${e.callee} takes ${sig.params.length} argument(s), called with ${e.args.length}`);\n e.args.forEach((a, i) => {\n const want = sig.params[i]?.type as SubsetType;\n const got = typeOf(a, scope, ctx, fail, want);\n if (!fits(got, want, ctx))\n fail(\n `argument ${i + 1} of ${e.callee} is a ${describe(got)}, not the ${describe(want)} it takes`,\n );\n });\n return sig.returns;\n }\n case \"field\": {\n const o = typeOf(e.object, scope, ctx, fail);\n if (o.kind === \"list\") {\n if (e.field !== \"length\") fail(`${e.field} read from a list (the subset has length)`);\n elementOf(o, \"length\", fail);\n return { kind: \"int\" };\n }\n if (o.kind === \"nullable\")\n fail(\n `field ${e.field} read from a ${describe(o)}: compare it with null first, which narrows it`,\n );\n if (o.kind === \"union\") {\n // Only a field every member has, with one type: the tag, typically. Narrowing by the tag is not in the subset yet.\n const members = membersIn(o.name, ctx);\n const types = members.map((rec) => rec.fields.find((x) => x.name === e.field)?.type);\n if (types.some((t) => t === undefined))\n fail(\n `field ${e.field} is not on every member of ${o.name} (test the tag first, which narrows it)`,\n );\n const first = types[0] as SubsetType;\n if (!types.every((t) => sameType(t as SubsetType, first)))\n fail(`field ${e.field} has different types across the members of ${o.name}`);\n return first;\n }\n if (o.kind !== \"record\") fail(`field ${e.field} read from a ${describe(o)}`);\n const f = ctx.records.get(o.name)?.fields.find((x) => x.name === e.field);\n if (!f) fail(`${o.name} has no field ${e.field}`);\n return f.type;\n }\n case \"record\": {\n // The record types whose fields are exactly these names, then those whose field types the values fit.\n const names = e.fields\n .map((f) => f.name)\n .sort()\n .join(\",\");\n // The context's type, when the compiler gave one, narrows the candidates: the record itself, or a union's members.\n const context = e.type;\n const candidates =\n context?.kind === \"record\"\n ? [...ctx.records.values()].filter((rec) => rec.name === context.name)\n : context?.kind === \"union\"\n ? membersIn(context.name, ctx)\n : [...ctx.records.values()];\n const byNames = candidates.filter(\n (rec) =>\n rec.fields\n .map((f) => f.name)\n .sort()\n .join(\",\") === names,\n );\n if (byNames.length === 0)\n fail(`a record literal with fields ${names} matches no declared record type`);\n const types = new Map(e.fields.map((f) => [f.name, typeOf(f.value, scope, ctx, fail)]));\n const fitting = byNames.filter((rec) =>\n rec.fields.every((f) => fits(types.get(f.name) as SubsetType, f.type, ctx)),\n );\n if (fitting.length === 0) {\n const rec = byNames[0] as RecordType;\n const off = rec.fields.find(\n (f) => !fits(types.get(f.name) as SubsetType, f.type, ctx),\n ) as Field;\n fail(\n `field ${off.name} of a ${rec.name} literal holds a ${describe(types.get(off.name) as SubsetType)}, not a ${describe(off.type)}`,\n );\n }\n // Among a union's members, the literal's tag tells them apart.\n const literalOf = (name: string): string | boolean | undefined => {\n const v = e.fields.find((f) => f.name === name)?.value;\n return v?.kind === \"string\" || v?.kind === \"bool\" ? v.value : undefined;\n };\n const tagged = fitting.filter((rec) =>\n rec.fields.every((f) => f.literal === undefined || literalOf(f.name) === f.literal),\n );\n const chosen = tagged.length > 0 ? tagged : fitting;\n if (chosen.length > 1)\n fail(\n `a record literal with fields ${names} matches ${chosen.map((r) => r.name).join(\" and \")} alike`,\n );\n return { kind: \"record\", name: (chosen[0] as RecordType).name };\n }\n case \"list\": {\n let element: SubsetType = { kind: \"nothing\" };\n const add = (t: SubsetType) => {\n const joined = join(element, t, ctx);\n if (!joined) fail(`an array literal of a ${describe(element)} and a ${describe(t)}`);\n element = joined;\n };\n for (const item of e.items) add(typeOf(item, scope, ctx, fail));\n if (e.rest) add(elementOf(typeOf(e.rest, scope, ctx, fail), \"a spread\", fail));\n return { kind: \"list\", element };\n }\n case \"tail\": {\n const t = typeOf(e.list, scope, ctx, fail);\n elementOf(t, \"slice\", fail);\n return t;\n }\n case \"headOr\": {\n const element = elementOf(typeOf(e.list, scope, ctx, fail), \"[0]\", fail);\n // `??` replaces null as well as the missing head: on a list of a nullable type it is not headD.\n if (element.kind === \"nullable\" || element.kind === \"null\")\n fail(\"xs[0] ?? on a list of a nullable type (?? replaces a null element too)\");\n const fallback = typeOf(e.fallback, scope, ctx, fail);\n const joined = join(element, fallback, ctx);\n if (!joined) fail(`?? between a ${describe(element)} and a ${describe(fallback)}`);\n return joined;\n }\n case \"iterate\": {\n const body = typeOf(e.body, iterateScope(e, e.list, scope, ctx, fail), ctx, fail);\n if (e.op === \"map\") return { kind: \"list\", element: body };\n if (e.op === \"flatMap\")\n return { kind: \"list\", element: elementOf(body, \"flatMap's callback result\", fail) };\n if (body.kind !== \"bool\")\n fail(`${e.op}'s callback returns a ${describe(body)}, not a boolean`);\n return { kind: \"bool\" };\n }\n case \"fold\":\n return foldScope(e, e.list, e.init, scope, ctx, fail).acc;\n }\n}\n\n/** Every name an expression binds or refers to: its variables and its lets. */\nfunction boundNames(e: Expr, out = new Set<string>()): Set<string> {\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n return out;\n case \"var\":\n out.add(e.name);\n return out;\n case \"narrow\":\n case \"narrowTag\":\n out.add(e.name);\n return boundNames(e.body, out);\n case \"neg\":\n case \"not\":\n case \"isInteger\":\n case \"floor\":\n return boundNames(e.operand, out);\n case \"binary\":\n boundNames(e.left, out);\n return boundNames(e.right, out);\n case \"cond\":\n boundNames(e.test, out);\n boundNames(e.ifTrue, out);\n return boundNames(e.ifFalse, out);\n case \"call\":\n for (const a of e.args) boundNames(a, out);\n return out;\n case \"field\":\n return boundNames(e.object, out);\n case \"record\":\n for (const f of e.fields) boundNames(f.value, out);\n return out;\n case \"let\":\n out.add(e.name);\n boundNames(e.value, out);\n return boundNames(e.body, out);\n case \"list\":\n for (const x of e.items) boundNames(x, out);\n return e.rest ? boundNames(e.rest, out) : out;\n case \"tail\":\n return boundNames(e.list, out);\n case \"headOr\":\n boundNames(e.list, out);\n return boundNames(e.fallback, out);\n case \"iterate\":\n out.add(e.item);\n if (e.index !== undefined) out.add(e.index);\n boundNames(e.list, out);\n return boundNames(e.body, out);\n case \"fold\":\n out.add(e.acc);\n out.add(e.item);\n boundNames(e.list, out);\n boundNames(e.init, out);\n return boundNames(e.body, out);\n }\n}\n\n/** A name not among `taken`: the name with underscores appended. */\nfunction fresh(name: string, taken: ReadonlySet<string>): string {\n let out = `${name}_`;\n while (taken.has(out)) out += \"_\";\n return out;\n}\n\n/**\n * The expression with its variables renamed (an arrow's own parameter\n * names to the binders'). A `let` whose name is a rename's target would\n * capture the renamed references in its body, so such a let is renamed to\n * a fresh name first; a let whose name is a rename's source shadows it.\n */\nexport function renameVars(\n e: Expr,\n names: ReadonlyMap<string, string>,\n taken: ReadonlySet<string> = new Set([...names.keys(), ...names.values(), ...boundNames(e)]),\n /** Names no binder in `e` may keep (the scope `e` is inlined into): such a binder moves to a fresh name. */\n avoid: ReadonlySet<string> = new Set(),\n): Expr {\n const go = (x: Expr): Expr => renameVars(x, names, taken, avoid);\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n return e;\n case \"var\":\n return { kind: \"var\", name: names.get(e.name) ?? e.name };\n case \"narrow\":\n return { kind: \"narrow\", name: names.get(e.name) ?? e.name, body: go(e.body) };\n case \"narrowTag\":\n return { ...e, name: names.get(e.name) ?? e.name, body: go(e.body) };\n case \"neg\":\n case \"not\":\n case \"isInteger\":\n case \"floor\":\n return { kind: e.kind, operand: go(e.operand) };\n case \"binary\":\n return { kind: \"binary\", op: e.op, left: go(e.left), right: go(e.right) };\n case \"cond\":\n return { kind: \"cond\", test: go(e.test), ifTrue: go(e.ifTrue), ifFalse: go(e.ifFalse) };\n case \"call\":\n return { kind: \"call\", callee: e.callee, args: e.args.map(go) };\n case \"field\":\n return { kind: \"field\", object: go(e.object), field: e.field };\n case \"record\":\n return { ...e, fields: e.fields.map((f) => ({ name: f.name, value: go(f.value) })) };\n case \"let\": {\n // A let binds its own name; a binder of that name is shadowed inside, as in the source.\n const inner = new Map(names);\n inner.delete(e.name);\n let bound = e.name;\n const targets = new Set([...names.values(), ...avoid]);\n if (targets.has(e.name)) {\n // The let would capture a renamed reference: the let itself moves out of the way, to a name\n // nothing in the expression uses (another let may already be spelled with the underscore).\n bound = fresh(e.name, taken);\n inner.set(e.name, bound);\n }\n return {\n ...e,\n name: bound,\n value: go(e.value),\n body: renameVars(e.body, inner, new Set([...taken, bound]), avoid),\n };\n }\n case \"list\":\n return { kind: \"list\", items: e.items.map(go), ...(e.rest ? { rest: go(e.rest) } : {}) };\n case \"tail\":\n return { kind: \"tail\", list: go(e.list) };\n case \"headOr\":\n return { kind: \"headOr\", list: go(e.list), fallback: go(e.fallback) };\n case \"iterate\": {\n const own = [e.item, ...(e.index === undefined ? [] : [e.index])];\n const { inner, bound, scoped } = bindAll(own, names, taken, avoid);\n return {\n ...e,\n list: go(e.list),\n item: bound[0] as string,\n ...(e.index === undefined ? {} : { index: bound[1] as string }),\n body: renameVars(e.body, inner, scoped, avoid),\n };\n }\n case \"fold\": {\n const { inner, bound, scoped } = bindAll([e.acc, e.item], names, taken, avoid);\n return {\n ...e,\n list: go(e.list),\n init: go(e.init),\n acc: bound[0] as string,\n item: bound[1] as string,\n body: renameVars(e.body, inner, scoped, avoid),\n };\n }\n }\n}\n\n/**\n * The renames inside a callback that binds `own` names, as for a let:\n * each shadows a rename of its own name, and one that is a rename's target\n * moves to a fresh name so it captures nothing.\n */\nfunction bindAll(\n own: readonly string[],\n names: ReadonlyMap<string, string>,\n taken: ReadonlySet<string>,\n avoid: ReadonlySet<string>,\n): { inner: Map<string, string>; bound: string[]; scoped: Set<string> } {\n const inner = new Map(names);\n const targets = new Set([...names.values(), ...avoid]);\n const scoped = new Set(taken);\n const bound = own.map((n) => {\n inner.delete(n);\n if (!targets.has(n)) return n;\n const moved = fresh(n, scoped);\n scoped.add(moved);\n inner.set(n, moved);\n return moved;\n });\n return { inner, bound, scoped };\n}\n\n/** The functions an expression calls. */\nfunction callees(e: Expr, out = new Set<string>()): Set<string> {\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n case \"var\":\n return out;\n case \"narrow\":\n case \"narrowTag\":\n return callees(e.body, out);\n case \"neg\":\n case \"not\":\n case \"isInteger\":\n case \"floor\":\n return callees(e.operand, out);\n case \"binary\":\n callees(e.left, out);\n return callees(e.right, out);\n case \"cond\":\n callees(e.test, out);\n callees(e.ifTrue, out);\n return callees(e.ifFalse, out);\n case \"call\":\n out.add(e.callee);\n for (const a of e.args) callees(a, out);\n return out;\n case \"field\":\n return callees(e.object, out);\n case \"record\":\n for (const f of e.fields) callees(f.value, out);\n return out;\n case \"let\":\n callees(e.value, out);\n return callees(e.body, out);\n case \"list\":\n for (const x of e.items) callees(x, out);\n return e.rest ? callees(e.rest, out) : out;\n case \"tail\":\n return callees(e.list, out);\n case \"headOr\":\n callees(e.list, out);\n return callees(e.fallback, out);\n case \"iterate\":\n callees(e.list, out);\n return callees(e.body, out);\n case \"fold\":\n callees(e.list, out);\n callees(e.init, out);\n return callees(e.body, out);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Reading: a module through the compiler, an arrow from its text.\n\n/** The path a module read from text alone is compiled under: an import of another file does not resolve from it. */\nconst virtualModulePath = \"/eutaxy/reader/module.ts\";\n\nexport interface ReadSubsetOptions {\n /** The module's path on disk, under which its imports resolve. Without it the module stands alone. */\n readonly path?: string;\n /** Other files the read sees in place of (or beside) the files on disk, by path. */\n readonly files?: readonly InputFile[];\n}\n\n/** What typing a module's expressions needs, shared by every function read. */\nfunction moduleContext(\n records: Map<string, RecordType>,\n unions: readonly UnionType[],\n): {\n ctx: TypeContext;\n signatures: Map<string, CalleeSignature>;\n} {\n const signatures = new Map<string, CalleeSignature>();\n return { ctx: { records, unions, signatures }, signatures };\n}\n\n/** The contextual type the compiler gives a record literal, as the subset reads it; undefined where it has none the subset takes. */\nfunction contextualType(\n checker: Checker,\n types: SubsetTypes,\n node: ObjectLiteralExpression,\n): SubsetType | undefined {\n const type = checker.getContextualType(node);\n if (!type) return undefined;\n // A context inferred from the literal itself (a callback's result, say) declares nothing: the\n // literal is matched against the declared records instead.\n const fromLiteral = (t: Type): boolean =>\n t.isObjectType() && t.getSymbol()?.name === InternalSymbolName.Object;\n if (fromLiteral(type) || (type.isUnionType() && type.getTypes().some(fromLiteral)))\n return undefined;\n const skip = Symbol(\"outside\");\n try {\n const read = types.of(type, () => {\n throw skip;\n });\n return read.kind === \"nullable\" ? read.inner : read;\n } catch (err) {\n if (err === skip) return undefined;\n throw err;\n }\n}\n\n/** The line of the first direct `eval` in the file: a mention that is not a property of something else. */\nfunction directEval(sf: SourceFile): number | undefined {\n let line: number | undefined;\n const visit = (node: Node): void => {\n if (line !== undefined) return;\n if (is.isIdentifier(node) && node.text === \"eval\") {\n const parent = node.parent;\n const property =\n (is.isPropertyAccessExpression(parent) && parent.name === node) ||\n (is.isPropertyAssignment(parent) && parent.name === node);\n if (!property) {\n line = lineAt(sf, node);\n return;\n }\n }\n node.forEachChild(visit);\n };\n visit(sf);\n return line;\n}\n\n/** An expression TypeScript lets wrap another without changing what it names: parentheses and assertions. */\ntype Wrapper =\n | ParenthesizedExpression\n | NonNullExpression\n | AsExpression\n | SatisfiesExpression\n | TypeAssertion;\n\nfunction isWrapper(n: Node): n is Wrapper {\n return (\n is.isParenthesizedExpression(n) ||\n is.isNonNullExpression(n) ||\n is.isAsExpression(n) ||\n is.isSatisfiesExpression(n) ||\n is.isTypeAssertion(n)\n );\n}\n\n/** Whether a node is written to: assigned, updated, or bound by a destructuring or a `for` head. */\nfunction isWritten(node: Node): boolean {\n let n: Node = node;\n for (;;) {\n const p: Node = n.parent;\n if (!p) return false;\n if (isWrapper(p) && p.expression === n) {\n n = p;\n continue;\n }\n if (is.isBinaryExpression(p)) {\n const k = p.operatorToken.kind;\n if (p.left === n && k >= SyntaxKind.FirstAssignment && k <= SyntaxKind.LastAssignment)\n return true;\n return false;\n }\n if (is.isPrefixUnaryExpression(p) || is.isPostfixUnaryExpression(p))\n return p.operator === SyntaxKind.PlusPlusToken || p.operator === SyntaxKind.MinusMinusToken;\n if (is.isForInStatement(p) || is.isForOfStatement(p)) return p.initializer === n;\n // Inside a destructuring target, the whole pattern is what gets assigned.\n if (is.isArrayLiteralExpression(p) || is.isSpreadElement(p) || is.isSpreadAssignment(p)) {\n n = p;\n continue;\n }\n if (is.isPropertyAssignment(p) && p.initializer === n) {\n n = p.parent;\n continue;\n }\n if (is.isShorthandPropertyAssignment(p) && p.name === n) {\n n = p.parent;\n continue;\n }\n if (is.isObjectLiteralExpression(p)) {\n n = p;\n continue;\n }\n return false;\n }\n}\n\n/** What every PROVEN rests on besides the engine's model: the reader's assumption about the built-ins. */\nexport const builtinsAssumption =\n \"the built-ins the subset reads (Math, Number and the array methods) are the standard ones: a direct assignment to a global of the standard library or to a property of one, or through globalThis, self or window, in a read file is refused, but one made another way (Object.defineProperty, through an alias) or elsewhere (a polyfill, another module) is not seen\";\n\n/** Names a file reaches the globals through that the library the reads compile against does not declare. */\nconst globalObjects = new Set([\"globalThis\", \"self\", \"window\", \"global\"]);\n\n/**\n * The first direct assignment (or `delete`) in a file whose target is a\n * global of the compiler's standard library or a property of one, at any\n * depth (`Math.floor = …`, `Number[\"isInteger\"] = …`, `Array.prototype.map\n * = …`, `Math = …`), or anything under `globalThis`, `self`, `window` or\n * `global`, with its line; inside a function or not. The chain's root is\n * resolved by the compiler, so a local's `prototype` field is the local's.\n * What reaches a built-in another way (`Object.defineProperty`, an alias)\n * is not seen: `builtinsAssumption` says so.\n */\nexport function rebound(\n sf: SourceFile,\n checker: Checker,\n standardGlobal: (id: Identifier) => boolean,\n): { line: number; target: string } | undefined {\n let found: { line: number; target: string } | undefined;\n // `window` and its kin, by name, unless the name is a parameter or a local of some function here.\n const globalObject = (r: Identifier): boolean => {\n if (!globalObjects.has(r.text)) return false;\n const decl = checker.getSymbolAtLocation(r)?.valueDeclaration?.resolve();\n if (!decl) return true;\n if (decl.kind === SyntaxKind.Parameter) return false;\n return !(is.isVariableDeclaration(decl) && decl.parent.parent.parent !== decl.getSourceFile());\n };\n // The node a `delete` would take: the target with the wrappers around it.\n const outermost = (node: Node): Node => {\n let out: Node = node;\n for (let p: Node = out.parent; p && isWrapper(p) && p.expression === out; p = p.parent) out = p;\n return out;\n };\n const root = (node: Node): Node => {\n let n: Node = node;\n while (is.isPropertyAccessExpression(n) || is.isElementAccessExpression(n) || isWrapper(n))\n n = n.expression;\n return n;\n };\n const builtin = (node: Node): boolean => {\n const r = root(node);\n return is.isIdentifier(r) && (globalObject(r) || standardGlobal(r));\n };\n const visit = (node: Node): void => {\n if (found) return;\n if (\n (is.isPropertyAccessExpression(node) ||\n is.isElementAccessExpression(node) ||\n is.isIdentifier(node)) &&\n (isWritten(node) || is.isDeleteExpression(outermost(node).parent)) &&\n builtin(node)\n ) {\n found = { line: lineAt(sf, node), target: textOf(sf, node) };\n return;\n }\n node.forEachChild(visit);\n };\n visit(sf);\n return found;\n}\n\n/**\n * The first `@ts-ignore` or `@ts-expect-error` directive in a range of a\n * file, with its position: a comment shaped as the compiler reads one (the\n * directive opens a `//` comment, or the last line of a block comment),\n * found as the compiler finds comments, leading or trailing a node's\n * text, so the words in prose or in a string are not one. A comment\n * before a closing token alone (`/* … *\\/ }`) is not seen; what it could\n * hide is on that token's line.\n */\nfunction directiveIn(\n sf: SourceFile,\n start: number,\n end: number,\n): { text: string; pos: number } | undefined {\n const text = sf.text;\n const singleLine = /^\\/\\/\\/?\\s*@ts-(ignore|expect-error)/;\n const lastLine = /^(?:\\/|\\*)*\\s*@ts-(ignore|expect-error)/;\n let found: { text: string; pos: number } | undefined;\n const check = (pos: number, commentEnd: number): void => {\n if (found || pos < start || commentEnd > end) return;\n const comment = text.slice(pos, commentEnd);\n // The compiler trims the block comment's last line before looking (`trimStringStart`).\n const m = comment.startsWith(\"//\")\n ? singleLine.exec(comment)\n : lastLine.exec(comment.slice(comment.lastIndexOf(\"\\n\") + 1).trimStart());\n if (m) found = { text: `@ts-${m[1]}`, pos };\n };\n const visit = (node: Node): void => {\n if (found || node.end < start || node.pos > end) return;\n forEachLeadingCommentRange(text, node.pos, check);\n forEachTrailingCommentRange(text, node.end, check);\n node.forEachChild(visit);\n };\n visit(sf);\n return found;\n}\n\n/**\n * The line of a `@ts-nocheck` directive at the top of a file, which turns\n * the compiler's checks off for all of it: as the compiler reads it, a\n * `//` comment opening with it, the last of it and `@ts-check` deciding.\n */\nfunction noCheckDirective(sf: SourceFile): number | undefined {\n const text = sf.text;\n const from = text.startsWith(\"#!\") ? Math.max(0, text.indexOf(\"\\n\")) : 0;\n let line: number | undefined;\n forEachLeadingCommentRange(text, from, (pos, end) => {\n const m = /^\\/\\/\\/?\\s*@ts-(check|nocheck)\\b/.exec(text.slice(pos, end));\n if (m) line = m[1] === \"nocheck\" ? sf.getLineAndCharacterOfPosition(pos).line + 1 : undefined;\n });\n return line;\n}\n\n/** A declaration's text, and the statement's leading comments, where a directive reaches its first line. */\ninterface DeclaredRange {\n readonly start: number;\n readonly end: number;\n readonly lead?: { readonly start: number; readonly end: number };\n}\n\n/**\n * Why a range of a file is not read: the first error the compiler reports\n * inside it, or a `@ts-ignore` or `@ts-expect-error` directive in it or\n * in the leading comments (where a directive reaches the first line),\n * which hides one from the reader. Undefined when the range is clean.\n */\nfunction notCompiled(\n sf: SourceFile,\n typeErrors: (path: string) => readonly CompilerError[],\n { start, end, lead }: DeclaredRange,\n): { message: string; line: number } | undefined {\n const error = typeErrors(sf.fileName).find((e) => e.pos < end && e.end > start);\n if (error)\n return { message: `the compiler reports an error: ${error.message}`, line: error.line };\n const silenced =\n (lead ? directiveIn(sf, lead.start, lead.end) : undefined) ?? directiveIn(sf, start, end);\n if (silenced)\n return {\n message: `a ${silenced.text} comment, which hides a compiler error from the reader`,\n line: sf.getLineAndCharacterOfPosition(silenced.pos).line + 1,\n };\n return undefined;\n}\n\n/**\n * Where a declared function's errors are looked for: its own declaration\n * (in a `const` list, a sibling's error, or a directive in a sibling's\n * body, is the sibling's), and for directives the statement's leading\n * comments too, since a directive above the statement reaches its first\n * line, siblings included.\n */\nfunction rangeOf(d: Declared): DeclaredRange {\n let declaration: Node = d.node;\n while (!is.isFunctionDeclaration(declaration) && !is.isVariableDeclaration(declaration))\n declaration = declaration.parent;\n const sf = d.statement.getSourceFile();\n return {\n start: declaration.pos,\n end: declaration.end,\n lead: { start: d.statement.pos, end: d.statement.getStart(sf) },\n };\n}\n\n/**\n * The declared functions the module assigns to anywhere, with the line\n * of the first assignment: what runs under such a name may not be its\n * declaration. A name is confirmed through the compiler, so a local of\n * the same name assigned in some block is not the function.\n */\nfunction assigned(\n sf: SourceFile,\n checker: Checker,\n declarations: ReadonlyMap<string, Declared>,\n): Map<string, number> {\n const out = new Map<string, number>();\n const symbolIds = new Map<string, number | undefined>();\n const idOf = (name: string): number | undefined => {\n if (!symbolIds.has(name)) {\n const decl = declarations.get(name);\n symbolIds.set(name, decl ? checker.getSymbolAtLocation(decl.name)?.id : undefined);\n }\n return symbolIds.get(name);\n };\n const visit = (node: Node): void => {\n if (\n is.isIdentifier(node) &&\n declarations.has(node.text) &&\n !out.has(node.text) &&\n isWritten(node)\n ) {\n const id = idOf(node.text);\n // In `({ f } = …)` the name is the property's; the value it assigns is the binding's symbol.\n const parent = node.parent;\n const symbol =\n is.isShorthandPropertyAssignment(parent) && parent.name === node\n ? checker.getShorthandAssignmentValueSymbol(parent)\n : checker.getSymbolAtLocation(node);\n if (id !== undefined && symbol?.id === id) out.set(node.text, lineAt(sf, node));\n }\n node.forEachChild(visit);\n };\n visit(sf);\n return out;\n}\n\n/** A function as written: a declaration, or the arrow (or function expression) a module-level binding holds. */\ntype FunctionNode = FunctionDeclaration | ArrowFunction | FunctionExpression;\n\n/** A module-level function: its name, its node, and the statement declaring it (for its line). */\ninterface Declared {\n readonly name: Identifier;\n readonly node: FunctionNode;\n readonly statement: Node;\n}\n\n/** A function's header read: its typed parameters and return type, with the body still to read. */\ninterface Head {\n readonly name: string;\n readonly decl: FunctionNode;\n readonly params: readonly Param[];\n readonly returns: SubsetType;\n readonly line: number;\n readonly offset: number;\n}\n\n/** The parameter names of a function the subset can take at all: synchronous, no generator, plain parameters. */\nfunction shape(reader: ExprReader, decl: FunctionNode): string[] {\n if (isAsync(decl)) reader.fail(\"an async function (core functions are synchronous)\", decl);\n if (!is.isArrowFunction(decl) && decl.asteriskToken) reader.fail(\"a generator function\", decl);\n return decl.parameters.map((p) => {\n if (!is.isIdentifier(p.name)) reader.fail(\"a destructured parameter\", p);\n const pname = p.name.text;\n if (p.dotDotDotToken) reader.fail(\"a rest parameter\", p);\n // `this: T` annotates the receiver and is erased; it is no argument the function is called with.\n if (pname === \"this\") reader.fail(\"a this parameter (the receiver is not modelled)\", p);\n if (p.questionToken) reader.fail(`optional parameter ${pname}`, p);\n if (p.initializer) reader.fail(`a default value for ${pname}`, p);\n return pname;\n });\n}\n\n/** `export function name(params): Type {` or `export const name = (params): Type => …` read, the types through the compiler. */\nfunction head(reader: ExprReader, types: SubsetTypes, checker: Checker, d: Declared): Head {\n const sf = reader.sf;\n const decl = d.node;\n const name = d.name.text;\n const pnames = shape(reader, decl);\n if (decl.typeParameters) reader.fail(\"type parameters\", decl.typeParameters[0] ?? decl);\n const params: Param[] = decl.parameters.map((p, i) => {\n const pname = pnames[i] as string;\n if (!p.type) reader.fail(`parameter ${pname} without a type`, p);\n return {\n name: pname,\n type: types.of(checker.getTypeAtLocation(p.type), reader.refuseAt(p.type)),\n };\n });\n if (!decl.type)\n reader.fail(\n `${name} without a return type (the subset needs it to name the record returned)`,\n decl,\n );\n const returns = types.of(checker.getTypeAtLocation(decl.type), reader.refuseAt(decl.type));\n if (!decl.body) reader.fail(\"a function without a body\", decl);\n const offset = openParen(sf, decl);\n if (offset === undefined) reader.fail(\"a function without a parameter list\", decl);\n return { name, decl, params, returns, line: lineAt(sf, d.statement), offset };\n}\n\n/** The function, its body read and typed against its header. */\nfunction declaration(reader: ExprReader, h: Head): SubsetFunction {\n const body = h.decl.body as NonNullable<FunctionNode[\"body\"]>;\n const scope = new Map(h.params.map((p) => [p.name, p.type]));\n // An arrow's expression body is its one return. Null checks narrow the names they guard in the\n // branches they guard, before anything is typed.\n const statements = is.isBlock(body)\n ? reader.block(body.statements, scope, body)\n : reader.expression(body, scope);\n const read = reader.narrowed(statements, scope, body);\n // Typing the whole body here: a record literal of no declared type, a field read on an integer or\n // a body of another type than declared are all outside the subset, found now rather than by an engine.\n const actual = reader.typeOfExpr(read, scope, body, h.returns);\n if (!fits(actual, h.returns, reader.ctx))\n reader.fail(\n `${h.name} returns a ${describe(actual)} but declares ${describe(h.returns)}`,\n body,\n );\n return {\n name: h.name,\n params: h.params,\n returns: h.returns,\n body: read,\n line: h.line,\n offset: h.offset,\n };\n}\n\n/** A file's top-level functions, and the ones whose name may run something else, with why. */\ninterface FileFunctions {\n readonly declarations: ReadonlyMap<string, Declared>;\n readonly overloaded: ReadonlySet<string>;\n readonly untrusted: ReadonlyMap<string, OutsideFunction>;\n /** What puts the whole file outside, functions and constants alike: eval, a built-in assigned to, or the compiler's checks turned off. */\n readonly tainted?: { readonly line: number; readonly message: string };\n}\n\n/**\n * A file's top-level functions: declarations, and the arrows module-level\n * consts hold. A binding that may be reassigned (let, var) or holds a\n * function expression is listed, for its callers' typing, and untrusted;\n * so is every function of a file mentioning eval directly or assigning to\n * a built-in, and a function the file assigns to.\n */\nfunction fileFunctions(\n sf: SourceFile,\n checker: Checker,\n standardGlobal: (id: Identifier) => boolean,\n): FileFunctions {\n const declarations = new Map<string, Declared>();\n const overloaded = new Set<string>();\n const untrusted = new Map<string, OutsideFunction>();\n const declare = (name: Identifier, node: FunctionNode, statement: Node): void => {\n if (declarations.has(name.text)) overloaded.add(name.text);\n else declarations.set(name.text, { name, node, statement });\n };\n for (const st of sf.statements) {\n if (is.isFunctionDeclaration(st)) {\n if (st.name) declare(st.name, st, st);\n continue;\n }\n if (!is.isVariableStatement(st)) continue;\n for (const d of st.declarationList.declarations) {\n if (!is.isIdentifier(d.name) || !d.initializer) continue;\n let init: Expression = d.initializer;\n while (is.isParenthesizedExpression(init)) init = init.expression;\n if (!is.isArrowFunction(init) && !is.isFunctionExpression(init)) continue;\n const name = d.name.text;\n declare(d.name, init, st);\n if (!isConst(st.declarationList))\n untrusted.set(name, {\n name,\n line: lineAt(sf, st),\n message: `${name} is declared with let or var, so what runs under its name may be another function`,\n });\n else if (is.isFunctionExpression(init))\n untrusted.set(name, {\n name,\n line: lineAt(sf, st),\n message: `${name} holds a function expression (write a function declaration or an arrow)`,\n });\n }\n }\n // A direct eval can rebind any declaration of the file without naming it, so any mention of `eval`\n // that is not a property of something else (`globalThis.eval` is indirect, and cannot) puts every\n // function outside: `eval(…)`, `(eval)(…)`, inside a template substitution alike. So does a\n // `@ts-nocheck` comment, which turns off the compiler's checks the reader relies on, and a direct\n // assignment to a built-in the subset reads as standard (`Math.floor = …`, `Array.prototype.map =\n // …`), wherever it is in the file: once it has run, the file's functions compute something else.\n // The engines state the assumption that nothing the reader does not see does this.\n const evalLine = directEval(sf);\n const noCheck = noCheckDirective(sf);\n const patched = rebound(sf, checker, standardGlobal);\n const tainted =\n evalLine !== undefined\n ? {\n line: evalLine,\n message: \"the module mentions eval directly, which can rebind any of its declarations\",\n }\n : noCheck !== undefined\n ? {\n line: noCheck,\n message:\n \"its file has a @ts-nocheck comment, which turns off the compiler's checks the reader relies on\",\n }\n : patched !== undefined\n ? {\n line: patched.line,\n message: `its file assigns to ${patched.target} (line ${patched.line}), so the built-ins its functions use may not be the standard ones`,\n }\n : undefined;\n if (tainted) for (const name of declarations.keys()) untrusted.set(name, { name, ...tainted });\n for (const [name, line] of assigned(sf, checker, declarations))\n if (!untrusted.has(name))\n untrusted.set(name, {\n name,\n line,\n message: `${name} is assigned in the module, so what runs under its name may not be its declaration`,\n });\n return { declarations, overloaded, untrusted, ...(tainted ? { tainted } : {}) };\n}\n\n/** What inlining a module's calls needs from the read it belongs to. */\ninterface InlinerContext {\n readonly checker: Checker;\n readonly types: SubsetTypes;\n readonly typeSource: TypeSource;\n readonly ctx: TypeContext;\n /** The module being read, and its functions. */\n readonly module: SourceFile;\n readonly own: FileFunctions;\n readonly parseError: (path: string) => { line: number; message: string } | undefined;\n readonly typeErrors: (path: string) => readonly CompilerError[];\n /** Whether an identifier names the global of its name (`Math`): the compiler resolves it to its standard library. */\n readonly standardGlobal: (id: Identifier) => boolean;\n}\n\n/**\n * Bind the type parameters in `declared` so that it is `expected`, or a\n * member of `expected` when that is a union: a parameter binds to what it\n * meets, and two instantiations of one alias match argument by argument.\n * Returns the type matched (the union member, say), or undefined, with\n * `bound` unchanged by a member that did not match.\n */\nfunction match(declared: Type, expected: Type, bound: Map<number, Type>): Type | undefined {\n if (declared.isTypeParameter()) {\n const had = bound.get(declared.id);\n if (had && had.id !== expected.id) return undefined;\n bound.set(declared.id, expected);\n return expected;\n }\n const alias = declared.getAliasSymbol();\n const other = expected.getAliasSymbol();\n if (alias && other && alias.id === other.id) {\n const xs = declared.getAliasTypeArguments();\n const ys = expected.getAliasTypeArguments();\n if (xs.length !== ys.length) return undefined;\n const trial = new Map(bound);\n for (let i = 0; i < xs.length; i++)\n if (!match(xs[i] as Type, ys[i] as Type, trial)) return undefined;\n for (const [k, v] of trial) bound.set(k, v);\n return expected;\n }\n if (expected.isUnionType())\n for (const member of expected.getTypes()) {\n const trial = new Map(bound);\n if (match(declared, member, trial)) {\n for (const [k, v] of trial) bound.set(k, v);\n return member;\n }\n }\n return undefined;\n}\n\n/**\n * Calls to functions the module cannot name as its own, read inlined: a\n * generic function (of the module or not) at the call's instantiation,\n * and a function of another file, as the compiler resolves the import.\n * The callee's body is read in its own file under the parameter types the\n * call's resolved signature gives, its literals typed by the resolved\n * return type, its names moved away from the caller's, and bound by `let`\n * to the arguments in order: a pure function called by value computes\n * exactly that. The callee's own calls inline the same way, so the\n * helpers of its file come with it. A callee with no body here (a\n * declaration file), one its file may rebind, or one reached again while\n * it is being inlined (recursion) is outside the subset, with why.\n */\nfunction inliner(c: InlinerContext): { inline: Inline; constant: Constant } {\n const files = new Map<SourceFile, FileFunctions>([[c.module, c.own]]);\n const functionsOf = (file: SourceFile): FileFunctions => {\n let found = files.get(file);\n if (!found) {\n found = fileFunctions(file, c.checker, c.standardGlobal);\n files.set(file, found);\n }\n return found;\n };\n // Whether a declaration's text compiles, once per declaration however often it is read.\n const vetted = new Map<Node, { message: string; line: number } | undefined>();\n const vet = (\n file: SourceFile,\n key: Node,\n range: DeclaredRange,\n ): { message: string; line: number } | undefined => {\n if (!vetted.has(key)) vetted.set(key, notCompiled(file, c.typeErrors, range));\n return vetted.get(key);\n };\n const inlining: string[] = [];\n // The type parameters of the functions being read, bound to the types their calls give them,\n // innermost last: a generic function read inside another sees the outer one's as concrete types.\n const substitutions: Map<number, Type>[] = [];\n const concrete = (t: Type): Type => {\n const top = substitutions[substitutions.length - 1];\n return top && t.isTypeParameter() ? (top.get(t.id) ?? t) : t;\n };\n // `fail` is annotated so that the compiler narrows after a call to it.\n const inline: Inline = (call, callee, scope, readArgs, fail: (what: string) => never) => {\n // A call the compiler rejects (a name imported with `import type`, which does not exist when the\n // code runs; arguments that do not fit) is no call the reader may stand in for.\n const caller = call.getSourceFile();\n const start = call.getStart(caller);\n if (c.typeErrors(caller.fileName).some((e) => e.pos < call.end && e.end > start))\n fail(`the compiler reports an error on this call to ${callee.text}`);\n let symbol = c.checker.getSymbolAtLocation(callee);\n if (!symbol) return undefined;\n if (symbol.flags & SymbolFlags.Alias) symbol = c.checker.getAliasedSymbol(symbol);\n const decl = symbol.valueDeclaration?.resolve();\n if (!decl || !(is.isFunctionDeclaration(decl) || is.isVariableDeclaration(decl)))\n return undefined;\n const file = decl.getSourceFile();\n // The declaration's own name: a default export's symbol is named `default`.\n const name = decl.name && is.isIdentifier(decl.name) ? decl.name.text : symbol.name;\n const where = file === c.module ? name : `${name} (from ${file.fileName})`;\n if (file.isDeclarationFile)\n fail(`${where} has no body to read: it is declared in a declaration file`);\n const fns = functionsOf(file);\n const d = fns.declarations.get(name);\n // Only a top-level function of its file is read; anything else is refused by the usual message.\n if (!d || !decl.name || d.name.pos !== decl.name.pos) return undefined;\n if (c.parseError(file.fileName)) fail(`${where} is in a file the compiler cannot parse`);\n const untrusted = fns.untrusted.get(name);\n if (untrusted) fail(`${where} is outside the subset: ${untrusted.message}`);\n if (fns.overloaded.has(name)) fail(`${where} is declared more than once (overloads)`);\n const body = d.node.body;\n if (!body) fail(`${where} has no body to read`);\n // A callee the compiler reports an error in computes something its text does not say.\n const bad = vet(file, d.node, rangeOf(d));\n if (bad)\n fail(\n `${where} is outside the subset: ${bad.message} (line ${bad.line}${file === c.module ? \"\" : \" of its file\"})`,\n );\n const signature = c.checker.getResolvedSignature(call);\n if (c.checker.isUnknownSignature(signature)) fail(`the call to ${where} does not resolve`);\n const fileNames: Names = {\n callable: () => false,\n target: (n) => n,\n declared: (n) => fns.declarations.has(n),\n spec: false,\n global: c.standardGlobal,\n };\n const typeSource: TypeSource = {\n annotation: (node, refuse) => c.types.of(concrete(c.checker.getTypeAtLocation(node)), refuse),\n contextual: c.typeSource.contextual,\n };\n const reader = new ExprReader(file, fileNames, typeSource, c.ctx, undefined, inline, constant);\n const params = shape(reader, d.node);\n const symbols = signature.getParameters();\n if (symbols.length !== params.length || call.arguments.length !== params.length)\n fail(`${where} takes ${params.length} argument(s), called with ${call.arguments.length}`);\n // A generic callee is instantiated by where its value goes first: the compiler infers `E` in\n // `err({ type: \"locked\" })` from the argument alone, a record of its own, where the caller's\n // declared result names the error union the literal belongs to. What the context leaves open\n // is the compiler's instantiation.\n const bound = new Map<number, Type>();\n const declared = c.checker.getSignatureFromDeclaration(d.node);\n const generalReturn = c.checker.getReturnTypeOfSignature(declared);\n const context = d.node.typeParameters ? c.checker.getContextualType(call) : undefined;\n const matched = context ? match(generalReturn, concrete(context), bound) : undefined;\n const declaredParams = declared.getParameters();\n const generalParams = symbols.map((_, i) => {\n const own = declaredParams[i];\n return own ? c.checker.getTypeOfSymbol(own) : undefined;\n });\n const resolvedParams = symbols.map((p) => concrete(c.checker.getTypeOfSymbol(p)));\n const resolvedReturn = concrete(c.checker.getReturnTypeOfSignature(signature));\n // The callee's own type parameters, for its body: the context's first, the compiler's after.\n generalParams.forEach((g, i) => {\n if (g) match(g, resolvedParams[i] as Type, bound);\n });\n match(generalReturn, resolvedReturn, bound);\n const types = symbols.map((_, i) => {\n const g = generalParams[i];\n const type =\n g?.isTypeParameter() && bound.has(g.id)\n ? concrete(bound.get(g.id) as Type)\n : (resolvedParams[i] as Type);\n return c.types.of(type, (what) =>\n fail(`${where}, parameter ${params[i]} at this call: ${what}`),\n );\n });\n const returns = c.types.of(matched ?? resolvedReturn, (what) =>\n fail(`${where} returns, at this call, ${what}`),\n );\n const own = new Map([...bound].map(([k, v]) => [k, concrete(v)]));\n // The arguments in the caller's scope, before this callee is marked as being read: a nested call\n // to the same function is no recursion.\n const args = readArgs(types);\n const key = `${file.fileName}#${name}`;\n if (inlining.includes(key))\n fail(\n `${where} is recursive, which a function read at its calls cannot be (recursion is in the subset only as a module's own structural recursion)`,\n );\n inlining.push(key);\n substitutions.push(own);\n try {\n const inner = new Map(params.map((p, i) => [p, types[i] as SubsetType]));\n const readBody = (): Expr => {\n const read = returning(\n is.isBlock(body)\n ? reader.block(body.statements, inner, body)\n : reader.expression(body, inner),\n returns,\n );\n const actual = reader.typeOfExpr(reader.narrowed(read, inner, body), inner, body, returns);\n if (!fits(actual, returns, c.ctx))\n reader.fail(\n `returns a ${describe(actual)}, not the ${describe(returns)} called for`,\n body,\n );\n return read;\n };\n let read: Expr;\n try {\n read = readBody();\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n fail(\n `${where}, read at this call, is outside the subset: ${err.message} (line ${err.line} of its file)`,\n );\n }\n // Its parameters and its own names move away from every name the caller has here.\n const callerNames = new Set([...scope.keys(), ...args.flatMap((a) => [...boundNames(a)])]);\n // Every parameter name is reserved, used or not, so no fresh name repeats one.\n const taken = new Set([...callerNames, ...boundNames(read), ...params]);\n const renames = new Map<string, string>();\n for (const p of params) {\n const to = callerNames.has(p) ? fresh(p, taken) : p;\n taken.add(to);\n renames.set(p, to);\n }\n const renamed = renameVars(read, renames, taken, callerNames);\n return params.reduceRight<Expr>(\n (rest, p, i) => ({\n kind: \"let\",\n name: renames.get(p) as string,\n value: args[i] as Expr,\n body: rest,\n type: types[i] as SubsetType,\n }),\n renamed,\n );\n } finally {\n substitutions.pop();\n inlining.pop();\n }\n };\n // The constants being read, innermost last: one that reaches itself is refused.\n const reading: string[] = [];\n const constant: Constant = (name, fail: (what: string) => never) => {\n let symbol = c.checker.getSymbolAtLocation(name);\n if (!symbol) return undefined;\n const imported = (symbol.flags & SymbolFlags.Alias) !== 0;\n if (imported) symbol = c.checker.getAliasedSymbol(symbol);\n const decl = symbol.valueDeclaration?.resolve();\n if (!decl || !is.isVariableDeclaration(decl) || !is.isIdentifier(decl.name)) return undefined;\n const list = decl.parent;\n const statement = list.parent;\n const file = decl.getSourceFile();\n // A module-level `const` only: a `let` or `var` may be rebound, a local is not this name.\n if (!is.isVariableDeclarationList(list) || !is.isVariableStatement(statement)) return undefined;\n // A local the compiler resolves the name to, which the reader has not bound, is declared later in\n // its block: a const there throws when used before its line, a var reads undefined.\n if (statement.parent !== file)\n fail(`${name.text}, which is declared after this use in its block`);\n const where = file === c.module ? decl.name.text : `${decl.name.text} (from ${file.fileName})`;\n // A global (Math, say) is declared in the compiler's own declaration files: no constant here.\n if (file.isDeclarationFile && !imported) return undefined;\n if (file.isDeclarationFile)\n fail(`${where} has no value to read: it is declared in a declaration file`);\n if (!isConst(list)) fail(`${where} is a module-level let or var, which may be rebound`);\n // A name the compiler rejects here (used before its declaration, say) is not read.\n const at = name.getSourceFile();\n const start = name.getStart(at);\n if (c.typeErrors(at.fileName).some((e) => e.pos < name.end && e.end > start))\n fail(`the compiler reports an error on ${name.text} here`);\n if (c.parseError(file.fileName)) fail(`${where} is in a file the compiler cannot parse`);\n const init = decl.initializer;\n if (!init) fail(`${where} has no initializer`);\n if (is.isArrowFunction(init) || is.isFunctionExpression(init)) return undefined;\n // The declaration as a whole: a declared type the value does not fit is reported on the name.\n const bad = vet(file, decl, {\n start: decl.pos,\n end: decl.end,\n lead: { start: statement.pos, end: statement.getStart(file) },\n });\n if (bad)\n fail(\n `${where} is outside the subset: ${bad.message} (line ${bad.line}${file === c.module ? \"\" : \" of its file\"})`,\n );\n const key = `${file.fileName}#${decl.name.text}`;\n if (reading.includes(key)) fail(`${where} is defined in terms of itself`);\n const fns = functionsOf(file);\n // A constant of a file that may rebind a built-in, or whose checks are off, is no value to trust.\n if (fns.tainted) fail(`${where} is outside the subset: ${fns.tainted.message}`);\n const fileNames: Names = {\n callable: () => false,\n target: (n) => n,\n declared: (n) => fns.declarations.has(n),\n spec: false,\n global: c.standardGlobal,\n };\n const reader = new ExprReader(\n file,\n fileNames,\n c.typeSource,\n c.ctx,\n undefined,\n undefined,\n constant,\n );\n reading.push(key);\n try {\n const value = reader.expression(init, new Map());\n if (!isValue(value))\n reader.fail(\n `${decl.name.text} holds something other than a number, boolean or string built from literals, operators and other such constants`,\n init,\n );\n return value;\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n fail(\n `${where}, read where it is used, is outside the subset: ${err.message} (line ${err.line} of its file)`,\n );\n } finally {\n reading.pop();\n }\n };\n return { inline, constant };\n}\n\n/**\n * Whether an expression is a value a constant may hold: literals of the\n * primitive types and the operators on them, with no name, call or record.\n */\nfunction isValue(e: Expr): boolean {\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n return true;\n case \"neg\":\n case \"not\":\n case \"isInteger\":\n case \"floor\":\n return isValue(e.operand);\n case \"binary\":\n return isValue(e.left) && isValue(e.right);\n case \"cond\":\n return isValue(e.test) && isValue(e.ifTrue) && isValue(e.ifFalse);\n default:\n return false;\n }\n}\n\n/**\n * The expression with the record literals it returns typed `t`, where\n * they have no type of their own: a function inlined at a call returns\n * its instantiated type, which a literal in a generic body cannot name.\n */\nfunction returning(e: Expr, t: SubsetType): Expr {\n const target = t.kind === \"nullable\" ? t.inner : t;\n if (target.kind !== \"record\" && target.kind !== \"union\") return e;\n switch (e.kind) {\n case \"record\":\n return e.type ? e : { ...e, type: target };\n case \"let\":\n case \"narrow\":\n case \"narrowTag\":\n return { ...e, body: returning(e.body, t) };\n case \"cond\":\n return { ...e, ifTrue: returning(e.ifTrue, t), ifFalse: returning(e.ifFalse, t) };\n default:\n return e;\n }\n}\n\n/**\n * Read a module: every function the subset takes (in source order, so\n * callees come before callers), the record types and unions they use,\n * and, for the other functions, why not. A function calling one outside\n * the subset is outside it too. The names given are what the caller\n * cares about; one the module does not declare at its top level is\n * reported among the others, not thrown.\n */\nexport function readSubset(\n source: string,\n functions?: readonly string[],\n options: ReadSubsetOptions = {},\n): SubsetModule {\n const path = options.path ?? virtualModulePath;\n return withProgram(\n [{ path, text: source }, ...(options.files ?? [])],\n ({ checker, file, parseError, typeErrors, standardGlobal }) => {\n const sf = file(path);\n // Pass 1: the module's top-level functions, and what makes them untrustworthy. A generic one is\n // no function of the subset (no claim is stated over a type parameter); its callers read it inlined.\n const own = fileFunctions(sf, checker, standardGlobal);\n const { declarations, overloaded } = own;\n const declared = new Set(declarations.keys());\n const generic = new Set(\n [...declarations].filter(([, d]) => d.node.typeParameters).map(([name]) => name),\n );\n const outside = new Map<string, OutsideFunction>();\n const error = parseError(path);\n // Source the compiler cannot parse is source the reader cannot trust: every function is outside.\n if (error) {\n for (const name of new Set([...declared, ...(functions ?? [])]))\n outside.set(name, {\n name,\n line: 0,\n message: `the module could not be parsed: ${error.message} (line ${error.line})`,\n });\n return { records: [], unions: [], functions: [], outside: [...outside.values()] };\n }\n // A name asked for that is no module-level declaration (inside a namespace, say) is reported, not thrown.\n for (const name of functions ?? [])\n if (!declared.has(name))\n outside.set(name, {\n name,\n line: 0,\n message: `the module declares no function ${name} at its top level`,\n });\n for (const [name, why] of own.untrusted) if (!outside.has(name)) outside.set(name, why);\n // The module's own declared types first, in their order, so a record literal of no declared type\n // is matched against every record the module declares, and a record belongs to the union declared\n // first. A declared type the subset does not take is left out here; a function using it says why.\n const types = new SubsetTypes(checker);\n const skip = Symbol(\"outside\");\n for (const st of sf.statements) {\n if (!is.isInterfaceDeclaration(st) && !is.isTypeAliasDeclaration(st)) continue;\n if (st.typeParameters) continue; // a generic alias is read where it is instantiated\n const symbol = checker.getSymbolAtLocation(st.name);\n if (!symbol) continue;\n try {\n types.of(checker.getDeclaredTypeOfSymbol(symbol), () => {\n throw skip;\n });\n } catch (err) {\n if (err !== skip) throw err;\n }\n }\n // Pass 2: signatures, so every function's return type is known before any body is read.\n const { ctx, signatures } = moduleContext(types.records, types.unions);\n const names: Names = {\n callable: (n) => declared.has(n) && !generic.has(n),\n target: (n) => n,\n declared: (n) => declared.has(n),\n spec: false,\n global: standardGlobal,\n };\n const typeSource: TypeSource = {\n annotation: (node, refuse) => types.of(checker.getTypeAtLocation(node), refuse),\n contextual: (node) => contextualType(checker, types, node),\n };\n const { inline, constant } = inliner({\n checker,\n types,\n typeSource,\n ctx,\n module: sf,\n own,\n parseError,\n typeErrors,\n standardGlobal,\n });\n const reader = new ExprReader(sf, names, typeSource, ctx, undefined, inline, constant);\n const heads: Head[] = [];\n for (const [name, decl] of declarations) {\n try {\n if (overloaded.has(name))\n reader.fail(`${name} is declared more than once (overloads)`, decl.statement);\n const h = head(reader, types, checker, decl);\n // Callers of an assigned function still type-check against its declaration; they are then outside with it.\n signatures.set(name, { params: h.params, returns: h.returns });\n if (!outside.has(name)) heads.push(h);\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n if (!outside.has(name)) outside.set(name, { name, line: err.line, message: err.message });\n }\n }\n // Pass 3: bodies. Text the compiler rejects (a const used before its declaration, which\n // throws where the reader sees a value) may compute something other than what it says: a\n // function read fine is still outside, with the compiler's message, when it has such an error.\n const read = new Map<string, SubsetFunction>();\n for (const h of heads) {\n try {\n const fn = declaration(reader, h);\n const bad = notCompiled(sf, typeErrors, rangeOf(declarations.get(h.name) as Declared));\n if (bad) throw new OutsideSubset(bad.message, bad.line);\n read.set(h.name, fn);\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n outside.set(h.name, { name: h.name, line: err.line, message: err.message });\n }\n }\n closeOverCallees(read, outside);\n // Recursion is in the subset as structural recursion on a list (`structuralOn`), a function calling\n // itself directly; any other recursion is outside, and so are its callers.\n const reaches = (from: string, target: string, seen = new Set<string>()): boolean => {\n const fn = read.get(from);\n if (!fn) return false;\n for (const c of callees(fn.body)) {\n if (c === target) return true;\n if (!seen.has(c)) {\n seen.add(c);\n if (reaches(c, target, seen)) return true;\n }\n }\n return false;\n };\n for (const [name, fn] of [...read])\n if (reaches(name, name)) {\n const direct = [...callees(fn.body)].every((c) => c === name || !reaches(c, name));\n const on = direct ? structuralOn(fn) : undefined;\n if (on !== undefined) {\n read.set(name, { ...fn, structural: on });\n continue;\n }\n read.delete(name);\n outside.set(name, {\n name,\n line: fn.line,\n message: `${name} is recursive in a way the subset does not take: it takes a function calling itself on a list parameter's slice(1), after a first test of that list's length against 0 (if (xs.length === 0) return …)`,\n });\n }\n closeOverCallees(read, outside);\n // Callees before callers, whatever the source order: Lean needs a definition before its use.\n const ordered: SubsetFunction[] = [];\n const placed = new Set<string>();\n while (ordered.length < read.size)\n // A structurally recursive function calls itself: that callee needs no placing first.\n for (const [name, fn] of read)\n if (\n !placed.has(name) &&\n [...callees(fn.body)].every((c) => c === name || placed.has(c))\n ) {\n ordered.push(fn);\n placed.add(name);\n }\n return {\n records: [...types.records.values()],\n unions: types.unions,\n functions: ordered,\n outside: [...outside.values()],\n };\n },\n );\n}\n\n/** A caller of a function outside the subset is outside it too, however many steps away. */\nfunction closeOverCallees(\n read: Map<string, SubsetFunction>,\n outside: Map<string, OutsideFunction>,\n): void {\n for (let changed = true; changed; ) {\n changed = false;\n for (const [name, fn] of read) {\n const bad = [...callees(fn.body)].find((c) => outside.has(c));\n if (bad === undefined) continue;\n read.delete(name);\n outside.set(name, {\n name,\n line: fn.line,\n message: `calls ${bad}, which is outside the subset: ${outside.get(bad)?.message}`,\n });\n changed = true;\n }\n }\n}\n\n/**\n * A reader over text that is not the module: with `aliases`, the text is\n * a spec file's, whose names for the module's functions are its own\n * imports and nothing else; without, the text sees the module's names.\n * No compiler stands behind the text, so a `const` annotation is read\n * from its syntax against the module's declared types, and a record\n * literal has no contextual type. Lines are not reported: the text's\n * position is the caller's to know.\n */\nfunction arrowReader(\n sf: SourceFile,\n module: SubsetModule,\n aliases?: ReadonlyMap<string, string>,\n): ExprReader {\n const records = new Map(module.records.map((rec) => [rec.name, rec]));\n const unionNames = new Set(module.unions.map((u) => u.name));\n const inSubset = new Set(module.functions.map((f) => f.name));\n let names: Names;\n if (aliases) {\n const declared = new Set(aliases.keys());\n const callable = new Set(\n [...aliases].filter(([, fn]) => inSubset.has(fn)).map(([local]) => local),\n );\n names = {\n callable: (n) => callable.has(n),\n target: (n) => aliases.get(n) ?? n,\n declared: (n) => declared.has(n),\n spec: true,\n global: () => true,\n };\n } else {\n const declared = new Set([...inSubset, ...module.outside.map((o) => o.name)]);\n names = {\n callable: (n) => inSubset.has(n),\n target: (n) => n,\n declared: (n) => declared.has(n),\n spec: false,\n global: () => true,\n };\n }\n const recordNames = new Set(records.keys());\n const typeSource: TypeSource = {\n annotation: (node, refuse) => syntacticType(sf, node, recordNames, unionNames, refuse),\n contextual: () => undefined,\n };\n const signatures = new Map<string, CalleeSignature>(\n module.functions.map((f) => [f.name, { params: f.params, returns: f.returns }]),\n );\n return new ExprReader(\n sf,\n names,\n typeSource,\n { records, unions: module.unions, signatures },\n () => 0,\n );\n}\n\n/** The one expression a fragment `(text)` parsed to, or why the text is not one expression. */\nfunction fragmentExpression(sf: SourceFile): Expression {\n const [first, second] = sf.statements;\n if (second) throw new OutsideSubset(`unexpected ${textOf(sf, second)} after the expression`, 0);\n if (!first || !is.isExpressionStatement(first) || !is.isParenthesizedExpression(first.expression))\n throw new OutsideSubset(\"could not be parsed as an expression\", 0);\n let broken: string | undefined;\n const visit = (node: Node): void => {\n if (broken !== undefined) return;\n if (is.isIdentifier(node) && node.text === \"\")\n broken = \"could not be parsed (something is missing)\";\n node.forEachChild(visit);\n };\n visit(first);\n if (broken !== undefined) throw new OutsideSubset(broken, 0);\n return first.expression.expression;\n}\n\n/**\n * One TypeScript expression (a claim's body, say) in a scope of typed\n * names, over a module already read. The whole text must be the\n * expression.\n */\nexport function readExpression(\n text: string,\n scope: ReadonlyMap<string, SubsetType>,\n module: SubsetModule,\n aliases?: ReadonlyMap<string, string>,\n): Expr {\n return withSourceFile(`(${text}\\n)`, (sf) => {\n const expr = fragmentExpression(sf);\n return arrowReader(sf, module, aliases).expression(expr, scope);\n });\n}\n\n/**\n * The body of a spec file's arrow (`when` or `ensures`) as a boolean\n * expression: an expression body as it is, a block body through the same\n * statement reader as a function body (`const`, `if`, early returns).\n * The scope maps the arrow's own parameter names to the binders' types;\n * `aliases` maps the spec file's local names to the module's functions,\n * and a free name that is neither is outside the subset: the spec file's\n * scope is its imports, never the module's. `Math` and `Number` are the\n * globals wherever the arrow's own scope does not bind them: `readSpecs`\n * has checked that every built-in a claim names resolves to the standard\n * library in the spec file.\n */\nexport function readArrowBody(\n arrow: Arrow,\n scope: ReadonlyMap<string, SubsetType>,\n module: SubsetModule,\n aliases: ReadonlyMap<string, string> = new Map(),\n): Expr {\n if (!arrow.block)\n return withSourceFile(`(${arrow.body}\\n)`, (sf) => {\n const expr = fragmentExpression(sf);\n const reader = arrowReader(sf, module, aliases);\n return reader.narrowed(reader.expression(expr, scope), scope, sf);\n });\n return withSourceFile(`{${arrow.body}\\n}`, (sf) => {\n const block = blockOf(sf);\n if (!block) throw new OutsideSubset(\"could not be parsed as a block\", 0);\n const reader = arrowReader(sf, module, aliases);\n return reader.narrowed(reader.block(block.statements, new Map(scope), block), scope, sf);\n });\n}\n\n/**\n * The list parameter a function recurses on structurally, or undefined:\n * its body is `if (p.length === 0) … else …` for a list parameter p, the\n * test and the first branch do not call it, and every call to it in the\n * other branch passes `p.slice(1)` for p. Lean takes such a definition as\n * a match on `[]` and `head :: tail`, recursing on the tail.\n */\nfunction structuralOn(fn: SubsetFunction): number | undefined {\n const body = fn.body;\n if (body.kind !== \"cond\") return undefined;\n const t = body.test;\n if (t.kind !== \"binary\" || t.op !== \"===\") return undefined;\n const sides = [t.left, t.right];\n const zero = sides.find((x) => x.kind === \"int\" && x.value === \"0\");\n const len = sides.find((x) => x !== zero);\n if (!zero || len?.kind !== \"field\" || len.field !== \"length\" || len.object.kind !== \"var\")\n return undefined;\n const list = len.object.name;\n const at = fn.params.findIndex((p) => p.name === list && p.type.kind === \"list\");\n if (at < 0) return undefined;\n if (callees(t).has(fn.name) || callees(body.ifTrue).has(fn.name)) return undefined;\n const calls = selfCalls(body.ifFalse, fn.name);\n const onTail = (a: Expr | undefined) =>\n a?.kind === \"tail\" && a.list.kind === \"var\" && a.list.name === list;\n return calls.length > 0 && calls.every((c) => onTail(c.args[at])) ? at : undefined;\n}\n\n/** Every call to `name` in an expression. */\nfunction selfCalls(e: Expr, name: string): Extract<Expr, { kind: \"call\" }>[] {\n const out: Extract<Expr, { kind: \"call\" }>[] = [];\n const walk = (x: Expr): void => {\n if (x.kind === \"call\" && x.callee === name) out.push(x);\n for (const child of children(x)) walk(child);\n };\n walk(e);\n return out;\n}\n\n/** An expression's direct subexpressions. */\nexport function children(e: Expr): Expr[] {\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n case \"var\":\n return [];\n case \"narrow\":\n case \"narrowTag\":\n return [e.body];\n case \"neg\":\n case \"not\":\n case \"isInteger\":\n case \"floor\":\n return [e.operand];\n case \"binary\":\n return [e.left, e.right];\n case \"cond\":\n return [e.test, e.ifTrue, e.ifFalse];\n case \"call\":\n return [...e.args];\n case \"field\":\n return [e.object];\n case \"record\":\n return e.fields.map((f) => f.value);\n case \"let\":\n return [e.value, e.body];\n case \"list\":\n return [...e.items, ...(e.rest ? [e.rest] : [])];\n case \"tail\":\n return [e.list];\n case \"headOr\":\n return [e.list, e.fallback];\n case \"iterate\":\n return [e.list, e.body];\n case \"fold\":\n return [e.list, e.init, e.body];\n }\n}\n\n/** Whether an expression holds a node of the kinds named. */\nfunction hasNode(e: Expr, kinds: ReadonlySet<Expr[\"kind\"]>): boolean {\n if (kinds.has(e.kind)) return true;\n switch (e.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n case \"var\":\n return false;\n case \"narrow\":\n case \"narrowTag\":\n return hasNode(e.body, kinds);\n case \"neg\":\n case \"not\":\n case \"isInteger\":\n case \"floor\":\n return hasNode(e.operand, kinds);\n case \"binary\":\n return hasNode(e.left, kinds) || hasNode(e.right, kinds);\n case \"cond\":\n return hasNode(e.test, kinds) || hasNode(e.ifTrue, kinds) || hasNode(e.ifFalse, kinds);\n case \"call\":\n return e.args.some((a) => hasNode(a, kinds));\n case \"field\":\n return hasNode(e.object, kinds);\n case \"record\":\n return e.fields.some((f) => hasNode(f.value, kinds));\n case \"let\":\n return hasNode(e.value, kinds) || hasNode(e.body, kinds);\n case \"list\":\n return e.items.some((x) => hasNode(x, kinds)) || (e.rest ? hasNode(e.rest, kinds) : false);\n case \"tail\":\n return hasNode(e.list, kinds);\n case \"headOr\":\n return hasNode(e.list, kinds) || hasNode(e.fallback, kinds);\n case \"iterate\":\n return hasNode(e.list, kinds) || hasNode(e.body, kinds);\n case \"fold\":\n return hasNode(e.list, kinds) || hasNode(e.init, kinds) || hasNode(e.body, kinds);\n }\n}\n\n/**\n * The module as an engine that takes only some of the subset's types sees\n * it: records with a field of a type it does not take are dropped, and so\n * are functions whose signature holds one, whose body uses what the\n * types bring (`null`, narrowing), or which call such a function; each is\n * reported outside with `reason`.\n */\nexport function restrictModule(\n module: SubsetModule,\n takes: (t: SubsetType) => boolean,\n reason: string,\n /** Expression kinds a function's body may not hold here: by default what nullable types and unions bring. */\n bodies: ReadonlySet<Expr[\"kind\"]> = new Set([\"null\", \"narrow\", \"narrowTag\"]),\n /** A body the engine refuses for what it computes, not its kinds or types (a division, say). */\n refused?: (body: Expr) => boolean,\n): SubsetModule {\n // A record with a field the engine does not take is out, and so is a union with such a member, and\n // so, in turn, is a record with a field of that union: to a fixed point.\n const badRecords = new Set<string>();\n for (const u of module.unions)\n if (!takes({ kind: \"union\", name: u.name })) badRecords.add(`union:${u.name}`);\n for (let changed = true; changed; ) {\n changed = false;\n for (const rec of module.records)\n if (\n !badRecords.has(rec.name) &&\n rec.fields.some((f) => !typeTaken(f.type, takes, badRecords))\n ) {\n badRecords.add(rec.name);\n changed = true;\n }\n for (const u of module.unions) {\n if (!badRecords.has(`union:${u.name}`) && u.members.some((m) => badRecords.has(m.record))) {\n badRecords.add(`union:${u.name}`);\n changed = true;\n }\n // A member of a dropped union stays a record of its own: every record has its own sort, so a\n // member of several unions does not go with one of them.\n }\n }\n const outside = new Map(module.outside.map((o) => [o.name, o]));\n const kept = new Map(module.functions.map((f) => [f.name, f]));\n const uses = (f: SubsetFunction) =>\n !f.params.every((p) => typeTaken(p.type, takes, badRecords)) ||\n !typeTaken(f.returns, takes, badRecords) ||\n annotations(f.body).some((t) => !typeTaken(t, takes, badRecords)) ||\n hasNode(f.body, bodies) ||\n refused?.(f.body) === true;\n for (const f of module.functions)\n if (uses(f)) {\n kept.delete(f.name);\n outside.set(f.name, { name: f.name, line: f.line, message: reason });\n }\n for (let changed = true; changed; ) {\n changed = false;\n for (const [name, f] of kept) {\n const bad = [...callees(f.body)].find((c) => outside.has(c));\n if (bad === undefined) continue;\n kept.delete(name);\n outside.set(name, {\n name,\n line: f.line,\n message: `calls ${bad}, which is outside the engine's subset: ${outside.get(bad)?.message}`,\n });\n changed = true;\n }\n }\n return {\n // A kept record names only the unions kept with it.\n records: module.records\n .filter((r) => !badRecords.has(r.name))\n .map((r) => {\n const unions = r.unions?.filter((u) => !badRecords.has(`union:${u}`));\n if (unions === r.unions) return r;\n const { unions: _, ...rest } = r;\n return unions && unions.length > 0 ? { ...rest, unions } : rest;\n }),\n unions: module.unions.filter((u) => !badRecords.has(`union:${u.name}`)),\n functions: module.functions.filter((f) => kept.has(f.name)),\n outside: [...outside.values()],\n };\n}\n\nfunction typeTaken(\n t: SubsetType,\n takes: (t: SubsetType) => boolean,\n badRecords: ReadonlySet<string>,\n): boolean {\n if (!takes(t)) return false;\n if (t.kind === \"record\") return !badRecords.has(t.name);\n if (t.kind === \"union\") return !badRecords.has(`union:${t.name}`);\n if (t.kind === \"nullable\") return typeTaken(t.inner, takes, badRecords);\n if (t.kind === \"list\") return typeTaken(t.element, takes, badRecords);\n return true;\n}\n\n/** The types a body's `const` annotations and its record literals' contexts name. */\nfunction annotations(e: Expr, out: SubsetType[] = []): SubsetType[] {\n if ((e.kind === \"let\" || e.kind === \"record\") && e.type) out.push(e.type);\n for (const c of children(e)) annotations(c, out);\n return out;\n}\n\n/** An expression only lists bring. */\nexport type ListExpr = Extract<Expr, { kind: \"list\" | \"tail\" | \"headOr\" | \"iterate\" | \"fold\" }>;\n\n/** The expression kinds only lists bring, for an engine that does not take them. */\nexport const listKinds: ReadonlySet<Expr[\"kind\"]> = new Set<ListExpr[\"kind\"]>([\n \"list\",\n \"tail\",\n \"headOr\",\n \"iterate\",\n \"fold\",\n]);\n\n/** Whether an expression is one only lists bring (a type guard over `listKinds`). */\nexport const isListExpr = (e: Expr): e is ListExpr => listKinds.has(e.kind);\n","/**\n * A module and its spec file read into `ModuleSpecs` through the\n * compiler. From the module: the exported functions and their parameter\n * types (`function` declarations and `const` arrows alike), the types as\n * the compiler resolves them. From the spec file: every\n * `export const name = forall(f, { sample, when, ensures })` and\n * `total(f)`, with the combinators imported from `eutaxy/spec` and `f`\n * imported from the module beside the spec file (the import resolved by\n * the compiler); the arrows are kept as text, their parameter names\n * naming the binders, and the precondition's conjuncts about one\n * parameter become that binder's hint. Anything else is an error with a\n * line, never a guess.\n */\n\nimport type {\n Arrow,\n Binder,\n Endpoint,\n FunctionSpec,\n Hint,\n ModuleSpecs,\n Param,\n Property,\n SpecError,\n SpecType,\n} from \"@eutaxy/spec\";\nimport {\n type ArrowFunction,\n type Expression,\n type FunctionLikeBase,\n type ImportDeclaration,\n type Node,\n type SourceFile,\n SyntaxKind,\n} from \"typescript/ast\";\nimport * as is from \"typescript/ast/is\";\nimport type { Checker, Program } from \"typescript/sync\";\nimport { endpointBigInt, endpointNumber } from \"../generate.ts\";\nimport {\n isAsync,\n isConst,\n isExported,\n lineAt,\n type Opened,\n openParen,\n textOf,\n withProgram,\n withSourceFile,\n} from \"./compiler.ts\";\nimport { rebound } from \"./subset.ts\";\nimport { specTypeOf, unionOf } from \"./types.ts\";\n\nexport interface ReadSpecsInput {\n /** The module's source. */\n readonly module: string;\n /** The spec file's source. */\n readonly spec: string;\n /**\n * The module's path, under which its imports resolve; the spec file\n * is beside it unless `specPath` says otherwise. For a module given\n * by text alone, any absolute path the spec file's import of the\n * module resolves to (`/x/domain.ts` for `import … from \"./domain.ts\"`).\n */\n readonly modulePath: string;\n /** The spec file's path; `<module>.props.ts` by default. */\n readonly specPath?: string;\n /** Specifiers the combinators come from; `eutaxy/spec` and the workspace name by default. */\n readonly specSpecifiers?: readonly string[];\n}\n\n// ---------------------------------------------------------------------------\n// The module: exported functions and their parameter types.\n\ninterface Declaration {\n readonly name: string;\n readonly params: readonly Param[];\n readonly line: number;\n readonly offset: number;\n}\n\ninterface ModuleSide {\n readonly declarations: ReadonlyMap<string, Declaration>;\n /** Exported name to local declaration name. */\n readonly exports: ReadonlyMap<string, string>;\n readonly errors: readonly SpecError[];\n}\n\n/** The parameters of a function-like declaration: `name?: T = default`, `...rest`, destructured. */\nfunction readParams(checker: Checker, fn: FunctionLikeBase): Param[] {\n const params: Param[] = [];\n for (const p of fn.parameters) {\n const name = is.isIdentifier(p.name) ? p.name.text : null;\n if (name === \"this\") continue; // a receiver annotation, no argument\n if (p.dotDotDotToken) {\n params.push({ name: null, type: { kind: \"unknown\", text: `...${name ?? \"\"}` } });\n continue;\n }\n let type: SpecType;\n if (p.type) type = specTypeOf(checker, checker.getTypeAtLocation(p.type));\n else if (p.initializer) type = specTypeOf(checker, checker.getTypeAtLocation(p));\n else type = { kind: \"unknown\", text: \"(no type annotation)\" };\n // An optional parameter, or one with a default, may be passed undefined.\n if (p.questionToken || p.initializer) type = unionOf([type, { kind: \"undefined\" }]);\n params.push({ name, type });\n }\n return params;\n}\n\nfunction readModuleSide(sf: SourceFile, checker: Checker): ModuleSide {\n const errors: SpecError[] = [];\n const declarations = new Map<string, Declaration>();\n const exports = new Map<string, string>();\n const declare = (name: string, fn: FunctionLikeBase, at: Node): void => {\n const offset = openParen(sf, fn);\n if (offset === undefined) return; // an arrow without parentheses: no parameter list to point at\n if (declarations.has(name)) {\n errors.push({\n line: lineAt(sf, at),\n message: `${name} is declared more than once (overloads): a spec is checked against one signature`,\n inModule: true,\n });\n return;\n }\n declarations.set(name, { name, params: readParams(checker, fn), line: lineAt(sf, at), offset });\n };\n for (const st of sf.statements) {\n if (is.isFunctionDeclaration(st)) {\n if (!st.name) continue;\n declare(st.name.text, st, st);\n if (isExported(st)) exports.set(st.name.text, st.name.text);\n continue;\n }\n if (is.isVariableStatement(st)) {\n // `export const f = (a: T): R => …` or `= function (a: T) …`: a function by another declaration.\n for (const d of st.declarationList.declarations) {\n if (!is.isIdentifier(d.name) || !d.initializer) continue;\n let init: Expression = d.initializer;\n while (is.isParenthesizedExpression(init)) init = init.expression;\n if (!is.isArrowFunction(init) && !is.isFunctionExpression(init)) continue;\n declare(d.name.text, init, st);\n if (isExported(st)) exports.set(d.name.text, d.name.text);\n }\n continue;\n }\n // `export { a, b as c }`; with `from`, a re-export of another module's names (not this module's).\n if (is.isExportDeclaration(st) && !st.moduleSpecifier && !st.isTypeOnly && st.exportClause) {\n if (!is.isNamedExports(st.exportClause)) continue;\n for (const e of st.exportClause.elements) {\n if (e.isTypeOnly) continue;\n const local = e.propertyName ?? e.name;\n if (is.isIdentifier(local) && is.isIdentifier(e.name)) exports.set(e.name.text, local.text);\n }\n }\n }\n return { declarations, exports, errors };\n}\n\n// ---------------------------------------------------------------------------\n// The spec file.\n\ninterface Imported {\n readonly from: string;\n /** The exported name imported; `*` for a namespace import. */\n readonly name: string;\n readonly declaration: ImportDeclaration;\n}\n\n/** `import { a, b as c } from \"x\"`, `import * as ns from \"x\"`, `import d from \"x\"`; type-only imports skipped. */\nfunction imports(sf: SourceFile): Map<string, Imported> {\n const out = new Map<string, Imported>();\n for (const st of sf.statements) {\n if (!is.isImportDeclaration(st) || !st.importClause) continue;\n const clause = st.importClause;\n if (clause.phaseModifier === SyntaxKind.TypeKeyword) continue;\n if (!is.isStringLiteral(st.moduleSpecifier)) continue;\n const from = st.moduleSpecifier.text;\n if (clause.name) out.set(clause.name.text, { from, name: \"default\", declaration: st });\n const bindings = clause.namedBindings;\n if (!bindings) continue;\n if (is.isNamespaceImport(bindings))\n out.set(bindings.name.text, { from, name: \"*\", declaration: st });\n else\n for (const e of bindings.elements) {\n if (e.isTypeOnly) continue;\n const imported = e.propertyName ?? e.name;\n const name = is.isIdentifier(imported) ? imported.text : imported.text;\n out.set(e.name.text, { from, name, declaration: st });\n }\n }\n return out;\n}\n\n/** `1`, `-1`, `1_000`, `1.5`, `10n` as an endpoint value; undefined otherwise. */\nfunction numberText(sf: SourceFile, node: Expression): string | undefined {\n if (is.isNumericLiteral(node) || is.isBigIntLiteral(node))\n return textOf(sf, node).replace(/_/g, \"\");\n if (\n is.isPrefixUnaryExpression(node) &&\n node.operator === SyntaxKind.MinusToken &&\n (is.isNumericLiteral(node.operand) || is.isBigIntLiteral(node.operand))\n )\n return `-${textOf(sf, node.operand).replace(/_/g, \"\")}`;\n return undefined;\n}\n\n/** The top-level conjuncts of an expression, parentheses stripped. */\nfunction conjuncts(node: Expression, out: Expression[] = []): Expression[] {\n let e = node;\n while (is.isParenthesizedExpression(e)) e = e.expression;\n if (is.isBinaryExpression(e) && e.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) {\n conjuncts(e.left, out);\n conjuncts(e.right, out);\n } else out.push(e);\n return out;\n}\n\nconst comparisons: Partial<Record<SyntaxKind, string>> = {\n [SyntaxKind.LessThanToken]: \"<\",\n [SyntaxKind.LessThanEqualsToken]: \"<=\",\n [SyntaxKind.GreaterThanToken]: \">\",\n [SyntaxKind.GreaterThanEqualsToken]: \">=\",\n};\n\n/**\n * What an expression says about each of the named parameters on its own:\n * its top-level conjuncts of the forms `Number.isInteger(x)`, `x < n`,\n * `n <= x` (and the other comparisons) and `/re/.test(x)`, by parameter\n * index.\n */\nfunction hintsIn(\n sf: SourceFile,\n body: Expression,\n params: readonly (string | null)[],\n): Map<number, Hint> {\n const out = new Map<number, Hint>();\n const position = new Map<string, number>();\n params.forEach((p, i) => {\n if (p !== null) position.set(p, i);\n });\n const merge = (i: number, h: Hint) => {\n const old = out.get(i) ?? {};\n out.set(i, { ...old, ...h });\n };\n for (const conjunct of conjuncts(body)) {\n if (is.isCallExpression(conjunct)) {\n const callee = conjunct.expression;\n const [arg, extra] = conjunct.arguments;\n if (!is.isPropertyAccessExpression(callee) || !is.isIdentifier(callee.name) || !arg || extra)\n continue;\n if (!is.isIdentifier(arg)) continue;\n const at = position.get(arg.text);\n if (at === undefined) continue;\n // Number.isInteger(x)\n if (\n is.isIdentifier(callee.expression) &&\n callee.expression.text === \"Number\" &&\n callee.name.text === \"isInteger\"\n )\n merge(at, { integer: true });\n // /re/.test(x)\n else if (is.isRegularExpressionLiteral(callee.expression) && callee.name.text === \"test\") {\n const m = /^\\/([\\s\\S]*)\\/([a-z]*)$/.exec(textOf(sf, callee.expression));\n if (m) merge(at, { regex: { pattern: m[1] as string, flags: m[2] as string } });\n }\n continue;\n }\n // x op n, n op x\n if (!is.isBinaryExpression(conjunct)) continue;\n const op = comparisons[conjunct.operatorToken.kind];\n if (op === undefined) continue;\n const bound = (variable: Expression, literal: Expression, variableOnLeft: boolean) => {\n if (!is.isIdentifier(variable)) return;\n const value = numberText(sf, literal);\n if (value === undefined) return;\n const at = position.get(variable.text);\n if (at === undefined) return;\n // `x < n` bounds x above; `n < x` bounds it below.\n const above = variableOnLeft ? op.startsWith(\"<\") : op.startsWith(\">\");\n const endpoint: Endpoint = { value, inclusive: op.endsWith(\"=\") };\n merge(at, above ? { upper: endpoint } : { lower: endpoint });\n };\n if (is.isIdentifier(conjunct.left)) bound(conjunct.left, conjunct.right, true);\n else if (is.isIdentifier(conjunct.right)) bound(conjunct.right, conjunct.left, false);\n }\n return out;\n}\n\n/**\n * What the precondition says about each of its parameters on its own,\n * read from the arrow's text: see `hintsIn`. A block body gives none.\n */\nexport function hintsOf(arrow: Arrow): Map<number, Hint> {\n if (arrow.block) return new Map();\n return withSourceFile(`(${arrow.body}\\n)`, (sf) => {\n const [first, second] = sf.statements;\n if (second || !first || !is.isExpressionStatement(first)) return new Map();\n let e = first.expression;\n while (is.isParenthesizedExpression(e)) e = e.expression;\n return hintsIn(sf, e, arrow.params);\n });\n}\n\ninterface SpecExport {\n readonly name: string;\n readonly kind: \"forall\" | \"total\";\n readonly fn: string;\n readonly sample?: Arrow;\n readonly when?: Arrow;\n readonly ensures?: Arrow;\n readonly text: string;\n readonly line: number;\n /** The hints the sample and the precondition give, combined per binder index. */\n readonly hints: ReadonlyMap<number, Hint>;\n}\n\nclass SpecFail extends Error {\n readonly line: number;\n constructor(message: string, line: number) {\n super(message);\n this.line = line;\n }\n}\n\n/** The module's exports the spec file imports by name, as `local` to exported `name`. */\ninterface ModuleImport {\n readonly local: string;\n readonly name: string;\n}\n\n/** Read the spec file's exports. */\nfunction readSpecSide(\n sf: SourceFile,\n { program, checker, standardGlobal }: Opened,\n modulePath: string,\n moduleKey: string,\n specSpecifiers: ReadonlySet<string>,\n): { specs: SpecExport[]; errors: SpecError[]; imports: ModuleImport[] } {\n const errors: SpecError[] = [];\n const bound = imports(sf);\n const specs: SpecExport[] = [];\n function fail(message: string, at: Node): never {\n throw new SpecFail(message, lineAt(sf, at));\n }\n // Whether an import's specifier resolves to the module beside the spec file.\n const resolvesToModule = new Map<string, boolean>();\n const fromModule = (imp: Imported): boolean => {\n const known = resolvesToModule.get(imp.from);\n if (known !== undefined) return known;\n const resolved = program.getResolvedModuleFromModuleSpecifier(\n imp.declaration.moduleSpecifier as Parameters<\n Program[\"getResolvedModuleFromModuleSpecifier\"]\n >[0],\n sf.fileName,\n );\n const target = resolved ? program.getSourceFile(resolved.resolvedFileName) : undefined;\n const is = target !== undefined && target.path === moduleKey;\n resolvesToModule.set(imp.from, is);\n return is;\n };\n /** The combinator a callee names (`forall`, `ns.forall`), or undefined. */\n const combinator = (callee: Expression): \"forall\" | \"total\" | undefined => {\n if (is.isPropertyAccessExpression(callee)) {\n if (!is.isIdentifier(callee.expression) || !is.isIdentifier(callee.name)) return undefined;\n const ns = bound.get(callee.expression.text);\n const member = callee.name.text;\n if (\n ns?.name === \"*\" &&\n specSpecifiers.has(ns.from) &&\n (member === \"forall\" || member === \"total\")\n )\n return member;\n return undefined;\n }\n if (!is.isIdentifier(callee)) return undefined;\n const imp = bound.get(callee.text);\n if (imp && specSpecifiers.has(imp.from) && (imp.name === \"forall\" || imp.name === \"total\"))\n return imp.name;\n return undefined;\n };\n /** The module function a first argument names, or why not. */\n const functionArg = (arg: Expression | undefined, call: Node): string => {\n if (!arg)\n return fail(\"the first argument must name a function of the module, found the end\", call);\n if (\n is.isPropertyAccessExpression(arg) &&\n is.isIdentifier(arg.expression) &&\n is.isIdentifier(arg.name)\n ) {\n const ns = bound.get(arg.expression.text);\n if (ns?.name === \"*\" && fromModule(ns)) return arg.name.text;\n return fail(`${textOf(sf, arg)} is not a function imported from the module`, arg);\n }\n if (!is.isIdentifier(arg))\n return fail(\n `the first argument must name a function of the module, found ${textOf(sf, arg)}`,\n arg,\n );\n const imp = bound.get(arg.text);\n if (!imp)\n return fail(\n `${arg.text} is not imported from the module (import it from ./${modulePath.split(\"/\").pop()})`,\n arg,\n );\n if (!fromModule(imp))\n return fail(\n `${arg.text} is imported from ${JSON.stringify(imp.from)}, not from the module beside this spec file`,\n arg,\n );\n if (imp.name === \"*\" || imp.name === \"default\")\n return fail(`${arg.text} must be a named import of the module's function`, arg);\n return imp.name;\n };\n /**\n * A claim is read from its arrow's text alone, where `Math` and `Number`\n * are the globals unless the arrow binds them itself: an arrow naming\n * one that resolves to anything else here (a binding of the spec file,\n * an import, a const of the arrow's own block declared after the use)\n * is refused, so a claim is never read as something it does not\n * compute. A parameter or const of the arrow bound before the use is\n * the arrow reader's own name for it (a parameter named `Math` reads as\n * that parameter), and a binding the claims do not name, or a type-only\n * import, is fine.\n */\n const builtins = (arrow: ArrowFunction, node: Node, what: string): void => {\n if (\n is.isPropertyAccessExpression(node) &&\n is.isIdentifier(node.expression) &&\n (node.expression.text === \"Math\" || node.expression.text === \"Number\") &&\n !standardGlobal(node.expression)\n ) {\n const id = node.expression;\n const bound = checker.getSymbolAtLocation(id)?.declarations[0]?.resolve();\n const own =\n bound !== undefined &&\n bound.getSourceFile() === sf &&\n bound.pos >= arrow.pos &&\n bound.end <= arrow.end &&\n bound.getStart(sf) < id.getStart(sf);\n if (!own) {\n const file = bound?.getSourceFile();\n const where =\n bound && file\n ? ` (bound at line ${lineAt(file, bound)}${file === sf ? \"\" : ` of ${file.fileName}`})`\n : \"\";\n fail(\n `${what} names ${id.text}, which is not the global ${id.text} here${where}; rename the binding`,\n id,\n );\n }\n }\n node.forEachChild((child) => builtins(arrow, child, what));\n };\n /** An arrow function: its params, body text and whether the body is a block. */\n const arrow = (node: Expression, what: string): { arrow: Arrow; node: ArrowFunction } => {\n if (!is.isArrowFunction(node))\n return fail(\n `${what} must be an arrow function, found ${textOf(sf, node).split(/\\s/)[0] ?? \"\"}`,\n node,\n );\n if (isAsync(node)) fail(`${what} is an async arrow; it must be synchronous`, node);\n builtins(node, node.body, what);\n // A rest or destructured parameter has no name of its own: the binder keeps the function's.\n const params = node.parameters.map((p) =>\n !p.dotDotDotToken && is.isIdentifier(p.name) ? p.name.text : null,\n );\n const body = node.body;\n const line = lineAt(sf, node);\n if (is.isBlock(body))\n return {\n arrow: {\n params,\n body: sf.text.slice(body.getStart(sf) + 1, body.end - 1),\n block: true,\n line,\n },\n node,\n };\n return { arrow: { params, body: textOf(sf, body), block: false, line }, node };\n };\n for (const st of sf.statements) {\n if (!is.isVariableStatement(st)) continue;\n const exported = isExported(st);\n const constant = isConst(st.declarationList);\n for (const d of st.declarationList.declarations) {\n if (!is.isIdentifier(d.name) || !d.initializer) continue;\n const name = d.name.text;\n // `satisfies`, `as`, `!` and parentheses change nothing at runtime: the call is inside them.\n let init: Expression = d.initializer;\n while (\n is.isParenthesizedExpression(init) ||\n is.isSatisfiesExpression(init) ||\n is.isAsExpression(init) ||\n is.isNonNullExpression(init)\n )\n init = init.expression;\n if (!is.isCallExpression(init)) continue;\n const kind = combinator(init.expression);\n if (!kind) continue;\n const line = lineAt(sf, st);\n try {\n if (!exported) fail(`${name} is a spec but not exported, so nothing would check it`, st);\n if (!constant)\n fail(\n `a spec must be a const export, not ${textOf(sf, st).split(/\\s/)[exported ? 1 : 0] ?? \"let\"}`,\n st,\n );\n const [first, second, third] = init.arguments;\n const fn = functionArg(first, init);\n if (kind === \"total\") {\n if (second) fail(\"total takes the function alone\", second);\n specs.push({ name, kind: \"total\", fn, text: `total(${fn})`, line, hints: new Map() });\n continue;\n }\n if (!second) return fail(\"forall takes the function, then { when, ensures }\", init);\n if (third) return fail(`unexpected ${textOf(sf, third)} after forall's arguments`, third);\n if (!is.isObjectLiteralExpression(second))\n return fail(\n \"forall's second argument must be an object literal { when, ensures }\",\n second,\n );\n let sample: { arrow: Arrow; node: ArrowFunction } | undefined;\n let when: { arrow: Arrow; node: ArrowFunction } | undefined;\n let ensures: { arrow: Arrow; node: ArrowFunction } | undefined;\n for (const prop of second.properties) {\n const key =\n is.isPropertyAssignment(prop) ||\n is.isShorthandPropertyAssignment(prop) ||\n is.isMethodDeclaration(prop)\n ? prop.name\n : undefined;\n const keyName =\n key && is.isIdentifier(key) ? key.text : key ? textOf(sf, key) : textOf(sf, prop);\n if (keyName !== \"sample\" && keyName !== \"when\" && keyName !== \"ensures\")\n fail(`forall's properties are sample, when and ensures, found ${keyName}`, prop);\n if (!is.isPropertyAssignment(prop))\n fail(`${keyName} must be written as ${keyName}: (…) => …`, prop);\n const read = arrow(prop.initializer, keyName);\n if (keyName === \"sample\") {\n if (sample) fail(\"sample is given twice\", prop);\n sample = read;\n } else if (keyName === \"when\") {\n if (when) fail(\"when is given twice\", prop);\n when = read;\n } else {\n if (ensures) fail(\"ensures is given twice\", prop);\n ensures = read;\n }\n }\n if (!ensures) return fail(\"forall needs an ensures\", second);\n // The precondition and the sample both steer the draws, combined per binder.\n const hintsOfArrow = (\n a: { arrow: Arrow; node: ArrowFunction } | undefined,\n ): Map<number, Hint> =>\n a && !is.isBlock(a.node.body) ? hintsIn(sf, a.node.body, a.arrow.params) : new Map();\n const fromSample = hintsOfArrow(sample);\n const fromWhen = hintsOfArrow(when);\n const hints = new Map<number, Hint>();\n for (const i of new Set([...fromSample.keys(), ...fromWhen.keys()])) {\n const h = combineHints(fromWhen.get(i), fromSample.get(i));\n if (h) hints.set(i, h);\n }\n specs.push({\n name,\n kind: \"forall\",\n fn,\n ...(sample ? { sample: sample.arrow } : {}),\n ...(when ? { when: when.arrow } : {}),\n ensures: ensures.arrow,\n text: ensures.arrow.body.replace(/\\s+/g, \" \").trim(),\n line,\n hints,\n });\n } catch (err) {\n if (!(err instanceof SpecFail)) throw err;\n errors.push({ line: err.line, message: `${name}: ${err.message}` });\n }\n }\n }\n const moduleImports: ModuleImport[] = [...bound]\n .filter(([, imp]) => imp.name !== \"*\" && imp.name !== \"default\" && fromModule(imp))\n .map(([local, imp]) => ({ local, name: imp.name }));\n return { specs, errors, imports: moduleImports };\n}\n\n/** The tighter of two endpoints on one side; the first when they cannot be compared. */\nfunction tighter(\n first: Endpoint | undefined,\n second: Endpoint | undefined,\n side: \"lower\" | \"upper\",\n): Endpoint | undefined {\n if (!first) return second;\n if (!second) return first;\n // Integral literals compare exactly (bigints reach past every double); others as doubles.\n const integral = (e: Endpoint) => !/[.eE]/.test(e.value);\n let order: number;\n try {\n if (integral(first) && integral(second)) {\n const a = endpointBigInt(first.value);\n const b = endpointBigInt(second.value);\n order = a === b ? 0 : a > b ? 1 : -1;\n } else {\n const a = endpointNumber(first.value);\n const b = endpointNumber(second.value);\n if (Number.isNaN(a) || Number.isNaN(b)) return first;\n order = a === b ? 0 : a > b ? 1 : -1;\n }\n } catch {\n return first;\n }\n if (order !== 0) return (side === \"lower\" ? order > 0 : order < 0) ? first : second;\n return first.inclusive ? second : first;\n}\n\n/**\n * Two hints on one binder as one: integer when either says so, the\n * tighter bound on each side, the first's regex (two cannot be combined,\n * and the draws are checked against both arrows anyway).\n */\nfunction combineHints(first: Hint | undefined, second: Hint | undefined): Hint | undefined {\n if (!first) return second;\n if (!second) return first;\n const lower = tighter(first.lower, second.lower, \"lower\");\n const upper = tighter(first.upper, second.upper, \"upper\");\n const regex = first.regex ?? second.regex;\n return {\n ...(first.integer || second.integer ? { integer: true as const } : {}),\n ...(lower ? { lower } : {}),\n ...(upper ? { upper } : {}),\n ...(regex ? { regex } : {}),\n };\n}\n\n/** Read a module and its spec file. */\nexport function readSpecs(input: ReadSpecsInput): ModuleSpecs {\n const modulePath = input.modulePath;\n const specPath = input.specPath ?? modulePath.replace(/\\.ts$/, \".props.ts\");\n return withProgram(\n [\n { path: modulePath, text: input.module },\n { path: specPath, text: input.spec },\n ],\n (opened) => {\n const { checker, file, parseError } = opened;\n const moduleError = parseError(modulePath);\n const specError = parseError(specPath);\n const errors: SpecError[] = [];\n if (moduleError)\n errors.push({\n line: moduleError.line,\n message: `the module could not be parsed: ${moduleError.message}`,\n inModule: true,\n });\n if (specError)\n errors.push({\n line: specError.line,\n message: `the spec file could not be parsed: ${specError.message}`,\n });\n if (moduleError || specError) return { functions: [], errors };\n const moduleFile = file(modulePath);\n const moduleSide = readModuleSide(moduleFile, checker);\n const specSide = readSpecSide(\n file(specPath),\n opened,\n modulePath,\n moduleFile.path,\n new Set(input.specSpecifiers ?? [\"eutaxy/spec\", \"@eutaxy/spec\"]),\n );\n errors.push(...moduleSide.errors, ...specSide.errors);\n // The spec file runs whenever it is imported (the TESTED rung imports it): an assignment to a\n // built-in there makes the claims compute something other than what they are read as.\n const patched = rebound(file(specPath), checker, opened.standardGlobal);\n if (patched)\n errors.push({\n line: patched.line,\n message: `the spec file assigns to ${patched.target}, so the built-ins its claims are read with may not be the standard ones`,\n });\n // The claims' free names: the spec file's local names for the module's declarations.\n const imports = specSide.imports.flatMap((i) => {\n const fn = moduleSide.exports.get(i.name);\n return fn === undefined ? [] : [{ local: i.local, fn }];\n });\n const byFunction = new Map<string, { decl: Declaration; properties: Property[] }>();\n for (const s of specSide.specs) {\n const local = moduleSide.exports.get(s.fn);\n const decl = local === undefined ? undefined : moduleSide.declarations.get(local);\n if (!decl) {\n errors.push({\n line: s.line,\n message: `${s.name}: the module exports no function ${s.fn} whose parameters the reader can read (a function declaration or a const arrow)`,\n });\n continue;\n }\n const entry = byFunction.get(s.fn) ?? { decl, properties: [] };\n if (entry.properties.some((p) => p.name === s.name)) {\n errors.push({ line: s.line, message: `${s.name} is exported twice` });\n continue;\n }\n const binders: Binder[] = decl.params.map((p, i) => {\n const fromEnsures = s.ensures?.params[i];\n const name = fromEnsures ?? p.name ?? `arg${i}`;\n const hint = s.hints.get(i);\n return { name, type: p.type, ...(hint ? { hint } : {}) };\n });\n entry.properties.push({\n name: s.name,\n kind: s.kind,\n binders,\n ...(s.sample ? { sample: s.sample } : {}),\n ...(s.when ? { when: s.when } : {}),\n ...(s.ensures ? { ensures: s.ensures } : {}),\n imports,\n text: s.text,\n line: s.line,\n });\n byFunction.set(s.fn, entry);\n }\n const functions: FunctionSpec[] = [...byFunction.entries()].map(\n ([name, { decl, properties }]) => ({\n name,\n params: decl.params,\n properties,\n line: decl.line,\n offset: decl.offset,\n }),\n );\n return { functions, errors };\n },\n );\n}\n","/**\n * Where a pinned prover toolchain lives on this machine once `eutaxy prover\n * install` has put it there, and what that command downloads: one upstream\n * release file per platform, with the checksum the download must match.\n * Node-side only (`@eutaxy/prover/toolchain`, a subpath so workerd never\n * loads it): it reads the file system, so this file alone references Node's\n * types, as the reader alone uses the compiler's. Nothing here downloads or\n * runs anything; the engines ask `installed` and the command does the rest.\n */\n/// <reference types=\"node\" />\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\n\n/** The platforms Eutaxy runs a prover on: Node's `process.platform-process.arch`. */\nexport type Platform = \"linux-x64\" | \"linux-arm64\" | \"darwin-x64\" | \"darwin-arm64\" | \"win32-x64\";\nexport const platforms: readonly Platform[] = [\n \"linux-x64\",\n \"linux-arm64\",\n \"darwin-x64\",\n \"darwin-arm64\",\n \"win32-x64\",\n];\n\n/** One file of an upstream release: where it is, what it must hash to, how big it is. */\nexport interface ReleaseFile {\n /** The file's name in the release, which a mirror or offline copy keeps. */\n readonly file: string;\n readonly url: string;\n /** Lower-case hex SHA-256 of the file. */\n readonly sha256: string;\n readonly bytes: number;\n /**\n * For a zip, the files taken from it, each path in the archive mapped to\n * its path under the toolchain directory; nothing else in the zip is\n * unpacked. A zip must list them. A `tar.zst` is unpacked whole.\n */\n readonly entries?: Readonly<Record<string, string>>;\n}\n\n/** A prover toolchain as `eutaxy prover install` knows it. */\nexport interface Toolchain {\n /** The name the command takes: the engine's. */\n readonly name: string;\n readonly version: string;\n /** The executable inside the unpacked release, relative to its root; `.exe` is added on Windows. */\n readonly executable: string;\n readonly files: Readonly<Partial<Record<Platform, ReleaseFile>>>;\n}\n\n/** What of the machine the lookup depends on, so tests can hand in another. */\nexport interface Host {\n readonly platform: string;\n readonly arch: string;\n readonly env: Readonly<Record<string, string | undefined>>;\n readonly home: string;\n}\n\nexport function host(): Host {\n return { platform: process.platform, arch: process.arch, env: process.env, home: homedir() };\n}\n\nexport function platformOf(h: Host): Platform | undefined {\n const key = `${h.platform}-${h.arch}`;\n return (platforms as readonly string[]).includes(key) ? (key as Platform) : undefined;\n}\n\n/**\n * Eutaxy's cache directory: `EUTAXY_CACHE_DIR`, else the platform's user\n * cache (`$XDG_CACHE_HOME/eutaxy` or `~/.cache/eutaxy` on Linux,\n * `~/Library/Caches/eutaxy` on macOS, `%LOCALAPPDATA%\\eutaxy\\Cache` on\n * Windows). Always absolute: the engines spawn the executable from a\n * scratch directory, where a relative path would not resolve.\n */\nexport function cacheDir(h: Host = host()): string {\n const set = h.env[\"EUTAXY_CACHE_DIR\"];\n if (set) return resolve(set);\n if (h.platform === \"darwin\") return join(h.home, \"Library\", \"Caches\", \"eutaxy\");\n if (h.platform === \"win32\")\n return join(h.env[\"LOCALAPPDATA\"] || join(h.home, \"AppData\", \"Local\"), \"eutaxy\", \"Cache\");\n return resolve(h.env[\"XDG_CACHE_HOME\"] || join(h.home, \".cache\"), \"eutaxy\");\n}\n\n/** Where one toolchain's unpacked release lives: `<cache>/toolchains/<name>/<version>`. */\nexport function toolchainDir(\n cache: string,\n toolchain: Pick<Toolchain, \"name\" | \"version\">,\n): string {\n return join(cache, \"toolchains\", toolchain.name, toolchain.version);\n}\n\n/** The file the command writes last, so its presence means the install completed. */\nexport const markerFile = \"eutaxy-toolchain.json\";\n\nexport interface InstallMarker {\n readonly name: string;\n readonly version: string;\n readonly platform: Platform;\n readonly file: string;\n readonly sha256: string;\n /** Where the file came from: the upstream URL, or the mirror or directory given. */\n readonly source: string;\n}\n\nexport function executableName(toolchain: Pick<Toolchain, \"executable\">, h: Host): string {\n return h.platform === \"win32\" ? `${toolchain.executable}.exe` : toolchain.executable;\n}\n\nexport interface Installed {\n readonly dir: string;\n readonly executable: string;\n readonly marker: InstallMarker;\n}\n\n/**\n * The toolchain the command put in the cache, if its marker and its\n * executable are both there and the marker names this toolchain for this\n * platform (a cache carried to another machine holds the wrong binary).\n */\nexport function installed(toolchain: Toolchain, h: Host = host()): Installed | undefined {\n const dir = toolchainDir(cacheDir(h), toolchain);\n const executable = join(dir, executableName(toolchain, h));\n const markerPath = join(dir, markerFile);\n if (!existsSync(markerPath) || !existsSync(executable)) return undefined;\n try {\n const marker = JSON.parse(readFileSync(markerPath, \"utf8\")) as Partial<InstallMarker>;\n if (\n marker.name !== toolchain.name ||\n marker.version !== toolchain.version ||\n marker.platform !== platformOf(h) ||\n typeof marker.file !== \"string\" ||\n typeof marker.sha256 !== \"string\" ||\n typeof marker.source !== \"string\"\n )\n return undefined;\n return { dir, executable, marker: marker as InstallMarker };\n } catch {\n return undefined;\n }\n}\n","/**\n * Lean's toolchain comes through elan, Lean's own toolchain manager. This\n * file holds what `eutaxy prover install lean` and the engine share about\n * it: the pinned elan installer (`elanDownloads`, fetched only when no elan\n * is on the machine), where Eutaxy keeps an elan of its own (`elanHome`,\n * inside Eutaxy's cache), the elans the engine and the command look for\n * (`elanCandidates`), and the digest of the pinned toolchain's files\n * (`leanDigests`, `toolchainDigest`), which the command checks after elan\n * has installed it, since elan does not check the toolchain it downloads\n * against a pinned checksum.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { readdirSync, readFileSync, readlinkSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, relative, sep } from \"node:path\";\nimport { cacheDir, type Host, type Platform, type Toolchain } from \"@eutaxy/prover/toolchain\";\n\n/** The elan release whose installer the command fetches when the machine has no elan. */\nexport const elanVersion = \"4.2.4\";\n\nconst elanRelease = `https://github.com/leanprover/elan/releases/download/v${elanVersion}`;\nconst elanFile = (name: string, sha256: string, bytes: number) => {\n // Each archive holds the one installer, at its root.\n const installer = name.endsWith(\".zip\") ? \"elan-init.exe\" : \"elan-init\";\n return {\n file: name,\n url: `${elanRelease}/${name}`,\n sha256,\n bytes,\n entries: { [installer]: installer },\n };\n};\n/**\n * The upstream elan installer for each platform, as published on elan's\n * GitHub release with the checksums it reports; a test holds the file\n * names to `elanVersion`. The installer links only system libraries.\n */\nexport const elanDownloads: Toolchain = {\n name: \"elan\",\n version: elanVersion,\n executable: \"elan-init\",\n files: {\n \"linux-x64\": elanFile(\n \"elan-x86_64-unknown-linux-gnu.tar.gz\",\n \"42b94d4244e8353142c456ec0e4ca6528fd898a6c604d4059f494e706e431f63\",\n 4996571,\n ),\n \"linux-arm64\": elanFile(\n \"elan-aarch64-unknown-linux-gnu.tar.gz\",\n \"05febd124d84ebf994b2e7479922a5650b1e950c17ae3bd1ddd776b65bb72bf9\",\n 5131114,\n ),\n \"darwin-x64\": elanFile(\n \"elan-x86_64-apple-darwin.tar.gz\",\n \"8a340b309d8ed2e96f930761fa223b3af57a38f5d253b53ac90293c9516f8cd4\",\n 2330818,\n ),\n \"darwin-arm64\": elanFile(\n \"elan-aarch64-apple-darwin.tar.gz\",\n \"7ad829861392c718dfebde3a83b5c8508df47be02af68894b094b0b3952616e5\",\n 2190845,\n ),\n \"win32-x64\": elanFile(\n \"elan-x86_64-pc-windows-msvc.zip\",\n \"fad2e980a191c15884cc1d80d170ffc5fa84f3774541020145b66d1a644c6111\",\n 2508099,\n ),\n },\n};\n\n/** Where Eutaxy's own elan keeps itself and its toolchains: `<cache>/elan`. */\nexport function elanHome(h: Host): string {\n return join(cacheDir(h), \"elan\");\n}\n\n/** An elan to run, with the environment it needs (`ELAN_HOME` for Eutaxy's own). */\nexport interface Elan {\n readonly command: string;\n readonly env?: Readonly<Record<string, string>>;\n}\n\n/**\n * The elans to try, in order: Eutaxy's own in the cache, then the one on\n * the PATH, then the one in elan's home (`ELAN_HOME`, else `~/.elan`).\n */\nexport function elanCandidates(h: Host): Elan[] {\n const exe = h.platform === \"win32\" ? \"elan.exe\" : \"elan\";\n const own = elanHome(h);\n const home = h.env[\"ELAN_HOME\"] || join(h.home || homedir(), \".elan\");\n return [\n { command: join(own, \"bin\", exe), env: { ELAN_HOME: own } },\n { command: \"elan\" },\n { command: join(home, \"bin\", exe) },\n ];\n}\n\n/**\n * The pinned toolchain's `toolchainDigest`, per platform: computed over\n * Lean's GitHub release file for that platform, checked against the\n * checksum the release reports, and unpacked. elan installs exactly that\n * release (on macOS arm64 the digest of an elan-installed toolchain was\n * checked to equal it), so a toolchain elan installed whose digest differs\n * is not the pinned one.\n */\nexport const leanDigests: Readonly<Record<Platform, string>> = {\n \"linux-x64\": \"d6bb6c4de1fce52bc5d88ff52f7fcf7d347ee5b3ba7d187de775ccf915714c35\",\n \"linux-arm64\": \"1bcaf2cf93006e3017a07234e3a33ba8bd1dec404e7dc0e4c202111b0bf2be41\",\n \"darwin-x64\": \"b817cf3c90432b774405bad998bad5985f0ef9594d1c31aeddb3df6479c1bd0c\",\n \"darwin-arm64\": \"2a31778d0185a17655be5f97e6e930dd0ece0d1db9f41a2825f500b3ca8c5c0a\",\n \"win32-x64\": \"441877e59afc80b7af1f1b6fc3db64b2c947d581de26a040486387aa4ec7a3cb\",\n};\n\nexport interface ToolchainDigest {\n readonly digest: string;\n readonly files: number;\n readonly bytes: number;\n}\n\n/**\n * A digest of everything under a toolchain's directory: one line per file\n * (`<sha256> <path>`) and per link (`-> <target> <path>`), paths relative\n * and with `/`, sorted, the whole hashed. Directories count only through\n * what they hold.\n */\nexport function toolchainDigest(prefix: string): ToolchainDigest {\n const lines: (readonly [string, string])[] = [];\n let files = 0;\n let bytes = 0;\n for (const entry of readdirSync(prefix, { recursive: true, withFileTypes: true })) {\n const at = join(entry.parentPath, entry.name);\n const path = relative(prefix, at).split(sep).join(\"/\");\n if (entry.isSymbolicLink()) lines.push([path, `-> ${readlinkSync(at)} ${path}`]);\n else if (entry.isFile()) {\n const data = readFileSync(at);\n files++;\n bytes += data.length;\n lines.push([path, `${createHash(\"sha256\").update(data).digest(\"hex\")} ${path}`]);\n }\n }\n lines.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return {\n digest: createHash(\"sha256\")\n .update(`${lines.map(([, line]) => line).join(\"\\n\")}\\n`)\n .digest(\"hex\"),\n files,\n bytes,\n };\n}\n","/**\n * Lean 4 for a module in the subset and the properties on it. The\n * module's record types become structures, its functions definitions over\n * `Int`, `Bool` and `String`, each property a theorem whose statement is\n * the claim over its binders, with the precondition as a hypothesis.\n * Booleans stay `Bool` in terms, as in TypeScript, and become propositions\n * with `= true` where a statement needs one; comparisons are `decide`d.\n * Every theorem is closed by one tactic script, except where a proof is\n * supplied beside the spec file (`supplied.ts`): then the statement is\n * fixed as a definition first, and the supplied tactics must prove it.\n */\n\nimport {\n children,\n type Expr,\n hasLoneSurrogate,\n OutsideSubset,\n type RecordType,\n readArrowBody,\n renameVars,\n type SubsetFunction,\n type SubsetModule,\n type SubsetType,\n type TypeContext,\n typeOf,\n} from \"@eutaxy/prover/reader\";\nimport { type Arrow, describeType, type Property, type SpecType } from \"@eutaxy/spec\";\n\n/**\n * TypeScript names as Lean identifiers that can clash with nothing Lean\n * defines and not with each other: functions get `f_`, record types `R_`,\n * variables `v_`, theorems `t_`. The schemes differ in their first letter,\n * so no two names from different kinds coincide whatever the author\n * wrote (`ts_f` and `f_` would, under suffixing), and Lean's prelude has\n * no names of these shapes, so a function called `decide` or a parameter\n * called `max` stays what the author meant.\n */\nexport const ident = {\n fn: (name: string) => quote(`f_${name}`),\n record: (name: string) => quote(`R_${name}`),\n variable: (name: string) => quote(`v_${name}`),\n // Fields keep their names, which may be Lean keywords: those are quoted.\n field: (name: string) => (leanKeywords.has(name) ? `«${name}»` : quote(name)),\n};\n\n/** Lean's keywords, which a field name may coincide with. */\nconst leanKeywords = new Set(\n \"at by calc def deriving do else end example export extends from fun have if import in inductive instance lemma let macro match mutual namespace open private protected return section set_option show structure syntax termination_by then theorem universe variable where with abbrev axiom class opaque partial noncomputable unsafe nomatch nofun omit include local scoped attribute initialize builtin_initialize elab notation infix infixl infixr prefix postfix declare_syntax_cat macro_rules elab_rules syntax_rules suffices obtain exists forall Type Prop Sort true false fun\".split(\n \" \",\n ),\n);\n\nfunction quote(name: string): string {\n // Guillemets hold anything but guillemets: those are escaped as `%ab` and `%bb`, with `%` itself\n // as `%25` first, in every name, so two names never meet in one identifier.\n const escaped = name.replace(/%/g, \"%25\").replace(/«/g, \"%ab\").replace(/»/g, \"%bb\");\n return /^[A-Za-z_][A-Za-z0-9_]*$/.test(escaped) ? escaped : `«${escaped}»`;\n}\n\nfunction leanType(t: SubsetType): string {\n switch (t.kind) {\n case \"int\":\n return \"Int\";\n case \"bool\":\n return \"Bool\";\n case \"string\":\n return \"String\";\n case \"record\":\n return ident.record(t.name);\n case \"list\":\n return `(List ${leanType(t.element)})`;\n case \"nothing\":\n return fail(\"the element type of an empty array, which nothing gives\");\n case \"nullable\":\n case \"union\":\n case \"null\":\n return fail(`a ${t.kind} type, which the Lean engine does not take yet`);\n }\n}\n\nexport function emitRecord(r: RecordType): string {\n return [\n `structure ${ident.record(r.name)} where`,\n ...r.fields.map((f) => ` ${ident.field(f.name)} : ${leanType(f.type)}`),\n \" deriving Repr, DecidableEq\",\n ].join(\"\\n\");\n}\n\ninterface Env {\n readonly module: SubsetModule;\n readonly ctx: TypeContext;\n /**\n * In the non-empty branch of a structurally recursive function: the list\n * parameter is `head :: tail` there, so `xs[0] ?? d` is the head,\n * `xs.slice(1)` the tail (what the recursive call must be given for Lean\n * to see the recursion is structural), and `xs` itself `head :: tail`.\n */\n readonly cons?: { readonly list: string; readonly head: string; readonly tail: string };\n}\n\nfunction env(module: SubsetModule): Env {\n return {\n module,\n ctx: {\n records: new Map(module.records.map((r) => [r.name, r])),\n unions: module.unions,\n signatures: new Map(\n module.functions.map((f) => [f.name, { params: f.params, returns: f.returns }]),\n ),\n },\n };\n}\n\nexport const divisionOutside =\n \"division other than Math.floor(x / c) with c a positive integer constant: this engine models numbers as integers, which / leaves (the SMT engine takes it)\";\n\n/** Whether an expression divides other than as Math.floor(x / c), c a positive integer constant. */\nexport function dividesOutside(e: Expr): boolean {\n if (e.kind === \"floor\" && e.operand.kind === \"binary\" && e.operand.op === \"/\") {\n const c = integerValue(e.operand.right);\n if (c !== undefined && c > 0n) return dividesOutside(e.operand.left);\n }\n if (e.kind === \"binary\" && e.op === \"/\") return true;\n return children(e).some(dividesOutside);\n}\n\n/** The value of an integer expression built from literals by + - * and negation, if it is one. */\nfunction integerValue(e: Expr): bigint | undefined {\n if (e.kind === \"int\") return BigInt(e.value);\n if (e.kind === \"neg\") {\n const v = integerValue(e.operand);\n return v === undefined ? undefined : -v;\n }\n if (e.kind !== \"binary\") return undefined;\n const l = integerValue(e.left);\n const r = integerValue(e.right);\n if (l === undefined || r === undefined) return undefined;\n if (e.op === \"+\") return l + r;\n if (e.op === \"-\") return l - r;\n if (e.op === \"*\") return l * r;\n return undefined;\n}\n\nconst fail: (message: string) => never = (message) => {\n throw new OutsideSubset(message, 0);\n};\n\n/** A term of the expression's TypeScript type: `Int`, `Bool`, `String` or a structure. */\nexport function term(e: Expr, scope: ReadonlyMap<string, SubsetType>, env: Env): string {\n const t = (x: Expr) => term(x, scope, env);\n switch (e.kind) {\n case \"int\":\n return `(${e.value} : Int)`;\n case \"bool\":\n return e.value ? \"true\" : \"false\";\n case \"string\":\n return leanString(e.value);\n case \"var\":\n if (env.cons?.list === e.name) return `(${env.cons.head} :: ${env.cons.tail})`;\n return ident.variable(e.name);\n case \"null\":\n case \"narrow\":\n return fail(\"null, which the Lean engine does not take yet\");\n case \"narrowTag\":\n return fail(\"a union, which the Lean engine does not take yet\");\n case \"neg\":\n return `(-${t(e.operand)})`;\n case \"not\":\n return `(!${t(e.operand)})`;\n case \"isInteger\":\n // Every number is an integer in this engine's model. The operand is still emitted, so what\n // this engine refuses in it (a division) is refused here too, not dropped with it.\n typeOf(e.operand, scope, env.ctx, fail);\n t(e.operand);\n return \"true\";\n case \"floor\": {\n // Of an integer, Math.floor is the integer; of x / c, with c a positive integer constant, it is\n // Lean's Int division, which rounds toward negative infinity as Math.floor does.\n const o = e.operand;\n if (o.kind !== \"binary\" || o.op !== \"/\") return t(o);\n const c = integerValue(o.right);\n if (c === undefined || c <= 0n) fail(divisionOutside);\n return `(${t(o.left)} / (${c} : Int))`;\n }\n case \"binary\":\n switch (e.op) {\n case \"+\": {\n const lt = typeOf(e.left, scope, env.ctx, fail);\n return `(${t(e.left)} ${lt.kind === \"string\" ? \"++\" : \"+\"} ${t(e.right)})`;\n }\n case \"-\":\n case \"*\":\n return `(${t(e.left)} ${e.op} ${t(e.right)})`;\n case \"/\":\n return fail(divisionOutside);\n case \"<\":\n case \">\":\n return `(decide (${t(e.left)} ${e.op} ${t(e.right)}))`;\n case \"<=\":\n return `(decide (${t(e.left)} ≤ ${t(e.right)}))`;\n case \">=\":\n return `(decide (${t(e.left)} ≥ ${t(e.right)}))`;\n case \"===\":\n case \"!==\": {\n // === on objects compares references in JavaScript; Lean's = would compare the fields.\n const lt = typeOf(e.left, scope, env.ctx, fail);\n if (lt.kind === \"record\")\n fail(\n `${e.op} on records compares references in JavaScript; compare their fields instead`,\n );\n return `(decide (${t(e.left)} ${e.op === \"===\" ? \"=\" : \"≠\"} ${t(e.right)}))`;\n }\n case \"&&\":\n return `(${t(e.left)} && ${t(e.right)})`;\n case \"||\":\n return `(${t(e.left)} || ${t(e.right)})`;\n }\n break;\n case \"cond\":\n return `(if ${t(e.test)} = true then ${t(e.ifTrue)} else ${t(e.ifFalse)})`;\n case \"call\":\n return `(${ident.fn(e.callee)}${e.args.map((a) => ` ${t(a)}`).join(\"\")})`;\n case \"field\":\n // A list's length is a natural number in Lean; the subset counts in Int.\n if (typeOf(e.object, scope, env.ctx, fail).kind === \"list\")\n return `(Int.ofNat (List.length ${t(e.object)}))`;\n return `${t(e.object)}.${ident.field(e.field)}`;\n case \"record\": {\n const type = typeOf(e, scope, env.ctx, fail);\n const name =\n type.kind === \"record\"\n ? ident.record(type.name)\n : fail(\"a record literal of no record type\");\n return `({ ${e.fields.map((f) => `${ident.field(f.name)} := ${t(f.value)}`).join(\", \")} } : ${name})`;\n }\n case \"let\": {\n const inner = new Map(scope);\n const bound = e.type ?? typeOf(e.value, scope, env.ctx, fail);\n inner.set(e.name, bound);\n // The annotation, when there is one, types the binding in Lean too (`const xs: number[] = []`).\n const annotated = e.type ? ` : ${leanType(e.type)}` : \"\";\n return `(let ${ident.variable(e.name)}${annotated} := ${t(e.value)}; ${term(e.body, inner, env)})`;\n }\n case \"list\": {\n if (e.items.length === 0 && !e.rest) return \"[]\";\n if (!e.rest) return `[${e.items.map(t).join(\", \")}]`;\n return `(${[...e.items.map(t), t(e.rest)].join(\" :: \")})`;\n }\n case \"tail\":\n if (e.list.kind === \"var\" && env.cons?.list === e.list.name) return env.cons.tail;\n return `(List.tail ${t(e.list)})`;\n case \"headOr\":\n if (e.list.kind === \"var\" && env.cons?.list === e.list.name) return env.cons.head;\n return `(List.headD ${t(e.list)} ${t(e.fallback)})`;\n case \"iterate\": {\n const listType = typeOf(e.list, scope, env.ctx, fail);\n if (listType.kind !== \"list\") fail(`${e.op} on a ${listType.kind}`);\n const inner = new Map(scope);\n inner.set(e.item, listType.element);\n if (e.index !== undefined) inner.set(e.index, { kind: \"int\" });\n const body = term(e.body, inner, env);\n // The index counts from 0 as a natural number; the subset's is an Int.\n const nat = e.index === undefined ? \"\" : quote(`nv_${e.index}`);\n const fn =\n e.index === undefined\n ? `(fun ${ident.variable(e.item)} => ${body})`\n : `(fun (${ident.variable(e.item)}, ${nat}) => let ${ident.variable(e.index)} := Int.ofNat ${nat}; ${body})`;\n const list = e.index === undefined ? t(e.list) : `(List.zipIdx ${t(e.list)})`;\n // map and flatMap take the function first; all and any take the list first.\n if (e.op === \"map\") return `(List.map ${fn} ${list})`;\n if (e.op === \"flatMap\") return `(List.flatMap ${fn} ${list})`;\n return `(${e.op === \"every\" ? \"List.all\" : \"List.any\"} ${list} ${fn})`;\n }\n case \"fold\": {\n const listType = typeOf(e.list, scope, env.ctx, fail);\n if (listType.kind !== \"list\") fail(`reduce on a ${listType.kind}`);\n const inner = new Map(scope);\n inner.set(e.acc, typeOf(e, scope, env.ctx, fail));\n inner.set(e.item, listType.element);\n return `(List.foldl (fun ${ident.variable(e.acc)} ${ident.variable(e.item)} => ${term(e.body, inner, env)}) ${t(e.init)} ${t(e.list)})`;\n }\n }\n}\n\nexport function emitFunction(f: SubsetFunction, module: SubsetModule): string {\n const e = env(module);\n const scope = new Map(f.params.map((p) => [p.name, p.type]));\n const params = f.params.map((p) => `(${ident.variable(p.name)} : ${leanType(p.type)})`).join(\" \");\n const head = `def ${ident.fn(f.name)} ${params} : ${leanType(f.returns)} :=`;\n if (f.structural === undefined || f.body.kind !== \"cond\")\n return `${head}\\n ${term(f.body, scope, e)}`;\n // Structural recursion: a match on the list the body tests against 0, recursing on its tail.\n // `vh_`/`vt_` names cannot meet a variable, whose names all start `v_`.\n const list = (f.params[f.structural] as { name: string }).name;\n const cons = { list, head: quote(`vh_${list}`), tail: quote(`vt_${list}`) };\n return [\n head,\n ` match ${ident.variable(list)} with`,\n ` | [] => ${term(f.body.ifTrue, scope, e)}`,\n ` | ${cons.head} :: ${cons.tail} => ${term(f.body.ifFalse, scope, { ...e, cons })}`,\n ].join(\"\\n\");\n}\n\n/**\n * The subset type a binder ranges over, or `OutsideSubset`: `number` is\n * `Int` (the engine's integer model, an assumption every PROVEN carries),\n * a union of string literals is `String` (the proof covers every string,\n * more than the type admits), a record is the module's structure of that\n * name. Nullable types, tagged unions, bigint and whatever the reader\n * could not read are outside.\n */\nexport function binderType(name: string, t: SpecType, module: SubsetModule): SubsetType {\n switch (t.kind) {\n case \"number\":\n return { kind: \"int\" };\n case \"boolean\":\n return { kind: \"bool\" };\n case \"string\":\n return { kind: \"string\" };\n case \"literal\":\n if (typeof t.value === \"string\") return { kind: \"string\" };\n if (typeof t.value === \"boolean\") return { kind: \"bool\" };\n return { kind: \"int\" };\n case \"bigint\":\n // A BigInt passed to a function over number throws on the first mixed operation in JavaScript.\n fail(`binder ${name} over bigint: the subset has no bigint`);\n break;\n case \"union\":\n if (t.members.every((m) => m.kind === \"literal\" && typeof m.value === \"string\"))\n return { kind: \"string\" };\n if (t.members.some((m) => m.kind === \"null\" || m.kind === \"undefined\"))\n fail(\n `binder ${name} over ${describeType(t)}: nullable types are not in the engine's subset yet`,\n );\n fail(`binder ${name} over ${describeType(t)}: unions are not in the engine's subset yet`);\n break;\n case \"record\":\n if (t.name !== undefined && module.records.some((r) => r.name === t.name))\n return { kind: \"record\", name: t.name };\n fail(\n `binder ${name} over ${describeType(t)}: ${t.name === undefined ? \"an inline record type\" : `record type ${t.name} is outside the subset`}`,\n );\n break;\n case \"null\":\n case \"undefined\":\n fail(`binder ${name} over ${t.kind}`);\n break;\n case \"array\":\n return { kind: \"list\", element: binderType(name, t.element, module) };\n case \"unknown\":\n fail(`binder ${name} over ${t.text}, which the reader could not read`);\n }\n}\n\n/** An arrow of the spec file as a Bool term over the binders, its own parameter names renamed to theirs. */\nfunction arrowTerm(\n arrow: Arrow,\n what: \"when\" | \"ensures\",\n property: Property,\n types: readonly SubsetType[],\n e: Env,\n): string {\n try {\n return arrowTermAt(arrow, what, property, types, e);\n } catch (err) {\n // What the subset refused, located in the spec file.\n if (!(err instanceof OutsideSubset)) throw err;\n throw new OutsideSubset(`${what} (spec file line ${arrow.line}): ${err.message}`, arrow.line);\n }\n}\n\nfunction arrowTermAt(\n arrow: Arrow,\n what: \"when\" | \"ensures\",\n property: Property,\n types: readonly SubsetType[],\n e: Env,\n): string {\n const binders = property.binders;\n const scope = new Map<string, SubsetType>();\n const names = new Map<string, string>();\n arrow.params.forEach((p, i) => {\n const binder = binders[i];\n const type = types[i];\n if (p === null) fail(`a destructured parameter in ${what}`);\n if (!binder || !type) fail(`${what} takes more parameters than the function has`);\n scope.set(p, type);\n names.set(p, binder.name);\n });\n const aliases = new Map(property.imports.map((i) => [i.local, i.fn]));\n const read = readArrowBody(arrow, scope, e.module, aliases);\n const t = typeOf(read, scope, e.ctx, fail);\n if (t.kind !== \"bool\")\n fail(`${what} is not boolean (a ${t.kind === \"record\" ? t.name : t.kind})`);\n const renamed = renameVars(read, names);\n const binderScope = new Map(binders.map((b, i) => [b.name, types[i] as SubsetType]));\n return term(renamed, binderScope, e);\n}\n\n/** The proposition a property claims: binders universally quantified, the precondition in front. */\nexport function statement(property: Property, module: SubsetModule): string {\n return stated(property, module).text;\n}\n\n/** The statement and how many hypotheses stand before the claim (the tactic script introduces them by name). */\nexport function stated(\n property: Property,\n module: SubsetModule,\n): { readonly text: string; readonly hypotheses: number } {\n if (property.kind !== \"forall\" || !property.ensures) fail(\"not a forall property\");\n const e = env(module);\n const types = property.binders.map((b) => binderType(b.name, b.type, module));\n const binders = property.binders\n .map((b, i) => `(${ident.variable(b.name)} : ${leanType(types[i] as SubsetType)})`)\n .join(\" \");\n const hyps = property.when\n ? [`(${arrowTerm(property.when, \"when\", property, types, e)} = true)`]\n : [];\n const claim = `(${arrowTerm(property.ensures, \"ensures\", property, types, e)} = true)`;\n const body = [...hyps, claim].join(\" →\\n \");\n return {\n // A function of no parameters has nothing to quantify over: the proposition stands alone.\n text: binders === \"\" ? body : `∀ ${binders},\\n ${body}`,\n hypotheses: hyps.length,\n };\n}\n\n/**\n * The tactic script every theorem is closed by. Booleans become\n * propositions first, while the `Decidable` instances in the statement\n * still match their propositions (unfolding under `decide` first leaves\n * them stale and stops `simp`); Bool binders are cased, so boolean claims\n * are decided by enumeration; then the module's definitions unfold, each\n * conditional splits, and linear integer arithmetic (`omega`) closes what\n * remains. Nothing here is specific to a property; what Lean checks is\n * the statement.\n */\nexport function tactics(module: SubsetModule, property: Property, hypotheses: number): string {\n const defs = module.functions.map((f) => ident.fn(f.name)).join(\", \");\n const names = property.binders.map((b) => ident.variable(b.name));\n const hyps = Array.from({ length: hypotheses }, (_, i) => `h${i}_`);\n const bools = property.binders\n .filter(\n (b) =>\n b.type.kind === \"boolean\" ||\n (b.type.kind === \"literal\" && typeof b.type.value === \"boolean\"),\n )\n .map((b) => ident.variable(b.name));\n const introduced = [...names, ...hyps];\n return [\n ...(introduced.length > 0 ? [` intro ${introduced.join(\" \")}`] : []),\n ...(bools.length > 0 ? [` ${bools.map((b) => `cases ${b}`).join(\" <;> \")}`] : []),\n \" all_goals (try simp_all)\",\n ` all_goals (try simp only [${defs}] at *)`,\n \" all_goals (repeat' (split <;> simp_all))\",\n \" all_goals (try simp_all)\",\n \" all_goals (first | decide | trivial | omega)\",\n ].join(\"\\n\");\n}\n\n/** A Lean-safe theorem name: unique by position, readable by the function's and property's names. */\nexport function theoremName(index: number, fn: string, property: string): string {\n return `t${index}_${fn}_${property}`.replace(/[^A-Za-z0-9_]/g, \"_\");\n}\n\nexport interface EmittedTheorem {\n readonly function: string;\n readonly property: string;\n readonly name: string;\n /** 1-based lines of the theorem in the emitted file, inclusive. */\n readonly from: number;\n readonly to: number;\n /** Closed by a supplied proof, not the tactic script. */\n readonly supplied?: true;\n /** For a supplied proof: the 1-based line of the `#print axioms` that audits it. */\n readonly axiomsLine?: number;\n /** For a supplied proof: the 1-based line of the `#check` that shows its type, which must be the statement alone. */\n readonly typeLine?: number;\n}\n\nexport interface Emitted {\n readonly source: string;\n readonly theorems: readonly EmittedTheorem[];\n /** Properties the emitter could not state, with why. */\n readonly skipped: readonly {\n readonly function: string;\n readonly property: string;\n readonly reason: string;\n }[];\n /** 1-based lines of the supplied lemmas in the emitted file, inclusive, when there are any. */\n readonly lemmas?: { readonly from: number; readonly to: number };\n}\n\n/** The supplied proofs to use: lemmas, and each property's tactic proof by name. */\nexport interface SuppliedText {\n readonly lemmas: string;\n readonly proofs: ReadonlyMap<string, string>;\n}\n\n/** A tactic block at the indentation a `by` takes: its common indentation stripped, two spaces put back. */\nfunction indented(block: string): string {\n const lines = block.split(\"\\n\");\n const widths = lines.filter((l) => l.trim() !== \"\").map((l) => /^ */.exec(l)?.[0].length ?? 0);\n const common = widths.length > 0 ? Math.min(...widths) : 0;\n return lines.map((l) => (l.trim() === \"\" ? \"\" : ` ${l.slice(common)}`)).join(\"\\n\");\n}\n\n/**\n * The whole file: structures, definitions, one theorem per property, any\n * extra lines (translation checks), then the properties with supplied\n * proofs: each statement fixed as a definition before any supplied text,\n * the supplied lemmas, each theorem proving its definition with the\n * supplied tactics, and `#print axioms` for each.\n */\nexport function emitModule(\n module: SubsetModule,\n properties: readonly { readonly function: string; readonly property: Property }[],\n extra: readonly string[] = [],\n supplied?: SuppliedText,\n): Emitted {\n const parts: string[] = [\n \"-- Generated by Eutaxy's first-party engine from the module and its spec file; the theorems are its properties.\",\n \"set_option linter.unusedSimpArgs false\",\n \"set_option linter.unusedVariables false\",\n ...module.records.map(emitRecord),\n ...module.functions.map((f) => emitFunction(f, module)),\n ];\n const theorems: EmittedTheorem[] = [];\n const skipped: Emitted[\"skipped\"][number][] = [];\n const later: { fn: string; property: string; name: string; statement: string; proof: string }[] =\n [];\n for (const { function: fn, property } of properties) {\n let body: { text: string; hypotheses: number };\n try {\n body = stated(property, module);\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n skipped.push({ function: fn, property: property.name, reason: err.message });\n continue;\n }\n const name = theoremName(theorems.length + skipped.length + later.length, fn, property.name);\n const proof = supplied?.proofs.get(property.name);\n if (proof !== undefined) {\n later.push({ fn, property: property.name, name, statement: body.text, proof });\n continue;\n }\n const text = `theorem ${name} :\\n ${body.text} := by\\n${tactics(module, property, body.hypotheses)}`;\n const from = parts.join(\"\\n\\n\").split(\"\\n\").length + 2;\n parts.push(text);\n theorems.push({\n function: fn,\n property: property.name,\n name,\n from,\n to: from + text.split(\"\\n\").length - 1,\n });\n }\n parts.push(...extra);\n const lineAfter = () => parts.join(\"\\n\\n\").split(\"\\n\").length + 2;\n let lemmas: Emitted[\"lemmas\"];\n if (later.length > 0) {\n for (const l of later) parts.push(`def s_${l.name} : Prop :=\\n ${l.statement}`);\n if (supplied && supplied.lemmas !== \"\") {\n const from = lineAfter();\n parts.push(supplied.lemmas);\n lemmas = { from, to: from + supplied.lemmas.split(\"\\n\").length - 1 };\n }\n const ownProofs: EmittedTheorem[] = [];\n for (const l of later) {\n const text = `theorem ${l.name} : s_${l.name} := by\\n unfold s_${l.name}\\n${indented(l.proof)}`;\n const from = lineAfter();\n parts.push(text);\n ownProofs.push({\n function: l.fn,\n property: l.property,\n name: l.name,\n from,\n to: from + text.split(\"\\n\").length - 1,\n supplied: true,\n });\n }\n // Each audit's line is recorded: only Lean's message at that line counts as the audit.\n for (const t of ownProofs) {\n // Its type, as Lean has it: a hypothesis the supplied text slipped in (a section variable) shows here.\n const typeLine = lineAfter();\n parts.push(`#check @${t.name}`);\n const axiomsLine = lineAfter();\n parts.push(`#print axioms ${t.name}`);\n theorems.push({ ...t, axiomsLine, typeLine });\n }\n }\n return { source: `${parts.join(\"\\n\\n\")}\\n`, theorems, skipped, ...(lemmas ? { lemmas } : {}) };\n}\n\n/**\n * A JavaScript string as a Lean string literal: `\"` and `\\` escaped, control\n * characters as `\\xHH`, everything else written as it is (Lean source is\n * UTF-8). A lone surrogate has no Lean character and is refused.\n */\nexport function leanString(value: string): string {\n if (hasLoneSurrogate(value))\n fail(\"a string with a lone surrogate, which Lean's strings cannot hold\");\n let out = '\"';\n for (const c of value) {\n const code = c.codePointAt(0) as number;\n if (c === '\"') out += '\\\\\"';\n else if (c === \"\\\\\") out += \"\\\\\\\\\";\n else if (code < 0x20 || code === 0x7f) out += `\\\\x${code.toString(16).padStart(2, \"0\")}`;\n else out += c;\n }\n return `${out}\"`;\n}\n\n/** A TypeScript value of a subset type as a Lean term, for translation checks. */\nexport function value(v: unknown, t: SubsetType, module: SubsetModule): string {\n switch (t.kind) {\n case \"int\":\n if (typeof v !== \"number\" || !Number.isInteger(v)) fail(`${String(v)} is not an integer`);\n return `(${v} : Int)`;\n case \"bool\":\n if (typeof v !== \"boolean\") fail(`${String(v)} is not a boolean`);\n return v ? \"true\" : \"false\";\n case \"string\":\n if (typeof v !== \"string\") fail(`${String(v)} is not a string`);\n return leanString(v);\n case \"record\": {\n const rec = module.records.find((r) => r.name === t.name) ?? fail(`no record ${t.name}`);\n if (typeof v !== \"object\" || v === null) fail(`${String(v)} is not a record`);\n const o = v as Record<string, unknown>;\n const extra = Object.keys(o).filter((k) => !rec.fields.some((f) => f.name === k));\n if (extra.length > 0) fail(`${t.name} value has unexpected fields ${extra.join(\", \")}`);\n return `({ ${rec.fields.map((f) => `${ident.field(f.name)} := ${value(o[f.name], f.type, module)}`).join(\", \")} } : ${ident.record(t.name)})`;\n }\n case \"list\":\n if (!Array.isArray(v)) fail(`${String(v)} is not an array`);\n return `([${v.map((x) => value(x, t.element, module)).join(\", \")}] : ${leanType(t)})`;\n case \"nothing\":\n return fail(\"a value of no type\");\n case \"nullable\":\n case \"union\":\n case \"null\":\n return fail(`a ${t.kind} type, which the Lean engine does not take yet`);\n }\n}\n","/**\n * Running Lean over a process boundary. The engine is pinned to one Lean\n * release, looked for through elan (Lean's toolchain manager), asked for it\n * by name: Eutaxy's own elan in its cache first (where `eutaxy prover\n * install lean` puts one when the machine has none), then the user's; then\n * as a bare `lean` that must report that version. Nothing is ever downloaded during\n * a check; a missing toolchain is `unavailable`, with the command that\n * installs it. Diagnostics come back as `file:line:col: severity: message`\n * lines, which the engine maps to theorems.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { mkdtempSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir, tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { type Host, host } from \"@eutaxy/prover/toolchain\";\nimport { type Elan, elanCandidates } from \"./elan.ts\";\n\n/**\n * The Lean release the engine's contract corpus is checked against. On a\n * bump: run the corpus and the supplied-proof tests on the new release,\n * and read its release notes for a new command that runs code while a\n * file is checked (a `#` command is already refused; a new word goes into\n * `supplied.ts`'s refused list in the same change). CI caches the\n * toolchain by this file's hash.\n */\nexport const leanToolchain = \"leanprover/lean4:v4.35.0\";\nexport const leanVersion = \"4.35.0\";\n/** How to put the pinned toolchain on this machine. */\nexport const installHint = `run: eutaxy prover install lean (or install elan, https://elan.lean-lang.org, and run: elan toolchain install ${leanToolchain})`;\n\nexport interface LeanRun {\n readonly code: number | null;\n readonly stdout: string;\n readonly stderr: string;\n readonly timedOut: boolean;\n}\n\nexport interface LeanDiagnostic {\n readonly line: number;\n readonly column: number;\n readonly severity: \"error\" | \"warning\" | \"info\";\n readonly message: string;\n}\n\nexport interface LeanToolchain {\n /** The `lean` executable to run, with the arguments that select the pinned toolchain. */\n readonly command: string;\n readonly args: readonly string[];\n readonly version: string;\n /** Environment to add when running it (`ELAN_HOME` for Eutaxy's own elan). */\n readonly env?: Readonly<Record<string, string>>;\n}\n\nfunction run(\n command: string,\n args: readonly string[],\n options: {\n readonly cwd?: string;\n readonly timeoutMs: number;\n readonly env?: Readonly<Record<string, string>> | undefined;\n },\n): Promise<LeanRun> {\n return new Promise((resolve) => {\n let child: ReturnType<typeof spawn>;\n try {\n // Its own process group, so a timeout kills `lean` under `elan run`, not just elan.\n child = spawn(command, args, {\n cwd: options.cwd,\n ...(options.env === undefined ? {} : { env: { ...process.env, ...options.env } }),\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n detached: process.platform !== \"win32\",\n });\n } catch (err) {\n resolve({ code: null, stdout: \"\", stderr: String(err), timedOut: false });\n return;\n }\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n try {\n if (process.platform !== \"win32\" && child.pid !== undefined)\n process.kill(-child.pid, \"SIGKILL\");\n else child.kill(\"SIGKILL\");\n } catch {\n child.kill(\"SIGKILL\");\n }\n }, options.timeoutMs);\n child.stdout?.on(\"data\", (d: Buffer) => {\n stdout += d.toString();\n });\n child.stderr?.on(\"data\", (d: Buffer) => {\n stderr += d.toString();\n });\n child.on(\"error\", (err) => {\n clearTimeout(timer);\n resolve({ code: null, stdout, stderr: `${stderr}${String(err)}`, timedOut });\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n resolve({ code, stdout, stderr, timedOut });\n });\n });\n}\n\n/** Candidates for a bare `lean`: the PATH, then elan's default home. */\nfunction leanCandidates(h: Host): string[] {\n const home = h.env[\"ELAN_HOME\"] || join(h.home || homedir(), \".elan\");\n return [\"lean\", join(home, \"bin\", \"lean\")];\n}\n\n/**\n * The pinned toolchain if it is installed: through `elan run <toolchain>`\n * with the first elan that has it (Eutaxy's own, then the user's), else,\n * only when no elan answered at all, a bare `lean` of exactly that version.\n * Nothing is downloaded: an elan is run only for its toolchain list, and\n * with an elan present a bare `lean` would be its proxy.\n */\nexport async function findLean(\n h: Host = host(),\n elans: readonly Elan[] = elanCandidates(h),\n leans: readonly string[] = leanCandidates(h),\n): Promise<LeanToolchain | { readonly unavailable: string }> {\n let lacking: string | undefined;\n for (const elan of elans) {\n const list = await run(elan.command, [\"toolchain\", \"list\"], {\n timeoutMs: 20_000,\n env: elan.env,\n });\n if (list.code !== 0) continue;\n if (list.stdout.split(\"\\n\").some((l) => l.trim().split(\" \")[0] === leanToolchain))\n return {\n command: elan.command,\n args: [\"run\", leanToolchain, \"lean\"],\n version: leanVersion,\n ...(elan.env === undefined ? {} : { env: elan.env }),\n };\n lacking ??= `elan (${elan.command}) has no ${leanToolchain}`;\n }\n // With an elan on the machine a bare `lean` is most likely its proxy, which downloads whatever\n // toolchain it is asked for: never run it then, so a check downloads nothing.\n if (lacking !== undefined) return { unavailable: `${lacking}; ${installHint}` };\n for (const lean of leans) {\n const v = await run(lean, [\"--version\"], { timeoutMs: 20_000 });\n if (v.code !== 0) continue;\n const m = /Lean \\(version ([^,]+),/.exec(v.stdout);\n if (m?.[1] === leanVersion) return { command: lean, args: [], version: leanVersion };\n return {\n unavailable: `lean ${m?.[1] ?? \"of unknown version\"} found, but the engine is pinned to ${leanVersion}; ${installHint}`,\n };\n }\n return { unavailable: `no Lean toolchain found; ${installHint}` };\n}\n\n/** Parse Lean's diagnostics for the one file it was given. */\n/**\n * Lean's messages from `--json` output: one object per line, each with\n * its position. Lines that are not such an object (whatever a program\n * writes to the terminal) are not messages and are skipped, so nothing in\n * the checked file can pose as a message at a position it is not at.\n */\nexport function jsonDiagnostics(output: string): LeanDiagnostic[] {\n const out: LeanDiagnostic[] = [];\n for (const raw of output.split(\"\\n\")) {\n if (!raw.startsWith(\"{\")) continue;\n let m: { pos?: { line?: unknown; column?: unknown }; severity?: unknown; data?: unknown };\n try {\n m = JSON.parse(raw) as typeof m;\n } catch {\n continue;\n }\n const severity =\n m.severity === \"error\"\n ? \"error\"\n : m.severity === \"warning\"\n ? \"warning\"\n : m.severity === \"information\"\n ? \"info\"\n : undefined;\n if (severity === undefined || typeof m.pos?.line !== \"number\" || typeof m.data !== \"string\")\n continue;\n out.push({\n line: m.pos.line,\n column: typeof m.pos.column === \"number\" ? m.pos.column : 0,\n severity,\n message: m.data.trimEnd(),\n });\n }\n return out;\n}\n\nexport function diagnostics(output: string): LeanDiagnostic[] {\n const out: LeanDiagnostic[] = [];\n const re = /^(?:.*?):(\\d+):(\\d+): (error|warning|info): (.*)$/;\n let current:\n | { line: number; column: number; severity: LeanDiagnostic[\"severity\"]; lines: string[] }\n | undefined;\n const flush = (c: NonNullable<typeof current>) =>\n out.push({\n line: c.line,\n column: c.column,\n severity: c.severity,\n message: c.lines.join(\"\\n\").trimEnd(),\n });\n for (const raw of output.split(\"\\n\")) {\n const m = re.exec(raw);\n if (m) {\n if (current) flush(current);\n current = {\n line: Number(m[1]),\n column: Number(m[2]),\n severity: m[3] as LeanDiagnostic[\"severity\"],\n lines: [m[4] as string],\n };\n } else if (current) current.lines.push(raw);\n }\n if (current) flush(current);\n return out;\n}\n\nexport interface CheckedFile {\n readonly run: LeanRun;\n readonly diagnostics: readonly LeanDiagnostic[];\n}\n\n/** Write the source to a scratch directory pinned to the toolchain and check it. */\nexport async function checkLean(\n toolchain: LeanToolchain,\n source: string,\n options: { readonly timeoutMs?: number; readonly keep?: boolean } = {},\n): Promise<CheckedFile> {\n const dir = mkdtempSync(join(tmpdir(), \"eutaxy-lean-\"));\n try {\n writeFileSync(join(dir, \"lean-toolchain\"), `${leanToolchain}\\n`);\n writeFileSync(join(dir, \"Eutaxy.lean\"), source);\n const result = await run(toolchain.command, [...toolchain.args, \"--json\", \"Eutaxy.lean\"], {\n cwd: dir,\n timeoutMs: options.timeoutMs ?? 120_000,\n env: toolchain.env,\n });\n return { run: result, diagnostics: jsonDiagnostics(`${result.stdout}\\n${result.stderr}`) };\n } finally {\n if (!options.keep) rmSync(dir, { recursive: true, force: true });\n }\n}\n","/**\n * Proofs supplied beside a spec file, for claims the engine's tactic\n * script does not close: `domain.props.lean` beside `domain.props.ts`.\n * Lemmas come first; then each `-- proof: <property>` line opens the\n * tactic proof of that property's statement, which Eutaxy emits and the\n * proof cannot change (it is fixed as a definition before any supplied\n * text). Lean's kernel checks the proof, and Eutaxy accepts it only when\n * it rests on Lean's standard axioms; what could switch checking off, add\n * an axiom or change how the statement reads is refused outright.\n */\n\nexport interface SuppliedProofs {\n /** The proof file's name, for verdicts. */\n readonly file: string;\n /** Everything before the first `-- proof:` line: lemmas the proofs use. */\n readonly lemmas: string;\n /** Each property's tactic proof, by property name (the names also when the file is refused). */\n readonly proofs: ReadonlyMap<string, string>;\n /** Why the file is refused, when it is; then none of its proofs is used, and its properties say why. */\n readonly refused?: string;\n /** The SHA-256 of the module source the proofs were written for, when the file says (a goal file does). */\n readonly sourceSha256?: string;\n /** The SHA-256 of the spec file the proofs were written for, when the file says. */\n readonly specSha256?: string;\n}\n\n/** The lines a goal file carries, and a proof file copied from one keeps, tying the proofs to the files they were written for. */\nexport const sourceHashMarker = \"-- eutaxy-source-sha256: \";\nexport const specHashMarker = \"-- eutaxy-spec-sha256: \";\n\n/** The axioms a supplied proof may rest on: Lean's standard ones. */\nexport const standardAxioms: ReadonlySet<string> = new Set([\n \"propext\",\n \"Classical.choice\",\n \"Quot.sound\",\n]);\n\n/**\n * Words a supplied proof may not use, anywhere in the file, comments and\n * strings included: what adds axioms or trusted code (`axiom`, `sorry`,\n * `unsafe`, `implemented_by`, `extern`, `opaque`, `native_decide`),\n * switches checks off (`set_option`), registers code Lean would run while\n * the file is checked (`attribute`, `initialize`, `simproc` and the like)\n * or changes how text reads (`macro`, `syntax`, `notation` and the like),\n * and `import`. The list narrows when a legitimate proof is refused and\n * grows only with a Lean bump that adds such a command (see\n * `leanToolchain`); never because of what a hostile file could do, which\n * the design answers.\n */\nconst refusedWords = [\n \"sorry\",\n \"admit\",\n \"axiom\",\n \"unsafe\",\n \"implemented_by\",\n \"extern\",\n \"opaque\",\n \"native_decide\",\n \"set_option\",\n \"macro\",\n \"macro_rules\",\n \"syntax\",\n \"notation\",\n \"infix\",\n \"infixl\",\n \"infixr\",\n \"prefix\",\n \"postfix\",\n \"elab\",\n \"elab_rules\",\n \"import\",\n \"attribute\",\n \"initialize\",\n \"simproc\",\n \"dsimproc\",\n \"simproc_decl\",\n \"dsimproc_decl\",\n // Section variables become hypotheses of the theorems after them: `variable (h : False)` would.\n \"section\",\n \"namespace\",\n \"variable\",\n \"include\",\n \"omit\",\n \"universe\",\n];\n\n/** Command families refused by how a word starts: `run_cmd`, `builtin_initialize`, `register_option`, `declare_syntax_cat`. */\nconst refusedStarts = [\"run_\", \"builtin_\", \"register_\", \"declare_\"];\n\n/**\n * Refused wherever they appear, inside a name too: every command run\n * while the file is checked starts with `#`, and every attribute (which\n * can hand Lean a tactic, an elaborator or a simplification procedure to\n * run) with `@[`.\n */\nconst refusedAnywhere = [\"#\", \"@[\"];\n\n/** Lean's ASCII identifier characters after the first. */\nconst identRest = /[A-Za-z0-9_'!?]/u;\n\n/**\n * Whether the text just before `at` continues a name, so that a word\n * starting there is part of that name rather than a token of its own.\n * Only a run of identifier characters that starts with an ASCII letter or\n * `_` counts: one that starts with a digit is a numeral, and Lean starts a\n * new token right after a numeral (`0xfsorry` is `0xf`, then `sorry`).\n * Anything else (`.`, `«`, Unicode) counts as a boundary, which refuses\n * more, never less.\n */\nfunction continuesName(text: string, at: number): boolean {\n let i = at;\n while (i > 0 && identRest.test(text[i - 1] as string)) i--;\n return i < at && /[A-Za-z_]/u.test(text[i] as string);\n}\n\n/** The first refused word or command the text holds, as a token of its own, or undefined. */\nexport function refusedIn(text: string): string | undefined {\n const anywhere = refusedAnywhere.find((w) => text.includes(w));\n if (anywhere !== undefined) return anywhere;\n for (const [words, whole] of [\n [refusedWords, true],\n [refusedStarts, false],\n ] as const) {\n for (const w of words) {\n for (let at = text.indexOf(w); at >= 0; at = text.indexOf(w, at + 1)) {\n if (continuesName(text, at)) continue;\n // A whole word followed by an identifier character is a longer name, which Lean reads as one.\n if (whole && identRest.test(text[at + w.length] ?? \"\")) continue;\n return w;\n }\n }\n }\n return undefined;\n}\n\n/** `-- proof: <property>`: any name the spec file can export, Unicode letters included. */\nconst marker = /^-- proof: (\\S+)\\s*$/u;\n\n/** Read a proof file: its lemmas, its proofs by property, or why it is refused. */\nexport function readSupplied(file: string, text: string): SuppliedProofs {\n const lemmas: string[] = [];\n const proofs = new Map<string, string[]>();\n let current: string[] = lemmas;\n let twice: string | undefined;\n for (const line of text.split(\"\\n\")) {\n const m = marker.exec(line);\n if (!m) {\n current.push(line);\n continue;\n }\n const name = m[1] as string;\n twice ??= proofs.has(name) ? name : undefined;\n current = [];\n proofs.set(name, current);\n }\n if (twice !== undefined) return refuse({ file, proofs }, `${file} proves ${twice} twice`);\n // Checked over the whole text, comments and strings too: telling them apart is lexing Lean, and a\n // lexer that slips (`\"/-\"` in a string read as a comment) would let a refused command through. A\n // refused word in a comment refuses the file as well, which costs a word, never soundness.\n const word = refusedIn(text);\n if (word !== undefined)\n return refuse(\n { file, proofs },\n `${file} uses ${word}, which a supplied proof may not (it could add an axiom, switch a check off, run code while the file is checked or change how the statement reads)`,\n );\n const hashLine = (marker: string): string | undefined => {\n const line = lemmas.find((l) => l.startsWith(marker));\n const hex = line?.slice(marker.length).trim();\n return hex !== undefined && /^[0-9a-f]{64}$/.test(hex) ? hex : undefined;\n };\n const sourceSha256 = hashLine(sourceHashMarker);\n const specSha256 = hashLine(specHashMarker);\n return {\n file,\n lemmas: lemmas.join(\"\\n\").trim(),\n proofs: new Map([...proofs].map(([k, v]) => [k, v.join(\"\\n\").replace(/\\s+$/, \"\")])),\n ...(sourceSha256 === undefined ? {} : { sourceSha256 }),\n ...(specSha256 === undefined ? {} : { specSha256 }),\n };\n}\n\n/** The file refused: none of its proofs is used, and every property it names says why. */\nexport function refuse(\n supplied: { readonly file: string; readonly proofs: ReadonlyMap<string, unknown> },\n reason: string,\n): SuppliedProofs {\n return {\n file: supplied.file,\n lemmas: \"\",\n proofs: new Map([...supplied.proofs.keys()].map((k) => [k, \"\"])),\n refused: reason,\n };\n}\n\n/** Lean's messages at one line: an audit is read only when Lean's own message is the only one there. */\nfunction onlyAt(\n messages: readonly {\n readonly line: number;\n readonly severity: string;\n readonly message: string;\n }[],\n line: number,\n): string | undefined {\n const at = messages.filter((m) => m.line === line);\n return at.length === 1 && at[0]?.severity === \"info\" ? at[0].message : undefined;\n}\n\n/**\n * The axioms Lean reports a theorem depends on: the message of the\n * `#print axioms` at `line`, Eutaxy's own audit command, and no other.\n * Undefined unless that message is the only one at the line: anything\n * else there (a forged copy, printed by code the file ran) makes the\n * audit unreadable rather than letting either message stand.\n */\nexport function axiomsOf(\n messages: readonly {\n readonly line: number;\n readonly severity: string;\n readonly message: string;\n }[],\n line: number,\n theorem: string,\n): string[] | undefined {\n const message = onlyAt(messages, line);\n if (message === undefined) return undefined;\n if (message === `'${theorem}' does not depend on any axioms`) return [];\n const prefix = `'${theorem}' depends on axioms: [`;\n if (message.startsWith(prefix) && message.endsWith(\"]\"))\n return message\n .slice(prefix.length, -1)\n .split(\",\")\n .map((x) => x.trim())\n .filter((x) => x.length > 0);\n return undefined;\n}\n\n/**\n * Whether Lean's message at the `#check` of a supplied theorem shows it\n * proves exactly its fixed statement `s_<name>`: no hypothesis added (a\n * section variable would show as `False → …`).\n */\nexport function provesExactly(\n messages: readonly {\n readonly line: number;\n readonly severity: string;\n readonly message: string;\n }[],\n line: number,\n theorem: string,\n): boolean {\n return onlyAt(messages, line) === `${theorem} : s_${theorem}`;\n}\n","/**\n * The goal file: the properties the tactic script gave up on, each with\n * the statement Lean was asked to prove, written in the form of the proof\n * file the engine accepts (`domain.props.lean`) with every proof left\n * open. A coding agent copies it beside the spec file, puts lemmas above\n * the proofs and tactics under them, and the engine checks them as it\n * checks any supplied proof: nothing new is trusted. The hashes tie the\n * proofs to the module and the spec they were written for; the engine\n * calls a proof file stale once either changed.\n */\n\nimport type { OpenGoal } from \"@eutaxy/prover\";\nimport { ident } from \"./emit.ts\";\nimport { leanVersion } from \"./lean.ts\";\nimport { refusedIn, sourceHashMarker, specHashMarker } from \"./supplied.ts\";\n\nexport interface GoalFileInput {\n /** The spec file's name, for the header: `domain.props.ts`. */\n readonly specFile: string;\n readonly sourceSha256: string;\n readonly specSha256: string;\n readonly goals: readonly OpenGoal[];\n}\n\n/** The proof file's name beside a spec file: `domain.props.lean` for `domain.props.ts`. */\nexport function proofFileFor(specFile: string): string {\n return specFile.replace(/\\.ts$/, \".lean\");\n}\n\n/** The goal file's name beside a spec file: `domain.props.goals.lean` for `domain.props.ts`. */\nexport function goalFileFor(specFile: string): string {\n return specFile.replace(/\\.ts$/, \".goals.lean\");\n}\n\n/** A line of generated commentary: one a proof file may hold, or a note that it was left out. */\nconst commentLine = (text: string): string =>\n refusedIn(text) === undefined\n ? text\n : \"-- (a line left out: it held a word a proof file may not use)\";\n\nconst comment = (text: string): string =>\n text\n .split(\"\\n\")\n .map((l) => commentLine(l.length > 0 ? `-- ${l}` : \"--\"))\n .join(\"\\n\");\n\n/**\n * Render the goal file: the header with the hashes, each goal described\n * in comments (the proof file's lemma area, where comments cost nothing),\n * then one open `-- proof:` part per goal at the end, since everything\n * after a `-- proof:` line belongs to that proof. The text avoids every\n * word a supplied proof may not use, so the file copied as is reads as a\n * proof file with open proofs: every generated line is checked, and one\n * that would refuse the file (a reason Lean gave, a file or function name\n * that is itself a refused word) is left out, with a note in its place.\n * The function is named by its Lean identifier, as the statement names it.\n */\nexport function renderGoals(input: GoalFileInput): string {\n const header = [\n `-- Open proof goals for ${input.specFile}, written by Eutaxy's Lean engine (Lean ${leanVersion}).`,\n \"-- Each goal below is a property the tactic script could not close, with the statement Eutaxy\",\n \"-- emits for it. To supply proofs, copy this file to\",\n `-- ${proofFileFor(input.specFile)} beside the spec file, put lemmas above the \\`-- proof:\\` lines and`,\n \"-- tactics under each, and run the engine again (eutaxy report --prover lean). The hashes tie the\",\n \"-- proofs to these versions of the module and the spec: once either changes, the proofs are stale\",\n \"-- until the goals are written again.\",\n `${sourceHashMarker}${input.sourceSha256}`,\n `${specHashMarker}${input.specSha256}`,\n ];\n const described = input.goals.map((g) =>\n [\n commentLine(`-- goal: ${g.property}, a property of ${ident.fn(g.function)}`),\n commentLine(`-- Lean said: ${g.reason}`),\n \"-- statement:\",\n comment(g.statement.replace(/^/gm, \" \")),\n ].join(\"\\n\"),\n );\n const open = input.goals.map((g) => `-- proof: ${g.property}\\n -- tactics here`);\n return `${[header.map(commentLine).join(\"\\n\"), ...described, ...open].join(\"\\n\\n\")}\\n`;\n}\n","/**\n * The engine: a module's functions through the subset reader, the emitter\n * and Lean, and each property's outcome back. One Lean run per module;\n * errors are mapped to theorems by line, so one failed proof does not hide\n * another. A proof that fails is `gave_up` (the engine is weak or the\n * claim is false; Lean does not say which), a function or property outside\n * the subset is `unsupported`, and no pinned toolchain is `unavailable`.\n * `total` is proved by Lean accepting the definition.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { basename } from \"node:path\";\nimport type {\n ModuleProofs,\n OpenGoal,\n ProofOutcome,\n PropertyProof,\n Prover,\n ProveInput as ProverInput,\n} from \"@eutaxy/prover\";\nimport {\n builtinsAssumption,\n children,\n type Expr,\n listKinds,\n OutsideSubset,\n readSubset,\n restrictModule,\n type SubsetFunction,\n type SubsetModule,\n type SubsetType,\n} from \"@eutaxy/prover/reader\";\nimport type { FunctionSpec, Property, SpecError, SpecType } from \"@eutaxy/spec\";\nimport { dividesOutside, divisionOutside, type Emitted, emitModule, stated } from \"./emit.ts\";\nimport { checkLean, findLean, type LeanDiagnostic, leanVersion } from \"./lean.ts\";\nimport {\n axiomsOf,\n provesExactly,\n readSupplied,\n refuse,\n type SuppliedProofs,\n standardAxioms,\n} from \"./supplied.ts\";\n\nexport const engineName = \"lean\";\n\n/** The types this engine translates: the integers, Bool, String and records of those. */\nexport const leanTakes = (t: SubsetType): boolean =>\n t.kind === \"int\" ||\n t.kind === \"bool\" ||\n t.kind === \"string\" ||\n t.kind === \"record\" ||\n (t.kind === \"list\" && leanTakes(t.element));\n\nexport type { ModuleProofs, ProofOutcome, PropertyProof } from \"@eutaxy/prover\";\n\nexport interface ProveInput extends ProverInput {\n /** Extra Lean lines appended after the theorems (translation checks). */\n readonly extra?: readonly string[];\n}\n\n/** This engine's report, with the Lean it checked. */\nexport interface LeanModuleProofs extends ModuleProofs {\n /** The Lean source checked, when any function was in the subset. */\n readonly lean?: string;\n}\n\n/** What every PROVEN verdict of this engine rests on. */\nexport const engineAssumptions: readonly string[] = [\n \"number is modelled as the unbounded integers: no overflow, no fractions, no NaN\",\n \"string is modelled as Lean's String, a sequence of Unicode characters: a lone surrogate, which a JavaScript string can hold, is outside every string binder's domain\",\n \"the function and its callees are pure and total: the module's own, or generic or imported ones read at each call from their own files; nothing else is modelled\",\n builtinsAssumption,\n `the proof was checked by the Lean ${leanVersion} kernel on the emitted statement, not by Eutaxy`,\n];\n\n/** What a PROVEN over arrays rests on besides: the list model. */\nexport const listAssumption =\n \"an array is modelled as a Lean List, dense: a sparse array, whose holes JavaScript's array methods skip, is outside every array binder's domain\";\n\n/** What a PROVEN that unfolds a recursive function rests on besides: that the JavaScript returns. */\nexport const recursionAssumption =\n \"a recursive function is modelled as returning on every input: JavaScript's call stack is bounded, so on a long enough list the code throws (RangeError) where the model returns\";\n\nconst proven: Extract<ProofOutcome, { kind: \"PROVEN\" }> = {\n kind: \"PROVEN\",\n engine: { name: engineName, version: leanVersion },\n assumptions: engineAssumptions,\n};\n\nconst unknown = (\n cause: \"gave_up\" | \"unsupported\" | \"unavailable\",\n reason: string,\n): ProofOutcome => ({\n kind: \"UNKNOWN\",\n cause,\n reason,\n});\n\n/** Every property of the functions, with one outcome. */\nfunction allWith(fns: readonly FunctionSpec[], outcome: ProofOutcome): PropertyProof[] {\n return fns.flatMap((fn) =>\n fn.properties.map((property) => ({ function: fn.name, property: property.name, outcome })),\n );\n}\n\n/** The emitted Lean for the module's functions in the subset, and the functions with specs outside it with why. */\nexport interface Prepared {\n readonly module: SubsetModule;\n /** The proofs supplied beside the spec file, when there is a proof file. */\n readonly supplied?: SuppliedProofs;\n readonly emitted: Emitted;\n /** The functions to report on. */\n readonly fns: readonly FunctionSpec[];\n /** Those of them the subset does not take, with the reason. */\n readonly outside: ReadonlyMap<string, string>;\n /** Specs that did not read. */\n readonly specErrors: readonly SpecError[];\n}\n\n/**\n * Read and emit. Every function the subset takes is emitted (callees\n * included); properties are stated for the ones with specs among them.\n */\nexport function prepare(input: ProveInput): Prepared {\n const specs = input.specs;\n const wanted = input.functions ? new Set(input.functions) : undefined;\n const fns = specs.functions.filter((f) => !wanted || wanted.has(f.name));\n // Nullable types and tagged unions are read, but this engine does not take them yet: the SMT engine does.\n // Division leaves the integers this engine models, except as Math.floor(x / c).\n const module = restrictModule(\n restrictModule(\n readSubset(\n input.source,\n fns.map((f) => f.name),\n input.modulePath === undefined ? {} : { path: input.modulePath },\n ),\n leanTakes,\n \"nullable types and tagged unions are not in the Lean engine's subset yet\",\n ),\n () => true,\n divisionOutside,\n new Set(),\n dividesOutside,\n );\n const outside = new Map<string, string>();\n for (const o of module.outside)\n if (fns.some((f) => f.name === o.name))\n outside.set(\n o.name,\n `outside the engine's subset${o.line > 0 ? ` (line ${o.line})` : \"\"}: ${o.message}`,\n );\n // A spec belongs to one declaration: the one the reader found at that offset. A nested function (in a\n // namespace, say) named like a top-level one must not lend its properties to the top-level body.\n for (const fn of fns) {\n const read = module.functions.find((f) => f.name === fn.name);\n if (read && read.offset !== fn.offset)\n outside.set(\n fn.name,\n `outside the engine's subset (line ${fn.line}): the ${fn.name} the spec names is not the module's top-level declaration of that name (line ${read.line})`,\n );\n }\n const properties: { function: string; property: Property }[] = fns\n .filter((fn) => !outside.has(fn.name))\n .flatMap((fn) =>\n fn.properties\n .filter((p) => p.kind === \"forall\")\n .map((property) => ({ function: fn.name, property })),\n );\n const specErrors = specs.errors;\n // Proofs supplied beside the spec file: `domain.props.lean` beside `domain.props.ts`. A file that\n // names the hashes of the source and spec it was written for (a goal file does) is stale once either\n // changed: its proofs are not used, and its properties say so, rather than failing one by one on a\n // statement that moved under them.\n const proofFile = input.specPath?.replace(/\\.ts$/, \".lean\");\n let supplied =\n proofFile !== undefined && existsSync(proofFile)\n ? readSupplied(basename(proofFile), readFileSync(proofFile, \"utf8\"))\n : undefined;\n if (supplied && !supplied.refused) {\n const stale = staleness(supplied, input);\n if (stale !== undefined) supplied = refuse(supplied, stale);\n }\n try {\n return {\n module,\n ...(supplied ? { supplied } : {}),\n emitted: emitModule(\n module,\n properties,\n input.extra,\n supplied && !supplied.refused ? supplied : undefined,\n ),\n fns,\n outside,\n specErrors,\n };\n } catch (err) {\n // The emitter refusing something the reader let through is an engine gap: every function is unsupported, none guessed.\n if (!(err instanceof OutsideSubset)) throw err;\n for (const fn of fns) outside.set(fn.name, `outside the engine's subset: ${err.message}`);\n const empty: Emitted = { source: \"\", theorems: [], skipped: [] };\n return { module, emitted: empty, fns, outside, specErrors };\n }\n}\n\nconst sha256 = (text: string): string => createHash(\"sha256\").update(text).digest(\"hex\");\n\n/** Why a proof file is stale, when it names the hashes of the files it was written for and either moved. */\nfunction staleness(supplied: SuppliedProofs, input: ProveInput): string | undefined {\n const moved: string[] = [];\n if (supplied.sourceSha256 !== undefined && supplied.sourceSha256 !== sha256(input.source))\n moved.push(\"the module\");\n if (\n supplied.specSha256 !== undefined &&\n input.specPath !== undefined &&\n existsSync(input.specPath)\n ) {\n if (supplied.specSha256 !== sha256(readFileSync(input.specPath, \"utf8\")))\n moved.push(\"the spec file\");\n }\n if (moved.length === 0) return undefined;\n return `${supplied.file} is stale: ${moved.join(\" and \")} changed since its proofs were written (the hashes it names no longer match); write the goals again and bring the proofs over`;\n}\n\n/**\n * A supplied proof's outcome: given up on when its lemmas or its tactics\n * do not compile, or when it rests on an axiom beyond Lean's standard\n * ones (`sorry` is one); PROVEN otherwise, saying it was supplied.\n */\nfunction suppliedOutcome(\n file: string,\n error: LeanDiagnostic | undefined,\n axioms: readonly string[] | undefined,\n exact: boolean,\n assumptions: readonly string[],\n): ProofOutcome {\n if (error)\n return unknown(\n \"gave_up\",\n `the proof supplied in ${file} does not close: ${error.message.split(\"\\n\")[0]}`,\n );\n if (!exact)\n return unknown(\n \"gave_up\",\n `the proof supplied in ${file} proves more hypotheses than its statement has (a section variable?), or Lean did not report its type`,\n );\n if (axioms === undefined)\n return unknown(\"gave_up\", `Lean did not report the axioms of the proof supplied in ${file}`);\n const beyond = axioms.filter((a) => !standardAxioms.has(a));\n if (beyond.length > 0)\n return unknown(\n \"gave_up\",\n `the proof supplied in ${file} rests on ${beyond.join(\", \")}, beyond Lean's standard axioms`,\n );\n return {\n ...proven,\n assumptions: [\n ...assumptions,\n `the proof was supplied in ${file}, not found by the engine's tactic script; Lean's kernel checked it against the statement Eutaxy emitted, and it rests on no axioms beyond propext, Classical.choice and Quot.sound`,\n ],\n };\n}\n\n/** Prove a module's properties with the pinned Lean. */\nexport async function proveModule(input: ProveInput): Promise<LeanModuleProofs> {\n const { module, emitted, fns, outside, specErrors, supplied } = prepare(input);\n const inSubset = fns.filter((f) => !outside.has(f.name));\n const unsupported = fns\n .filter((f) => outside.has(f.name))\n .flatMap((f) =>\n f.properties.map((property) => ({\n function: f.name,\n property: property.name,\n outcome: unknown(\"unsupported\", outside.get(f.name) as string),\n })),\n );\n if (inSubset.length === 0) return { results: unsupported, specErrors };\n const lean = emitted.source;\n const rest = (outcome: ProofOutcome): LeanModuleProofs => ({\n results: [...unsupported, ...allWith(inSubset, outcome)],\n lean,\n specErrors,\n });\n const toolchain = await findLean();\n if (\"unavailable\" in toolchain) return rest(unknown(\"unavailable\", toolchain.unavailable));\n const timeoutMs = input.timeoutMs ?? 120_000;\n const checked = await checkLean(toolchain, lean, { timeoutMs });\n if (checked.run.timedOut)\n return rest(unknown(\"gave_up\", `Lean did not finish within ${timeoutMs} ms`));\n const errors = checked.diagnostics.filter((d) => d.severity === \"error\");\n const inTheorem = (d: LeanDiagnostic) =>\n emitted.theorems.find((t) => d.line >= t.from && d.line <= t.to);\n if (checked.run.code === null || (checked.run.code !== 0 && errors.length === 0))\n return rest(\n unknown(\n \"unavailable\",\n `Lean could not be run: ${checked.run.stderr.trim() || `exit ${checked.run.code}`}`,\n ),\n );\n const inLemmas = (d: LeanDiagnostic) =>\n emitted.lemmas !== undefined && d.line >= emitted.lemmas.from && d.line <= emitted.lemmas.to;\n const lemmaErrors = errors.filter(inLemmas);\n const elsewhere = errors.filter((d) => !inTheorem(d) && !inLemmas(d));\n if (elsewhere.length > 0) {\n // The emitted definitions themselves did not compile: an engine gap, never a verdict on the property.\n const where = elsewhere.map((d) => `line ${d.line}: ${d.message.split(\"\\n\")[0]}`).join(\"; \");\n return rest(unknown(\"unsupported\", `the emitted Lean did not compile: ${where}`));\n }\n const results: PropertyProof[] = [...unsupported];\n for (const fn of inSubset) {\n for (const property of fn.properties) {\n if (property.kind === \"total\") {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: {\n ...proven,\n assumptions: [\n ...engineAssumptions,\n ...modelAssumptions(property, fn.name, module),\n \"Lean accepted the definition, so it terminates on every input\",\n ],\n },\n });\n continue;\n }\n const skipped = emitted.skipped.find(\n (s) => s.function === fn.name && s.property === property.name,\n );\n if (skipped) {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: unknown(\"unsupported\", skipped.reason),\n });\n continue;\n }\n if (supplied?.refused && supplied.proofs.has(property.name)) {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: unknown(\"gave_up\", supplied.refused),\n });\n continue;\n }\n const theorem = emitted.theorems.find(\n (t) => t.function === fn.name && t.property === property.name,\n );\n const failed = theorem\n ? errors.filter((d) => d.line >= theorem.from && d.line <= theorem.to)\n : [];\n if (theorem?.supplied && supplied) {\n results.push({\n function: fn.name,\n property: property.name,\n outcome: suppliedOutcome(\n supplied.file,\n lemmaErrors[0] ?? failed[0],\n axiomsOf(checked.diagnostics, theorem.axiomsLine ?? 0, theorem.name),\n provesExactly(checked.diagnostics, theorem.typeLine ?? 0, theorem.name),\n [...engineAssumptions, ...modelAssumptions(property, fn.name, module)],\n ),\n });\n continue;\n }\n results.push({\n function: fn.name,\n property: property.name,\n outcome:\n failed.length === 0\n ? {\n ...proven,\n assumptions: [...engineAssumptions, ...modelAssumptions(property, fn.name, module)],\n }\n : unknown(\n \"gave_up\",\n `Lean could not close the proof: ${(failed[0] as LeanDiagnostic).message.split(\"\\n\")[0]}`,\n ),\n });\n }\n }\n // The open goals: every forall property given up on, with the statement Lean was asked to prove. The\n // list is present, empty or not, only here, where Lean answered; a timeout or an engine gap above\n // returns without it, so no one takes \"no answer\" for \"no open goals\".\n const goals: OpenGoal[] = [];\n for (const fn of inSubset)\n for (const property of fn.properties) {\n if (property.kind !== \"forall\") continue;\n const r = results.find((x) => x.function === fn.name && x.property === property.name);\n if (r?.outcome.kind !== \"UNKNOWN\" || r.outcome.cause !== \"gave_up\") continue;\n goals.push({\n function: fn.name,\n property: property.name,\n statement: stated(property, module).text,\n reason: r.outcome.reason,\n });\n }\n return { results, lean, specErrors, goals };\n}\n\n/** The engine as a `Prover`: available when the pinned toolchain is installed. */\nexport const leanProver: Prover = {\n name: engineName,\n async available() {\n const toolchain = await findLean();\n return \"unavailable\" in toolchain ? toolchain : { version: toolchain.version };\n },\n prove: (input) => proveModule(input),\n};\n\n/** The list and recursion models a proof rests on, where its claim may meet them. */\nfunction modelAssumptions(property: Property, fn: string, module: SubsetModule): string[] {\n // The module functions this claim's own arrows name, by the spec file's names for them: named at\n // all, called or not, so `(sum)(xs)` counts; a disclosure may err only toward saying more.\n const arrows = [property.when?.body ?? \"\", property.ensures?.body ?? \"\"].join(\"\\n\");\n const called = property.imports.filter((i) =>\n new RegExp(`(^|[^\\\\w$])${i.local.replace(/\\$/g, \"\\\\$\")}($|[^\\\\w$])`).test(arrows),\n );\n const roots = [fn, ...called.map((i) => i.fn)];\n return [\n ...(usesLists(property, roots, module) ? [listAssumption] : []),\n ...(reached(roots, module).some((f) => f.structural !== undefined)\n ? [recursionAssumption]\n : []),\n ];\n}\n\n/**\n * The functions a property's claim may unfold: its function, the module\n * functions its arrows call, and, through their calls, everything they\n * reach.\n */\nfunction reached(roots: readonly string[], module: SubsetModule): SubsetFunction[] {\n const byName = new Map(module.functions.map((f) => [f.name, f]));\n const out = new Map<string, SubsetFunction>();\n const visit = (name: string) => {\n const f = byName.get(name);\n if (!f || out.has(name)) return;\n out.set(name, f);\n const walk = (e: Expr): void => {\n if (e.kind === \"call\") visit(e.callee);\n for (const c of children(e)) walk(c);\n };\n walk(f.body);\n };\n for (const r of roots) visit(r);\n return [...out.values()];\n}\n\n/**\n * Whether a list can be in play in a property: a binder whose type holds\n * an array at any depth, or a function the claim may unfold that holds a\n * list in its types (through records too) or builds one.\n */\nfunction usesLists(property: Property, roots: readonly string[], module: SubsetModule): boolean {\n const records = new Map(module.records.map((r) => [r.name, r]));\n const seen = new Set<string>();\n const hasList = (t: SubsetType): boolean => {\n if (t.kind === \"list\") return true;\n if (t.kind === \"nullable\") return hasList(t.inner);\n if (t.kind === \"record\" && !seen.has(t.name)) {\n seen.add(t.name);\n return records.get(t.name)?.fields.some((f) => hasList(f.type)) ?? false;\n }\n return false;\n };\n const hasArray = (t: SpecType): boolean => {\n if (t.kind === \"array\") return true;\n if (t.kind === \"union\") return t.members.some(hasArray);\n if (t.kind === \"record\") return t.fields.some((f) => hasArray(f.type));\n return false;\n };\n const builds = (e: Expr): boolean => listKinds.has(e.kind) || children(e).some(builds);\n // The arrows' own array literals and methods, read from their text: a disclosure may err only toward saying more.\n const arrowLists = [property.when, property.ensures].some(\n (a) => a !== undefined && /\\[|\\.(map|flatMap|every|some|reduce|slice|length)\\b/.test(a.body),\n );\n return (\n property.binders.some((b) => hasArray(b.type)) ||\n arrowLists ||\n reached(roots, module).some(\n (f) => hasList(f.returns) || f.params.some((p) => hasList(p.type)) || builds(f.body),\n )\n );\n}\n","/**\n * SMT-LIB 2 for a module in the subset and the properties on it, as Z3\n * reads it. `number` is the IEEE double (the floating-point theory, so\n * NaN, the infinities and -0 are in every binder's domain and `===` is\n * `fp.eq`, as in JavaScript), `string` a sequence of 16-bit code units,\n * `boolean` Bool, a record a datatype with one constructor, a tagged\n * union a datatype with one constructor per member holding that member's\n * record (so a record may be a member of several unions: a member is\n * wrapped where one of its unions is expected, and unwrapped where a test\n * of the tag narrows the union to it), a nullable type an\n * option datatype (`none`, `some`), with a name narrowed by a null check\n * bound to its value in the branch the check guards. Each property is one\n * script: the definitions, the binders as constants with what their\n * TypeScript types say beyond their sorts, the precondition asserted, the\n * claim's negation asserted, `check-sat`; an `unsat` is a proof, a model\n * is a candidate counterexample. Values in Z3's models are decoded back to\n * JavaScript values by this module too.\n */\n\nimport {\n type Expr,\n isListExpr,\n OutsideSubset,\n type RecordType,\n readArrowBody,\n renameVars,\n type SubsetFunction,\n type SubsetModule,\n type SubsetType,\n type TypeContext,\n typeOf,\n type UnionType,\n} from \"@eutaxy/prover/reader\";\nimport { type Arrow, describeType, type Property, type SpecType } from \"@eutaxy/spec\";\n\nexport const F64 = \"(_ FloatingPoint 11 53)\";\nexport const STR = \"(Seq (_ BitVec 16))\";\n\n/** A name as an SMT-LIB symbol: simple when it can be, quoted with | otherwise. */\nexport function symbol(name: string): string {\n // A quoted symbol may hold anything but `|` and `\\`: those are escaped as `%7c` and `%5c`, with `%`\n // itself as `%25` first, in every name, so two names never meet in one symbol (a quoted symbol and\n // a simple one spelled alike are the same symbol; a record is named as the compiler prints its\n // type, which may spell any of them).\n const escaped = name.replace(/%/g, \"%25\").replace(/\\\\/g, \"%5c\").replace(/\\|/g, \"%7c\");\n return /^[A-Za-z~!@$%^&*_+=<>.?/-][A-Za-z0-9~!@$%^&*_+=<>.?/-]*$/.test(escaped)\n ? escaped\n : `|${escaped}|`;\n}\n\n/** TypeScript names as SMT symbols that cannot clash with each other or with the theories' names. */\nexport const ident = {\n fn: (name: string) => symbol(`f_${name}`),\n /** The datatype of a record, or of a union. */\n record: (name: string) => symbol(`R_${name}`),\n constructor: (name: string) => symbol(`mk_${name}`),\n /** A union's constructor for one member, holding the member's record, and its selector. */\n inject: (union: string, member: string) => symbol(`in.${union}.${member}`),\n project: (union: string, member: string) => symbol(`out.${union}.${member}`),\n // A dot, which no TypeScript identifier holds, so selectors of different records never coincide.\n field: (record: string, field: string) => symbol(`fld.${record}.${field}`),\n variable: (name: string) => symbol(`v_${name}`),\n /** The option datatype over a sort, and its constructors and selector. */\n option: (base: string) => symbol(`Opt.${base}`),\n none: (base: string) => symbol(`none.${base}`),\n some: (base: string) => symbol(`some.${base}`),\n val: (base: string) => symbol(`val.${base}`),\n};\n\n/** The short name a sort has inside option names: `Opt.F64`, `Opt.R_X`. */\nexport function sortName(t: SubsetType, module: SubsetModule): string {\n if (t.kind === \"list\" || t.kind === \"nothing\") return fail(listsOutside);\n switch (t.kind) {\n case \"int\":\n return \"F64\";\n case \"bool\":\n return \"Bool\";\n case \"string\":\n return \"Str\";\n case \"record\":\n case \"union\":\n return ident.record(t.name);\n case \"nullable\":\n return ident.option(sortName(t.inner, module));\n case \"null\":\n return fail(\"null has no sort of its own\");\n }\n}\n\nexport function sort(t: SubsetType, module: SubsetModule): string {\n if (t.kind === \"list\" || t.kind === \"nothing\") return fail(listsOutside);\n switch (t.kind) {\n case \"int\":\n return F64;\n case \"bool\":\n return \"Bool\";\n case \"string\":\n return STR;\n case \"record\":\n case \"union\":\n case \"nullable\":\n return sortName(t, module);\n case \"null\":\n return fail(\"null has no sort of its own\");\n }\n}\n\n/** A constructor applied: a bare symbol when there are no arguments. */\nfunction construct(name: string, values: readonly string[]): string {\n return values.length === 0\n ? ident.constructor(name)\n : `(${ident.constructor(name)} ${values.join(\" \")})`;\n}\n\n/** A double as a floating-point literal. */\nexport function numberTerm(n: number): string {\n if (Number.isNaN(n)) return \"(_ NaN 11 53)\";\n if (n === Number.POSITIVE_INFINITY) return \"(_ +oo 11 53)\";\n if (n === Number.NEGATIVE_INFINITY) return \"(_ -oo 11 53)\";\n if (Object.is(n, -0)) return \"(_ -zero 11 53)\";\n if (n === 0) return \"(_ +zero 11 53)\";\n // Exact bits, so a value round-trips whatever its magnitude.\n const view = new DataView(new ArrayBuffer(8));\n view.setFloat64(0, n);\n const bits = view.getBigUint64(0);\n const sign = (bits >> 63n) & 1n;\n const exponent = (bits >> 52n) & 0x7ffn;\n const significand = bits & ((1n << 52n) - 1n);\n return `(fp #b${sign} #b${exponent.toString(2).padStart(11, \"0\")} #b${significand.toString(2).padStart(52, \"0\")})`;\n}\n\n/** A JavaScript string as a sequence of its UTF-16 code units. */\nexport function stringTerm(s: string): string {\n if (s.length === 0) return `(as seq.empty ${STR})`;\n const units: string[] = [];\n for (let i = 0; i < s.length; i++)\n units.push(`(seq.unit #x${s.charCodeAt(i).toString(16).padStart(4, \"0\")})`);\n return units.length === 1 ? (units[0] as string) : `(seq.++ ${units.join(\" \")})`;\n}\n\ninterface Env {\n readonly module: SubsetModule;\n readonly ctx: TypeContext;\n /** Each node's type per scope, computed once: emission asks for types at every level. */\n readonly types: WeakMap<Expr, Map<string, SubsetType>>;\n}\n\nfunction env(module: SubsetModule): Env {\n return {\n module,\n types: new WeakMap(),\n ctx: {\n records: new Map(module.records.map((r) => [r.name, r])),\n unions: module.unions,\n signatures: new Map(\n module.functions.map((f) => [f.name, { params: f.params, returns: f.returns }]),\n ),\n },\n };\n}\n\n/** Why a list, or an operation on one, is refused here. */\nconst listsOutside = \"arrays are not in this engine's subset (the Lean engine takes them)\";\n\nconst fail: (message: string) => never = (message) => {\n throw new OutsideSubset(message, 0);\n};\n\n/** `Number.isInteger(x)`: finite and equal to its truncation. */\nfunction isIntegerTerm(x: string): string {\n return `(and (not (fp.isNaN ${x})) (not (fp.isInfinite ${x})) (fp.eq ${x} (fp.roundToIntegral RTZ ${x})))`;\n}\n\n/** The members of a union, as records, in declaration order. */\nfunction membersOf(union: string, env: Env): RecordType[] {\n const u = env.module.unions.find((x) => x.name === union) ?? fail(`no union ${union}`);\n return u.members.map((m) => env.ctx.records.get(m.record) ?? fail(`no record ${m.record}`));\n}\n\nconst tester = (constructorSymbol: string): string =>\n constructorSymbol.startsWith(\"|\")\n ? `|is-${constructorSymbol.slice(1)}`\n : `is-${constructorSymbol}`;\n\n/** `===` of two terms of a type, as JavaScript has it. */\nfunction sameAs(a: string, b: string, t: SubsetType, env: Env): string {\n if (t.kind === \"list\" || t.kind === \"nothing\") return fail(listsOutside);\n switch (t.kind) {\n case \"int\":\n return `(fp.eq ${a} ${b})`;\n case \"bool\":\n case \"string\":\n return `(= ${a} ${b})`;\n case \"nullable\": {\n const base = sortName(t.inner, env.module);\n return `(ite (and (${tester(ident.some(base))} ${a}) (${tester(ident.some(base))} ${b})) ${sameAs(`(${ident.val(base)} ${a})`, `(${ident.val(base)} ${b})`, t.inner, env)} (and (${tester(ident.none(base))} ${a}) (${tester(ident.none(base))} ${b})))`;\n }\n case \"record\":\n case \"union\":\n case \"null\":\n return fail(\"=== on records compares references in JavaScript; compare their fields instead\");\n }\n}\n\n/**\n * A term of type `actual` as a value of type `want`: a member record\n * wrapped in the union's constructor for it, a value wrapped in `some`\n * where a nullable is wanted, a nullable member mapped into the nullable\n * union. Anything else is already of the sort wanted.\n */\nfunction lift(inner: string, actual: SubsetType, want: SubsetType, module: SubsetModule): string {\n if (want.kind === \"union\" && actual.kind === \"record\")\n return `(${ident.inject(want.name, actual.name)} ${inner})`;\n if (want.kind !== \"nullable\") return inner;\n if (actual.kind === \"null\") return inner;\n if (actual.kind === \"nullable\") {\n if (want.inner.kind !== \"union\" || actual.inner.kind !== \"record\") return inner;\n const from = sortName(actual.inner, module);\n const to = sortName(want.inner, module);\n return `(ite (${tester(ident.none(from))} ${inner}) ${ident.none(to)} (${ident.some(to)} ${lift(`(${ident.val(from)} ${inner})`, actual.inner, want.inner, module)}))`;\n }\n return `(${ident.some(sortName(want.inner, module))} ${lift(inner, actual, want.inner, module)})`;\n}\n\n/**\n * A term of the expression's type, or of `expected` where one is given:\n * `null` and a non-null value become the option's constructors where a\n * nullable is expected, and a member record its union's where the union is.\n */\nexport function term(\n e: Expr,\n scope: ReadonlyMap<string, SubsetType>,\n env: Env,\n expected?: SubsetType,\n): string {\n const t = (x: Expr, want?: SubsetType) => term(x, scope, env, want);\n if (isListExpr(e)) return fail(listsOutside);\n // A node's type depends on the scope it is typed in (narrowing), so the memo is keyed by both.\n const typed = (x: Expr): SubsetType => {\n const key = JSON.stringify([...scope]);\n let byScope = env.types.get(x);\n if (!byScope) {\n byScope = new Map();\n env.types.set(x, byScope);\n }\n let found = byScope.get(key);\n if (!found) {\n found = typeOf(x, scope, env.ctx, fail);\n byScope.set(key, found);\n }\n return found;\n };\n // A value where `want` is expected: a conditional, a let or a narrowing produce the expected sort\n // themselves; anything else is lifted to it (`lift`).\n const coerceIn = (x: Expr, want: SubsetType, sc: ReadonlyMap<string, SubsetType>): string => {\n if (\n x.kind === \"cond\" ||\n x.kind === \"let\" ||\n x.kind === \"narrow\" ||\n x.kind === \"narrowTag\" ||\n x.kind === \"null\"\n )\n return term(x, sc, env, want);\n const actual = sc === scope ? typed(x) : typeOf(x, sc, env.ctx, fail);\n return lift(term(x, sc, env, want), actual, want, env.module);\n };\n const coerce = (x: Expr, want: SubsetType): string => coerceIn(x, want, scope);\n // A narrowed body is a value where the narrowing stands: coerced to what is expected there.\n const narrowed = (body: Expr, inner: ReadonlyMap<string, SubsetType>): string =>\n expected ? coerceIn(body, expected, inner) : term(body, inner, env);\n switch (e.kind) {\n case \"int\":\n return numberTerm(Number(e.value));\n case \"bool\":\n return e.value ? \"true\" : \"false\";\n case \"string\":\n return stringTerm(e.value);\n case \"null\":\n if (expected?.kind !== \"nullable\") fail(\"null where no nullable type is expected\");\n return ident.none(sortName(expected.inner, env.module));\n case \"var\":\n return ident.variable(e.name);\n case \"narrow\": {\n const nt = scope.get(e.name);\n if (nt?.kind !== \"nullable\") fail(`${e.name} is narrowed but is not a nullable`);\n const base = sortName(nt.inner, env.module);\n const inner = new Map(scope);\n inner.set(e.name, nt.inner);\n return `(let ((${ident.variable(e.name)} (${ident.val(base)} ${ident.variable(e.name)}))) ${narrowed(e.body, inner)})`;\n }\n case \"narrowTag\": {\n // The name is bound to the member's record inside the union's value (the guard the node sits\n // under makes the constructor the right one), typed as the member in the body.\n const nt = scope.get(e.name);\n if (nt?.kind !== \"union\") fail(`${e.name} is narrowed by a tag but is not a union`);\n const inner = new Map(scope);\n inner.set(e.name, { kind: \"record\", name: e.member });\n const v = ident.variable(e.name);\n return `(let ((${v} (${ident.project(nt.name, e.member)} ${v}))) ${narrowed(e.body, inner)})`;\n }\n case \"neg\":\n return `(fp.neg ${t(e.operand)})`;\n case \"not\":\n return `(not ${t(e.operand)})`;\n case \"isInteger\":\n return isIntegerTerm(t(e.operand));\n case \"floor\":\n // Math.floor: toward negative infinity, -0, NaN and the infinities kept, as IEEE 754 rounds.\n return `(fp.roundToIntegral RTN ${t(e.operand)})`;\n case \"binary\": {\n const lt = typed(e.left);\n const rt = typed(e.right);\n switch (e.op) {\n case \"+\":\n return lt.kind === \"string\"\n ? `(seq.++ ${t(e.left)} ${t(e.right)})`\n : `(fp.add RNE ${t(e.left)} ${t(e.right)})`;\n case \"-\":\n return `(fp.sub RNE ${t(e.left)} ${t(e.right)})`;\n case \"*\":\n return `(fp.mul RNE ${t(e.left)} ${t(e.right)})`;\n case \"/\":\n return `(fp.div RNE ${t(e.left)} ${t(e.right)})`;\n case \"<\":\n return `(fp.lt ${t(e.left)} ${t(e.right)})`;\n case \"<=\":\n return `(fp.leq ${t(e.left)} ${t(e.right)})`;\n case \">\":\n return `(fp.gt ${t(e.left)} ${t(e.right)})`;\n case \">=\":\n return `(fp.geq ${t(e.left)} ${t(e.right)})`;\n case \"===\":\n case \"!==\": {\n let eq: string;\n if (lt.kind === \"null\" || rt.kind === \"null\") {\n // Against null: whether the nullable side is none.\n const side = lt.kind === \"null\" ? e.right : e.left;\n const st = lt.kind === \"null\" ? rt : lt;\n if (st.kind !== \"nullable\")\n fail(\"a comparison with null of something that is not nullable\");\n eq = `(${tester(ident.none(sortName(st.inner, env.module)))} ${t(side)})`;\n } else if (lt.kind === \"nullable\" && rt.kind !== \"nullable\") {\n const base = sortName(lt.inner, env.module);\n eq = `(and (${tester(ident.some(base))} ${t(e.left)}) ${sameAs(`(${ident.val(base)} ${t(e.left)})`, t(e.right), lt.inner, env)})`;\n } else if (rt.kind === \"nullable\" && lt.kind !== \"nullable\") {\n const base = sortName(rt.inner, env.module);\n eq = `(and (${tester(ident.some(base))} ${t(e.right)}) ${sameAs(t(e.left), `(${ident.val(base)} ${t(e.right)})`, rt.inner, env)})`;\n } else eq = sameAs(t(e.left), t(e.right), lt, env);\n return e.op === \"===\" ? eq : `(not ${eq})`;\n }\n case \"&&\":\n return `(and ${t(e.left)} ${t(e.right)})`;\n case \"||\":\n return `(or ${t(e.left)} ${t(e.right)})`;\n }\n break;\n }\n case \"cond\": {\n // Both branches of one sort: the expected one, or what the branches share.\n const want = expected ?? typed(e);\n return `(ite ${t(e.test)} ${coerce(e.ifTrue, want)} ${coerce(e.ifFalse, want)})`;\n }\n case \"call\": {\n const sig = env.ctx.signatures.get(e.callee) ?? fail(`no signature for ${e.callee}`);\n const args = e.args.map((a, i) =>\n coerce(a, (sig.params[i] as (typeof sig.params)[number]).type),\n );\n return args.length === 0 ? ident.fn(e.callee) : `(${ident.fn(e.callee)} ${args.join(\" \")})`;\n }\n case \"field\": {\n const o = typed(e.object);\n const obj = t(e.object);\n if (o.kind === \"union\") {\n // The field every member has: read from whichever member the value is.\n const members = membersOf(o.name, env);\n return members.reduceRight<string | undefined>((rest, m) => {\n const read = `(${ident.field(m.name, e.field)} (${ident.project(o.name, m.name)} ${obj}))`;\n return rest === undefined\n ? read\n : `(ite (${tester(ident.inject(o.name, m.name))} ${obj}) ${read} ${rest})`;\n }, undefined) as string;\n }\n if (o.kind !== \"record\") fail(`field ${e.field} read from a ${o.kind}`);\n return `(${ident.field(o.name, e.field)} ${obj})`;\n }\n case \"record\": {\n const type = typed(e);\n if (type.kind !== \"record\") fail(\"a record literal of no record type\");\n const rec = env.ctx.records.get(type.name) ?? fail(`no record ${type.name}`);\n // Fields in the declaration's order, whatever order the literal wrote them in.\n const values = rec.fields.map((f) => {\n const given =\n e.fields.find((x) => x.name === f.name) ?? fail(`${type.name} literal without ${f.name}`);\n return coerce(given.value, f.type);\n });\n return construct(type.name, values);\n }\n case \"let\": {\n const inner = new Map(scope);\n const bound = e.type ?? typed(e.value);\n inner.set(e.name, bound);\n const value = e.type ? coerce(e.value, e.type) : t(e.value);\n // The body is the let's value: lifted to what is expected where the let stands.\n return `(let ((${ident.variable(e.name)} ${value})) ${narrowed(e.body, inner)})`;\n }\n }\n}\n\nexport function emitFunction(f: SubsetFunction, module: SubsetModule): string {\n const e = env(module);\n const scope = new Map(f.params.map((p) => [p.name, p.type]));\n const params = f.params\n .map((p) => `(${ident.variable(p.name)} ${sort(p.type, module)})`)\n .join(\" \");\n // The body as a value of the declared return type (`coerce` is local to `term`; the rule is repeated).\n const body = (() => {\n const b = f.body;\n if (\n b.kind === \"cond\" ||\n b.kind === \"let\" ||\n b.kind === \"narrow\" ||\n b.kind === \"narrowTag\" ||\n b.kind === \"null\"\n )\n return term(b, scope, e, f.returns);\n return lift(term(b, scope, e, f.returns), typeOf(b, scope, e.ctx, fail), f.returns, module);\n })();\n return `(define-fun ${ident.fn(f.name)} (${params}) ${sort(f.returns, module)}\\n ${body})`;\n}\n\n/**\n * An option sort over every sort the module could mention: the primitives,\n * every record, every union. A body may join a\n * value with `null` in a `const` that no signature shows, so nothing is\n * left to discovery.\n */\nfunction optionSorts(module: SubsetModule): Map<string, SubsetType> {\n const out = new Map<string, SubsetType>();\n const bases: SubsetType[] = [\n { kind: \"int\" },\n { kind: \"bool\" },\n { kind: \"string\" },\n ...module.records.map((r): SubsetType => ({ kind: \"record\", name: r.name })),\n ...module.unions.map((u): SubsetType => ({ kind: \"union\", name: u.name })),\n ];\n for (const b of bases) out.set(sortName(b, module), b);\n return out;\n}\n\n/**\n * Every datatype in one declaration, so records, unions and options may\n * refer to one another in any order: a record is one constructor, a union\n * one per member holding its record, an option `none` and `some` over its\n * base sort.\n */\nexport function emitDatatypes(module: SubsetModule): string {\n const plain = module.records;\n const unions = module.unions;\n const options = optionSorts(module);\n const names = [\n ...plain.map((r) => ident.record(r.name)),\n ...unions.map((u) => ident.record(u.name)),\n ...[...options.keys()].map((base) => ident.option(base)),\n ];\n if (names.length === 0) return \"\";\n const constructorOf = (r: RecordType): string =>\n `(${ident.constructor(r.name)}${r.fields.map((f) => ` (${ident.field(r.name, f.name)} ${sort(f.type, module)})`).join(\"\")})`;\n const bodies = [\n ...plain.map((r) => `(${constructorOf(r)})`),\n ...unions.map(\n (u) =>\n `(${u.members.map((m) => `(${ident.inject(u.name, m.record)} (${ident.project(u.name, m.record)} ${ident.record(m.record)}))`).join(\" \")})`,\n ),\n ...[...options].map(\n ([base, inner]) =>\n `((${ident.none(base)}) (${ident.some(base)} (${ident.val(base)} ${sort(inner, module)})))`,\n ),\n ];\n return `(declare-datatypes (${names.map((n) => `(${n} 0)`).join(\" \")}) (${bodies.join(\" \")}))`;\n}\n\n/**\n * The subset type a binder ranges over, or `OutsideSubset`: `number` is\n * the double, a union of string literals is a string (constrained to the\n * literals in the script), a record is the module's datatype of that\n * name, `T | null` the option over `T`, a union of records the declared\n * union whose members match. Bigint and what the reader could not read\n * are outside.\n */\nexport function binderType(name: string, t: SpecType, module: SubsetModule): SubsetType {\n switch (t.kind) {\n case \"number\":\n return { kind: \"int\" };\n case \"boolean\":\n return { kind: \"bool\" };\n case \"string\":\n return { kind: \"string\" };\n case \"literal\":\n if (typeof t.value === \"string\") return { kind: \"string\" };\n if (typeof t.value === \"boolean\") return { kind: \"bool\" };\n return { kind: \"int\" };\n case \"bigint\":\n fail(`binder ${name} over bigint: the subset has no bigint`);\n break;\n case \"union\": {\n const nulls = t.members.filter((m) => m.kind === \"null\");\n if (t.members.some((m) => m.kind === \"undefined\"))\n fail(`binder ${name} over ${describeType(t)}: undefined is not in the subset (null is)`);\n const rest = t.members.filter((m) => m.kind !== \"null\");\n let inner: SubsetType;\n if (rest.every((m) => m.kind === \"literal\" && typeof m.value === \"string\"))\n inner = { kind: \"string\" };\n else if (rest.every((m) => m.kind === \"literal\" && typeof m.value === \"boolean\"))\n inner = { kind: \"bool\" };\n else if (rest.length === 1) inner = binderType(name, rest[0] as SpecType, module);\n else if (rest.every((m) => m.kind === \"record\")) {\n const union = findUnion(rest as readonly Extract<SpecType, { kind: \"record\" }>[], module);\n if (!union)\n fail(\n `binder ${name} over ${describeType(t)}: no one union the module declares has exactly these members`,\n );\n inner = { kind: \"union\", name: union.name };\n } else fail(`binder ${name} over ${describeType(t)}: a union the subset does not read`);\n return nulls.length > 0 ? { kind: \"nullable\", inner } : inner;\n }\n case \"record\":\n if (t.name !== undefined && module.records.some((r) => r.name === t.name))\n return { kind: \"record\", name: t.name };\n fail(\n `binder ${name} over ${describeType(t)}: ${t.name === undefined ? \"an inline record type\" : `record type ${t.name} is outside the subset`}`,\n );\n break;\n case \"null\":\n case \"undefined\":\n fail(`binder ${name} over ${t.kind}`);\n break;\n case \"array\":\n fail(`binder ${name} over ${describeType(t)}: arrays are not in the engine's subset yet`);\n break;\n case \"unknown\":\n fail(`binder ${name} over ${t.text}, which the reader could not read`);\n }\n}\n\n/**\n * The one declared union these member types are, compared field by field\n * and type by type: a field holding one literal is that literal in the\n * union's member, a union of literals is a field of no literal, and\n * everything else reads to the field's own type. A record may be a member\n * of several unions, so tags and field names alone could name the wrong\n * one; when more than one union fits, none is chosen.\n */\nfunction findUnion(\n members: readonly Extract<SpecType, { kind: \"record\" }>[],\n module: SubsetModule,\n): UnionType | undefined {\n const recordOf = (name: string) => module.records.find((r) => r.name === name);\n // A nested record is compared by its fields, not its name: the spec reader and the subset reader\n // may name one inline type differently (`Extract<U, …>` against `U.a`).\n const recordFits = (sm: Extract<SpecType, { kind: \"record\" }>, rec: RecordType): boolean =>\n sm.fields.length === rec.fields.length &&\n rec.fields.every((f) => {\n const sf = sm.fields.find((x) => x.name === f.name);\n return sf !== undefined && fieldFits(sf.type, f);\n });\n const typeFits = (sf: SpecType, t: SubsetType): boolean => {\n if (t.kind === \"record\") {\n const rec = recordOf(t.name);\n return sf.kind === \"record\" && rec !== undefined && recordFits(sf, rec);\n }\n if (t.kind === \"nullable\" && sf.kind === \"union\" && sf.members.some((m) => m.kind === \"null\")) {\n const rest = sf.members.filter((m) => m.kind !== \"null\");\n const inner: SpecType =\n rest.length === 1 ? (rest[0] as SpecType) : { kind: \"union\", members: rest };\n return typeFits(inner, t.inner);\n }\n if (t.kind === \"union\") {\n const u = module.unions.find((x) => x.name === t.name);\n if (!u || sf.kind !== \"union\" || sf.members.length !== u.members.length) return false;\n return u.members.every((m) => {\n const rec = recordOf(m.record);\n return (\n rec !== undefined && sf.members.some((sm) => sm.kind === \"record\" && recordFits(sm, rec))\n );\n });\n }\n try {\n return JSON.stringify(binderType(\"field\", sf, module)) === JSON.stringify(t);\n } catch (err) {\n if (err instanceof OutsideSubset) return false;\n throw err;\n }\n };\n function fieldFits(sf: SpecType, f: RecordType[\"fields\"][number]): boolean {\n if (f.literal !== undefined) return sf.kind === \"literal\" && sf.value === f.literal;\n if (sf.kind === \"literal\") return false;\n return typeFits(sf, f.type);\n }\n const fitting = module.unions.filter((u) => {\n if (u.members.length !== members.length) return false;\n return u.members.every((m) => {\n const rec = recordOf(m.record);\n return rec !== undefined && members.some((sm) => recordFits(sm, rec));\n });\n });\n return fitting.length === 1 ? fitting[0] : undefined;\n}\n\n/**\n * What a binder's subset type says that its sort does not: a union's\n * members carry their tags, and so on\n * into fields and under an option. Undefined when the sort says it all.\n */\nexport function wellFormed(\n target: string,\n t: SubsetType,\n module: SubsetModule,\n): string | undefined {\n switch (t.kind) {\n case \"int\":\n case \"bool\":\n case \"string\":\n case \"null\":\n return undefined;\n case \"nullable\": {\n const base = sortName(t.inner, module);\n const inner = wellFormed(`(${ident.val(base)} ${target})`, t.inner, module);\n return inner === undefined\n ? undefined\n : `(or (${tester(ident.none(base))} ${target}) ${inner})`;\n }\n case \"record\": {\n const rec = module.records.find((r) => r.name === t.name);\n if (!rec) return undefined;\n const parts: string[] = [];\n for (const f of rec.fields) {\n const read = `(${ident.field(rec.name, f.name)} ${target})`;\n if (f.literal !== undefined)\n parts.push(\n typeof f.literal === \"string\"\n ? `(= ${read} ${stringTerm(f.literal)})`\n : `(= ${read} ${f.literal ? \"true\" : \"false\"})`,\n );\n const inner = wellFormed(read, f.type, module);\n if (inner !== undefined) parts.push(inner);\n }\n return parts.length === 0\n ? undefined\n : parts.length === 1\n ? parts[0]\n : `(and ${parts.join(\" \")})`;\n }\n case \"union\": {\n const u = module.unions.find((x) => x.name === t.name);\n if (!u) return undefined;\n const cases = u.members.map((m) => {\n const is = `(${tester(ident.inject(u.name, m.record))} ${target})`;\n const inner = wellFormed(\n `(${ident.project(u.name, m.record)} ${target})`,\n { kind: \"record\", name: m.record },\n module,\n );\n return inner === undefined ? is : `(and ${is} ${inner})`;\n });\n return `(or ${cases.join(\" \")})`;\n }\n }\n}\n\n/**\n * What a binder's TypeScript type says beyond its sort: a literal, or a\n * union of literals (with or without null), admits only those values,\n * which the solver must be told, since the sort alone would let it pick\n * any string or number.\n */\nexport function domainConstraint(\n symbolName: string,\n t: SpecType,\n subset: SubsetType,\n module: SubsetModule,\n): string | undefined {\n const literal = (target: string, v: string | number | boolean): string =>\n typeof v === \"string\"\n ? `(= ${target} ${stringTerm(v)})`\n : typeof v === \"number\"\n ? `(fp.eq ${target} ${numberTerm(v)})`\n : `(= ${target} ${v ? \"true\" : \"false\"})`;\n const literals: (string | number | boolean)[] = [];\n let withNull = false;\n if (t.kind === \"literal\") literals.push(t.value);\n else if (t.kind === \"union\") {\n for (const m of t.members) {\n if (m.kind === \"literal\") literals.push(m.value);\n else if (m.kind === \"null\") withNull = true;\n else return undefined;\n }\n } else return undefined;\n if (literals.length === 0) return undefined;\n const over = (target: string) => {\n const alternatives = literals.map((v) => literal(target, v));\n return alternatives.length === 1\n ? (alternatives[0] as string)\n : `(or ${alternatives.join(\" \")})`;\n };\n if (subset.kind === \"nullable\") {\n const base = sortName(subset.inner, module);\n const some = `(and (${tester(ident.some(base))} ${symbolName}) ${over(`(${ident.val(base)} ${symbolName})`)})`;\n return withNull ? `(or (${tester(ident.none(base))} ${symbolName}) ${some})` : some;\n }\n return over(symbolName);\n}\n\n/** An arrow of the spec file as a Bool term over the binders, its own parameter names renamed to theirs. */\nfunction arrowTerm(\n arrow: Arrow,\n what: \"when\" | \"ensures\",\n property: Property,\n types: readonly SubsetType[],\n e: Env,\n): string {\n try {\n const binders = property.binders;\n const scope = new Map<string, SubsetType>();\n const names = new Map<string, string>();\n arrow.params.forEach((p, i) => {\n const binder = binders[i];\n const type = types[i];\n if (p === null) fail(`a destructured parameter in ${what}`);\n if (!binder || !type) fail(`${what} takes more parameters than the function has`);\n scope.set(p, type);\n names.set(p, binder.name);\n });\n const aliases = new Map(property.imports.map((i) => [i.local, i.fn]));\n const read = readArrowBody(arrow, scope, e.module, aliases);\n const t = typeOf(read, scope, e.ctx, fail);\n if (t.kind !== \"bool\")\n fail(`${what} is not boolean (a ${t.kind === \"record\" ? t.name : t.kind})`);\n const renamed = renameVars(read, names);\n const binderScope = new Map(binders.map((b, i) => [b.name, types[i] as SubsetType]));\n return term(renamed, binderScope, e);\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n throw new OutsideSubset(`${what} (spec file line ${arrow.line}): ${err.message}`, arrow.line);\n }\n}\n\n/** The definitions every script of the module starts with: datatypes, then functions, callees first. */\nexport function prelude(module: SubsetModule): string {\n const datatypes = emitDatatypes(module);\n return [\n \";; Generated by Eutaxy's first-party SMT engine from the module and its spec file.\",\n \"(set-option :produce-models true)\",\n ...(datatypes === \"\" ? [] : [datatypes]),\n ...module.functions.map((f) => emitFunction(f, module)),\n ].join(\"\\n\");\n}\n\nexport interface PropertyScript {\n readonly script: string;\n /** The binders' SMT names and types, in order, for reading a model back. */\n readonly binders: readonly {\n readonly name: string;\n readonly symbol: string;\n readonly type: SubsetType;\n }[];\n}\n\n/**\n * One property's script: the binders as constants, what their types say\n * beyond their sorts, the precondition asserted, the claim's negation\n * asserted. `unsat` proves the claim; `sat` comes with the binders' values.\n * `definitions` is the module's `prelude`, when the caller already has it.\n */\nexport function propertyScript(\n property: Property,\n module: SubsetModule,\n definitions: string = prelude(module),\n): PropertyScript {\n if (property.kind !== \"forall\" || !property.ensures) fail(\"not a forall property\");\n const e = env(module);\n const types = property.binders.map((b) => binderType(b.name, b.type, module));\n const binders = property.binders.map((b, i) => ({\n name: b.name,\n symbol: ident.variable(b.name),\n type: types[i] as SubsetType,\n }));\n const lines = [\n definitions,\n ...binders.map((b) => `(declare-const ${b.symbol} ${sort(b.type, module)})`),\n // What a binder's subset type says that its sort does not: which member of a union, which tags.\n ...binders.flatMap((b) => {\n const c = wellFormed(b.symbol, b.type, module);\n return c === undefined ? [] : [`(assert ${c})`];\n }),\n ...property.binders.flatMap((b, i) => {\n const c = domainConstraint(\n (binders[i] as (typeof binders)[number]).symbol,\n b.type,\n types[i] as SubsetType,\n module,\n );\n return c === undefined ? [] : [`(assert ${c})`];\n }),\n ...(property.when ? [`(assert ${arrowTerm(property.when, \"when\", property, types, e)})`] : []),\n `(assert (not ${arrowTerm(property.ensures, \"ensures\", property, types, e)}))`,\n \"(check-sat)\",\n ...(binders.length > 0 ? [`(get-value (${binders.map((b) => b.symbol).join(\" \")}))`] : []),\n \"(get-info :reason-unknown)\",\n ];\n return { script: `${lines.join(\"\\n\")}\\n`, binders };\n}\n\n/** A TypeScript value of a subset type as a term, for translation checks. */\nexport function value(v: unknown, t: SubsetType, module: SubsetModule): string {\n if (t.kind === \"list\" || t.kind === \"nothing\") return fail(listsOutside);\n switch (t.kind) {\n case \"int\":\n if (typeof v !== \"number\") fail(`${String(v)} is not a number`);\n return numberTerm(v);\n case \"bool\":\n if (typeof v !== \"boolean\") fail(`${String(v)} is not a boolean`);\n return v ? \"true\" : \"false\";\n case \"string\":\n if (typeof v !== \"string\") fail(`${String(v)} is not a string`);\n return stringTerm(v);\n case \"nullable\": {\n const base = sortName(t.inner, module);\n return v === null ? ident.none(base) : `(${ident.some(base)} ${value(v, t.inner, module)})`;\n }\n case \"union\": {\n const u = module.unions.find((x) => x.name === t.name) ?? fail(`no union ${t.name}`);\n if (typeof v !== \"object\" || v === null) fail(`${String(v)} is not a ${t.name}`);\n const tag = (v as Record<string, unknown>)[u.tag];\n const member =\n u.members.find((m) => m.tag === tag) ?? fail(`${t.name} value with tag ${String(tag)}`);\n return `(${ident.inject(u.name, member.record)} ${value(v, { kind: \"record\", name: member.record }, module)})`;\n }\n case \"record\": {\n const rec = module.records.find((r) => r.name === t.name) ?? fail(`no record ${t.name}`);\n if (typeof v !== \"object\" || v === null) fail(`${String(v)} is not a record`);\n const o = v as Record<string, unknown>;\n const extra = Object.keys(o).filter((k) => !rec.fields.some((f) => f.name === k));\n if (extra.length > 0) fail(`${t.name} value has unexpected fields ${extra.join(\", \")}`);\n return construct(\n t.name,\n rec.fields.map((f) => value(o[f.name], f.type, module)),\n );\n }\n case \"null\":\n return fail(\"a value of type null\");\n }\n}\n\n/** Equality of two terms of a type, as JavaScript would have it: `fp.eq` on numbers, field by field on records. */\nexport function equal(a: string, b: string, t: SubsetType, module: SubsetModule): string {\n if (t.kind === \"list\" || t.kind === \"nothing\") return fail(listsOutside);\n switch (t.kind) {\n case \"int\":\n return `(fp.eq ${a} ${b})`;\n case \"bool\":\n case \"string\":\n return `(= ${a} ${b})`;\n case \"nullable\": {\n const base = sortName(t.inner, module);\n return `(ite (and (${tester(ident.some(base))} ${a}) (${tester(ident.some(base))} ${b})) ${equal(`(${ident.val(base)} ${a})`, `(${ident.val(base)} ${b})`, t.inner, module)} (and (${tester(ident.none(base))} ${a}) (${tester(ident.none(base))} ${b})))`;\n }\n case \"union\": {\n const u = module.unions.find((x) => x.name === t.name) ?? fail(`no union ${t.name}`);\n const cases = u.members.map((m) => {\n const is = tester(ident.inject(u.name, m.record));\n const out = ident.project(u.name, m.record);\n return `(and (${is} ${a}) (${is} ${b}) ${equal(`(${out} ${a})`, `(${out} ${b})`, { kind: \"record\", name: m.record }, module)})`;\n });\n return `(or ${cases.join(\" \")})`;\n }\n case \"record\": {\n const rec = module.records.find((r) => r.name === t.name) ?? fail(`no record ${t.name}`);\n const fields = rec.fields.map((f) =>\n equal(\n `(${ident.field(t.name, f.name)} ${a})`,\n `(${ident.field(t.name, f.name)} ${b})`,\n f.type,\n module,\n ),\n );\n if (fields.length === 0) return \"true\";\n return fields.length === 1 ? (fields[0] as string) : `(and ${fields.join(\" \")})`;\n }\n case \"null\":\n return fail(\"equality at type null\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// Reading Z3's answers.\n\nexport type SExpr = string | readonly SExpr[];\n\n/** Z3's output as S-expressions and atoms, in order. */\nexport function parseSExprs(text: string): SExpr[] {\n const out: SExpr[] = [];\n const stack: SExpr[][] = [];\n let i = 0;\n const push = (x: SExpr) => {\n const top = stack[stack.length - 1];\n if (top) top.push(x);\n else out.push(x);\n };\n while (i < text.length) {\n const c = text[i] as string;\n if (/\\s/.test(c)) {\n i++;\n continue;\n }\n if (c === \";\") {\n while (i < text.length && text[i] !== \"\\n\") i++;\n continue;\n }\n if (c === \"(\") {\n stack.push([]);\n i++;\n continue;\n }\n if (c === \")\") {\n const done = stack.pop();\n if (done) push(done);\n i++;\n continue;\n }\n if (c === '\"') {\n let j = i + 1;\n let s = \"\";\n while (j < text.length) {\n if (text[j] === '\"' && text[j + 1] === '\"') {\n s += '\"';\n j += 2;\n } else if (text[j] === '\"') break;\n else s += text[j++];\n }\n push(`\"${s}\"`);\n i = j + 1;\n continue;\n }\n if (c === \"|\") {\n const j = text.indexOf(\"|\", i + 1);\n push(text.slice(i, j < 0 ? text.length : j + 1));\n i = j < 0 ? text.length : j + 1;\n continue;\n }\n let j = i;\n while (j < text.length && !/[\\s()]/.test(text[j] as string)) j++;\n push(text.slice(i, j));\n i = j;\n }\n while (stack.length > 0) {\n const done = stack.pop();\n if (done) push(done);\n }\n return out;\n}\n\n/** Thrown when a model value is not of the shape the type calls for. */\nexport class UnreadableModel extends Error {}\n\nconst bitsOf = (atom: string): bigint =>\n atom.startsWith(\"#b\") ? BigInt(`0b${atom.slice(2)}`) : BigInt(`0x${atom.slice(2)}`);\n\n/** A model value of the type as a JavaScript value. */\nexport function decode(x: SExpr, t: SubsetType, module: SubsetModule): unknown {\n switch (t.kind) {\n case \"bool\":\n if (x === \"true\") return true;\n if (x === \"false\") return false;\n throw new UnreadableModel(`not a boolean: ${show(x)}`);\n case \"int\": {\n if (Array.isArray(x) && x[0] === \"_\") {\n const special = x[1];\n if (special === \"NaN\") return Number.NaN;\n if (special === \"+oo\") return Number.POSITIVE_INFINITY;\n if (special === \"-oo\") return Number.NEGATIVE_INFINITY;\n if (special === \"+zero\") return 0;\n if (special === \"-zero\") return -0;\n }\n if (Array.isArray(x) && x[0] === \"fp\" && x.length === 4) {\n const sign = bitsOf(x[1] as string);\n const exponent = bitsOf(x[2] as string);\n const significand = bitsOf(x[3] as string);\n const view = new DataView(new ArrayBuffer(8));\n view.setBigUint64(0, (sign << 63n) | (exponent << 52n) | significand);\n return view.getFloat64(0);\n }\n throw new UnreadableModel(`not a double: ${show(x)}`);\n }\n case \"string\":\n return decodeString(x);\n case \"nullable\": {\n const base = sortName(t.inner, module);\n if (x === ident.none(base)) return null;\n if (Array.isArray(x) && x[0] === ident.some(base) && x.length === 2)\n return decode(x[1] as SExpr, t.inner, module);\n throw new UnreadableModel(`not a ${describeSubset(t)}: ${show(x)}`);\n }\n case \"union\": {\n const u = module.unions.find((y) => y.name === t.name);\n if (!u) throw new UnreadableModel(`no union ${t.name}`);\n const head = Array.isArray(x) ? x[0] : x;\n const member = u.members.find((m) => ident.inject(u.name, m.record) === head);\n if (!member || !Array.isArray(x) || x.length !== 2)\n throw new UnreadableModel(`not a ${t.name}: ${show(x)}`);\n return decode(x[1] as SExpr, { kind: \"record\", name: member.record }, module);\n }\n case \"record\": {\n const rec = module.records.find((r) => r.name === t.name);\n if (!rec) throw new UnreadableModel(`no record ${t.name}`);\n if (rec.fields.length === 0 && x === ident.constructor(t.name)) return {};\n if (\n !Array.isArray(x) ||\n x[0] !== ident.constructor(t.name) ||\n x.length !== rec.fields.length + 1\n )\n throw new UnreadableModel(`not a ${t.name}: ${show(x)}`);\n const out: Record<string, unknown> = {};\n rec.fields.forEach((f, i) => {\n out[f.name] = decode(x[i + 1] as SExpr, f.type, module);\n });\n return out;\n }\n case \"null\":\n throw new UnreadableModel(\"a value of type null\");\n }\n}\n\nfunction describeSubset(t: SubsetType): string {\n return t.kind === \"nullable\"\n ? `${describeSubset(t.inner)} | null`\n : t.kind === \"record\" || t.kind === \"union\"\n ? t.name\n : t.kind;\n}\n\nfunction decodeString(x: SExpr): string {\n if (Array.isArray(x)) {\n if (x[0] === \"seq.unit\" && typeof x[1] === \"string\")\n return String.fromCharCode(Number(bitsOf(x[1])));\n if (x[0] === \"seq.++\") return x.slice(1).map(decodeString).join(\"\");\n if (x[0] === \"as\" && x[1] === \"seq.empty\") return \"\";\n if (x[0] === \"_\" && x[1] === \"seq.empty\") return \"\";\n }\n throw new UnreadableModel(`not a string: ${show(x)}`);\n}\n\nfunction show(x: SExpr): string {\n return typeof x === \"string\" ? x : `(${x.map(show).join(\" \")})`;\n}\n\nexport interface Answer {\n readonly result: \"sat\" | \"unsat\" | \"unknown\" | \"error\";\n /** The binders' values when `sat`, by SMT symbol. */\n readonly values: ReadonlyMap<string, SExpr>;\n readonly reason: string;\n /** Every `(error …)` Z3 printed, except the one for a model asked after `unsat`, which the script expects. */\n readonly errors: readonly string[];\n}\n\n/** What a property's script came back with. */\nexport function readAnswer(output: string): Answer {\n const parts = parseSExprs(output);\n const first = parts.find((p) => p === \"sat\" || p === \"unsat\" || p === \"unknown\");\n const errors = parts\n .filter((p): p is readonly SExpr[] => Array.isArray(p) && p[0] === \"error\")\n .map((e) => show(e))\n .filter((e) => !/model is not available/.test(e));\n const values = new Map<string, SExpr>();\n let reason = \"\";\n for (const p of parts) {\n if (!Array.isArray(p)) continue;\n if (p[0] === \":reason-unknown\" && typeof p[1] === \"string\") reason = p[1].replace(/^\"|\"$/g, \"\");\n if (p.every((x) => Array.isArray(x) && x.length === 2 && typeof x[0] === \"string\"))\n for (const pair of p as readonly (readonly [string, SExpr])[]) values.set(pair[0], pair[1]);\n }\n if (first === undefined)\n return { result: \"error\", values, reason: errors.join(\"; \") || output.trim(), errors };\n return { result: first as Answer[\"result\"], values, reason, errors };\n}\n","/**\n * Running Z3 over a process boundary. The engine is pinned to one Z3\n * release, looked for in Eutaxy's cache first (where `eutaxy prover install\n * smt` puts the upstream release named in `z3Downloads`), then as a `z3`\n * on the PATH (or in Homebrew's and the usual local prefixes) that must\n * report that version. Nothing is downloaded during a check; a missing\n * solver is `unavailable`, with how to install it. Every\n * run carries a resource limit, Z3's own machine-independent budget, so\n * the same script gives the same outcome on every machine; a wall-clock\n * timeout is only the safety net.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { mkdtempSync, rmSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { type Host, host, installed, type Toolchain } from \"@eutaxy/prover/toolchain\";\n\n/** The Z3 release the engine's contract corpus is checked against. */\nexport const z3Version = \"5.3.2\";\n/** How to put the pinned solver on this machine. */\nexport const installHint = `run: eutaxy prover install smt (or put Z3 ${z3Version} on the PATH, from https://github.com/Z3Prover/z3/releases/tag/z3-${z3Version} or Homebrew: brew install z3)`;\n\nconst z3Release = `https://github.com/Z3Prover/z3/releases/download/z3-${z3Version}`;\n/** The files the solver needs on Linux and macOS: the executable, which links only system libraries. */\nconst unixFiles = [\"bin/z3\"];\n/**\n * On Windows the executable also needs the Visual C++ runtime, which a fresh\n * Windows may lack; the release ships it beside `z3.exe`, and Windows loads\n * a DLL from the executable's own directory first.\n */\nconst windowsFiles = [\n \"bin/z3.exe\",\n \"bin/msvcp140.dll\",\n \"bin/vcruntime140.dll\",\n \"bin/vcruntime140_1.dll\",\n];\nconst z3File = (name: string, sha256: string, bytes: number, files: readonly string[]) => ({\n file: name,\n url: `${z3Release}/${name}`,\n sha256,\n bytes,\n // Each release puts everything under one directory named like the file.\n entries: Object.fromEntries(files.map((f) => [`${name.replace(/\\.zip$/, \"\")}/${f}`, f])),\n});\n/**\n * The upstream release files `eutaxy prover install smt` downloads, one per\n * platform, as published on Z3's GitHub release with the checksums it\n * reports, and the files taken from each (the rest of the zip, bindings for\n * other languages, headers and the shared library, is not unpacked); the\n * file names carry the version, and a test holds them to `z3Version`. The\n * Linux builds need glibc 2.39 (x64) or 2.38 (arm64).\n */\nexport const z3Downloads: Toolchain = {\n name: \"smt\",\n version: z3Version,\n executable: \"bin/z3\",\n files: {\n \"linux-x64\": z3File(\n \"z3-5.3.2-x64-glibc-2.39.zip\",\n \"26d463cddad3901cbf86e3868c784914539f4e3f9b4de1a0b8dc2969806d60e2\",\n 69479256,\n unixFiles,\n ),\n \"linux-arm64\": z3File(\n \"z3-5.3.2-arm64-glibc-2.38.zip\",\n \"30b6a718a6cfe1b2db056038cc32eda5410f6d02e5937622b5238645347f59d5\",\n 64803341,\n unixFiles,\n ),\n \"darwin-x64\": z3File(\n \"z3-5.3.2-x64-osx-13.3.zip\",\n \"b911dc193f7447a14fba001e8e8a0c2866a544274bb003e76a9e864f03b4d557\",\n 54270076,\n unixFiles,\n ),\n \"darwin-arm64\": z3File(\n \"z3-5.3.2-arm64-osx-13.3.zip\",\n \"524290057c943a044ec3d1372db65a9c93f333d9817d58191154c4719ff7f8ad\",\n 53576249,\n unixFiles,\n ),\n \"win32-x64\": z3File(\n \"z3-5.3.2-x64-win.zip\",\n \"a75aa2b0383a8ee355387a54daad796911d6a965076751eea18d21a27f38e983\",\n 70867398,\n windowsFiles,\n ),\n },\n};\n/** The resource budget a check runs under (Z3's `rlimit`, in its own units), unless configured. */\nexport const defaultResourceLimit = 50_000_000;\n\nexport interface Z3Run {\n readonly code: number | null;\n readonly stdout: string;\n readonly stderr: string;\n readonly timedOut: boolean;\n}\n\nexport interface Z3Solver {\n readonly command: string;\n readonly version: string;\n}\n\nfunction run(\n command: string,\n args: readonly string[],\n options: { readonly cwd?: string; readonly timeoutMs: number },\n): Promise<Z3Run> {\n return new Promise((resolve) => {\n let child: ReturnType<typeof spawn>;\n try {\n child = spawn(command, args, { cwd: options.cwd, stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n } catch (err) {\n resolve({ code: null, stdout: \"\", stderr: String(err), timedOut: false });\n return;\n }\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGKILL\");\n }, options.timeoutMs);\n child.stdout?.on(\"data\", (d: Buffer) => {\n stdout += d.toString();\n });\n child.stderr?.on(\"data\", (d: Buffer) => {\n stderr += d.toString();\n });\n child.on(\"error\", (err) => {\n clearTimeout(timer);\n resolve({ code: null, stdout, stderr: `${stderr}${String(err)}`, timedOut });\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n resolve({ code, stdout, stderr, timedOut });\n });\n });\n}\n\n/**\n * Candidates for the `z3` executable: the one `eutaxy prover install smt`\n * put in the cache, `EUTAXY_Z3`, the PATH, then the prefixes package\n * managers install into.\n */\nexport function candidates(h: Host = host()): string[] {\n const fromEnv = h.env[\"EUTAXY_Z3\"];\n const fromCache = installed(z3Downloads, h);\n return [\n ...(fromCache ? [fromCache.executable] : []),\n ...(fromEnv ? [fromEnv] : []),\n \"z3\",\n \"/opt/homebrew/bin/z3\",\n \"/usr/local/bin/z3\",\n \"/usr/bin/z3\",\n ];\n}\n\n/**\n * The pinned solver if it is installed: a `z3` of exactly that version,\n * wherever among the candidates it is; another version is reported only\n * when no candidate is the pinned one.\n */\nexport async function findZ3(\n where: readonly string[] = candidates(),\n): Promise<Z3Solver | { readonly unavailable: string }> {\n let other: string | undefined;\n for (const z3 of where) {\n const v = await run(z3, [\"--version\"], { timeoutMs: 20_000 });\n if (v.code !== 0) continue;\n const m = /Z3 version (\\S+)/.exec(v.stdout);\n if (m?.[1] === z3Version) return { command: z3, version: z3Version };\n other ??= m?.[1] ?? \"of unknown version\";\n }\n if (other !== undefined)\n return {\n unavailable: `z3 ${other} found, but the engine is pinned to ${z3Version}; ${installHint}`,\n };\n return { unavailable: `no z3 found; ${installHint}` };\n}\n\nexport interface SolvedScript {\n readonly run: Z3Run;\n /** Whether Z3 reported the resource limit exceeded. */\n readonly resourceLimit: boolean;\n}\n\n/** Write the script to a scratch file and run Z3 on it under the resource limit. */\nexport async function solve(\n solver: Z3Solver,\n script: string,\n options: {\n readonly timeoutMs?: number;\n readonly resourceLimit?: number;\n readonly keep?: boolean;\n } = {},\n): Promise<SolvedScript> {\n const dir = mkdtempSync(join(tmpdir(), \"eutaxy-smt-\"));\n try {\n const file = join(dir, \"property.smt2\");\n writeFileSync(file, script);\n const result = await run(\n solver.command,\n [`rlimit=${options.resourceLimit ?? defaultResourceLimit}`, \"-smt2\", file],\n { cwd: dir, timeoutMs: options.timeoutMs ?? 120_000 },\n );\n return { run: result, resourceLimit: /resource limit/i.test(result.stdout) };\n } finally {\n if (!options.keep) rmSync(dir, { recursive: true, force: true });\n }\n}\n","/**\n * The engine: a module's functions through the subset reader, the emitter\n * and Z3, one script per property, and each property's outcome back. An\n * `unsat` is `PROVEN` under the engine's models of the language. A model\n * is a candidate counterexample, never a verdict: the engine runs the\n * spec file's own `when` and `ensures` on it, and only a claim that fails\n * on the real function is `REFUTED`, with the input shrunk as the TESTED\n * rung shrinks; a model the function does not confirm is a modelling gap,\n * `UNKNOWN` (`unsupported`) with the input. A resource limit reached is\n * `gave_up`; a function or property outside the subset is `unsupported`;\n * no pinned solver is `unavailable`.\n */\n\nimport { existsSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { availableParallelism } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n conforms,\n evaluate,\n inPool,\n type ModuleProofs,\n type ProofOutcome,\n type PropertyProof,\n type Prover,\n type ProveInput as ProverInput,\n render,\n shrinkRefutation,\n} from \"@eutaxy/prover\";\nimport {\n builtinsAssumption,\n listKinds,\n OutsideSubset,\n readSubset,\n restrictModule,\n type SubsetModule,\n} from \"@eutaxy/prover/reader\";\nimport { type Fn, type Forall, type FunctionSpec, isSpec, type Property } from \"@eutaxy/spec\";\nimport {\n decode,\n equal,\n type PropertyScript,\n prelude,\n propertyScript,\n readAnswer,\n UnreadableModel,\n} from \"./emit.ts\";\nimport { findZ3, solve, z3Version } from \"./z3.ts\";\n\nexport const engineName = \"smt\";\n\nexport interface ProveInput extends ProverInput {\n /** Extra Bool terms over the module's definitions that must hold (translation checks): each is checked unsatisfiable when negated. */\n readonly extra?: readonly string[];\n /** Z3's resource budget per property, in its own units. */\n readonly resourceLimit?: number;\n}\n\n/** This engine's report, with the definitions it ran. */\nexport interface SmtModuleProofs extends ModuleProofs {\n /** The prelude shared by every script, when any function was in the subset. */\n readonly smt?: string;\n}\n\n/** What every PROVEN verdict of this engine rests on. */\nexport const engineAssumptions: readonly string[] = [\n \"number is modelled as the IEEE double (the floating-point theory): NaN, the infinities and -0 are in every binder's domain, and === is fp.eq\",\n \"string is modelled as a sequence of 16-bit code units, as JavaScript holds it\",\n \"the function and its callees are pure and total: the module's own, or generic or imported ones read at each call from their own files; nothing else is modelled\",\n builtinsAssumption,\n `Z3 ${z3Version} found the claim's negation unsatisfiable under a resource limit; no proof object was checked by a kernel`,\n];\n\nconst proven: Extract<ProofOutcome, { kind: \"PROVEN\" }> = {\n kind: \"PROVEN\",\n engine: { name: engineName, version: z3Version },\n assumptions: engineAssumptions,\n};\n\nconst unknown = (\n cause: \"gave_up\" | \"unsupported\" | \"unavailable\",\n reason: string,\n): ProofOutcome => ({ kind: \"UNKNOWN\", cause, reason });\n\n/** The scripts for the module's functions in the subset, and the functions with specs outside it with why. */\nexport interface Prepared {\n readonly module: SubsetModule;\n readonly fns: readonly FunctionSpec[];\n readonly outside: ReadonlyMap<string, string>;\n /** One script per statable forall property. */\n readonly scripts: ReadonlyMap<string, PropertyScript>;\n /** Properties the emitter could not state, with why. */\n readonly skipped: ReadonlyMap<string, string>;\n readonly prelude: string;\n}\n\nconst key = (fn: string, property: string): string => `${fn}\\u0000${property}`;\n\n/** Read and emit: every function the subset takes, and a script per property of the ones with specs. */\nexport function prepare(input: ProveInput): Prepared {\n const wanted = input.functions ? new Set(input.functions) : undefined;\n const fns = input.specs.functions.filter((f) => !wanted || wanted.has(f.name));\n // Lists are read, but this engine does not take them: functions using one are outside here, so the\n // prelude never meets them and the module's other functions still go through.\n const module = restrictModule(\n readSubset(\n input.source,\n fns.map((f) => f.name),\n input.modulePath === undefined ? {} : { path: input.modulePath },\n ),\n (t) => t.kind !== \"list\" && t.kind !== \"nothing\",\n \"arrays are not in this engine's subset (the Lean engine takes them)\",\n listKinds,\n );\n const outside = new Map<string, string>();\n for (const o of module.outside)\n if (fns.some((f) => f.name === o.name))\n outside.set(\n o.name,\n `outside the engine's subset${o.line > 0 ? ` (line ${o.line})` : \"\"}: ${o.message}`,\n );\n for (const fn of fns) {\n const read = module.functions.find((f) => f.name === fn.name);\n if (read && read.offset !== fn.offset)\n outside.set(\n fn.name,\n `outside the engine's subset (line ${fn.line}): the ${fn.name} the spec names is not the module's top-level declaration of that name (line ${read.line})`,\n );\n }\n const scripts = new Map<string, PropertyScript>();\n const skipped = new Map<string, string>();\n let pre = \"\";\n try {\n pre = prelude(module);\n for (const fn of fns) {\n if (outside.has(fn.name)) continue;\n for (const property of fn.properties) {\n if (property.kind !== \"forall\") continue;\n try {\n scripts.set(key(fn.name, property.name), propertyScript(property, module, pre));\n } catch (err) {\n if (!(err instanceof OutsideSubset)) throw err;\n skipped.set(key(fn.name, property.name), err.message);\n }\n }\n }\n } catch (err) {\n // The emitter refusing something the reader let through is an engine gap: every function is unsupported, none guessed.\n if (!(err instanceof OutsideSubset)) throw err;\n for (const fn of fns) outside.set(fn.name, `outside the engine's subset: ${err.message}`);\n scripts.clear();\n }\n return { module, fns, outside, scripts, skipped, prelude: pre };\n}\n\n/**\n * The spec file as a module. A relative import written without `.ts`\n * (`./domain`, `./domain.js`), which the simulator's loader resolves and\n * Node does not, is completed in a sibling copy that is imported and then\n * removed, so the copy's own relative imports still resolve.\n */\n/** Names each sibling copy apart from another made in the same millisecond. */\nlet copies = 0;\n\nasync function importSpecFile(specPath: string): Promise<Record<string, unknown>> {\n try {\n return (await import(pathToFileURL(specPath).href)) as Record<string, unknown>;\n } catch (err) {\n const code = (err as { code?: string }).code;\n if (code !== \"ERR_MODULE_NOT_FOUND\" && code !== \"ERR_UNSUPPORTED_DIR_IMPORT\") throw err;\n const source = readFileSync(specPath, \"utf8\");\n const dir = dirname(specPath);\n const rewritten = source.replace(\n /(from\\s*[\"'])(\\.{1,2}\\/[^\"']+?)(\\.js)?([\"'])/g,\n (whole, pre: string, rel: string, _js: string | undefined, post: string) =>\n existsSync(join(dir, `${rel}.ts`)) ? `${pre}${rel}.ts${post}` : whole,\n );\n if (rewritten === source) throw err;\n const copy = join(dir, `.eutaxy-replay-${process.pid}-${Date.now()}-${copies++}.props.ts`);\n writeFileSync(copy, rewritten);\n try {\n return (await import(pathToFileURL(copy).href)) as Record<string, unknown>;\n } finally {\n rmSync(copy, { force: true });\n }\n }\n}\n\n/**\n * The spec file, imported once per proof of a module: every counterexample\n * that module's solves turn up is replayed through the same import (the\n * solves run side by side, and a sibling copy each would be one import\n * removing another's file mid-import).\n */\ntype SpecLoader = (specPath: string) => Promise<Record<string, unknown>>;\n\nfunction specLoader(): SpecLoader {\n const loaded = new Map<string, Promise<Record<string, unknown>>>();\n return (specPath) => {\n let ns = loaded.get(specPath);\n if (ns === undefined) {\n ns = importSpecFile(specPath);\n loaded.set(specPath, ns);\n }\n return ns;\n };\n}\n\n/** The spec file's export for a property, loaded for replay, or why it could not be. */\nasync function loadSpec(\n load: SpecLoader,\n specPath: string | undefined,\n property: Property,\n fn: string,\n): Promise<Forall<Fn> | string> {\n if (specPath === undefined)\n return \"the engine was not given the spec file's path to replay the counterexample\";\n let ns: Record<string, unknown>;\n try {\n ns = await load(specPath);\n } catch (err) {\n return `the spec file could not be loaded to replay the counterexample: ${String(err)}`;\n }\n const exported = Object.hasOwn(ns, property.name) ? ns[property.name] : undefined;\n if (!isSpec(exported) || exported.kind !== \"forall\")\n return `the spec file exports no forall named ${property.name} to replay the counterexample with`;\n if (typeof exported.fn !== \"function\" || exported.fn.name !== fn)\n return `the spec file's ${property.name} is not on ${fn}`;\n return exported;\n}\n\n/** Prove a module's properties with the pinned Z3. */\nexport async function proveModule(input: ProveInput): Promise<SmtModuleProofs> {\n const { fns, outside, scripts, skipped, module, prelude: smt } = prepare(input);\n const specErrors = input.specs.errors;\n const inSubset = fns.filter((f) => !outside.has(f.name));\n const results: PropertyProof[] = fns\n .filter((f) => outside.has(f.name))\n .flatMap((f) =>\n f.properties.map((property) => ({\n function: f.name,\n property: property.name,\n outcome: unknown(\"unsupported\", outside.get(f.name) as string),\n })),\n );\n if (inSubset.length === 0) return { results, specErrors };\n const allWith = (outcome: ProofOutcome): SmtModuleProofs => ({\n results: [\n ...results,\n ...inSubset.flatMap((fn) =>\n fn.properties.map((p) => ({ function: fn.name, property: p.name, outcome })),\n ),\n ],\n smt,\n specErrors,\n });\n const solver = await findZ3();\n if (\"unavailable\" in solver) return allWith(unknown(\"unavailable\", solver.unavailable));\n const options = {\n ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),\n ...(input.resourceLimit === undefined ? {} : { resourceLimit: input.resourceLimit }),\n };\n // Translation checks first: a definition that does not compute what the TypeScript computes is an engine gap.\n if (input.extra && input.extra.length > 0) {\n const script = [\n smt,\n ...input.extra.flatMap((x) => [\"(push)\", `(assert (not ${x}))`, \"(check-sat)\", \"(pop)\"]),\n \"\",\n ].join(\"\\n\");\n const checked = await solve(solver, script, options);\n const answers = checked.run.stdout\n .split(\"\\n\")\n .map((l) => l.trim())\n .filter((l) => /^(sat|unsat|unknown)$/.test(l));\n if (checked.run.timedOut)\n return allWith(unknown(\"gave_up\", \"Z3 did not finish the translation checks in time\"));\n // The budget ran out on a check: nothing is known about the definitions, and nothing is claimed.\n if (answers.includes(\"unknown\"))\n return allWith(unknown(\"gave_up\", \"Z3 reached its resource limit on a translation check\"));\n const failed = answers.findIndex((a) => a !== \"unsat\");\n const errors = readAnswer(checked.run.stdout).errors;\n if (\n checked.run.code !== 0 ||\n errors.length > 0 ||\n answers.length !== input.extra.length ||\n failed >= 0\n )\n return allWith(\n unknown(\n \"unsupported\",\n `the emitted SMT failed a translation check${failed >= 0 ? ` (${input.extra[failed]})` : \"\"}: ${errors[0] ?? (checked.run.stderr || checked.run.stdout).trim().split(\"\\n\")[0] ?? \"\"}`,\n ),\n );\n }\n // One Z3 process per property, several at once (no more than the machine's cores, so each run keeps\n // about a core): each outcome rests on Z3's resource limit, with the wall-clock timeout a backstop far\n // above what a property takes, and the results keep the properties' order. (Not one process with\n // push/pop: incremental mode can answer differently.)\n const load = specLoader();\n const jobs = inSubset.flatMap((fn) => fn.properties.map((property) => ({ fn, property })));\n const proofs = await inPool(\n jobs,\n Math.min(8, availableParallelism()),\n async ({ fn, property }): Promise<PropertyProof | undefined> => {\n if (property.kind === \"total\")\n return {\n function: fn.name,\n property: property.name,\n outcome: unknown(\n \"unsupported\",\n \"total is not decided by this engine (Lean proves it by acceptance)\",\n ),\n };\n const k = key(fn.name, property.name);\n const why = skipped.get(k);\n if (why !== undefined)\n return { function: fn.name, property: property.name, outcome: unknown(\"unsupported\", why) };\n const script = scripts.get(k);\n if (!script) return undefined;\n const solved = await solve(solver, script.script, options);\n return {\n function: fn.name,\n property: property.name,\n outcome: await outcomeOf(solved, script, module, property, fn.name, input, load),\n };\n },\n );\n for (const proof of proofs) if (proof) results.push(proof);\n return { results, smt, specErrors };\n}\n\nasync function outcomeOf(\n solved: Awaited<ReturnType<typeof solve>>,\n script: PropertyScript,\n module: SubsetModule,\n property: Property,\n fn: string,\n input: ProveInput,\n load: SpecLoader,\n): Promise<ProofOutcome> {\n if (solved.run.timedOut)\n return unknown(\"gave_up\", `Z3 did not finish within ${input.timeoutMs ?? 120_000} ms`);\n if (solved.run.code === null)\n return unknown(\"unavailable\", `Z3 could not be run: ${solved.run.stderr.trim()}`);\n const answer = readAnswer(solved.run.stdout);\n // An error Z3 printed means a command was dropped; whatever verdict line followed is not about the\n // claim. (The exit code says nothing here: Z3 exits non-zero for the model asked after `unsat` too.)\n if (answer.errors.length > 0)\n return unknown(\"unsupported\", `the emitted SMT did not run: ${answer.errors[0]}`);\n if (answer.result === \"unsat\") return proven;\n if (answer.result === \"unknown\")\n return unknown(\n \"gave_up\",\n solved.resourceLimit\n ? `Z3 reached its resource limit${answer.reason ? ` (${answer.reason})` : \"\"}`\n : `Z3 gave up: ${answer.reason || \"unknown\"}`,\n );\n if (answer.result === \"error\")\n return unknown(\"unsupported\", `the emitted SMT did not run: ${answer.reason}`);\n // sat: a candidate counterexample, replayed through the spec file's own claim.\n let values: unknown[];\n try {\n values = script.binders.map((b) => {\n const v = answer.values.get(b.symbol);\n if (v === undefined) throw new UnreadableModel(`no value for ${b.name} in the model`);\n return decode(v, b.type, module);\n });\n } catch (err) {\n if (!(err instanceof UnreadableModel)) throw err;\n return unknown(\"unsupported\", `Z3's model could not be read: ${err.message}`);\n }\n const rendered = property.binders.map((b, i) => `${b.name} = ${render(values[i])}`).join(\", \");\n // The solver saw the sorts; the claim quantifies over the TypeScript types, which may be narrower.\n if (!property.binders.every((b, i) => conforms(b.type, values[i])))\n return unknown(\n \"unsupported\",\n `Z3's model lies outside the parameter types (${rendered}): the engine's model of the types is wider than the types`,\n );\n const spec = await loadSpec(load, input.specPath, property, fn);\n if (typeof spec === \"string\") return unknown(\"unsupported\", `${spec} (the model: ${rendered})`);\n const evaluation = evaluate(spec, values);\n if (\"malformed\" in evaluation)\n return unknown(\n \"unsupported\",\n `the property could not be evaluated on the model (${rendered}): ${evaluation.malformed}`,\n );\n if (evaluation.outcome !== \"refuted\")\n return unknown(\n \"unsupported\",\n `the claim ${evaluation.outcome === \"held\" ? \"held\" : \"was outside its precondition\"} on the model Z3 gave (${rendered}): the engine's model of the language differs from the runtime here`,\n );\n const smallest = shrinkRefutation(spec, property.binders, values, evaluation);\n return {\n kind: \"REFUTED\",\n engine: { name: engineName, version: z3Version },\n counterexample: {\n binders: property.binders.map((b, i) => ({\n name: b.name,\n value: render(smallest.values[i]),\n })),\n ...(smallest.error === undefined ? {} : { error: smallest.error }),\n },\n assumptions: [\n \"found as a model of the claim's negation by Z3, confirmed by running the spec on it, then shrunk\",\n ],\n };\n}\n\n/** The engine as a `Prover`: available when the pinned solver is installed. */\nexport const smtProver: Prover = {\n name: engineName,\n async available() {\n const solver = await findZ3();\n return \"unavailable\" in solver ? solver : { version: solver.version };\n },\n prove: (input) => proveModule(input),\n};\n\nexport { equal };\n","/**\n * Relative imports from a `.ts` file that Node cannot resolve are tried as\n * TypeScript resolves them, so `./domain.js` and `./domain` find `domain.ts`\n * (or `domain/index.ts`), as `tsc` and Vite would. Used where the command\n * imports a user's module in Node: `eutaxy report` for spec modules, `eutaxy\n * check` for a scenario that names callees.\n */\n\nimport { registerHooks } from \"node:module\";\n\nlet registered = false;\n\n/** Register the hook once per process. */\nexport function resolveAsTypeScript(): void {\n if (registered) return;\n registered = true;\n registerHooks({\n resolve(specifier, context, nextResolve) {\n try {\n return nextResolve(specifier, context);\n } catch (err) {\n const relative = specifier.startsWith(\"./\") || specifier.startsWith(\"../\");\n if (!relative || !context.parentURL?.endsWith(\".ts\")) throw err;\n const stem = specifier.endsWith(\".js\") ? specifier.slice(0, -3) : specifier;\n for (const candidate of [`${stem}.ts`, `${stem}/index.ts`]) {\n try {\n return nextResolve(candidate, context);\n } catch {}\n }\n throw err;\n }\n },\n });\n}\n","/**\n * Wrangler config reading, one copy for `check` and `draft`: JSON and JSONC\n * parsing, the bindings a config declares, and the rules that name their\n * resources (a D1 database's id, an R2 bucket's name, a KV namespace's id,\n * which Durable Object classes are SQLite-backed). Only JSON and JSONC are\n * read; a TOML config is refused.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { basename, extname } from \"node:path\";\nimport type { JsonValue } from \"@eutaxy/core\";\n\n/**\n * JSON with comments and trailing commas, as wrangler.jsonc allows: comments\n * are removed outside strings, a comma before `}` or `]` dropped, and the\n * rest is JSON.\n */\nexport function parseJsonc(text: string): unknown {\n let out = \"\";\n let i = 0;\n /** The index of the next character that is neither whitespace nor inside a comment, from `from`. */\n const nextToken = (from: number): number => {\n let k = from;\n for (;;) {\n while (k < text.length && /\\s/.test(text[k] as string)) k++;\n if (text[k] === \"/\" && text[k + 1] === \"/\") {\n while (k < text.length && text[k] !== \"\\n\") k++;\n } else if (text[k] === \"/\" && text[k + 1] === \"*\") {\n const end = text.indexOf(\"*/\", k + 2);\n k = end < 0 ? text.length : end + 2;\n } else return k;\n }\n };\n while (i < text.length) {\n const c = text[i] as string;\n if (c === '\"') {\n let j = i + 1;\n while (j < text.length && text[j] !== '\"') j += text[j] === \"\\\\\" ? 2 : 1;\n out += text.slice(i, j + 1);\n i = j + 1;\n } else if (c === \"/\" && text[i + 1] === \"/\") {\n while (i < text.length && text[i] !== \"\\n\") i++;\n } else if (c === \"/\" && text[i + 1] === \"*\") {\n const end = text.indexOf(\"*/\", i + 2);\n i = end < 0 ? text.length : end + 2;\n } else if (c === \",\") {\n // A trailing comma, outside strings only: dropped.\n const next = text[nextToken(i + 1)];\n if (next !== \"}\" && next !== \"]\") out += c;\n i++;\n } else {\n out += c;\n i++;\n }\n }\n return JSON.parse(out);\n}\n\n/** Read a wrangler config as an object; only JSON and JSONC are read. */\nexport function readWranglerConfig(path: string): Record<string, unknown> {\n const ext = extname(path);\n if (ext !== \".json\" && ext !== \".jsonc\")\n throw new Error(\n `${basename(path)}: eutaxy reads a wrangler config as JSON or JSONC; a TOML config is not read`,\n );\n const parsed = parseJsonc(readFileSync(path, \"utf8\"));\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed))\n throw new Error(`${basename(path)}: not a wrangler config object`);\n return parsed as Record<string, unknown>;\n}\n\n/** The `name` of a wrangler config, when the config can be read and names one. */\nexport function workerName(path: string): string | undefined {\n try {\n const name = readWranglerConfig(path)[\"name\"];\n return typeof name === \"string\" && name ? name : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The object entries of a config list; anything else is no entry. */\nexport const list = (v: unknown): Record<string, unknown>[] =>\n Array.isArray(v) ? v.filter((x): x is Record<string, unknown> => typeof x === \"object\" && x) : [];\nconst str = (v: unknown, fallback = \"\"): string => (typeof v === \"string\" ? v : fallback);\nconst strings = (v: unknown): string[] =>\n Array.isArray(v) ? v.filter((x): x is string => typeof x === \"string\") : [];\n\n/** A D1 binding's database: its id, else its name, else the binding (the same database in two configs is one). */\nexport const d1Id = (db: Record<string, unknown>): string =>\n str(db[\"database_id\"], str(db[\"database_name\"], str(db[\"binding\"])));\n/** An R2 binding's bucket: its name, else the binding. */\nexport const r2Bucket = (b: Record<string, unknown>): string =>\n str(b[\"bucket_name\"], str(b[\"binding\"]));\n/** A KV binding's namespace: its id, else the binding. */\nexport const kvId = (k: Record<string, unknown>): string => str(k[\"id\"], str(k[\"binding\"]));\n\n/**\n * The SQLite-backed Durable Object classes of a config, with its migrations applied in order as\n * wrangler applies them: a class is SQLite-backed from the migration that created it so, through\n * renames, until one deletes it.\n */\nexport function sqliteClasses(config: Record<string, unknown>): Set<string> {\n const sqlite = new Set<string>();\n for (const m of list(config[\"migrations\"])) {\n for (const c of strings(m[\"new_sqlite_classes\"])) sqlite.add(c);\n for (const r of list(m[\"renamed_classes\"])) {\n const from = str(r[\"from\"]);\n if (sqlite.delete(from)) sqlite.add(str(r[\"to\"]));\n }\n for (const c of strings(m[\"deleted_classes\"])) sqlite.delete(c);\n }\n return sqlite;\n}\n\n/** The bindings a wrangler config declares, each resource named by the rules above. */\nexport interface WranglerBindings {\n readonly name: string | undefined;\n readonly main: string | undefined;\n readonly d1: readonly { readonly binding: string; readonly id: string }[];\n readonly r2: readonly { readonly binding: string; readonly bucket: string }[];\n readonly kv: readonly { readonly binding: string; readonly id: string }[];\n readonly durableObjects: readonly {\n readonly binding: string;\n readonly className: string;\n readonly sqlite: boolean;\n /** Another Worker's script, when the class is its. */\n readonly scriptName?: string;\n }[];\n readonly workflows: readonly {\n readonly binding: string;\n readonly className: string;\n readonly name: string;\n }[];\n /** The service bindings: the Worker each names, the entrypoint it reaches and the props it carries, when set. */\n readonly services: readonly {\n readonly binding: string;\n readonly service: string;\n readonly entrypoint?: string;\n readonly props?: Readonly<Record<string, JsonValue>>;\n }[];\n readonly queues: readonly { readonly binding: string; readonly queue: string }[];\n readonly vars: Readonly<Record<string, JsonValue>>;\n readonly sqliteClasses: readonly string[];\n /** Every top-level key of the config. */\n readonly keys: readonly string[];\n}\n\n/** Read a config's bindings. */\nexport function readBindings(config: Record<string, unknown>): WranglerBindings {\n const sqlite = sqliteClasses(config);\n const dos = config[\"durable_objects\"] as { bindings?: unknown } | undefined;\n const queues = config[\"queues\"] as { producers?: unknown } | undefined;\n const vars: Record<string, JsonValue> = {};\n const rawVars = config[\"vars\"];\n if (typeof rawVars === \"object\" && rawVars !== null)\n for (const [k, v] of Object.entries(rawVars as Record<string, JsonValue>)) vars[k] = v;\n return {\n name: str(config[\"name\"]) || undefined,\n main: str(config[\"main\"]) || undefined,\n d1: list(config[\"d1_databases\"]).map((d) => ({ binding: str(d[\"binding\"]), id: d1Id(d) })),\n r2: list(config[\"r2_buckets\"]).map((b) => ({\n binding: str(b[\"binding\"]),\n bucket: r2Bucket(b),\n })),\n kv: list(config[\"kv_namespaces\"]).map((k) => ({ binding: str(k[\"binding\"]), id: kvId(k) })),\n durableObjects: list(dos?.bindings).map((b) => {\n const className = str(b[\"class_name\"]);\n return {\n binding: str(b[\"name\"]),\n className,\n sqlite: sqlite.has(className),\n ...(b[\"script_name\"] === undefined ? {} : { scriptName: str(b[\"script_name\"]) }),\n };\n }),\n workflows: list(config[\"workflows\"]).map((w) => ({\n binding: str(w[\"binding\"]),\n className: str(w[\"class_name\"]),\n name: str(w[\"name\"], str(w[\"binding\"])),\n })),\n services: list(config[\"services\"]).map((s) => ({\n binding: str(s[\"binding\"]),\n service: str(s[\"service\"]),\n ...(typeof s[\"entrypoint\"] === \"string\" ? { entrypoint: s[\"entrypoint\"] } : {}),\n ...(typeof s[\"props\"] === \"object\" && s[\"props\"] !== null\n ? { props: s[\"props\"] as Record<string, JsonValue> }\n : {}),\n })),\n queues: list(queues?.producers).map((p) => ({\n binding: str(p[\"binding\"]),\n queue: str(p[\"queue\"]),\n })),\n vars,\n sqliteClasses: [...sqlite],\n keys: Object.keys(config),\n };\n}\n","/**\n * The callees a scenario names (`callee()` steps), read on the Node side for\n * `eutaxy check`. Each callee's wrangler config gives its Worker's name and\n * its bindings; the command adds them to the test's isolate under qualified\n * names (`<name>/<binding>`): the main module it generates re-exports the\n * caller's exports as they are and the callees' Durable Object and Workflow\n * classes under qualified aliases, and the Vitest config's miniflare options\n * add the callees' resources. Probed inside workerd (2026-11): the plugin\n * takes a `main` beside the caller's `wrangler.configPath`, miniflare options\n * add to and override the wrangler config's bindings, and wrangler, miniflare\n * and workerd accept a slash in a binding name.\n */\n\nimport { fork } from \"node:child_process\";\nimport { basename, relative, resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport type { JsonValue, ScenarioSpec } from \"@eutaxy/core\";\nimport { resolveAsTypeScript } from \"./resolve.ts\";\nimport { readBindings, readWranglerConfig } from \"./wrangler.ts\";\n\n/** A `callee` setup step as the scenario holds it. */\nexport interface CalleeStep {\n readonly binding: string;\n readonly entry: string;\n readonly config: string;\n readonly entrypoint?: string;\n}\n\n/** What a callee's wrangler config says that the test's isolate must hold. */\nexport interface CalleeConfig {\n readonly binding: string;\n /** The Worker's name, which qualifies its bindings. */\n readonly name: string;\n /** The callee's module, absolute. */\n readonly entry: string;\n readonly d1: readonly { readonly binding: string; readonly id: string }[];\n readonly r2: readonly { readonly binding: string; readonly bucket: string }[];\n readonly kv: readonly { readonly binding: string; readonly id: string }[];\n readonly durableObjects: readonly {\n readonly binding: string;\n readonly className: string;\n readonly sqlite: boolean;\n /** The Worker whose script holds the class, when it is another's. */\n readonly scriptName?: string;\n }[];\n readonly workflows: readonly {\n readonly binding: string;\n readonly className: string;\n readonly name: string;\n }[];\n readonly services: readonly string[];\n /** What each of its service bindings carries in its config (the entrypoint reached, the props), for a callee of its own. */\n readonly carries: readonly {\n readonly binding: string;\n readonly entrypoint?: string;\n readonly props?: Readonly<Record<string, JsonValue>>;\n }[];\n readonly queues: readonly { readonly binding: string; readonly queue: string }[];\n readonly vars: Readonly<Record<string, JsonValue>>;\n /** The classes the migrations make SQLite-backed, bound by this Worker or not. */\n readonly sqliteClasses: readonly string[];\n /** Config the command does not carry into the isolate, named so the user knows. */\n readonly notAdded: readonly string[];\n}\n\n/** The `callee` steps of a setup, as the scenario wrote them. */\nexport function calleeSteps(setup: ScenarioSpec[\"setup\"]): CalleeStep[] {\n return setup\n .filter((s) => s.kind === \"callee\")\n .map((s) => ({\n binding: String(s[\"binding\"]),\n entry: String(s[\"entry\"]),\n config: String(s[\"config\"]),\n ...(s[\"entrypoint\"] === undefined ? {} : { entrypoint: String(s[\"entrypoint\"]) }),\n }));\n}\n\n/**\n * Whether the scenario's source names a callee at all: the command imports\n * the scenario module in Node only then, since reading its steps needs it.\n */\nexport function mentionsCallee(scenarioSource: string): boolean {\n return /\\bcallee\\s*\\(/.test(scenarioSource);\n}\n\n/** What the command reads from the scenario module: its setup and its Worker. */\nexport type LoadedScenario = Pick<ScenarioSpec, \"setup\" | \"worker\">;\n\n/** The argument that makes a process started on this module load one scenario and report it. */\nconst scenarioFlag = \"--eutaxy-load-scenario\";\n\ntype ScenarioOutput =\n | { readonly kind: \"eutaxy-scenario\"; readonly scenario: LoadedScenario }\n | { readonly kind: \"eutaxy-scenario-error\"; readonly message: string };\n\n/** Inside the child: import the scenario and keep what the command reads. */\nasync function loadHere(scenarioPath: string): Promise<LoadedScenario> {\n resolveAsTypeScript();\n const mod = (await import(pathToFileURL(scenarioPath).href)) as { default?: ScenarioSpec };\n const spec = mod.default;\n if (!spec || !Array.isArray(spec.setup) || typeof spec.worker?.entry !== \"string\")\n throw new Error(\"the scenario module's default export is not a scenario\");\n return { setup: spec.setup, worker: spec.worker };\n}\n\nconst send = process.send?.bind(process);\nif (process.argv[2] === scenarioFlag && send) {\n process.once(\"disconnect\", () => process.exit(0));\n process.once(\"message\", async (scenarioPath: string) => {\n let output: ScenarioOutput;\n try {\n output = { kind: \"eutaxy-scenario\", scenario: await loadHere(scenarioPath) };\n } catch (err) {\n output = { kind: \"eutaxy-scenario-error\", message: String(err) };\n }\n send(output, () => process.exit(0));\n });\n}\n\n/** How long a scenario module may take to load before the command gives up on it. */\nconst loadBudgetMs = 60_000;\n\n/**\n * Import the scenario module in Node and return its setup and Worker, in a\n * child process started on this module (as `eutaxy report` loads modules):\n * a long-lived process (the MCP server) would otherwise get Node's cached\n * module after the scenario or what it imports changed. Relative imports\n * are resolved as TypeScript resolves them (`./setup.js` and `./setup` find\n * `setup.ts`). Rejects with what the import threw.\n */\nexport function loadScenario(scenarioPath: string): Promise<LoadedScenario> {\n return new Promise((resolveLoad, reject) => {\n const child = fork(fileURLToPath(import.meta.url), [scenarioFlag], {\n stdio: [\"ignore\", \"ignore\", \"pipe\", \"ipc\"],\n serialization: \"advanced\",\n });\n let errors = \"\";\n child.stderr?.on(\"data\", (d: Buffer) => {\n errors += d.toString();\n });\n let settled = false;\n const settle = (outcome: () => void) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n outcome();\n };\n const timer = setTimeout(() => {\n child.kill(\"SIGKILL\");\n settle(() => reject(new Error(`the scenario module did not load within ${loadBudgetMs} ms`)));\n }, loadBudgetMs);\n child.on(\"message\", (output: ScenarioOutput) => {\n settle(() => {\n if (output.kind === \"eutaxy-scenario\") resolveLoad(output.scenario);\n else reject(new Error(output.message));\n });\n });\n child.once(\"error\", (err) => settle(() => reject(err)));\n child.once(\"close\", (code, signal) =>\n settle(() =>\n reject(\n new Error(\n `the scenario module's process ended (${signal ?? `exit ${code}`}) before reporting${errors ? `:\\n${errors}` : \"\"}`,\n ),\n ),\n ),\n );\n child.send(scenarioPath);\n });\n}\n\n/** The qualified names the callees' bindings get in the isolate, for a regression test's note. */\nexport function isolateBindings(callees: readonly CalleeConfig[]): string[] {\n const names: string[] = [];\n for (const c of callees) {\n for (const d of c.d1) names.push(qualified(c.name, d.binding));\n for (const b of c.r2) names.push(qualified(c.name, b.binding));\n for (const k of c.kv) names.push(qualified(c.name, k.binding));\n for (const o of c.durableObjects)\n if (o.scriptName === undefined) names.push(qualified(c.name, o.binding));\n for (const w of c.workflows) names.push(qualified(c.name, w.binding));\n for (const s of c.services) names.push(qualified(c.name, s));\n for (const q of c.queues) names.push(qualified(c.name, q.binding));\n for (const v of Object.keys(c.vars)) names.push(qualified(c.name, v));\n }\n return names;\n}\n\n/** The keys of a wrangler config whose bindings the command carries into the isolate. */\nconst carried = new Set([\n \"name\",\n \"main\",\n \"compatibility_date\",\n \"compatibility_flags\",\n \"d1_databases\",\n \"r2_buckets\",\n \"kv_namespaces\",\n \"durable_objects\",\n \"migrations\",\n \"workflows\",\n \"services\",\n \"queues\",\n \"vars\",\n \"$schema\",\n \"observability\",\n \"triggers\",\n \"routes\",\n \"route\",\n \"workers_dev\",\n \"account_id\",\n \"placement\",\n \"limits\",\n \"upload_source_maps\",\n \"minify\",\n \"keep_vars\",\n \"preview_urls\",\n]);\n\n/** Read a callee's wrangler config into what the isolate needs; `scenarioDir` resolves the step's paths. */\nexport function readCalleeConfig(step: CalleeStep, scenarioDir: string): CalleeConfig {\n const path = resolve(scenarioDir, step.config);\n const bindings = readBindings(readWranglerConfig(path));\n if (bindings.name === undefined)\n throw new Error(\n `${basename(path)}: the callee's wrangler config has no name, which qualifies its bindings`,\n );\n return {\n binding: step.binding,\n name: bindings.name,\n entry: resolve(scenarioDir, step.entry),\n d1: bindings.d1,\n r2: bindings.r2,\n kv: bindings.kv,\n durableObjects: bindings.durableObjects,\n workflows: bindings.workflows,\n services: bindings.services.map((s) => s.binding),\n carries: bindings.services.map(({ binding, entrypoint, props }) => ({\n binding,\n ...(entrypoint === undefined ? {} : { entrypoint }),\n ...(props === undefined ? {} : { props }),\n })),\n queues: bindings.queues,\n vars: bindings.vars,\n sqliteClasses: bindings.sqliteClasses,\n notAdded: bindings.keys.filter((key) => !carried.has(key)),\n };\n}\n\n/** A Worker's name as an identifier prefix (`my-worker` → `my_worker`, `1st` → `_1st`). */\nconst ident = (s: string): string => {\n const safe = s.replace(/[^A-Za-z0-9_$]/g, \"_\");\n return /^[A-Za-z_$]/.test(safe) ? safe : `_${safe}`;\n};\n\n/** The export name a callee's class gets in the generated main module. */\nexport function classAlias(worker: string, className: string): string {\n return `${ident(worker)}__${className}`;\n}\n\n/** The qualified name of a callee's binding. */\nexport function qualified(worker: string, binding: string): string {\n return `${worker}/${binding}`;\n}\n\nfunction toPosix(p: string): string {\n const s = p.split(\"\\\\\").join(\"/\");\n return s.startsWith(\".\") ? s : `./${s}`;\n}\n\n/**\n * The main module the plugin runs: the caller's exports as they are, and\n * each callee's Durable Object and Workflow classes under qualified aliases,\n * so the miniflare options can bind them. workerd constructs those classes\n * with the main Worker's env, so each alias is a subclass handing its parent\n * the callee's view of it (`calleeEnv`), under which `this.env.DB` is the\n * callee's `<name>/DB`.\n */\nexport function mainModuleSource(\n workDir: string,\n callerEntry: string,\n callees: readonly CalleeConfig[],\n isolate: ReturnType<typeof isolateOf> = noIsolate,\n): string {\n const caller = toPosix(relative(workDir, callerEntry));\n const lines = [\n \"// Generated by eutaxy check; deleted after the run.\",\n `export * from ${JSON.stringify(caller)};`,\n `export { default } from ${JSON.stringify(caller)};`,\n ];\n const adapters: string[] = [];\n // Two bindings may reach one Worker (two entrypoints of it): one adapter per Worker and class.\n const emitted = new Set<string>();\n callees.forEach((c, i) => {\n const classes = [\n ...c.durableObjects.filter((d) => d.scriptName === undefined).map((d) => d.className),\n ...c.workflows.map((w) => w.className),\n // Classes of this script the caller binds, which the callee binds nowhere itself.\n ...(isolate.extraClasses[c.name] ?? []),\n ];\n const unique = [...new Set(classes)].filter((n) => n && !emitted.has(classAlias(c.name, n)));\n if (unique.length === 0) return;\n lines.push(\n `import { ${unique.map((n) => `${n} as callee${i}_${n}`).join(\", \")} } from ${JSON.stringify(toPosix(relative(workDir, c.entry)))};`,\n );\n // The aliases of this callee's bindings: workerd constructs the class with the raw env, where an alias\n // has no key of its own, so the view resolves them.\n const own = Object.fromEntries(\n Object.entries(isolate.aliases).filter(([k]) => k.startsWith(`${c.name}/`)),\n );\n const view = `calleeEnv(${JSON.stringify(c.name)}, env${Object.keys(own).length === 0 ? \"\" : `, ${JSON.stringify(own)}`})`;\n for (const n of unique) {\n emitted.add(classAlias(c.name, n));\n adapters.push(\n `export class ${classAlias(c.name, n)} extends callee${i}_${n} {`,\n ` constructor(ctx: unknown, env: object) {`,\n ` super(ctx as never, ${view} as never);`,\n ` }`,\n `}`,\n );\n }\n });\n if (adapters.length > 0) lines.splice(1, 0, 'import { calleeEnv } from \"eutaxy/cloudflare\";');\n return `${[...lines, ...adapters].join(\"\\n\")}\\n`;\n}\n\n/** The name the generated config gives the function answering a service binding nobody calls. */\nexport const neverCalled = \"neverCalled\";\n\n/**\n * The miniflare options adding the callees' resources under qualified names,\n * as source (an object literal) for the generated Vitest config. Service\n * bindings, the caller's to its callees and the callees' own, are answered\n * by a function of the config's (`neverCalled`): the Worker the caller's\n * config names is not in the isolate, a worker name given through these\n * options must be one the plugin knows, and the binding is never called\n * anyway (the scenario names a callee for it or scripts it); its value is a\n * Fetcher all the same, which is what the platform recognises.\n */\nexport function miniflareOptionsSource(\n callees: readonly CalleeConfig[],\n isolate: ReturnType<typeof isolateOf> = noIsolate,\n /**\n * The caller's own service bindings: each is answered by the platform (scripted with service(), or a\n * callee hosted inside the call), never by the Worker its config names, which the isolate may not hold.\n */\n callerServices: readonly string[] = [],\n): string {\n const d1: Record<string, string> = {};\n const r2: Record<string, string> = {};\n const kv: Record<string, string> = {};\n const dos: Record<string, { className: string; useSQLite?: boolean }> = {};\n const workflows: Record<string, { name: string; className: string }> = {};\n const services: Record<string, string> = {};\n const queues: Record<string, string> = {};\n const vars: Record<string, JsonValue> = {};\n // An alias is a second name of the caller's binding in env, which the platform gives it: nothing to add.\n const aliased = (name: string): boolean => name in isolate.aliases;\n Object.assign(dos, isolate.redirected);\n for (const b of callerServices) services[b] = neverCalled;\n for (const c of callees) {\n for (const d of c.d1)\n if (!aliased(qualified(c.name, d.binding))) d1[qualified(c.name, d.binding)] = d.id;\n for (const b of c.r2)\n if (!aliased(qualified(c.name, b.binding))) r2[qualified(c.name, b.binding)] = b.bucket;\n for (const k of c.kv)\n if (!aliased(qualified(c.name, k.binding))) kv[qualified(c.name, k.binding)] = k.id;\n for (const o of c.durableObjects) {\n // A class of another Worker's script is that Worker's: an alias when it is the caller's (see\n // `isolateOf`), not added otherwise.\n if (o.scriptName !== undefined || aliased(qualified(c.name, o.binding))) continue;\n dos[qualified(c.name, o.binding)] = {\n className: classAlias(c.name, o.className),\n ...(o.sqlite ? { useSQLite: true } : {}),\n };\n }\n for (const w of c.workflows)\n workflows[qualified(c.name, w.binding)] = {\n name: w.name,\n className: classAlias(c.name, w.className),\n };\n services[c.binding] = neverCalled;\n for (const s of c.services) services[qualified(c.name, s)] = neverCalled;\n for (const q of c.queues) queues[qualified(c.name, q.binding)] = q.queue;\n for (const [k, v] of Object.entries(c.vars)) vars[qualified(c.name, k)] = v;\n }\n const options: Record<string, object> = {};\n const add = (key: string, value: object) => {\n if (Object.keys(value).length > 0) options[key] = value;\n };\n add(\"d1Databases\", d1);\n add(\"r2Buckets\", r2);\n add(\"kvNamespaces\", kv);\n add(\"durableObjects\", dos);\n add(\"workflows\", workflows);\n add(\"queueProducers\", queues);\n add(\"bindings\", vars);\n // JSON for the data, which is also an object literal; the service bindings name the config's function.\n const data = JSON.stringify(options);\n const bindings = Object.keys(services);\n if (bindings.length === 0) return data;\n const literal = `\"serviceBindings\":{${bindings.map((b) => `${JSON.stringify(b)}:${neverCalled}`).join(\",\")}}`;\n return data === \"{}\" ? `{${literal}}` : `${data.slice(0, -1)},${literal}}`;\n}\n\n/** What the caller's config says that the isolate must reconcile with the callees'. */\nexport interface CallerResources {\n readonly name: string | undefined;\n readonly d1: readonly { readonly binding: string; readonly id: string }[];\n readonly r2: readonly { readonly binding: string; readonly bucket: string }[];\n readonly kv: readonly { readonly binding: string; readonly id: string }[];\n readonly durableObjects: readonly {\n readonly binding: string;\n readonly className: string;\n readonly scriptName?: string;\n }[];\n /** The caller's service bindings: the Worker each names, the entrypoint it reaches and the props it carries, when set. */\n readonly services: readonly {\n readonly binding: string;\n readonly service: string;\n readonly entrypoint?: string;\n readonly props?: Readonly<Record<string, JsonValue>>;\n }[];\n}\n\n/** The caller's resources from its wrangler config, when the config can be read (JSON or JSONC); none otherwise. */\nexport function readCallerResources(wranglerPath: string): CallerResources | undefined {\n try {\n const bindings = readBindings(readWranglerConfig(wranglerPath));\n return {\n name: bindings.name,\n d1: bindings.d1,\n r2: bindings.r2,\n kv: bindings.kv,\n durableObjects: bindings.durableObjects,\n services: bindings.services,\n };\n } catch {\n return undefined;\n }\n}\n\n/**\n * What the binding to a callee carries (its entrypoint and props), for the\n * test to pass with the module: from the caller's config, or for a callee's\n * own callee (`<callee>/<binding>`) from that callee's config, where the\n * binding is declared.\n */\nexport function bindingCarries(\n caller: CallerResources | undefined,\n binding: string,\n callees: readonly CalleeConfig[] = [],\n): { readonly entrypoint?: string; readonly props?: Readonly<Record<string, JsonValue>> } {\n const owner = callees.find((c) => binding.startsWith(`${c.name}/`));\n const s =\n caller?.services.find((x) => x.binding === binding) ??\n owner?.carries.find((x) => qualified(owner.name, x.binding) === binding);\n return {\n ...(s?.entrypoint === undefined ? {} : { entrypoint: s.entrypoint }),\n ...(s?.props === undefined ? {} : { props: s.props }),\n };\n}\n\n/**\n * The isolate's shared resources, from the two configs: a callee binding\n * that names a resource the caller binds too (the same `database_id`,\n * `bucket_name` or KV `id`; a Durable Object class of the caller's script,\n * or a caller binding to a class of the callee's script) is an alias of the\n * caller's binding, set up and snapshotted under the caller's name; a\n * caller's binding to a callee's class is redirected to the generated alias\n * class. What a callee binds in a third Worker's script is named as not\n * added.\n */\nexport function isolateOf(\n callees: readonly CalleeConfig[],\n caller: CallerResources | undefined,\n): {\n /** Qualified name → the caller's binding it is an alias of. */\n readonly aliases: Readonly<Record<string, string>>;\n /** The caller's own bindings redirected to a callee's class, as miniflare `durableObjects` entries. */\n readonly redirected: Readonly<Record<string, { className: string; useSQLite?: boolean }>>;\n /** Per callee name, classes of its script the caller binds that the callee binds nowhere itself: the main module exports them too. */\n readonly extraClasses: Readonly<Record<string, readonly string[]>>;\n readonly notAdded: readonly string[];\n} {\n const aliases: Record<string, string> = {};\n const redirected: Record<string, { className: string; useSQLite?: boolean }> = {};\n const extraClasses: Record<string, string[]> = {};\n const notAdded: string[] = [];\n // A caller config that already declares the callee's binding under its qualified name (for a test\n // of its own) names nothing else: no alias.\n const alias = (name: string, own: string) => {\n if (own !== name) aliases[name] = own;\n };\n for (const c of callees) {\n if (caller) {\n for (const d of c.d1) {\n const own = caller.d1.find((x) => x.id === d.id);\n if (own) alias(qualified(c.name, d.binding), own.binding);\n }\n for (const b of c.r2) {\n const own = caller.r2.find((x) => x.bucket === b.bucket);\n if (own) alias(qualified(c.name, b.binding), own.binding);\n }\n for (const k of c.kv) {\n const own = caller.kv.find((x) => x.id === k.id);\n if (own) alias(qualified(c.name, k.binding), own.binding);\n }\n // The caller binds a class of this callee's script: its binding is the class's alias; the\n // callee's own binding of that class is an alias of the caller's.\n for (const o of caller.durableObjects) {\n if (o.scriptName !== c.name) continue;\n const theirs = c.durableObjects.find(\n (x) => x.className === o.className && x.scriptName === undefined,\n );\n redirected[o.binding] = {\n className: classAlias(c.name, o.className),\n ...(c.sqliteClasses.includes(o.className) ? { useSQLite: true } : {}),\n };\n if (theirs) alias(qualified(c.name, theirs.binding), o.binding);\n else {\n const extra = extraClasses[c.name] ?? [];\n extra.push(o.className);\n extraClasses[c.name] = extra;\n }\n }\n }\n for (const o of c.durableObjects) {\n if (o.scriptName === undefined) continue;\n // A class of the caller's script: the callee's binding is an alias of the caller's binding to it.\n const own =\n caller && o.scriptName === caller.name\n ? caller.durableObjects.find(\n (x) => x.className === o.className && x.scriptName === undefined,\n )\n : undefined;\n if (own) alias(qualified(c.name, o.binding), own.binding);\n else\n notAdded.push(\n `${c.binding}: durable_objects binding ${o.binding} (script_name ${o.scriptName}: a class of another Worker)`,\n );\n }\n }\n return { aliases, redirected, extraClasses, notAdded };\n}\n\n/** An isolate with nothing shared. */\nexport const noIsolate: ReturnType<typeof isolateOf> = {\n aliases: {},\n redirected: {},\n extraClasses: {},\n notAdded: [],\n};\n\n/** Where a callee's config path and entry sit, for messages. */\nexport function describeCallee(c: CalleeConfig, scenarioDir: string): string {\n return `${c.binding} (${c.name}, ${toPosix(relative(scenarioDir, c.entry))})`;\n}\n","/**\n * Why Vitest failed the run a check started, from what that run left: its\n * JSON report (a test file that could not run, a failed test) and the\n * errors nothing handled, which fail a run without being in that report,\n * so the generated config's own reporter writes them beside it\n * (`unhandledErrorsFile`). Without this the command could only say that\n * Vitest exited non-zero: the run's only reporter is the JSON one, and its\n * files are deleted after the run.\n */\n\n/** Where the run's errors nothing handled are written: beside its report, under its stamp. */\nexport function unhandledErrorsFile(reportFile: string): string {\n return reportFile.replace(/\\.json$/, \".unhandled.json\");\n}\n\n/** Lines of an error kept in the explanation; a stack's first frames say where. */\nconst keptLines = 8;\n\n/** What the JSON report holds, as far as it is read; fields are checked, not trusted. */\ninterface Report {\n readonly testResults?: readonly {\n readonly status?: unknown;\n readonly message?: unknown;\n readonly assertionResults?: readonly {\n readonly status?: unknown;\n readonly failureMessages?: readonly unknown[];\n }[];\n }[];\n}\n\n/** An error nothing handled as the reporter wrote it: whatever was thrown, so any field may be data. */\ninterface Unhandled {\n readonly type?: unknown;\n readonly message?: unknown;\n readonly stack?: unknown;\n}\n\nfunction parsed<T>(text: string | undefined): T | undefined {\n if (text === undefined) return undefined;\n try {\n return JSON.parse(text) as T;\n } catch {\n return undefined;\n }\n}\n\n/** A field as text: a string as it is, anything else as JSON (a thrown value need not be an error). */\nfunction asText(value: unknown): string {\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value) ?? String(value);\n } catch {\n return String(value);\n }\n}\n\n/** What an error says: its stack or message when either is text, else whatever was thrown, as data. */\nfunction said(e: Unhandled): string {\n for (const v of [e.stack, e.message]) if (typeof v === \"string\" && v !== \"\") return v;\n const thrown = e.message ?? e.stack;\n return thrown === undefined || thrown === null ? \"(no message)\" : asText(thrown);\n}\n\n/** An error's first lines, each without its indent; a line at the end says how many were cut. */\nfunction firstLines(text: string): string[] {\n const lines = text\n .trimEnd()\n .split(\"\\n\")\n .map((l) => l.trimStart());\n const kept = lines.slice(0, keptLines);\n if (lines.length > keptLines) kept.push(`… ${lines.length - keptLines} more lines`);\n return kept;\n}\n\n/** An error's text, cut to its first lines and indented under its heading. */\nfunction cut(text: string): string {\n return firstLines(text).join(\"\\n \");\n}\n\n/** An error nothing handled, told once however often it came: its type, its first lines, how often. */\nexport interface StrayError {\n readonly type: string;\n readonly message: string;\n readonly times: number;\n}\n\n/** The errors nothing handled, the same type and text told once with how often it came, in first-seen order. */\nfunction distinct(unhandled: readonly Unhandled[]): StrayError[] {\n const seen = new Map<string, { type: string; message: string; times: number }>();\n for (const e of unhandled) {\n const type = typeof e.type === \"string\" && e.type !== \"\" ? e.type : \"Error\";\n const whole = said(e);\n // Told apart by the whole text: two errors may differ only past the lines that are shown.\n const key = `${type}\\n${whole}`;\n const found = seen.get(key);\n if (found) found.times++;\n else seen.set(key, { type, message: firstLines(whole).join(\"\\n\"), times: 1 });\n }\n return [...seen.values()];\n}\n\n/** The distinct errors, one a line under the count, each error's own lines indented under it. */\nfunction told(errors: readonly StrayError[]): string {\n return errors\n .map(\n ({ type, message, times }) =>\n `\\n ${type}${times > 1 ? ` (${times} times)` : \"\"}: ${message.split(\"\\n\").join(\"\\n \")}`,\n )\n .join(\"\");\n}\n\n/** How many errors came, and how many distinct when more than one. */\nfunction counted(errors: readonly StrayError[]): string {\n const all = errors.reduce((n, e) => n + e.times, 0);\n return all === 1\n ? \"1 error nothing handled\"\n : `${all} errors nothing handled, ${errors.length} distinct`;\n}\n\n/** Why each test file failed and each failed test's first error, and how many tests passed. */\nfunction reportCauses(report: Report | undefined): { causes: string[]; passed: number } {\n const causes: string[] = [];\n let passed = 0;\n for (const file of report?.testResults ?? []) {\n const tests = file.assertionResults ?? [];\n // The reporter gives a file the first error outside its tests: its import, a hook, a teardown.\n if (file.status === \"failed\" && file.message !== undefined && file.message !== \"\")\n causes.push(\n `the check's test file ${tests.length === 0 ? \"could not run\" : \"failed outside its test\"}: ${cut(asText(file.message))}`,\n );\n for (const t of tests) {\n if (t.status === \"passed\") passed++;\n else if (t.status === \"failed\") {\n const [first] = t.failureMessages ?? [];\n causes.push(\n `the check's test failed${first === undefined ? \"\" : `: ${cut(asText(first))}`}`,\n );\n }\n }\n }\n return { causes, passed };\n}\n\n/**\n * The kinds of error nothing handled that Vitest's error catcher in the\n * test's own runtime records (`listenForErrors`): what code that ran\n * inside the test left behind, the Worker's or the simulation's. The\n * runner, its pool and the reporters record their own failures through the\n * same channel (`Teardown Error`, `Unhandled Error`, `Unhandled Reporter\n * Error`, `Restart Error`, …); those mean the run broke.\n */\nconst fromTheTest = new Set([\"Unhandled Rejection\", \"Uncaught Exception\"]);\n\n/**\n * The errors nothing handled, when they are the run's only fault: every\n * test in the report passed, at least one did, no file failed outside its\n * tests, and there was at least one such error, every one recorded by the\n * test's own runtime (`fromTheTest`). Cloudflare's runtime only\n * logs an error nothing handled (a promise a Worker leaves rejected, say),\n * while Vitest fails the whole run on one, so then the verdict the test\n * left stands and these are told beside it. Otherwise undefined: the run\n * failed, and `vitestFailure` says why.\n */\nexport function strayErrors(left: {\n readonly report?: string | undefined;\n readonly unhandled?: string | undefined;\n}): readonly StrayError[] | undefined {\n const report = parsed<Report>(left.report);\n const unhandled = parsed<Unhandled[]>(left.unhandled);\n if (report === undefined || !Array.isArray(unhandled) || unhandled.length === 0) return undefined;\n if (!unhandled.every((e) => typeof e?.type === \"string\" && fromTheTest.has(e.type)))\n return undefined;\n const { causes, passed } = reportCauses(report);\n const allPassed = (report.testResults ?? []).every(\n (f) => f.status === \"passed\" && (f.assertionResults ?? []).every((t) => t.status === \"passed\"),\n );\n return passed > 0 && causes.length === 0 && allPassed ? distinct(unhandled) : undefined;\n}\n\n/** The note printed beside a verdict that stands despite errors nothing handled. */\nexport function strayNote(errors: readonly StrayError[]): string {\n return `note: the check's test passed, and its verdict stands, but there ${errors.reduce((n, e) => n + e.times, 0) === 1 ? \"was\" : \"were\"} ${counted(errors)} (Cloudflare's runtime only logs them; Vitest fails the run on them):${told(errors)}\\n`;\n}\n\n/**\n * The explanation, one cause a line (each error's own lines indented under\n * it), from the report's text and the unhandled errors' text, either of\n * which may be missing.\n */\nexport function vitestFailure(left: {\n readonly report?: string | undefined;\n readonly unhandled?: string | undefined;\n}): string {\n const report = parsed<Report>(left.report);\n const unhandled = parsed<Unhandled[]>(left.unhandled) ?? [];\n const { causes, passed } = reportCauses(report);\n if (unhandled.length > 0) {\n const errors = distinct(unhandled);\n const passedAlone = passed > 0 && causes.length === 0;\n // Errors the test's own runtime caught leave a passed test's verdict standing (`strayErrors`),\n // so with only those the run failed because the test left no verdict.\n const onlyFromTheTest = unhandled.every(\n (e) => typeof e?.type === \"string\" && fromTheTest.has(e.type),\n );\n const intro = !passedAlone\n ? \"\"\n : onlyFromTheTest\n ? \"its test passed but left no verdict in Vitest's report; there \"\n : \"its test passed, but Vitest fails a run on any error nothing handled, and there \";\n const also = passedAlone && onlyFromTheTest ? \"also \" : \"\";\n const verb = intro === \"\" ? \"\" : `${unhandled.length === 1 ? \"was\" : \"were\"} ${also}`;\n causes.push(`${intro}${verb}${counted(errors)}:${told(errors)}`);\n }\n if (causes.length === 0)\n causes.push(\n report === undefined\n ? \"Vitest left no report it could be told from\"\n : passed > 0\n ? \"its test passed but left no verdict in Vitest's report\"\n : \"Vitest reported no failed test and no error nothing handled\",\n );\n return causes.map((c) => ` ${c}\\n`).join(\"\");\n}\n","/**\n * The files `eutaxy check` writes into `<scenario dir>/.eutaxy/` before\n * running Vitest: a test that performs the check inside workerd and prints\n * the verdict on one marked line, and a Vitest config with the Cloudflare\n * plugin pointed at the scenario's wrangler config. For a scenario with\n * callees the test imports their modules, the config names a generated main\n * module and adds their resources through miniflare options (`callees.ts`).\n */\n\nimport { dirname, join } from \"node:path\";\nimport { neverCalled } from \"./callees.ts\";\nimport { unhandledErrorsFile } from \"./vitest-failure.ts\";\n\n/** Key under which the generated test stores its result in the Vitest task meta, read back from the JSON reporter. */\nexport const metaKey = \"eutaxy\";\n\nexport interface GeneratedCheck {\n readonly seed: string;\n readonly maxRuns?: number;\n /** Replaces the scenario's time budget. */\n readonly budgetMs?: number;\n /** Exhaustive exploration instead of seeded. */\n readonly exhaustive?: boolean;\n /** Import specifier of the scenario from the generated test (e.g. \"../scenario.sim.ts\"). */\n readonly scenarioImport: string;\n /** Import specifier of the Worker's entry when it lies outside the scenario's directory, where the test's glob does not reach. */\n readonly workerImport?: string;\n /** The callees the scenario names: each one's binding, Worker name and the import specifier of its module. */\n readonly callees?: readonly {\n readonly binding: string;\n readonly name: string;\n readonly importPath: string;\n /** From the caller's config: the entrypoint the binding reaches, the props it carries. */\n readonly entrypoint?: string;\n readonly props?: Readonly<Record<string, unknown>>;\n /** The callee is the scenario's own Worker, called back by a Worker it called. */\n readonly self?: boolean;\n }[];\n /** SQL files outside the scenario's directory (a callee's schema), by the key `schemasFor` looks up, with their import specifiers. */\n readonly sqlImports?: readonly { readonly key: string; readonly importPath: string }[];\n /** Qualified binding names that are aliases of the caller's bindings (shared resources). */\n readonly aliases?: Readonly<Record<string, string>>;\n}\n\n/**\n * The generated test: the module globs (Vite resolves them at build time,\n * so they must be written in the test) and one call to `checkInWorkerd`,\n * which does the rest.\n */\nexport function checkTestSource(g: GeneratedCheck): string {\n const options =\n `seed: ${JSON.stringify(g.seed)}` +\n (g.maxRuns === undefined ? \"\" : `, maxRuns: ${g.maxRuns}`) +\n (g.budgetMs === undefined ? \"\" : `, budgetMs: ${g.budgetMs}`) +\n (g.exhaustive ? \", exhaustive: true\" : \"\");\n const callees = g.callees ?? [];\n const sqlImports = g.sqlImports ?? [];\n const calleeImports = callees.map(\n (c, i) => `import * as callee_${i} from ${JSON.stringify(c.importPath)};\\n`,\n );\n const sqlImportLines = sqlImports.map(\n (f, i) => `import sql_${i} from ${JSON.stringify(`${f.importPath}?raw`)};\\n`,\n );\n const workerImportLine =\n g.workerImport === undefined\n ? \"\"\n : `import * as workerModule from ${JSON.stringify(g.workerImport)};\\n`;\n const workerOption = g.workerImport === undefined ? \"\" : \", worker: workerModule\";\n const calleesOption =\n callees.length === 0\n ? \"\"\n : `, callees: { ${callees\n .map(\n (c, i) =>\n `${JSON.stringify(c.binding)}: { name: ${JSON.stringify(c.name)}, exports: callee_${i}${c.entrypoint === undefined ? \"\" : `, entrypoint: ${JSON.stringify(c.entrypoint)}`}${c.props === undefined ? \"\" : `, props: ${JSON.stringify(c.props)}`}${c.self ? \", self: true\" : \"\"} }`,\n )\n .join(\", \")} }`;\n const extraSql =\n sqlImports.length === 0\n ? \"\"\n : `, extraSql: { ${sqlImports.map((f, i) => `${JSON.stringify(f.key)}: sql_${i}`).join(\", \")} }`;\n const aliases =\n g.aliases === undefined || Object.keys(g.aliases).length === 0\n ? \"\"\n : `, aliases: ${JSON.stringify(g.aliases)}`;\n return `// Generated by eutaxy check; deleted after the run.\nimport { checkInWorkerd } from \"eutaxy/cloudflare\";\nimport { env } from \"cloudflare:workers\";\nimport * as durableObjects from \"cloudflare:test\";\nimport { test } from \"vitest\";\nimport scenario from ${JSON.stringify(g.scenarioImport)};\n${workerImportLine}${calleeImports.join(\"\")}${sqlImportLines.join(\"\")}import { specEntries } from \"./specs.ts\";\n\nconst sqlFiles = import.meta.glob(\"../**/*.sql\", { query: \"?raw\", import: \"default\", eager: true }) as Record<string, string>;\nconst modules = import.meta.glob([\"../**/*.ts\", \"!../**/*.test.ts\", \"!../**/*.sim.ts\", \"!../**/node_modules/**\", \"!../**/.eutaxy/**\"]);\n\ntest(\"eutaxy check\", async ({ task }) => {\n task.meta[${JSON.stringify(metaKey)}] = await checkInWorkerd({ scenario, env, durableObjects, sqlFiles, modules, specEntries${workerOption}${calleesOption}${extraSql}${aliases}, ${options} });\n});\n`;\n}\n\n/**\n * The plugin's main module, absolute: the scenario's Worker entry, or for a scenario with callees the\n * generated module re-exporting the caller's and the callees' classes, with the callees' resources.\n */\nexport interface CalleeIsolate {\n readonly main: string;\n /** The miniflare options as source (an object literal); only a scenario with callees has them. */\n readonly miniflare?: string;\n}\n\nexport function vitestConfigSource(\n wranglerConfigPath: string,\n testPath: string,\n outputFile: string,\n isolate?: CalleeIsolate,\n): string {\n const plugin =\n isolate === undefined\n ? `cloudflareTest({ wrangler: { configPath: ${JSON.stringify(wranglerConfigPath)} } })`\n : `cloudflareTest({ main: ${JSON.stringify(isolate.main)}, wrangler: { configPath: ${JSON.stringify(wranglerConfigPath)} }${isolate.miniflare === undefined ? \"\" : `, miniflare: ${isolate.miniflare}`} })`;\n // A service binding the scenario scripts or runs as a callee is never called; the value must exist.\n const helpers =\n isolate?.miniflare === undefined\n ? \"\"\n : `const ${neverCalled} = () => new Response(\"eutaxy: a service binding the scenario scripts or runs as a callee is never called\", { status: 500 });\\n\\n`;\n return `// Generated by eutaxy check; deleted after the run.\nimport { writeFileSync } from \"node:fs\";\nimport { cloudflareTest } from \"@cloudflare/vitest-plugin\";\nimport { defineConfig } from \"vitest/config\";\n\n${helpers}export default defineConfig({\n // Vite's cache, kept with the generated files so it goes when they do (its default is the\n // project's node_modules/.vite, which a check would leave behind in the scenario's directory).\n cacheDir: ${JSON.stringify(join(dirname(testPath), \".vite\"))},\n plugins: [${plugin}],\n test: {\n include: [${JSON.stringify(testPath)}],\n testTimeout: 600_000,\n // An error nothing handled fails the run but is not in the JSON report; kept for the command to tell.\n reporters: [\"json\", { onTestRunEnd(_modules, errors) {\n if (errors.length > 0)\n writeFileSync(${JSON.stringify(unhandledErrorsFile(outputFile))}, JSON.stringify(errors.map((e) => ({ type: e.type, message: e.message, stack: e.stack }))));\n } }],\n outputFile: ${JSON.stringify(outputFile)},\n },\n});\n`;\n}\n","/**\n * Spec files for `eutaxy check`: every `<module>.props.ts` next to the\n * scenario, read with its module into `SpecIR` on the Node side, and the\n * generated `specs.ts` that hands workerd each module's specs together\n * with a loader for its spec file. Which of them a run checks is the\n * scenario's `specs`, read where the scenario is loaded, inside the\n * generated test; a spec file loads only when its module is named.\n */\n\nimport { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { basename, dirname, join, relative } from \"node:path\";\nimport { readSpecs } from \"@eutaxy/prover/reader\";\nimport type { ModuleSpecs } from \"@eutaxy/spec\";\nimport { specKey } from \"./keys.ts\";\n\nexport { specKey } from \"./keys.ts\";\n\n/** The suffix a spec file carries beside its module: `domain.ts` has `domain.props.ts`. */\nexport const specSuffix = \".props.ts\";\n\nexport interface SpecModule {\n /** The module's path relative to the scenario's directory, as a scenario names it: \"./domain.ts\". */\n readonly key: string;\n /** The module's absolute path. */\n readonly path: string;\n /** The spec file's absolute path. */\n readonly specPath: string;\n readonly specs: ModuleSpecs;\n}\n\nconst skipDirs = new Set([\"node_modules\", \".eutaxy\", \"dist\", \".git\"]);\n\n/** Read one module and its spec file; their imports resolve from where they are. */\nexport function readSpecModule(modulePath: string, specPath: string): ModuleSpecs {\n return readSpecs({\n module: readFileSync(modulePath, \"utf8\"),\n spec: readFileSync(specPath, \"utf8\"),\n modulePath,\n specPath,\n });\n}\n\n/** Spec files under `dir`, each with its module; a spec file without a module beside it is an error entry. */\nexport function findSpecModules(dir: string): SpecModule[] {\n const out: SpecModule[] = [];\n const walk = (at: string): void => {\n for (const entry of readdirSync(at, { withFileTypes: true })) {\n const path = join(at, entry.name);\n if (entry.isDirectory()) {\n if (!skipDirs.has(entry.name)) walk(path);\n continue;\n }\n if (!entry.name.endsWith(specSuffix)) continue;\n const modulePath = join(at, `${entry.name.slice(0, -specSuffix.length)}.ts`);\n const key = specKey(relative(dir, modulePath));\n if (!existsSync(modulePath)) {\n out.push({\n key,\n path: modulePath,\n specPath: path,\n specs: {\n functions: [],\n errors: [\n {\n line: 1,\n message: `${entry.name} has no module ${basename(modulePath)} beside it`,\n },\n ],\n },\n });\n continue;\n }\n out.push({ key, path: modulePath, specPath: path, specs: readSpecModule(modulePath, path) });\n }\n };\n walk(dir);\n return out.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));\n}\n\n/** A file `eutaxy check` writes into `.eutaxy/`, by its path there. */\nexport interface GeneratedFile {\n readonly name: string;\n readonly source: string;\n}\n\n/** A path as an import specifier from `.eutaxy/`: forward slashes, relative, `.ts` kept (Vite resolves it). */\nfunction importFrom(workDir: string, target: string): string {\n const rel = relative(workDir, target).split(\"\\\\\").join(\"/\");\n return rel.startsWith(\".\") ? rel : `./${rel}`;\n}\n\n/**\n * The generated `specs.ts`: each module's key mapped to its specs (plain\n * data read on the Node side) and a loader of its spec file. The loader is\n * lazy, so a spec file elsewhere that does not compile cannot stop a check\n * of a scenario that does not name its module.\n */\nexport function specFiles(modules: readonly SpecModule[], workDir: string): GeneratedFile[] {\n const header = \"// Generated by eutaxy check; deleted after the run.\";\n const lines = [\n header,\n \"// The `any`: this file runs in the user's Vitest, which does not type-check it; `SpecEntry` in workerd.ts is the shape.\",\n \"export const specEntries: Record<string, { specs: any; load: () => Promise<any> }> = {\",\n ...modules.map(\n (m) =>\n ` ${JSON.stringify(m.key)}: { specs: ${JSON.stringify(m.specs)}, load: () => import(${JSON.stringify(importFrom(workDir, m.specPath))}) },`,\n ),\n \"};\",\n ];\n return [{ name: \"specs.ts\", source: `${lines.join(\"\\n\")}\\n` }];\n}\n\n/** The directory a generated file's import is resolved from. */\nexport function specWorkDir(dir: string): string {\n return dirname(join(dir, \".eutaxy\", \"specs.ts\"));\n}\n","/**\n * `eutaxy check <scenario.sim.ts>`: run a scenario inside workerd through\n * the user's Vitest and the Cloudflare plugin, print the verdict as text or\n * JSON, and on a violation write a regression test next to the scenario.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { basename, dirname, join, relative, resolve } from \"node:path\";\nimport {\n canonicalJson,\n type JsonValue,\n type ScenarioVerdict,\n type SpecVerdict,\n type Violated,\n} from \"@eutaxy/core\";\nimport { aggregate, type EngineReport, type Prover } from \"@eutaxy/prover\";\nimport { leanProver } from \"@eutaxy/prover-lean\";\nimport { smtProver } from \"@eutaxy/prover-smt\";\nimport { renderSpecs, renderText } from \"@eutaxy/report\";\nimport {\n bindingCarries,\n type CalleeConfig,\n calleeSteps,\n describeCallee,\n isolateBindings,\n isolateOf,\n type LoadedScenario,\n loadScenario,\n mainModuleSource,\n mentionsCallee,\n miniflareOptionsSource,\n readCalleeConfig,\n readCallerResources,\n} from \"./callees.ts\";\nimport { checkTestSource, metaKey, vitestConfigSource } from \"./generate.ts\";\nimport { globKey } from \"./keys.ts\";\nimport { cloudflareRegressionTest } from \"./regression.ts\";\nimport { findSpecModules, type SpecModule, specFiles, specKey } from \"./specs.ts\";\nimport { strayErrors, strayNote, unhandledErrorsFile, vitestFailure } from \"./vitest-failure.ts\";\nimport type { CheckTransport } from \"./workerd.ts\";\n\nexport interface CheckOptions {\n readonly scenario: string;\n readonly cwd: string;\n readonly wrangler?: string;\n readonly seed?: string;\n readonly maxRuns?: number;\n /** Replaces the scenario's time budget. */\n readonly budgetMs?: number;\n /** Run every schedule within the bounds once instead of drawing them from the seed. */\n readonly exhaustive?: boolean;\n /** Engines to run the PROVEN rung with, by name, on the scenario's spec modules. */\n readonly provers?: readonly string[];\n readonly json: boolean;\n /** Where to write the regression test on a violation; default `<name>.regression.test.ts` beside the scenario. */\n readonly out?: string;\n readonly noRegression: boolean;\n /** Emit a regression test that asserts the violation (for corpora) rather than one that expects it fixed. */\n readonly expectViolation: boolean;\n /** Keep the generated `.eutaxy/` files for inspection. */\n readonly keep: boolean;\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\nexport const exitCodes = { BOUNDED: 0, VIOLATED: 1, UNSUPPORTED: 2, error: 3 } as const;\n\n/** The engines `--prover` can name. */\nexport const provers: Readonly<Record<string, Prover>> = { lean: leanProver, smt: smtProver };\n\n/** The engines named, or the error naming the first unknown one. */\nexport function enginesNamed(\n names: readonly string[],\n): { readonly engines: Prover[] } | { readonly error: string } {\n const engines: Prover[] = [];\n for (const name of names) {\n const engine = provers[name];\n if (!engine)\n return { error: `unknown prover ${name}; known: ${Object.keys(provers).join(\", \")}` };\n engines.push(engine);\n }\n return { engines };\n}\n\n/**\n * The PROVEN rung, on the Node side: each engine on each observed spec\n * module's source, the outcomes folded into the simulator's verdicts.\n * An engine that is not installed proves nothing and says so.\n */\nexport async function proveSpecs(\n dir: string,\n observed: readonly { readonly module: string; readonly functions: readonly string[] }[],\n specs: readonly SpecVerdict[],\n engines: readonly Prover[],\n modules: readonly SpecModule[] = findSpecModules(dir),\n /** Told each engine's report on each module, for what the verdicts do not carry: the open goals. */\n onReport?: (module: SpecModule, report: EngineReport) => void,\n): Promise<readonly SpecVerdict[]> {\n let out = specs;\n for (const m of observed) {\n // Verdicts carry the module as a normalized key (\"./domain.ts\"); the observed path is as the scenario wrote it.\n const key = specKey(m.module);\n const found = modules.find((s) => s.key === key);\n const withSpecs = m.functions.filter((f) =>\n specs.some((v) => v.module === key && v.function === f),\n );\n if (!found || withSpecs.length === 0) continue;\n const source = readFileSync(found.path, \"utf8\");\n const reports: EngineReport[] = [];\n for (const engine of engines) {\n const report: EngineReport = {\n engine: engine.name,\n proofs: await engine.prove({\n source,\n specs: found.specs,\n functions: withSpecs,\n modulePath: found.path,\n specPath: found.specPath,\n }),\n };\n reports.push(report);\n onReport?.(found, report);\n }\n out = aggregate(key, out, reports);\n }\n return out;\n}\n\nfunction findWrangler(dir: string, explicit: string | undefined, cwd: string): string | null {\n if (explicit) return resolve(cwd, explicit);\n for (const name of [\"wrangler.jsonc\", \"wrangler.json\", \"wrangler.toml\"]) {\n const p = join(dir, name);\n if (existsSync(p)) return p;\n }\n return null;\n}\n\nfunction vitestBin(from: string): string {\n const req = createRequire(join(from, \"package.json\"));\n return join(dirname(req.resolve(\"vitest/package.json\")), \"vitest.mjs\");\n}\n\nfunction runVitest(\n bin: string,\n configPath: string,\n cwd: string,\n): Promise<{ code: number; output: string }> {\n return new Promise((resolveRun) => {\n const child = spawn(process.execPath, [bin, \"run\", \"--config\", configPath], {\n cwd,\n env: { ...process.env, CI: \"1\", FORCE_COLOR: \"0\" },\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n let output = \"\";\n child.stdout.on(\"data\", (d: Buffer) => {\n output += d.toString();\n });\n child.stderr.on(\"data\", (d: Buffer) => {\n output += d.toString();\n });\n child.on(\"close\", (code) => resolveRun({ code: code ?? 1, output }));\n });\n}\n\n/** The transport the generated test left in its task meta, via Vitest's JSON reporter. */\nfunction readTransport(reportPath: string): CheckTransport | null {\n if (!existsSync(reportPath)) return null;\n const report = JSON.parse(readFileSync(reportPath, \"utf8\")) as {\n testResults?: { assertionResults?: { meta?: Record<string, unknown> }[] }[];\n };\n for (const file of report.testResults ?? []) {\n for (const t of file.assertionResults ?? []) {\n const m = t.meta?.[metaKey];\n if (m) return m as CheckTransport;\n }\n }\n return null;\n}\n\n/**\n * Whether a regression test for a scenario with these setup steps is given the Cloudflare test\n * helpers: real objects are reset and snapshotted through them, and a scripted namespace is watched\n * through them for an object that ran after all.\n */\nexport function needsObjectHelpers(setup: readonly { readonly kind: string }[]): boolean {\n return setup.some((s) => s.kind === \"durable_object\" || s.kind === \"scripted_object\");\n}\n\nfunction toPosix(p: string): string {\n const s = p.split(\"\\\\\").join(\"/\");\n return s.startsWith(\".\") ? s : `./${s}`;\n}\n\nexport async function runCheck(o: CheckOptions): Promise<number> {\n const scenarioPath = resolve(o.cwd, o.scenario);\n if (!existsSync(scenarioPath)) {\n o.stderr(`scenario not found: ${scenarioPath}\\n`);\n return exitCodes.error;\n }\n const dir = dirname(scenarioPath);\n const name = basename(scenarioPath)\n .replace(/\\.sim\\.ts$/, \"\")\n .replace(/\\.ts$/, \"\");\n // One run's files carry a stamp of their own, so two checks of one scenario running at once (a CLI run\n // beside the MCP server's, say) never share a test, a config or Vitest's report file; specs.ts is the\n // same for every run of the directory and is shared.\n const stamp = `${process.pid}-${randomBytes(3).toString(\"hex\")}`;\n const workDir = join(dir, \".eutaxy\");\n const testPath = join(workDir, `${name}.${stamp}.check.test.ts`);\n const configPath = join(workDir, `vitest.config.${stamp}.mts`);\n const mainPath = join(workDir, `main.${stamp}.ts`);\n // The scenario module is imported in Node, in a process of its own, for the Worker it names (its entry\n // is the isolate's main module, so the Durable Object and Workflow classes that run are the entry's, not\n // those of the wrangler config's `main`) and for its callees, whose configs are read here, before Vitest\n // starts, since the isolate must hold their resources.\n let callees: CalleeConfig[] = [];\n let loaded: LoadedScenario | undefined;\n try {\n loaded = await loadScenario(scenarioPath);\n } catch (err) {\n if (mentionsCallee(readFileSync(scenarioPath, \"utf8\"))) {\n o.stderr(`could not read the scenario's callees: ${String(err)}\\n`);\n return exitCodes.error;\n }\n o.stderr(\n `could not read the scenario in Node, so the isolate's main module is the wrangler config's: ${String(err).split(\"\\n\")[0]}\\n`,\n );\n }\n // The wrangler config: --wrangler, else the one the scenario names, else one beside the scenario.\n const named = o.wrangler === undefined ? loaded?.worker.config : undefined;\n const wrangler = named !== undefined ? resolve(dir, named) : findWrangler(dir, o.wrangler, o.cwd);\n if (!wrangler || !existsSync(wrangler)) {\n o.stderr(\n named !== undefined\n ? `the scenario's wrangler config was not found: ${wrangler}; pass --wrangler <path>\\n`\n : `no wrangler config found next to the scenario; pass --wrangler <path>\\n`,\n );\n return exitCodes.error;\n }\n try {\n callees = calleeSteps(loaded?.setup ?? []).map((step) => readCalleeConfig(step, dir));\n } catch (err) {\n o.stderr(`could not read the scenario's callees: ${String(err)}\\n`);\n return exitCodes.error;\n }\n // Shared resources, from the caller's config (readable as JSON or JSONC) and the callees'.\n const callerResources = readCallerResources(wrangler);\n // A callee step that names the scenario's own Worker (the Worker it called calls it in turn): its\n // module is the caller's and its resources are in the isolate already, under their own names.\n const isSelf = (c: CalleeConfig): boolean =>\n callerResources?.name !== undefined && c.name === callerResources.name;\n const allCallees = callees;\n callees = allCallees.filter((c) => !isSelf(c));\n for (const c of callees)\n if (c.notAdded.length > 0)\n o.stderr(\n `callee ${describeCallee(c, dir)}: not added to the test's isolate: ${c.notAdded.join(\", \")}\\n`,\n );\n const isolate = isolateOf(callees, callees.length > 0 ? callerResources : undefined);\n // The caller's service bindings, replaced in the isolate: the platform answers each one.\n const callerServices = (callerResources?.services ?? []).map((s) => s.binding).filter((b) => b);\n for (const reason of isolate.notAdded) o.stderr(`not added to the test's isolate: ${reason}\\n`);\n mkdirSync(workDir, { recursive: true });\n try {\n const sqlImports: { key: string; importPath: string }[] = [];\n /** Whether a path the scenario names lies outside its directory, where the test's globs do not reach. */\n const outside = (file: string): boolean => relative(dir, resolve(dir, file)).startsWith(\"..\");\n if (loaded) {\n // A schema outside the scenario's directory (a callee's, or a shared one) is imported by name.\n for (const step of loaded.setup) {\n if (step.kind !== \"d1\") continue;\n const file = String(step[\"schemaFile\"]);\n if (!outside(file)) continue;\n sqlImports.push({\n key: globKey(file),\n importPath: toPosix(relative(workDir, resolve(dir, file))),\n });\n }\n }\n writeFileSync(\n testPath,\n checkTestSource({\n seed: o.seed ?? name,\n ...(o.maxRuns === undefined ? {} : { maxRuns: o.maxRuns }),\n ...(o.budgetMs === undefined ? {} : { budgetMs: o.budgetMs }),\n ...(o.exhaustive ? { exhaustive: true } : {}),\n scenarioImport: `../${basename(scenarioPath)}`,\n // So is a Worker entry outside it, as a scenario kept apart from the Workers it checks has.\n ...(loaded && outside(loaded.worker.entry)\n ? { workerImport: toPosix(relative(workDir, resolve(dir, loaded.worker.entry))) }\n : {}),\n ...(allCallees.length === 0\n ? {}\n : {\n callees: allCallees.map((c) => ({\n binding: c.binding,\n name: c.name,\n importPath: toPosix(relative(workDir, c.entry)),\n ...bindingCarries(callerResources, c.binding, callees),\n ...(isSelf(c) ? { self: true } : {}),\n })),\n }),\n ...(sqlImports.length === 0 ? {} : { sqlImports }),\n ...(Object.keys(isolate.aliases).length === 0 ? {} : { aliases: isolate.aliases }),\n }),\n );\n const specModules = findSpecModules(dir);\n for (const f of specFiles(specModules, workDir)) {\n mkdirSync(dirname(join(workDir, f.name)), { recursive: true });\n writeFileSync(join(workDir, f.name), f.source);\n }\n const reportPath = join(workDir, `vitest-report.${stamp}.json`);\n rmSync(reportPath, { force: true }); // never read a report left by an earlier --keep run\n if (callees.length > 0 && loaded) {\n // The caller's module as the scenario names it, whatever the wrangler config's format.\n const callerEntry = resolve(dir, loaded.worker.entry);\n writeFileSync(mainPath, mainModuleSource(workDir, callerEntry, callees, isolate));\n writeFileSync(\n configPath,\n vitestConfigSource(wrangler, testPath, reportPath, {\n main: mainPath,\n miniflare: miniflareOptionsSource(callees, isolate, callerServices),\n }),\n );\n } else\n writeFileSync(\n configPath,\n vitestConfigSource(\n wrangler,\n testPath,\n reportPath,\n loaded\n ? {\n main: resolve(dir, loaded.worker.entry),\n ...(callerServices.length > 0\n ? { miniflare: miniflareOptionsSource([], undefined, callerServices) }\n : {}),\n }\n : undefined,\n ),\n );\n const { code, output } = await runVitest(vitestBin(dir), configPath, dir);\n const left = (path: string) => (existsSync(path) ? readFileSync(path, \"utf8\") : undefined);\n const ran = { report: left(reportPath), unhandled: left(unhandledErrorsFile(reportPath)) };\n // Vitest fails a run on an error nothing handled; Cloudflare's runtime only logs one, so when\n // those are the run's only fault the verdict its passed test left stands, told beside them.\n const stray = code === 0 ? undefined : strayErrors(ran);\n const transport = code === 0 || stray !== undefined ? readTransport(reportPath) : null;\n if (!transport) {\n const why = vitestFailure(ran);\n o.stderr(\n `eutaxy check could not read a verdict from Vitest (exit ${code}):\\n${why}Vitest's output:\\n${output}\\n`,\n );\n return exitCodes.error;\n }\n // Told first, so the errors are seen whatever the check goes on to say, an error of its own included.\n if (stray !== undefined) o.stderr(strayNote(stray));\n if (transport.specErrors && transport.specErrors.length > 0) {\n for (const e of transport.specErrors)\n o.stderr(`${e.module}${e.line > 0 ? `:${e.line}` : \"\"}: ${e.message}\\n`);\n return exitCodes.error;\n }\n const report = transport.report as { verdict: ScenarioVerdict; specs?: readonly SpecVerdict[] };\n const verdict = report.verdict;\n let specs = report.specs ?? [];\n if (o.provers && o.provers.length > 0) {\n const named = enginesNamed(o.provers);\n if (\"error\" in named) {\n o.stderr(`${named.error}\\n`);\n return exitCodes.error;\n }\n specs = await proveSpecs(dir, transport.observed ?? [], specs, named.engines, specModules);\n }\n // The regression test's path goes into the JSON report too (an optional field of schema 1), so a\n // caller that reads the report knows where the replay is without parsing the text.\n const regressionPath =\n verdict.kind === \"VIOLATED\" && !o.noRegression\n ? o.out\n ? resolve(o.cwd, o.out)\n : join(dir, `${name}.regression.test.ts`)\n : undefined;\n const printed = {\n ...(transport.report as object),\n ...(o.provers && o.provers.length > 0 ? { specs } : {}),\n ...(regressionPath === undefined\n ? {}\n : { regressionTest: toPosix(relative(o.cwd, regressionPath) || regressionPath) }),\n ...(stray === undefined ? {} : { unhandledErrors: stray }),\n };\n if (o.json) o.stdout(`${canonicalJson(printed as JsonValue)}\\n`);\n else o.stdout(`${renderText(verdict)}\\n${specs.length > 0 ? `\\n${renderSpecs(specs)}\\n` : \"\"}`);\n\n if (regressionPath !== undefined) {\n const outPath = regressionPath;\n const outDir = dirname(outPath);\n const schemaPaths: Record<string, string[]> = {};\n for (const step of transport.setup) {\n if (step.kind === \"d1\") {\n const binding = String(step[\"binding\"]);\n const path = toPosix(relative(outDir, resolve(dir, String(step[\"schemaFile\"]))));\n schemaPaths[binding] = [...(schemaPaths[binding] ?? []), path];\n }\n }\n const calleePaths: Record<\n string,\n {\n name: string;\n path: string;\n entrypoint?: string;\n props?: Readonly<Record<string, unknown>>;\n }\n > = {};\n for (const step of transport.setup) {\n if (step.kind !== \"callee\") continue;\n const binding = String(step[\"binding\"]);\n const carried = transport.callees?.[binding];\n if (carried === undefined) continue;\n calleePaths[binding] = {\n ...carried,\n path: toPosix(relative(outDir, resolve(dir, String(step[\"entry\"])))),\n };\n }\n const source = cloudflareRegressionTest(verdict as Violated, {\n scenarioPath: toPosix(relative(outDir, scenarioPath)),\n workerPath: toPosix(relative(outDir, resolve(dir, transport.worker.entry))),\n schemaPaths,\n ...(Object.keys(calleePaths).length === 0\n ? {}\n : {\n callees: calleePaths,\n calleeBindings: isolateBindings(callees).filter((b) => !(b in isolate.aliases)),\n ...(transport.aliases === undefined ? {} : { aliases: transport.aliases }),\n }),\n ...(o.budgetMs === undefined ? {} : { budgetMs: o.budgetMs }),\n ...(needsObjectHelpers(transport.setup) ? { durableObjects: true } : {}),\n ...(transport.setup.some((s) => s.kind === \"workflow\") ||\n (transport.drive?.kind === \"rpc\" && transport.drive[\"entrypoint\"] !== undefined)\n ? { exports: true }\n : {}),\n ...(o.expectViolation ? { expect: \"violates\" as const } : {}),\n ...((transport.observed ?? []).length > 0\n ? {\n specModules: (transport.observed ?? []).map((m) => ({\n path: toPosix(relative(outDir, resolve(dir, m.module))),\n functions: m.functions,\n })),\n }\n : {}),\n });\n mkdirSync(outDir, { recursive: true });\n writeFileSync(outPath, source);\n if (!o.json)\n o.stdout(`\\nRegression test written to ${relative(o.cwd, outPath) || outPath}\\n`);\n }\n // A refuted spec fails the check like a violation does; so does a conflict between engines.\n if (\n verdict.kind !== \"VIOLATED\" &&\n specs.some((v) => v.kind === \"REFUTED\" || v.kind === \"CONFLICT\")\n )\n return exitCodes.VIOLATED;\n return exitCodes[verdict.kind];\n } finally {\n if (!o.keep) cleanUp(workDir, stamp);\n }\n}\n\n/**\n * Remove this run's files; the shared ones and the directory go only when\n * no other run's files are left there (another check may still be using\n * them).\n */\nfunction cleanUp(workDir: string, stamp: string): void {\n if (!existsSync(workDir)) return;\n for (const f of readdirSync(workDir))\n if (f.includes(`.${stamp}.`)) rmSync(join(workDir, f), { force: true });\n const others = readdirSync(workDir).some((f) =>\n /\\.check\\.test\\.ts$|^vitest\\.config\\..*\\.mts$|^vitest-report\\./.test(f),\n );\n if (!others) rmSync(workDir, { recursive: true, force: true });\n}\n","/**\n * `eutaxy draft`: a scenario skeleton from a wrangler config and the Worker\n * module it names. The config's bindings become setup steps, the Worker's\n * handlers the drive, the hosts its code fetches the externals; the\n * invariants and the drive's events are left as holes marked TODO, since\n * only the author knows what must hold and which events matter. Nothing is\n * imported or run: the config is read as JSON or JSONC and the module's\n * source (with the modules it imports relatively) is scanned as text.\n */\n\nimport { existsSync, readdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, extname, join, relative, resolve } from \"node:path\";\nimport { d1Id, list, r2Bucket, readWranglerConfig, sqliteClasses, workerName } from \"./wrangler.ts\";\n\n/** The drive a draft chooses, with what names its target; the events themselves are left to fill in. */\nexport type DraftDrive =\n | { readonly kind: \"queue\"; readonly queue: string }\n | { readonly kind: \"cron\"; readonly cron: string }\n | { readonly kind: \"websocket\"; readonly agent: string }\n | { readonly kind: \"http\" };\n\n/** A setup step a draft writes. Paths are relative to the scenario's directory. */\nexport type DraftStep =\n | { readonly kind: \"d1\"; readonly binding: string; readonly schemaFile: string }\n | { readonly kind: \"durable_object\"; readonly binding: string; readonly sqlite: boolean }\n | { readonly kind: \"r2\"; readonly binding: string }\n | {\n readonly kind: \"workflow\";\n readonly binding: string;\n readonly className: string;\n /** Its name in the config, which `event.workflowName` reads. */\n readonly name?: string;\n }\n | {\n readonly kind: \"callee\";\n readonly binding: string;\n readonly entry: string;\n readonly config: string;\n }\n | { readonly kind: \"service\"; readonly binding: string };\n\nexport interface Draft {\n readonly name: string;\n readonly worker: { readonly entry: string; readonly config: string };\n readonly drive: DraftDrive;\n readonly setup: readonly DraftStep[];\n readonly externals: readonly { readonly name: string; readonly host: string }[];\n /** What the draft could not decide or does not model, written into the file as comments. */\n readonly notes: readonly string[];\n}\n\nconst text = (v: unknown): string => (typeof v === \"string\" ? v : \"\");\nconst record = (v: unknown): Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : {};\n\n/** A path relative to `from`, with forward slashes and a leading `./`. */\nfunction ref(from: string, to: string): string {\n const p = relative(from, to).split(\"\\\\\").join(\"/\");\n return p.startsWith(\".\") ? p : `./${p}`;\n}\n\n/** Binding kinds the simulation does not proxy: a run that touches one is UNSUPPORTED. */\nconst unmodelled: Readonly<Record<string, string>> = {\n kv_namespaces: \"KV namespace\",\n ai: \"Workers AI\",\n vectorize: \"Vectorize index\",\n hyperdrive: \"Hyperdrive config\",\n analytics_engine_datasets: \"Analytics Engine dataset\",\n browser: \"Browser Rendering\",\n send_email: \"email sender\",\n dispatch_namespaces: \"dispatch namespace\",\n mtls_certificates: \"mTLS certificate\",\n secrets_store_secrets: \"Secrets Store secret\",\n images: \"Images\",\n version_metadata: \"version metadata\",\n pipelines: \"pipeline\",\n};\n\n/**\n * The schema file of a D1 binding, beside its config: `schema.sql`, else `<database_name>.sql`, else the\n * only `.sql` file there; `found` false when none is, and the step names `schema.sql` to create.\n */\nfunction schemaOf(configDir: string, database: string): { file: string; found: boolean } {\n for (const name of [\"schema.sql\", database ? `${database}.sql` : \"\"])\n if (name && existsSync(join(configDir, name)))\n return { file: join(configDir, name), found: true };\n const sql = readdirSync(configDir).filter((f) => f.endsWith(\".sql\"));\n if (sql.length === 1) return { file: join(configDir, sql[0] as string), found: true };\n return { file: join(configDir, \"schema.sql\"), found: false };\n}\n\n/**\n * Migrations in the order wrangler applies them: by the number a name starts with, compared as a number\n * (`2_add` before `10_seed`), then by name; a name with no number after the numbered ones.\n */\nexport function migrationOrder(a: string, b: string): number {\n const na = /^\\d+/.exec(a)?.[0];\n const nb = /^\\d+/.exec(b)?.[0];\n if (na !== undefined && nb !== undefined && Number(na) !== Number(nb))\n return Number(na) - Number(nb);\n if (na !== undefined && nb === undefined) return -1;\n if (na === undefined && nb !== undefined) return 1;\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/**\n * A migrations directory's files in the order wrangler applies them: its `.sql` files, and a\n * subdirectory's `migration.sql` (one folder per migration, as drizzle-kit writes them).\n */\nfunction migrationFiles(dir: string): string[] {\n if (!existsSync(dir)) return [];\n return readdirSync(dir, { withFileTypes: true })\n .sort((a, b) => migrationOrder(a.name, b.name))\n .flatMap((e) => {\n if (e.isFile() && e.name.endsWith(\".sql\")) return [join(dir, e.name)];\n const nested = join(dir, e.name, \"migration.sql\");\n return e.isDirectory() && existsSync(nested) ? [nested] : [];\n });\n}\n\n/** Wrangler configs under `root` (not in node_modules or dot directories), by their `name`. */\nfunction configsByName(root: string, depth = 3): Map<string, string> {\n const out = new Map<string, string>();\n const walk = (dir: string, left: number): void => {\n let entries: import(\"node:fs\").Dirent[];\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const e of entries) {\n const path = join(dir, e.name);\n if (e.isDirectory()) {\n if (left > 0 && e.name !== \"node_modules\" && !e.name.startsWith(\".\")) walk(path, left - 1);\n } else if (e.name === \"wrangler.jsonc\" || e.name === \"wrangler.json\") {\n const name = workerName(path); // an unreadable config names nothing\n if (name !== undefined && !out.has(name)) out.set(name, path);\n }\n }\n };\n walk(root, depth);\n return out;\n}\n\n/** The source of a module and of the modules it imports by relative path, transitively. */\nfunction sources(entry: string): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n const visit = (file: string): void => {\n if (seen.has(file) || !existsSync(file)) return;\n seen.add(file);\n const src = readFileSync(file, \"utf8\");\n out.push(src);\n // `from` clauses (imports and re-exports), side-effect imports and dynamic imports of a literal path.\n for (const m of src.matchAll(/(?:\\bfrom\\s*|\\bimport\\s*\\(?\\s*)[\"'](\\.{1,2}\\/[^\"']+)[\"']/g)) {\n const spec = resolve(dirname(file), m[1] as string);\n const candidates = [spec, spec.replace(/\\.js$/, \".ts\"), `${spec}.ts`, join(spec, \"index.ts\")];\n const found = candidates.find((c) => existsSync(c) && extname(c) !== \"\");\n if (found) visit(found);\n }\n };\n visit(entry);\n return out;\n}\n\n/**\n * The hosts a module's code fetches by a literal URL, in order of first appearance, as `URL.host` has\n * them (which the fetch interceptor matches): lowercase, a non-default port kept.\n */\nexport function fetchedHosts(srcs: readonly string[]): string[] {\n const hosts: string[] = [];\n for (const src of srcs)\n for (const m of src.matchAll(/\\bfetch\\(\\s*[\"'`](https?):\\/\\/([a-z0-9.-]+)(?::(\\d+))?/gi)) {\n const port = m[3];\n const defaultPort = (m[1] as string).toLowerCase() === \"https\" ? \"443\" : \"80\";\n const host = `${(m[2] as string).toLowerCase()}${port && port !== defaultPort ? `:${port}` : \"\"}`;\n if (!hosts.includes(host)) hosts.push(host);\n }\n return hosts;\n}\n\n/** An external's name from its host: the first label, made an identifier-like word, unique. */\nfunction externalName(host: string, taken: Set<string>): string {\n const base = (host.split(\".\")[0] ?? host).replace(/[^a-z0-9-]/gi, \"-\") || \"external\";\n let name = base;\n for (let i = 2; taken.has(name); i++) name = `${base}-${i}`;\n taken.add(name);\n return name;\n}\n\n/**\n * The SDK's route segment for an Agent's binding, as `routeAgentRequest` matches it: the Agents SDK's\n * `camelCaseToKebabCase` (an all-caps name lowercased, else a dash before every capital).\n */\nexport function agentSegment(binding: string): string {\n if (binding === binding.toUpperCase() && binding !== binding.toLowerCase())\n return binding.toLowerCase().replaceAll(\"_\", \"-\");\n const kebab = binding.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);\n return (kebab.startsWith(\"-\") ? kebab.slice(1) : kebab).replaceAll(\"_\", \"-\").replace(/-$/, \"\");\n}\n\nexport interface DraftInput {\n /** The wrangler config, absolute. */\n readonly config: string;\n /** The Worker module, absolute; default: the config's `main`. */\n readonly entry?: string;\n /** Where the scenario will live, absolute; default: the config's directory. */\n readonly scenarioDir?: string;\n}\n\nexport function draftScenario(input: DraftInput): Draft {\n const config = readWranglerConfig(input.config);\n const configDir = dirname(input.config);\n const scenarioDir = input.scenarioDir ?? configDir;\n const name = text(config[\"name\"]) || basename(configDir);\n const main = text(config[\"main\"]);\n if (input.entry === undefined && !main)\n throw new Error(`${basename(input.config)} names no main module; pass the Worker's module`);\n const entry = input.entry ?? resolve(configDir, main);\n if (!existsSync(entry)) throw new Error(`the Worker module ${entry} does not exist`);\n const notes: string[] = [];\n const setup: DraftStep[] = [];\n // The caller's own code decides the drive; with the callees' code it gives the externals.\n const callerSrcs = sources(entry);\n const srcs = [...callerSrcs];\n // The Workers behind the service bindings whose configs are found under the scenario's directory run\n // for real (callee()); their names decide which of the caller's bindings to their classes are shared.\n const others = list(config[\"services\"]).length > 0 ? configsByName(scenarioDir) : new Map();\n const callees = new Map<string, string>();\n for (const s of list(config[\"services\"])) {\n const service = text(s[\"service\"]);\n const found = service && service !== name ? others.get(service) : undefined;\n if (found !== undefined) callees.set(service, found);\n }\n // The caller's databases and buckets: a callee binding the same one reads it under the caller's name.\n const callerDatabases = new Map(\n list(config[\"d1_databases\"]).map((db) => [d1Id(db), text(db[\"binding\"])]),\n );\n const callerBuckets = new Map(\n list(config[\"r2_buckets\"]).map((b) => [r2Bucket(b), text(b[\"binding\"])]),\n );\n /** Classes of a callee's script the caller binds itself: one namespace, set up under the caller's name. */\n const sharedClasses = new Set(\n list(record(config[\"durable_objects\"])[\"bindings\"])\n .filter((b) => callees.has(text(b[\"script_name\"])))\n .map((b) => `${text(b[\"script_name\"])}:${text(b[\"class_name\"])}`),\n );\n\n /** The setup steps of one Worker's own resources: the caller's (prefix \"\"), or a callee's (`<name>/`). */\n const resourceSteps = (\n cfg: Record<string, unknown>,\n dir: string,\n worker: string,\n prefix: string,\n ): void => {\n const sqlite = sqliteClasses(cfg);\n for (const db of list(cfg[\"d1_databases\"])) {\n const binding = text(db[\"binding\"]);\n if (!binding) continue;\n const shared = prefix ? callerDatabases.get(d1Id(db)) : undefined;\n if (shared !== undefined) {\n notes.push(\n `D1 ${prefix}${binding} is the caller's database ${shared}: set it up and read it as ${shared}`,\n );\n continue;\n }\n const schema = schemaOf(dir, text(db[\"database_name\"]));\n // A pattern choosing the migration files is the config's own rule, which the draft does not apply.\n const pattern = text(db[\"migrations_pattern\"]);\n if (!schema.found && pattern)\n notes.push(\n `D1 ${prefix}${binding}: its migrations are the files matching ${pattern}; add a d1Schema step for each, in the order wrangler applies them`,\n );\n const migrations =\n schema.found || pattern\n ? []\n : migrationFiles(join(dir, text(db[\"migrations_dir\"]) || \"migrations\"));\n if (migrations.length > 0) {\n // No schema file, but migrations: one step per migration, applied in order as wrangler does.\n for (const file of migrations)\n setup.push({\n kind: \"d1\",\n binding: `${prefix}${binding}`,\n schemaFile: ref(scenarioDir, file),\n });\n continue;\n }\n if (!schema.found && !pattern)\n notes.push(\n `D1 ${prefix}${binding}: no schema file found; write the tables it needs into ${ref(scenarioDir, schema.file)}`,\n );\n setup.push({\n kind: \"d1\",\n binding: `${prefix}${binding}`,\n schemaFile: ref(scenarioDir, schema.file),\n });\n }\n for (const b of list(record(cfg[\"durable_objects\"])[\"bindings\"])) {\n const binding = text(b[\"name\"]);\n const className = text(b[\"class_name\"]);\n const script = text(b[\"script_name\"]);\n if (!binding) continue;\n if (script && script !== worker) {\n // Another Worker's class: one shared namespace when that Worker runs here as a callee.\n if (!prefix && callees.has(script))\n setup.push({\n kind: \"durable_object\",\n binding,\n sqlite: sqliteClasses(readWranglerConfig(callees.get(script) as string)).has(className),\n });\n else\n notes.push(\n `Durable Object ${prefix}${binding} is ${script}'s class ${className}: name ${script} with callee() to run it`,\n );\n continue;\n }\n if (prefix && sharedClasses.has(`${worker}:${className}`)) {\n notes.push(\n `Durable Object ${prefix}${binding} is the namespace the caller binds to ${worker}'s class ${className}: set it up and read it under the caller's name`,\n );\n continue;\n }\n setup.push({\n kind: \"durable_object\",\n binding: `${prefix}${binding}`,\n sqlite: sqlite.has(className),\n });\n }\n for (const b of list(cfg[\"r2_buckets\"])) {\n const binding = text(b[\"binding\"]);\n if (!binding) continue;\n const shared = prefix ? callerBuckets.get(r2Bucket(b)) : undefined;\n if (shared !== undefined) {\n notes.push(\n `R2 ${prefix}${binding} is the caller's bucket ${shared}: set it up and read it as ${shared}`,\n );\n continue;\n }\n setup.push({ kind: \"r2\", binding: `${prefix}${binding}` });\n }\n for (const w of list(cfg[\"workflows\"])) {\n const binding = text(w[\"binding\"]);\n const className = text(w[\"class_name\"]);\n const script = text(w[\"script_name\"]);\n if (!binding || !className) continue;\n if (script && script !== worker) {\n notes.push(\n `Workflow ${prefix}${binding} runs in ${script}: name ${script} with callee() to run it`,\n );\n continue;\n }\n const workflowName = text(w[\"name\"]);\n setup.push({\n kind: \"workflow\",\n binding: `${prefix}${binding}`,\n className,\n ...(workflowName ? { name: workflowName } : {}),\n });\n }\n for (const [key, what] of Object.entries(unmodelled)) {\n const v = cfg[key];\n const bindings = Array.isArray(v)\n ? list(v).map((b) => text(b[\"binding\"]) || text(b[\"name\"]))\n : v !== undefined\n ? [text(record(v)[\"binding\"]) || key]\n : [];\n for (const b of bindings)\n notes.push(`not modelled: ${what} ${prefix}${b}; a run that touches it is UNSUPPORTED`);\n }\n for (const q of list(record(cfg[\"queues\"])[\"producers\"]))\n notes.push(\n `not modelled: Queue producer ${prefix}${text(q[\"binding\"])}; a run that sends to it is UNSUPPORTED`,\n );\n };\n\n resourceSteps(config, configDir, name, \"\");\n for (const s of list(config[\"services\"])) {\n const binding = text(s[\"binding\"]);\n const service = text(s[\"service\"]);\n if (!binding) continue;\n const calleeConfig = callees.get(service);\n if (calleeConfig === undefined) {\n setup.push({ kind: \"service\", binding });\n notes.push(\n `service binding ${binding}: no wrangler config named ${service || \"(none)\"} under the scenario's directory, so its answers are scripted; script them with service(), or run that Worker with callee()`,\n );\n continue;\n }\n const callee = readWranglerConfig(calleeConfig);\n const calleeDir = dirname(calleeConfig);\n const calleeMain = resolve(calleeDir, text(callee[\"main\"]));\n setup.push({\n kind: \"callee\",\n binding,\n entry: ref(scenarioDir, calleeMain),\n config: ref(scenarioDir, calleeConfig),\n });\n resourceSteps(callee, calleeDir, service, `${service}/`);\n srcs.push(...sources(calleeMain));\n }\n\n // eutaxy check finds the Worker's module and its own schema files beneath the scenario's directory.\n const outside = [\n entry,\n ...setup.flatMap((s) =>\n s.kind === \"d1\" && !s.binding.includes(\"/\") ? [resolve(scenarioDir, s.schemaFile)] : [],\n ),\n ].filter((f) => relative(scenarioDir, f).startsWith(\"..\"));\n if (outside.length > 0)\n throw new Error(\n `eutaxy check finds the Worker's module and its schema files beneath the scenario's directory, and ${outside.map((f) => relative(scenarioDir, f)).join(\", \")} is not; write the scenario beside the wrangler config or in a directory above the Worker`,\n );\n\n // The drive: a queue consumer, else a Cron Trigger, else an Agent's WebSocket route, else fetch().\n const consumers = list(record(config[\"queues\"])[\"consumers\"]);\n const crons = Array.isArray(record(config[\"triggers\"])[\"crons\"])\n ? (record(config[\"triggers\"])[\"crons\"] as unknown[]).filter((c) => typeof c === \"string\")\n : [];\n const routesAgents = callerSrcs.some((s) => /\\brouteAgentRequest\\s*\\(/.test(s));\n const firstObject = setup.find((s) => s.kind === \"durable_object\" && !s.binding.includes(\"/\"));\n let drive: DraftDrive;\n if (consumers.length > 0) {\n drive = { kind: \"queue\", queue: text(consumers[0]?.[\"queue\"]) };\n if (consumers.length > 1)\n notes.push(\n `the Worker consumes ${consumers.length} queues; one drive per scenario, so a scenario per queue`,\n );\n } else if (crons.length > 0) drive = { kind: \"cron\", cron: crons[0] as string };\n else if (routesAgents && firstObject)\n drive = { kind: \"websocket\", agent: agentSegment(firstObject.binding) };\n else drive = { kind: \"http\" };\n if (drive.kind !== \"cron\" && crons.length > 0)\n notes.push(`the Worker also has Cron Triggers (${crons.join(\", \")}); a scenario per drive`);\n\n const taken = new Set<string>();\n const externals = fetchedHosts(srcs).map((host) => ({ name: externalName(host, taken), host }));\n return {\n name,\n worker: { entry: ref(scenarioDir, entry), config: ref(scenarioDir, input.config) },\n drive,\n setup,\n externals,\n notes,\n };\n}\n\nconst q = (s: string): string => JSON.stringify(s);\n\nfunction stepSource(s: DraftStep): string {\n switch (s.kind) {\n case \"d1\":\n return `d1Schema(${q(s.binding)}, ${q(s.schemaFile)}),`;\n case \"durable_object\":\n return s.sqlite\n ? `// SQLite-backed: seed tables with { sql: { <object name>: { schema, rows } } }.\\n durableObject(${q(s.binding)}, {}),`\n : `durableObject(${q(s.binding)}, {}),`;\n case \"r2\":\n return `r2Bucket(${q(s.binding)}),`;\n case \"workflow\":\n return s.name === undefined\n ? `workflow(${q(s.binding)}, ${q(s.className)}),`\n : `workflow(${q(s.binding)}, ${q(s.className)}, { name: ${q(s.name)} }),`;\n case \"callee\":\n return `callee(${q(s.binding)}, { entry: ${q(s.entry)}, config: ${q(s.config)} }),`;\n case \"service\":\n return `// TODO: the answers of the Worker behind ${s.binding}, e.g. { methods: { <method>: { value: … } } }.\\n service(${q(s.binding)}),`;\n }\n}\n\nfunction driveSource(d: DraftDrive): { helper: string; source: string } {\n switch (d.kind) {\n case \"queue\":\n return {\n helper: \"queue\",\n source: `// TODO: the messages to deliver.\\n drive: queue(${q(d.queue)}, [{ body: {} }]),`,\n };\n case \"cron\":\n return {\n helper: \"cron\",\n source: `// TODO: how many ticks, and how many times a failed tick is re-run.\\n drive: cron(${q(d.cron)}, { ticks: 2 }),`,\n };\n case \"websocket\":\n return {\n helper: \"websocket\",\n source: `// TODO: the connections, the Agent instance they reach and the messages each sends.\\n drive: websocket([\\n { id: \"a\", path: ${q(`/agents/${d.agent}/<name>`)}, messages: [{ data: {} }] },\\n ]),`,\n };\n case \"http\":\n return {\n helper: \"http\",\n source: `// TODO: the requests, and how the caller resends one that got no 2xx.\\n drive: http([{ path: \"/\", body: {} }], { retries: 3 }),`,\n };\n }\n}\n\n/** Example invariants for the draft's bindings, as comments: the hole the author fills. */\nfunction invariantHints(d: Draft): string[] {\n const hints: string[] = [];\n const d1 = d.setup.find((s) => s.kind === \"d1\");\n if (d1) hints.push(`unique(\"one-row-per-key\", d1Rows(${q(d1.binding)}, \"<table>\"), \"<column>\"),`);\n const sqliteObject = d.setup.find((s) => s.kind === \"durable_object\" && s.sqlite);\n if (sqliteObject)\n hints.push(\n `everyRow(\"<rule>\", durableObjectTable(${q(sqliteObject.binding)}, \"<object name>\", \"<table>\"), [{ column: \"<column>\", op: \"gte\", value: 0 }]),`,\n );\n const external = d.externals[0];\n if (external)\n hints.push(\n `atMostOncePerKey(\"<call>-once\", fetchCall(${q(external.name)}, \"POST\"), \"args.body.<id>\"),`,\n );\n if (hints.length === 0)\n hints.push(\n `atMostOncePerKey(\"<effect>-once\", httpResponse(\"/\", { ok: true }), \"args.requestId\"),`,\n );\n return hints;\n}\n\n/** The scenario's source. With no invariant it does not check until the holes are filled. */\nexport function renderDraft(d: Draft): string {\n const drive = driveSource(d.drive);\n const helpers = new Set<string>([\"defineScenario\", drive.helper]);\n const stepHelper: Record<DraftStep[\"kind\"], string> = {\n d1: \"d1Schema\",\n durable_object: \"durableObject\",\n r2: \"r2Bucket\",\n workflow: \"workflow\",\n callee: \"callee\",\n service: \"service\",\n };\n for (const s of d.setup) helpers.add(stepHelper[s.kind]);\n if (d.externals.length > 0) helpers.add(\"external\");\n const imports = [...helpers].sort((a, b) => a.localeCompare(b));\n const lines: string[] = [];\n lines.push(`import { ${imports.join(\", \")} } from \"eutaxy/cloudflare\";`, \"\");\n lines.push(\n `// Drafted by eutaxy draft from ${d.worker.config}. Fill in each TODO, then run`,\n `// eutaxy check on this file; it does not check until it has an invariant.`,\n );\n for (const n of d.notes) lines.push(`// Note: ${n}.`);\n lines.push(`export default defineScenario({`);\n lines.push(` name: ${q(d.name)},`);\n lines.push(` worker: { entry: ${q(d.worker.entry)}, config: ${q(d.worker.config)} },`);\n if (d.setup.length > 0) {\n lines.push(` setup: [`);\n for (const s of d.setup) lines.push(` ${stepSource(s)}`);\n lines.push(` ],`);\n }\n lines.push(` ${drive.source}`);\n if (d.externals.length > 0) {\n lines.push(\n ` // Each host the Worker fetches answers 200 with an empty body until you script its responses.`,\n );\n lines.push(` externals: [`);\n for (const e of d.externals) lines.push(` external(${q(e.name)}, ${q(e.host)}),`);\n lines.push(` ],`);\n }\n lines.push(` invariants: [`);\n lines.push(\n ` // TODO: what must hold after every run, for example (import what you use from eutaxy/cloudflare):`,\n );\n for (const h of invariantHints(d)) lines.push(` // ${h}`);\n lines.push(` ],`);\n lines.push(\n ` bounds: { maxFaultsPerRun: 1, maxRedeliveries: 2, maxConcurrentInvocations: 1, budgetMs: 2000 },`,\n );\n lines.push(`});`, \"\");\n return lines.join(\"\\n\");\n}\n\nexport interface DraftOptions {\n readonly cwd: string;\n /** The wrangler config; default: wrangler.jsonc or wrangler.json in the working directory. */\n readonly config?: string;\n /** The Worker module; default: the config's `main`. */\n readonly worker?: string;\n /** Where to write the scenario; default: print it. An existing file is not overwritten. */\n readonly out?: string;\n readonly json: boolean;\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\n/** Exit 0 with the draft printed or written, 3 on an error. */\nexport function runDraft(o: DraftOptions): number {\n const config =\n o.config !== undefined\n ? resolve(o.cwd, o.config)\n : [\"wrangler.jsonc\", \"wrangler.json\"].map((f) => join(o.cwd, f)).find((p) => existsSync(p));\n if (config === undefined || !existsSync(config)) {\n o.stderr(\n config === undefined\n ? \"no wrangler.jsonc or wrangler.json in the working directory; name the config\\n\"\n : `wrangler config not found: ${config}\\n`,\n );\n return 3;\n }\n const out = o.out === undefined ? undefined : resolve(o.cwd, o.out);\n if (out !== undefined && existsSync(out)) {\n o.stderr(`${out} exists; eutaxy draft does not overwrite a file\\n`);\n return 3;\n }\n if (out !== undefined && !existsSync(dirname(out))) {\n o.stderr(`the directory of ${out} does not exist\\n`);\n return 3;\n }\n let draft: Draft;\n try {\n draft = draftScenario({\n config,\n ...(o.worker === undefined ? {} : { entry: resolve(o.cwd, o.worker) }),\n ...(out === undefined ? {} : { scenarioDir: dirname(out) }),\n });\n } catch (err) {\n o.stderr(`${err instanceof Error ? err.message : String(err)}\\n`);\n return 3;\n }\n const source = renderDraft(draft);\n if (out !== undefined) writeFileSync(out, source);\n if (o.json)\n o.stdout(\n `${JSON.stringify({ schemaVersion: 1, draft, source, ...(out === undefined ? {} : { written: out }) }, null, 2)}\\n`,\n );\n else if (out === undefined) o.stdout(source);\n else {\n o.stdout(`Scenario drafted in ${relative(o.cwd, out) || out}\\n`);\n for (const n of draft.notes) o.stdout(` note: ${n}\\n`);\n }\n return 0;\n}\n","/**\n * Reading the two archive formats the release files come in, with Node's\n * standard library alone: a zip (Z3; elan's installer on Windows) and a\n * gzip-compressed tar (elan's installer elsewhere). From either, only the\n * files the caller names are taken, each to the path the caller gives: the\n * archive chooses no path and makes no link, so nothing in it can write\n * anywhere else. A named entry that is missing, there twice, a link or a\n * directory, or whose data does not match what its headers say, is refused,\n * and nothing is written until every named entry has been read.\n */\n\nimport { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, resolve, sep } from \"node:path\";\nimport { crc32, gunzipSync, inflateRawSync } from \"node:zlib\";\n\nexport class ArchiveError extends Error {}\n\nconst inside = (dest: string, path: string): boolean =>\n path === dest || path.startsWith(dest + sep);\n\n/** Each named entry's place under `dest`, checked before the archive is read. */\nfunction placesOf(entries: Readonly<Record<string, string>>, dest: string): Map<string, string> {\n const root = resolve(dest);\n const places = new Map<string, string>();\n for (const [name, to] of Object.entries(entries)) {\n const place = resolve(root, to);\n if (place === root || !inside(root, place))\n throw new ArchiveError(`${JSON.stringify(to)} is not a path under the toolchain directory`);\n places.set(name, place);\n }\n return places;\n}\n\n/**\n * Write what was read, once every named entry has been: files with mode\n * 0644 (the caller makes its executable runnable). Returns how many.\n */\nfunction writeFound(\n kind: string,\n places: ReadonlyMap<string, string>,\n found: ReadonlyMap<string, Buffer>,\n): number {\n const missing = [...places.keys()].filter((name) => !found.has(name));\n if (missing.length > 0)\n throw new ArchiveError(\n `the ${kind} holds no ${missing.map((m) => JSON.stringify(m)).join(\", \")}`,\n );\n for (const [name, data] of found) {\n const place = places.get(name) as string;\n mkdirSync(dirname(place), { recursive: true });\n writeFileSync(place, data, { mode: 0o644 });\n }\n return found.size;\n}\n\nconst ZIP_EOCD = 0x06054b50;\nconst ZIP64_EOCD = 0x06064b50;\nconst ZIP64_LOCATOR = 0x07064b50;\nconst ZIP_CENTRAL = 0x02014b50;\nconst ZIP_LOCAL = 0x04034b50;\n\n/** The central directory's position and entry count, through the zip64 records when the plain ones overflow. */\nfunction centralDirectory(zip: Buffer): { offset: number; entries: number } {\n const start = Math.max(0, zip.length - 22 - 65_535);\n let eocd = -1;\n for (let i = zip.length - 22; i >= start; i--)\n if (zip.readUInt32LE(i) === ZIP_EOCD) {\n eocd = i;\n break;\n }\n if (eocd < 0) throw new ArchiveError(\"not a zip file: no end-of-central-directory record\");\n let entries: number = zip.readUInt16LE(eocd + 10);\n let offset: number = zip.readUInt32LE(eocd + 16);\n if (entries === 0xffff || offset === 0xffffffff) {\n const locator = eocd - 20;\n if (locator < 0 || zip.readUInt32LE(locator) !== ZIP64_LOCATOR)\n throw new ArchiveError(\"zip64 archive without its locator\");\n const at = Number(zip.readBigUInt64LE(locator + 8));\n if (at + 56 > zip.length || zip.readUInt32LE(at) !== ZIP64_EOCD)\n throw new ArchiveError(\"zip64 archive without its end record\");\n entries = Number(zip.readBigUInt64LE(at + 32));\n offset = Number(zip.readBigUInt64LE(at + 48));\n }\n return { offset, entries };\n}\n\n/** Sizes and offset of one entry, from its zip64 extra field when the plain ones overflow. */\nfunction zip64Fields(\n extra: Buffer,\n plain: { compressed: number; uncompressed: number; offset: number },\n): { compressed: number; uncompressed: number; offset: number } {\n let at = 0;\n while (at + 4 <= extra.length) {\n const id = extra.readUInt16LE(at);\n const size = extra.readUInt16LE(at + 2);\n const end = at + 4 + size;\n if (end > extra.length) throw new ArchiveError(\"an entry's extra field is cut short\");\n if (id === 0x0001) {\n let p = at + 4;\n const next = (): number => {\n if (p + 8 > end) throw new ArchiveError(\"an entry's zip64 field is cut short\");\n const value = Number(extra.readBigUInt64LE(p));\n p += 8;\n return value;\n };\n const out = { ...plain };\n if (out.uncompressed === 0xffffffff) out.uncompressed = next();\n if (out.compressed === 0xffffffff) out.compressed = next();\n if (out.offset === 0xffffffff) out.offset = next();\n return out;\n }\n at += 4 + size;\n }\n return plain;\n}\n\n/**\n * Take the named files of a zip, and nothing else: `entries` maps each\n * file's path in the archive to the path under `dest` it is written to.\n * Every named entry must be there exactly once, must be a plain file\n * (a directory or a link is refused), and must inflate to its declared\n * size and CRC-32; nothing is written until all of them have. Files are\n * written with mode 0644 (the caller makes its executable runnable).\n * Returns how many files were written.\n */\nexport function extractZipEntries(\n file: string,\n entries: Readonly<Record<string, string>>,\n dest: string,\n): number {\n const places = placesOf(entries, dest);\n const zip = readFileSync(file);\n const { offset, entries: count } = centralDirectory(zip);\n const found = new Map<string, Buffer>();\n let at = offset;\n for (let i = 0; i < count; i++) {\n if (at + 46 > zip.length || zip.readUInt32LE(at) !== ZIP_CENTRAL)\n throw new ArchiveError(\"a central directory entry is not where the zip says it is\");\n const madeBy = zip.readUInt16LE(at + 4) >> 8;\n const method = zip.readUInt16LE(at + 10);\n const crc = zip.readUInt32LE(at + 16);\n const nameLength = zip.readUInt16LE(at + 28);\n const extraLength = zip.readUInt16LE(at + 30);\n const commentLength = zip.readUInt16LE(at + 32);\n const externalAttributes = zip.readUInt32LE(at + 38);\n const name = zip.subarray(at + 46, at + 46 + nameLength).toString(\"utf8\");\n const extra = zip.subarray(at + 46 + nameLength, at + 46 + nameLength + extraLength);\n const sizes = zip64Fields(extra, {\n compressed: zip.readUInt32LE(at + 20),\n uncompressed: zip.readUInt32LE(at + 24),\n offset: zip.readUInt32LE(at + 42),\n });\n at += 46 + nameLength + extraLength + commentLength;\n if (!places.has(name)) continue;\n const quoted = JSON.stringify(name);\n if (found.has(name)) throw new ArchiveError(`entry ${quoted} is in the zip twice`);\n const type = (madeBy === 3 ? externalAttributes >>> 16 : 0) & 0o170000;\n if (name.endsWith(\"/\") || type === 0o040000)\n throw new ArchiveError(`entry ${quoted} is a directory, not a file`);\n if (type === 0o120000) throw new ArchiveError(`entry ${quoted} is a link, not a file`);\n const local = sizes.offset;\n if (local + 30 > zip.length || zip.readUInt32LE(local) !== ZIP_LOCAL)\n throw new ArchiveError(`entry ${quoted} has no local header where the zip says`);\n const dataStart = local + 30 + zip.readUInt16LE(local + 26) + zip.readUInt16LE(local + 28);\n const raw = zip.subarray(dataStart, dataStart + sizes.compressed);\n let data: Buffer;\n if (method === 0) data = raw;\n else if (method === 8) {\n try {\n // Never more than the entry declares, so a short entry cannot inflate into a huge one; the\n // declared size itself comes from the zip, whose SHA-256 the install checked first.\n data = inflateRawSync(raw, { maxOutputLength: Math.max(1, sizes.uncompressed) });\n } catch (err) {\n throw new ArchiveError(\n `entry ${quoted} did not inflate within its declared size: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n } else\n throw new ArchiveError(\n `entry ${quoted} uses compression method ${method}; only stored and deflated entries are read`,\n );\n if (data.length !== sizes.uncompressed)\n throw new ArchiveError(`entry ${quoted} did not inflate to its declared size`);\n if (crc32(data) !== crc) throw new ArchiveError(`entry ${quoted} fails its CRC-32 check`);\n found.set(name, data);\n }\n return writeFound(\"zip\", places, found);\n}\n\n/** The largest tar a release's installer comes in, uncompressed; elan's is 6 to 14 MB. */\nconst maxTarBytes = 256 * 1024 * 1024;\n\nconst text = (block: Buffer, start: number, length: number): string => {\n const slice = block.subarray(start, start + length);\n const end = slice.indexOf(0);\n return slice.subarray(0, end < 0 ? slice.length : end).toString(\"utf8\");\n};\n\n/** An octal field, or GNU base-256 when the high bit of the first byte is set. */\nconst numeric = (block: Buffer, start: number, length: number): number => {\n const first = block[start] as number;\n if (first & 0x80) {\n let n = 0;\n for (let i = start + 1; i < start + length; i++) n = n * 256 + (block[i] as number);\n return n;\n }\n const t = text(block, start, length).trim();\n if (t.length === 0) return 0;\n if (!/^[0-7]+$/.test(t))\n throw new ArchiveError(`a tar header holds ${JSON.stringify(t)} where a number goes`);\n return Number.parseInt(t, 8);\n};\n\n/** `length key=value\\n` records of a pax extended header. */\nfunction paxRecords(data: Buffer): Map<string, string> {\n const out = new Map<string, string>();\n let at = 0;\n while (at < data.length) {\n const space = data.indexOf(0x20, at);\n if (space < 0) break;\n const length = Number.parseInt(data.subarray(at, space).toString(\"latin1\"), 10);\n if (!Number.isInteger(length) || length <= 0) break;\n const record = data.subarray(space + 1, at + length - 1).toString(\"utf8\");\n const eq = record.indexOf(\"=\");\n if (eq > 0) out.set(record.slice(0, eq), record.slice(eq + 1));\n at += length;\n }\n return out;\n}\n\n/**\n * Take the named files of a gzip-compressed tar, and nothing else, as\n * `extractZipEntries` does for a zip: `entries` maps each file's path in\n * the archive (after any pax or GNU long name) to its path under `dest`.\n * Every header's checksum is checked; a named entry must be a regular file.\n */\nexport function extractTarGzEntries(\n file: string,\n entries: Readonly<Record<string, string>>,\n dest: string,\n): number {\n const places = placesOf(entries, dest);\n let tar: Buffer;\n try {\n tar = gunzipSync(readFileSync(file), { maxOutputLength: maxTarBytes });\n } catch (err) {\n throw new ArchiveError(\n `not a gzip-compressed tar within ${maxTarBytes} bytes: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n const found = new Map<string, Buffer>();\n let next: { path?: string; size?: number } = {};\n let at = 0;\n while (at + 512 <= tar.length) {\n const block = tar.subarray(at, at + 512);\n if (block.every((b) => b === 0)) break;\n let sum = 0;\n for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 0x20 : (block[i] as number);\n if (sum !== numeric(block, 148, 8)) throw new ArchiveError(\"a tar header fails its checksum\");\n const type = block[156] === 0 ? \"0\" : String.fromCharCode(block[156] as number);\n const size =\n type === \"x\" || type === \"L\"\n ? numeric(block, 124, 12)\n : (next.size ?? numeric(block, 124, 12));\n const start = at + 512;\n if (start + size > tar.length)\n throw new ArchiveError(\"the tar ends inside an entry; the file is truncated\");\n const data = tar.subarray(start, start + size);\n at = start + Math.ceil(size / 512) * 512;\n if (type === \"x\") {\n const records = paxRecords(data);\n const path = records.get(\"path\");\n const declared = records.get(\"size\");\n if (declared !== undefined && !/^\\d+$/.test(declared))\n throw new ArchiveError(`a pax header gives the size ${JSON.stringify(declared)}`);\n next = {\n ...(path === undefined ? {} : { path }),\n ...(declared === undefined ? {} : { size: Number(declared) }),\n };\n continue;\n }\n if (type === \"L\") {\n next = { ...next, path: text(data, 0, data.length) };\n continue;\n }\n if (type === \"g\") continue;\n // Only a POSIX header (\"ustar\\0\") has a name prefix there; an old GNU one (\"ustar \") keeps times.\n const prefix = text(block, 257, 6) === \"ustar\" ? text(block, 345, 155) : \"\";\n const plain = text(block, 0, 100);\n const name = next.path ?? (prefix.length > 0 ? `${prefix}/${plain}` : plain);\n next = {};\n if (!places.has(name)) continue;\n const quoted = JSON.stringify(name);\n if (found.has(name)) throw new ArchiveError(`entry ${quoted} is in the tar twice`);\n if (type === \"5\") throw new ArchiveError(`entry ${quoted} is a directory, not a file`);\n if (type === \"1\" || type === \"2\")\n throw new ArchiveError(`entry ${quoted} is a link, not a file`);\n if (type !== \"0\" && type !== \"7\")\n throw new ArchiveError(`entry ${quoted} is of tar type ${JSON.stringify(type)}, not a file`);\n found.set(name, Buffer.from(data));\n }\n return writeFound(\"tar\", places, found);\n}\n","/**\n * `eutaxy prover install <lean|smt>`: the pinned toolchain of a prover put\n * on this machine, where the engines look first.\n *\n * `installToolchain` installs a pinned upstream release file into Eutaxy's\n * cache: the file for this platform is downloaded (or copied from a mirror\n * or an offline directory given with `--from`), its SHA-256 checked against\n * the table before anything is unpacked, the files the table names taken\n * from it (a zip or a `tar.gz`) beside a marker written last, and the\n * download deleted. A mismatch or a failed download installs nothing, and\n * nothing is run. Z3 comes this way, and so does elan's installer.\n *\n * `installLean` installs Lean through elan, Lean's toolchain manager: the\n * machine's elan if it has one, else elan installed into Eutaxy's cache\n * from its pinned installer (without touching the PATH or the shell's\n * profile); then `elan toolchain install` of the pinned toolchain, whose\n * files' digest is checked against the pinned one, since elan checks no\n * pinned checksum itself.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { createHash, randomBytes } from \"node:crypto\";\nimport {\n chmodSync,\n closeSync,\n createReadStream,\n existsSync,\n mkdirSync,\n mkdtempSync,\n openSync,\n renameSync,\n rmSync,\n writeFileSync,\n writeSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport {\n cacheDir,\n executableName,\n type Host,\n host,\n type InstallMarker,\n installed,\n markerFile,\n type Platform,\n platformOf,\n platforms,\n type Toolchain,\n toolchainDir,\n} from \"@eutaxy/prover/toolchain\";\nimport {\n type Elan,\n elanCandidates,\n elanDownloads,\n elanHome,\n elanVersion,\n leanDigests,\n leanToolchain,\n leanVersion,\n toolchainDigest,\n} from \"@eutaxy/prover-lean\";\nimport { z3Downloads } from \"@eutaxy/prover-smt\";\nimport { reportSchemaVersion } from \"@eutaxy/report\";\nimport { extractTarGzEntries, extractZipEntries } from \"./archive.ts\";\nimport { exitCodes } from \"./check.ts\";\n\n/** The engines the command installs, by the name it takes. */\nexport const engines = [\"lean\", \"smt\"] as const;\nexport type Engine = (typeof engines)[number];\n\nexport class InstallError extends Error {}\n\nexport interface InstallOptions {\n readonly toolchain: Toolchain;\n readonly host?: Host;\n /** A mirror URL or a directory holding the release file under its upstream name. */\n readonly from?: string;\n /** How to download, for tests; the global `fetch` otherwise. */\n readonly fetch?: typeof fetch;\n /** Progress lines while a download runs. */\n readonly progress?: (text: string) => void;\n}\n\nexport interface InstallResult {\n readonly name: string;\n readonly version: string;\n readonly platform: Platform;\n readonly file: string;\n readonly source: string;\n readonly sha256: string;\n readonly bytes: number;\n readonly dir: string;\n readonly executable: string;\n /** False when the toolchain was already in the cache and nothing was downloaded. */\n readonly downloaded: boolean;\n}\n\nconst isUrl = (s: string): boolean => /^https?:\\/\\//.test(s);\n\n/** Write a byte stream to `path`, hashing it as it goes; the hash and the byte count come back. */\nasync function store(\n bytes: AsyncIterable<Uint8Array>,\n path: string,\n progress: ((written: number) => void) | undefined,\n): Promise<{ sha256: string; bytes: number }> {\n const hash = createHash(\"sha256\");\n const fd = openSync(path, \"w\");\n let written = 0;\n let reported = 0;\n try {\n for await (const chunk of bytes) {\n writeSync(fd, chunk);\n hash.update(chunk);\n written += chunk.byteLength;\n if (progress && written - reported >= 50_000_000) {\n reported = written;\n progress(written);\n }\n }\n } finally {\n closeSync(fd);\n }\n return { sha256: hash.digest(\"hex\"), bytes: written };\n}\n\nexport async function installToolchain(options: InstallOptions): Promise<InstallResult> {\n const { toolchain } = options;\n const h = options.host ?? host();\n const platform = platformOf(h);\n const release = platform === undefined ? undefined : toolchain.files[platform];\n if (platform === undefined || release === undefined)\n throw new InstallError(\n `no ${toolchain.name} ${toolchain.version} release for ${h.platform}-${h.arch}; the platforms are ${platforms.join(\", \")}`,\n );\n const cache = cacheDir(h);\n const dir = toolchainDir(cache, toolchain);\n const already = installed(toolchain, h);\n if (already)\n return {\n name: toolchain.name,\n version: toolchain.version,\n platform,\n file: already.marker.file,\n source: already.marker.source,\n sha256: already.marker.sha256,\n bytes: release.bytes,\n dir,\n executable: already.executable,\n downloaded: false,\n };\n const source =\n options.from === undefined\n ? release.url\n : isUrl(options.from)\n ? `${options.from.replace(/\\/+$/, \"\")}/${release.file}`\n : join(options.from, release.file);\n // Staging paths of this invocation alone, so two installs sharing a cache never touch each other's files.\n const stamp = `${process.pid}-${randomBytes(4).toString(\"hex\")}`;\n const downloads = join(cache, \"downloads\");\n const archive = join(downloads, `${release.file}.${stamp}.part`);\n const mb = (n: number) => `${Math.round(n / 1_000_000)} MB`;\n try {\n mkdirSync(downloads, { recursive: true });\n let bytes: AsyncIterable<Uint8Array>;\n if (isUrl(source)) {\n const fetchImpl = options.fetch ?? fetch;\n let response: Response;\n try {\n response = await fetchImpl(source);\n } catch (err) {\n throw new InstallError(\n `could not download ${source}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n if (!response.ok || response.body === null)\n throw new InstallError(\n `could not download ${source}: HTTP ${response.status} ${response.statusText}`,\n );\n options.progress?.(`downloading ${release.file} (${mb(release.bytes)}) from ${source}`);\n bytes = Readable.fromWeb(response.body as import(\"node:stream/web\").ReadableStream);\n } else {\n if (!existsSync(source)) throw new InstallError(`no ${release.file} in ${options.from}`);\n bytes = createReadStream(source);\n }\n let stored: { sha256: string; bytes: number };\n try {\n stored = await store(bytes, archive, (n) =>\n options.progress?.(`${mb(n)} of ${mb(release.bytes)}`),\n );\n } catch (err) {\n throw new InstallError(\n `could not download ${source}: ${err instanceof Error ? err.message : String(err)}; nothing was installed`,\n );\n }\n if (stored.sha256 !== release.sha256)\n throw new InstallError(\n `checksum mismatch for ${release.file} from ${source}: expected sha256 ${release.sha256}, got ${stored.sha256} (${stored.bytes} bytes, ${release.bytes} expected); nothing was installed`,\n );\n const partial = `${dir}.partial-${stamp}`;\n mkdirSync(partial, { recursive: true });\n try {\n options.progress?.(`unpacking ${release.file}`);\n const extract = release.file.endsWith(\".zip\")\n ? extractZipEntries\n : release.file.endsWith(\".tar.gz\")\n ? extractTarGzEntries\n : undefined;\n if (extract === undefined)\n throw new InstallError(`${release.file} is neither a .zip nor a .tar.gz`);\n if (release.entries === undefined)\n throw new InstallError(\n `the table names no files to take from ${release.file}; nothing was installed`,\n );\n extract(archive, release.entries, partial);\n const executable = executableName(toolchain, h);\n if (!existsSync(join(partial, executable)))\n throw new InstallError(`${release.file} holds no ${executable}; nothing was installed`);\n // The named executable must run whatever mode the archive gave it (a zip made elsewhere carries none).\n if (h.platform !== \"win32\") chmodSync(join(partial, executable), 0o755);\n const marker: InstallMarker = {\n name: toolchain.name,\n version: toolchain.version,\n platform,\n file: release.file,\n sha256: stored.sha256,\n source,\n };\n writeFileSync(join(partial, markerFile), `${JSON.stringify(marker, null, 2)}\\n`);\n rmSync(dir, { recursive: true, force: true });\n renameSync(partial, dir);\n } catch (err) {\n rmSync(partial, { recursive: true, force: true });\n throw err instanceof InstallError\n ? err\n : new InstallError(\n `could not unpack ${release.file}: ${err instanceof Error ? err.message : String(err)}; nothing was installed`,\n );\n }\n return {\n name: toolchain.name,\n version: toolchain.version,\n platform,\n file: release.file,\n source,\n sha256: stored.sha256,\n bytes: stored.bytes,\n dir,\n executable: join(dir, executableName(toolchain, h)),\n downloaded: true,\n };\n } catch (err) {\n // Anything but an install error here is the file system refusing (the cache not writable, say).\n throw err instanceof InstallError\n ? err\n : new InstallError(\n `could not install ${toolchain.name} ${toolchain.version} in ${cache}: ${err instanceof Error ? err.message : String(err)}`,\n );\n } finally {\n try {\n rmSync(archive, { force: true });\n } catch {\n // The download never got there (the cache is not a directory, say); the error above says why.\n }\n }\n}\n\n/** What running a command gave: its exit code (null when it could not start or timed out) and its output. */\nexport interface ExecResult {\n readonly code: number | null;\n readonly stdout: string;\n readonly stderr: string;\n readonly timedOut?: boolean;\n}\nexport interface ExecOptions {\n /** Environment added to the process's own. */\n readonly env?: Readonly<Record<string, string>> | undefined;\n readonly cwd?: string;\n /** Killed after this long; a command that hangs never holds the install forever. */\n readonly timeoutMs?: number;\n}\n/** Run a command to its end; tests hand in another. */\nexport type Exec = (\n command: string,\n args: readonly string[],\n options?: ExecOptions,\n) => Promise<ExecResult>;\n\n/** How long a quick elan command (a version, a list, a path) may take. */\nconst quickMs = 60_000;\n/** How long elan may take to install the toolchain: a 600 MB download and 2.8 GB unpacked. */\nconst toolchainInstallMs = 60 * 60_000;\n\nconst exec: Exec = (command, args, options = {}) =>\n new Promise((resolve) => {\n let child: ReturnType<typeof spawn>;\n try {\n child = spawn(command, args, {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n ...(options.cwd === undefined ? {} : { cwd: options.cwd }),\n ...(options.env === undefined ? {} : { env: { ...process.env, ...options.env } }),\n });\n } catch (err) {\n resolve({ code: null, stdout: \"\", stderr: String(err) });\n return;\n }\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGKILL\");\n }, options.timeoutMs ?? quickMs);\n child.stdout?.on(\"data\", (d: Buffer) => {\n stdout += d.toString();\n });\n child.stderr?.on(\"data\", (d: Buffer) => {\n stderr += d.toString();\n });\n child.on(\"error\", (err) => {\n clearTimeout(timer);\n resolve({ code: null, stdout, stderr: `${stderr}${String(err)}` });\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n resolve(\n timedOut\n ? { code: null, stdout, stderr: `${stderr}timed out`, timedOut: true }\n : { code, stdout, stderr },\n );\n });\n });\n\n/** The last lines of a command's error output, for a message. */\nconst tail = (text: string): string => text.trim().split(\"\\n\").slice(-5).join(\"\\n\");\n\nexport interface LeanInstallOptions {\n readonly host?: Host;\n /** Refused: Lean comes through elan, from its own host. */\n readonly from?: string;\n /** How to download elan's installer, for tests; the global `fetch` otherwise. */\n readonly fetch?: typeof fetch;\n readonly progress?: (text: string) => void;\n /** How to run elan, for tests. */\n readonly exec?: Exec;\n /** The digests to check against, for tests; `leanDigests` otherwise. */\n readonly digests?: Readonly<Partial<Record<Platform, string>>>;\n /** The elan installer to fetch, for tests; `elanDownloads` otherwise. */\n readonly elanInstaller?: Toolchain;\n}\n\n/**\n * Lean through elan. The result's `file` is the toolchain's name, `source`\n * the elan that installed it, `sha256` the digest of the toolchain's files,\n * `bytes` their size and `dir` the toolchain's directory.\n */\nexport async function installLean(options: LeanInstallOptions = {}): Promise<InstallResult> {\n const h = options.host ?? host();\n const platform = platformOf(h);\n const expected = platform === undefined ? undefined : (options.digests ?? leanDigests)[platform];\n if (platform === undefined || expected === undefined)\n throw new InstallError(\n `no lean ${leanVersion} toolchain for ${h.platform}-${h.arch}; the platforms are ${platforms.join(\", \")}`,\n );\n if (options.from !== undefined)\n throw new InstallError(\n `--from applies to smt only: Lean is installed by elan, which downloads it from releases.lean-lang.org; offline, unpack Lean's release by hand and register it with elan toolchain link`,\n );\n const run = options.exec ?? exec;\n const say = options.progress ?? (() => {});\n let elan: Elan | undefined;\n for (const candidate of elanCandidates(h)) {\n if ((await run(candidate.command, [\"--version\"], { env: candidate.env })).code === 0) {\n elan = candidate;\n break;\n }\n }\n if (elan === undefined) {\n const installer = await installToolchain({\n toolchain: options.elanInstaller ?? elanDownloads,\n host: h,\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n ...(options.progress === undefined ? {} : { progress: options.progress }),\n });\n const home = elanHome(h);\n say(`installing elan ${elanVersion} in ${home}`);\n const made = await run(\n installer.executable,\n [\"-y\", \"--no-modify-path\", \"--default-toolchain\", \"none\"],\n { env: { ELAN_HOME: home }, timeoutMs: 10 * 60_000 },\n );\n elan = elanCandidates(h)[0] as Elan;\n if (made.code !== 0 || (await run(elan.command, [\"--version\"], { env: elan.env })).code !== 0)\n throw new InstallError(\n `elan's installer did not install elan in ${home} (exit ${made.code}): ${tail(made.stderr)}`,\n );\n }\n const list = await run(elan.command, [\"toolchain\", \"list\"], { env: elan.env });\n // Without the list it is unknown whether the toolchain was there, and so whether it is the\n // user's: stop rather than guess, since a mismatch would uninstall what this run installed.\n if (list.code !== 0)\n throw new InstallError(\n `elan (${elan.command}) could not list its toolchains (exit ${list.code}): ${tail(list.stderr)}`,\n );\n const had = list.stdout.split(\"\\n\").some((line) => line.trim().split(\" \")[0] === leanToolchain);\n if (!had) {\n say(\n `installing ${leanToolchain} through ${elan.command} (about 600 MB to download, 2.8 GB unpacked)`,\n );\n const installed = await run(elan.command, [\"toolchain\", \"install\", leanToolchain], {\n env: elan.env,\n timeoutMs: toolchainInstallMs,\n });\n if (installed.code !== 0)\n throw new InstallError(\n `elan could not install ${leanToolchain} (exit ${installed.code}): ${tail(installed.stderr)}`,\n );\n }\n // Where it is, asked of elan without running anything from the toolchain, which is not checked\n // yet: `elan which` in a directory whose lean-toolchain file names it gives its `lean`'s path.\n const pinned = mkdtempSync(join(tmpdir(), \"eutaxy-lean-toolchain-\"));\n let where: ExecResult;\n try {\n writeFileSync(join(pinned, \"lean-toolchain\"), `${leanToolchain}\\n`);\n // ELAN_TOOLCHAIN, if the caller set one, would win over the file: name the pinned one there too.\n where = await run(elan.command, [\"which\", \"lean\"], {\n env: { ...elan.env, ELAN_TOOLCHAIN: leanToolchain },\n cwd: pinned,\n });\n } finally {\n rmSync(pinned, { recursive: true, force: true });\n }\n const leanPath = where.stdout.trim();\n const prefix = dirname(dirname(leanPath));\n if (where.code !== 0 || !/[\\\\/]bin[\\\\/]lean(\\.exe)?$/.test(leanPath) || !existsSync(prefix))\n throw new InstallError(\n `elan has ${leanToolchain} but did not say where (exit ${where.code}): ${tail(where.stderr) || leanPath}`,\n );\n say(`checking the files of ${leanToolchain} in ${prefix}`);\n const found = toolchainDigest(prefix);\n // An elan built for the other architecture of this system (x64 under Rosetta, say) installs the\n // pinned release for its own; that toolchain runs here too, so it is accepted, and said.\n const digests = options.digests ?? leanDigests;\n const sameSystem = Object.entries(digests).find(\n ([p, d]) => d === found.digest && p.startsWith(`${h.platform}-`),\n )?.[0];\n if (sameSystem !== undefined && sameSystem !== platform)\n say(\n `the toolchain is the pinned release for ${sameSystem}, the architecture ${elan.command} installs for, not ${platform}; it runs here too`,\n );\n if (sameSystem === undefined) {\n // Only a toolchain this run installed is removed; one that was already there is the user's.\n let fate = \"it was there before this command, so it was left as it is\";\n if (!had) {\n const removed = await run(elan.command, [\"toolchain\", \"uninstall\", leanToolchain], {\n env: elan.env,\n });\n fate =\n removed.code === 0\n ? \"it was uninstalled\"\n : `uninstalling it failed (exit ${removed.code}): remove it with elan toolchain uninstall ${leanToolchain}`;\n }\n throw new InstallError(\n `the toolchain in ${prefix} is not the pinned ${leanToolchain}: the digest of its files is ${found.digest}, expected ${expected}; ${fate}`,\n );\n }\n return {\n name: \"lean\",\n version: leanVersion,\n platform,\n file: leanToolchain,\n source: elan.command,\n sha256: found.digest,\n bytes: found.bytes,\n dir: prefix,\n executable: join(prefix, \"bin\", h.platform === \"win32\" ? \"lean.exe\" : \"lean\"),\n downloaded: !had,\n };\n}\n\nexport interface RunInstallOptions {\n readonly engine: Engine;\n readonly from?: string | undefined;\n readonly json: boolean;\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n readonly host?: Host;\n readonly fetch?: typeof fetch;\n readonly exec?: Exec;\n readonly digests?: Readonly<Partial<Record<Platform, string>>>;\n}\n\n/** The command: the result as text or `--json` on stdout, progress and errors on stderr; exit 0, or 3 on an error. */\nexport async function runInstall(options: RunInstallOptions): Promise<number> {\n try {\n const shared = {\n ...(options.host === undefined ? {} : { host: options.host }),\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n ...(options.from === undefined ? {} : { from: options.from }),\n progress: (text: string) => options.stderr(`${text}\\n`),\n };\n const result =\n options.engine === \"lean\"\n ? await installLean({\n ...shared,\n ...(options.exec === undefined ? {} : { exec: options.exec }),\n ...(options.digests === undefined ? {} : { digests: options.digests }),\n })\n : await installToolchain({ ...shared, toolchain: z3Downloads });\n if (options.json) {\n options.stdout(\n `${JSON.stringify({ schemaVersion: reportSchemaVersion, command: \"prover install\", ...result }, null, 2)}\\n`,\n );\n } else if (options.engine === \"lean\") {\n options.stdout(\n `${result.name} ${result.version} ${result.downloaded ? \"installed\" : \"already installed\"} in ${result.dir}\\n ${result.file} through ${result.source}\\n files checked, digest ${result.sha256}\\n`,\n );\n } else if (result.downloaded) {\n options.stdout(\n `${result.name} ${result.version} installed in ${result.dir}\\n ${result.file} from ${result.source}\\n sha256 ${result.sha256}\\n`,\n );\n } else {\n options.stdout(\n `${result.name} ${result.version} already installed in ${result.dir} (${result.file}, sha256 ${result.sha256})\\n`,\n );\n }\n return exitCodes.BOUNDED;\n } catch (err) {\n if (!(err instanceof InstallError)) throw err;\n options.stderr(`${err.message}\\n`);\n return exitCodes.error;\n }\n}\n","/**\n * What a module running ahead of its turn writes, held until its turn:\n * in memory up to a limit, then in a file, so a module that writes a lot\n * while an earlier one is still running cannot exhaust the report's heap.\n * Drained, it gives back exactly the text it was given, in order.\n */\nimport { closeSync, mkdtempSync, openSync, readSync, rmSync, writeSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { StringDecoder } from \"node:string_decoder\";\n\nexport class HeldOutput {\n readonly #limit: number;\n readonly #readBytes: number;\n #chunks: string[] = [];\n #bytes = 0;\n #dir: string | undefined;\n #fd: number | undefined;\n\n /** `limitBytes` is held in memory; past it, everything goes to a file, read back `readBytes` at a time. */\n constructor(limitBytes = 1 << 20, readBytes = 1 << 16) {\n this.#limit = limitBytes;\n this.#readBytes = readBytes;\n }\n\n /** Whether the text held so far went past the limit into a file. */\n get spilled(): boolean {\n return this.#fd !== undefined;\n }\n\n push(text: string): void {\n const bytes = Buffer.byteLength(text);\n if (this.#fd === undefined && this.#bytes + bytes <= this.#limit) {\n this.#chunks.push(text);\n this.#bytes += bytes;\n return;\n }\n if (this.#fd === undefined) {\n this.#dir = mkdtempSync(join(tmpdir(), \"eutaxy-report-\"));\n this.#fd = openSync(join(this.#dir, \"held\"), \"w+\");\n }\n writeSync(this.#fd, text);\n }\n\n /** Everything held, in order, to `out`; then nothing is held and the file is gone. */\n drain(out: (text: string) => void): void {\n for (const text of this.#chunks) out(text);\n this.#chunks = [];\n this.#bytes = 0;\n if (this.#fd === undefined) return;\n try {\n // A multi-byte character may straddle two reads; the decoder joins it.\n const decoder = new StringDecoder(\"utf8\");\n const buffer = Buffer.alloc(this.#readBytes);\n for (let at = 0; ; ) {\n const n = readSync(this.#fd, buffer, 0, buffer.length, at);\n if (n === 0) break;\n at += n;\n const text = decoder.write(buffer.subarray(0, n));\n if (text !== \"\") out(text);\n }\n const rest = decoder.end();\n if (rest !== \"\") out(rest);\n } finally {\n this.discard();\n }\n }\n\n /** Drop the file, if any. */\n discard(): void {\n if (this.#fd !== undefined) closeSync(this.#fd);\n if (this.#dir !== undefined) rmSync(this.#dir, { recursive: true, force: true });\n this.#fd = undefined;\n this.#dir = undefined;\n }\n}\n","/**\n * `eutaxy report [dir]`: every spec file under a directory through the\n * ladder, on the Node side. No scenario runs, so the ladder starts at\n * `TESTED` (inputs drawn from the parameter types); `--prover` adds the\n * `PROVEN` rung. Each module runs in a child process of its own, started\n * on this file: what the module prints goes to stderr, its state starts\n * fresh, and a property that never returns ends with the module's budget.\n * A process, not a worker thread: Node strips types with WebAssembly, and\n * V8 shares compiled wasm code between the threads of a process; V8 on\n * Node 24 can abort while one thread frees that code as another uses it\n * (seen as SIGSEGV, SIGBUS or SIGTRAP of the whole process).\n * A module that only loads inside workerd gets `UNKNOWN` until an engine\n * reads it.\n */\n\nimport { fork } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { availableParallelism } from \"node:os\";\nimport { basename, relative, resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { canonicalJson, type JsonValue, type SpecVerdict } from \"@eutaxy/core\";\nimport { checkSpecModule, inWindow, type OpenGoal, type Prover } from \"@eutaxy/prover\";\nimport { goalFileFor, leanProver, renderGoals } from \"@eutaxy/prover-lean\";\nimport { renderSpecReport, renderSpecReportJson } from \"@eutaxy/report\";\nimport { enginesNamed, exitCodes, proveSpecs } from \"./check.ts\";\nimport { HeldOutput } from \"./held-output.ts\";\nimport { resolveAsTypeScript } from \"./resolve.ts\";\nimport { findSpecModules, type SpecModule } from \"./specs.ts\";\n\nexport interface ReportOptions {\n /** The directory to search for spec files, relative to `cwd`; default `cwd` itself. */\n readonly dir?: string;\n readonly cwd: string;\n /** The seed the `TESTED` rung draws from; default \"report\". */\n readonly seed?: string;\n /** Engines to run the `PROVEN` rung with, by name. */\n readonly provers?: readonly string[];\n /** How long one module's properties may take at `TESTED`; default 60 s. */\n readonly moduleBudgetMs?: number;\n /** Only the module whose spec file this is (a path, relative to `cwd`), for a proof checked on its own. */\n readonly only?: string;\n /** Write each module's open Lean goals beside its spec file (`<spec>.goals.lean`) and list them. */\n readonly goals?: boolean;\n readonly json: boolean;\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\n/** The argument a module's process is started with, so this file knows to run it. */\nconst moduleFlag = \"--eutaxy-report-module\";\n\ninterface ModuleInput {\n readonly module: SpecModule;\n readonly seed: string;\n}\n\n/** What a module's process sends back; tagged, since the module itself may call `process.send`. */\ninterface ModuleOutput {\n readonly kind: \"eutaxy-report-verdicts\";\n readonly verdicts: SpecVerdict[];\n}\n\nfunction unknownAll(\n m: SpecModule,\n cause: \"gave_up\" | \"unavailable\",\n reason: string,\n): SpecVerdict[] {\n return m.specs.functions.flatMap((fn) =>\n fn.properties.map(\n (p): SpecVerdict => ({\n module: m.key,\n function: fn.name,\n property: p.name,\n text: p.text,\n kind: \"UNKNOWN\",\n cause,\n reason,\n assumptions: [],\n }),\n ),\n );\n}\n\n/** Inside the module's process: load the module and its spec file, run the `TESTED` rung. */\nasync function testHere(m: SpecModule, seed: string): Promise<SpecVerdict[]> {\n resolveAsTypeScript();\n let namespace: Readonly<Record<string, unknown>>;\n let props: Readonly<Record<string, unknown>>;\n try {\n namespace = (await import(pathToFileURL(m.path).href)) as Record<string, unknown>;\n props = (await import(pathToFileURL(m.specPath).href)) as Record<string, unknown>;\n } catch (err) {\n return unknownAll(\n m,\n \"unavailable\",\n `the module or its spec file did not load in Node: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n return checkSpecModule(\n m.key,\n m.specs,\n props,\n namespace,\n { calls: [], unobservable: {} },\n { checked: false, tested: { seed } },\n );\n}\n\nconst send = process.send?.bind(process);\nif (process.argv[2] === moduleFlag && send) {\n process.once(\"disconnect\", () => process.exit(0));\n process.once(\"message\", async (input: ModuleInput) => {\n const verdicts = await testHere(input.module, input.seed);\n // Exit once the verdicts and everything the module wrote are out, whatever timers it left.\n send({ kind: \"eutaxy-report-verdicts\", verdicts } satisfies ModuleOutput, () =>\n process.stdout.write(\"\", () => process.stderr.write(\"\", () => process.exit(0))),\n );\n });\n}\n\n/**\n * One module's verdicts at the `TESTED` rung, from a child process. What\n * the module writes goes to `stderr`; a module that does not load, or does\n * not finish within the budget, leaves each property `UNKNOWN`.\n */\nexport function testModule(\n m: SpecModule,\n seed: string,\n budgetMs: number,\n stderr: (text: string) => void,\n): Promise<SpecVerdict[]> {\n return new Promise((done) => {\n const child = fork(fileURLToPath(import.meta.url), [moduleFlag], {\n stdio: [\"ignore\", \"pipe\", \"pipe\", \"ipc\"],\n serialization: \"advanced\",\n });\n child.stdout?.on(\"data\", (d: Buffer) => stderr(d.toString()));\n child.stderr?.on(\"data\", (d: Buffer) => stderr(d.toString()));\n // Settled on `close`, once the process has exited and all it wrote is read; `reported` holds\n // its verdicts if it sent them, and `ended` why it stopped otherwise.\n let reported: SpecVerdict[] | undefined;\n let ended: SpecVerdict[] | undefined;\n let settled = false;\n const settle = (verdicts: SpecVerdict[]) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n done(verdicts);\n };\n const timer = setTimeout(() => {\n ended = unknownAll(\n m,\n \"gave_up\",\n `the module's properties did not finish within ${budgetMs} ms on generated inputs (one may never return)`,\n );\n child.kill(\"SIGKILL\");\n // A process the module started may still hold the pipes open.\n child.stdout?.destroy();\n child.stderr?.destroy();\n }, budgetMs);\n child.on(\"message\", (message: Partial<ModuleOutput> | null) => {\n if (message?.kind === \"eutaxy-report-verdicts\" && Array.isArray(message.verdicts))\n reported ??= message.verdicts;\n });\n child.once(\"error\", (err) => {\n ended ??= unknownAll(m, \"unavailable\", `the module's process failed: ${err.message}`);\n // A process that never started (no pid) emits no `close`.\n if (child.pid === undefined) settle(ended);\n else child.kill(\"SIGKILL\");\n });\n child.once(\"close\", (code, signal) => {\n settle(\n reported ??\n ended ??\n unknownAll(\n m,\n \"unavailable\",\n `the module's process exited (${signal ?? code}) before reporting`,\n ),\n );\n });\n child.send({ module: m, seed } satisfies ModuleInput);\n });\n}\n\n/**\n * Every module's verdicts, a few modules' processes at a time. The verdicts\n * come back in module order, and what each module writes reaches `stderr`\n * in module order too: a module's output is held until every module before\n * it has finished (in memory up to a limit, then in a file), so the report\n * reads as if they ran one after another. No module starts eight or more\n * places past the earliest unfinished one, so at most seven modules' output\n * is held at once.\n */\nexport async function testModules(\n modules: readonly SpecModule[],\n seed: string,\n budgetMs: number,\n stderr: (text: string) => void,\n): Promise<SpecVerdict[][]> {\n const held = modules.map(() => new HeldOutput());\n const finished = modules.map(() => false);\n // The module whose output goes straight through; every later one's is held.\n let current = 0;\n try {\n return await inWindow(modules, Math.min(8, availableParallelism()), async (m, i) => {\n const verdicts = await testModule(m, seed, budgetMs, (text) => {\n if (i === current) stderr(text);\n else held[i]?.push(text);\n });\n finished[i] = true;\n while (finished[current]) {\n current++;\n held[current]?.drain(stderr);\n }\n return verdicts;\n });\n } finally {\n for (const h of held) h.discard();\n }\n}\n\n/** One open goal as the report lists it: where its goal file is, and the goal itself. */\nexport interface WrittenGoal extends OpenGoal {\n readonly module: string;\n /** The goal file, relative to the working directory. */\n readonly file: string;\n}\n\n/**\n * Write a module's open Lean goals beside its spec file as\n * `<spec>.goals.lean`, a proof file with every proof open, and list them.\n * No open goal removes a goal file left from an earlier run.\n */\nfunction writeGoals(m: SpecModule, goals: readonly OpenGoal[], cwd: string): WrittenGoal[] {\n const path = goalFileFor(m.specPath);\n if (goals.length === 0) {\n rmSync(path, { force: true });\n return [];\n }\n const sha = (text: string) => createHash(\"sha256\").update(text).digest(\"hex\");\n writeFileSync(\n path,\n renderGoals({\n specFile: basename(m.specPath),\n sourceSha256: sha(readFileSync(m.path, \"utf8\")),\n specSha256: sha(readFileSync(m.specPath, \"utf8\")),\n goals,\n }),\n );\n const file = relative(cwd, path).split(\"\\\\\").join(\"/\");\n return goals.map((g) => ({ module: m.key, file, ...g }));\n}\n\nexport async function runReport(o: ReportOptions): Promise<number> {\n const root = resolve(o.cwd, o.dir ?? \".\");\n let engines: Prover[] = [];\n if (o.provers && o.provers.length > 0) {\n const named = enginesNamed(o.provers);\n if (\"error\" in named) {\n o.stderr(`${named.error}\\n`);\n return exitCodes.error;\n }\n engines = named.engines;\n }\n let modules: SpecModule[];\n try {\n modules = findSpecModules(root);\n } catch (err) {\n o.stderr(`cannot read ${root}: ${err instanceof Error ? err.message : String(err)}\\n`);\n return exitCodes.error;\n }\n if (o.only !== undefined) {\n const spec = resolve(o.cwd, o.only);\n modules = modules.filter((m) => m.specPath === spec);\n if (modules.length === 0) {\n o.stderr(`no spec file ${spec} under ${root}\\n`);\n return exitCodes.error;\n }\n }\n if (modules.length === 0) {\n o.stderr(`no spec files (*.props.ts) under ${root}\\n`);\n return exitCodes.error;\n }\n if (o.goals && !engines.some((e) => e.name === leanProver.name)) {\n o.stderr(\"--goals needs the lean engine among --prover\\n\");\n return exitCodes.error;\n }\n const errors = modules.flatMap((m) =>\n m.specs.errors.map((e) => `${m.key}${e.line > 0 ? `:${e.line}` : \"\"}: ${e.message}`),\n );\n if (errors.length > 0) {\n for (const e of errors) o.stderr(`${e}\\n`);\n return exitCodes.error;\n }\n let specs: readonly SpecVerdict[] = (\n await testModules(modules, o.seed ?? \"report\", o.moduleBudgetMs ?? 60_000, o.stderr)\n ).flat();\n const goals: WrittenGoal[] = [];\n if (engines.length > 0)\n specs = await proveSpecs(\n root,\n modules.map((m) => ({ module: m.key, functions: m.specs.functions.map((f) => f.name) })),\n specs,\n engines,\n modules,\n o.goals\n ? (m, report) => {\n if (report.engine !== leanProver.name) return;\n // An engine that did not answer (not installed, timed out, or the emitted Lean did not\n // compile) lists no goals; a goal file left from an earlier run stands until it answers.\n if (report.proofs.goals === undefined) return;\n goals.push(...writeGoals(m, report.proofs.goals, o.cwd));\n }\n : undefined,\n );\n if (o.json) {\n const json = JSON.parse(renderSpecReportJson(specs)) as Record<string, unknown>;\n o.stdout(\n `${canonicalJson({ ...json, ...(o.goals ? { goals } : {}) } as unknown as JsonValue)}\\n`,\n );\n } else {\n o.stdout(`${renderSpecReport(specs)}\\n`);\n if (o.goals)\n o.stdout(\n goals.length === 0\n ? \"\\nNo open Lean goals.\\n\"\n : `\\n${goals.length} open Lean goal${goals.length === 1 ? \"\" : \"s\"} written to ${[...new Set(goals.map((g) => g.file))].join(\", \")}\\n`,\n );\n }\n // The codes check uses: 1 for a refuted or conflicting spec, 0 otherwise; UNKNOWN fails nothing.\n return specs.some((v) => v.kind === \"REFUTED\" || v.kind === \"CONFLICT\")\n ? exitCodes.VIOLATED\n : exitCodes.BOUNDED;\n}\n","/** The published package's version, as the MCP server reports it; the release tooling keeps it in step. */\nexport const eutaxyVersion = \"0.17.2\"; // x-release-please-version\n","/**\n * `eutaxy mcp`: a Model Context Protocol server over stdio, so a coding\n * agent runs the loop \"check, read the report, fix or prove, check again\"\n * through one tool. One JSON-RPC message per line on stdin and stdout,\n * logs on stderr, exit when stdin closes; written with the standard\n * library alone. It speaks both eras of the protocol: the stateless\n * `2026-07-28` revision, every request carrying its version and client\n * capabilities in `_meta` and `server/discover` answering what is\n * supported; and the `2025-11-25` revision (and its predecessors) with the\n * `initialize` handshake today's clients open with. The tools are pure\n * functions of the repository's files that return the JSON report, as\n * structured content beside its text; a verdict is a result whatever it\n * says, and only a command that could not run is a tool error. Eutaxy\n * never calls a model: every verdict depends only on files.\n */\n\nimport { dirname } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport { type CheckOptions, exitCodes, provers, runCheck } from \"./check.ts\";\nimport { runDraft } from \"./draft.ts\";\nimport { type ReportOptions, runReport } from \"./report.ts\";\nimport { eutaxyVersion } from \"./version.ts\";\n\n/** The protocol revisions served: the stateless one by `_meta`, the handshake ones by `initialize`. */\nexport const modernVersions: readonly string[] = [\"2026-07-28\"];\nexport const legacyVersions: readonly string[] = [\n \"2025-11-25\",\n \"2025-06-18\",\n \"2025-03-26\",\n \"2024-11-05\",\n];\n\nconst protocolVersionKey = \"io.modelcontextprotocol/protocolVersion\";\nconst clientCapabilitiesKey = \"io.modelcontextprotocol/clientCapabilities\";\nconst serverInfoKey = \"io.modelcontextprotocol/serverInfo\";\n\nexport const serverInfo = { name: \"eutaxy\", version: eutaxyVersion } as const;\n\nexport const instructions = [\n \"Eutaxy checks Cloudflare Workers by deterministic simulation and proves properties of their pure TypeScript core.\",\n \"`check` runs a scenario file (*.sim.ts) and returns the verdict: BOUNDED (no violation within the bounds), VIOLATED (with the shrunk schedule, and a regression test written beside the scenario that replays it), or UNSUPPORTED.\",\n \"`report` runs every spec file (*.props.ts) under a directory through the TESTED rung and, with engines named, the PROVEN rung.\",\n \"`goals` lists the properties the Lean engine could not prove and writes each module's open goals beside its spec file as <spec>.goals.lean, a proof file with every proof open: copy it to <spec>.lean, add lemmas and tactics, then call `prove` on the spec file. A proof whose source or spec changed since the goals were written is stale, never PROVEN.\",\n \"`prover_status` says which proof engines are installed; `eutaxy prover install lean` or `smt` installs one.\",\n \"Verdicts depend only on files in the repository; nothing here calls a model.\",\n].join(\"\\n\");\n\ntype Json = null | boolean | number | string | Json[] | { [key: string]: Json };\ntype Params = Record<string, unknown>;\n\ninterface Request {\n readonly id: string | number;\n readonly method: string;\n readonly params: Params;\n /** The `_meta` the request carries, when it is of the stateless era. */\n readonly modern: boolean;\n}\n\n/** What a tool answers: structured content, its text form, and whether the tool itself failed. */\nexport interface ToolResult {\n readonly structured: Json;\n readonly text: string;\n readonly isError?: boolean;\n}\n\n/** The commands the tools run, injectable for tests; the real ones otherwise. */\nexport interface Runners {\n readonly check: (o: CheckOptions) => Promise<number>;\n readonly report: (o: ReportOptions) => Promise<number>;\n readonly status: () => Promise<Json>;\n}\n\nexport interface McpContext {\n readonly cwd: string;\n /** Where logs go: stderr. */\n readonly log: (text: string) => void;\n readonly runners?: Partial<Runners>;\n}\n\nconst realRunners: Runners = {\n check: runCheck,\n report: runReport,\n status: async () => {\n const engines: Json[] = [];\n for (const [name, engine] of Object.entries(provers)) {\n const a = await engine.available();\n engines.push({\n name,\n ...(\"unavailable\" in a\n ? { installed: false, reason: a.unavailable }\n : { installed: true, version: a.version }),\n });\n }\n return { engines };\n },\n};\n\nclass ToolError extends Error {}\n\n/** A command's exit code and what it printed. */\nasync function capture(\n run: (stdout: (t: string) => void, stderr: (t: string) => void) => Promise<number>,\n): Promise<{ code: number; stdout: string; stderr: string }> {\n let stdout = \"\";\n let stderr = \"\";\n const code = await run(\n (t) => {\n stdout += t;\n },\n (t) => {\n stderr += t;\n },\n );\n return { code, stdout, stderr };\n}\n\n/** The report a command printed as JSON, or a tool error with what it said instead. */\nfunction reported(what: string, r: { code: number; stdout: string; stderr: string }): Json {\n if (r.code === exitCodes.error)\n throw new ToolError(`${what} could not run (exit 3): ${r.stderr.trim() || r.stdout.trim()}`);\n try {\n return JSON.parse(r.stdout) as Json;\n } catch {\n throw new ToolError(`${what} printed no JSON report: ${(r.stdout + r.stderr).trim()}`);\n }\n}\n\nconst str = (args: Params, key: string, required = false): string | undefined => {\n const v = args[key];\n if (v === undefined) {\n if (required) throw new ToolError(`${key} is required`);\n return undefined;\n }\n if (typeof v !== \"string\" || v.length === 0)\n throw new ToolError(`${key} must be a non-empty string`);\n return v;\n};\nconst bool = (args: Params, key: string): boolean | undefined => {\n const v = args[key];\n if (v === undefined) return undefined;\n if (typeof v !== \"boolean\") throw new ToolError(`${key} must be a boolean`);\n return v;\n};\nconst positiveInt = (args: Params, key: string): number | undefined => {\n const v = args[key];\n if (v === undefined) return undefined;\n if (typeof v !== \"number\" || !Number.isInteger(v) || v <= 0)\n throw new ToolError(`${key} must be a positive integer`);\n return v;\n};\nconst strings = (args: Params, key: string): string[] | undefined => {\n const v = args[key];\n if (v === undefined) return undefined;\n if (!Array.isArray(v) || !v.every((x) => typeof x === \"string\" && x.length > 0))\n throw new ToolError(`${key} must be an array of non-empty strings`);\n return v as string[];\n};\nconst only = (args: Params, allowed: readonly string[]): void => {\n const extra = Object.keys(args).find((k) => !allowed.includes(k));\n if (extra !== undefined)\n throw new ToolError(`unknown argument ${extra}; the arguments are ${allowed.join(\", \")}`);\n};\n\ninterface Tool {\n readonly name: string;\n readonly title: string;\n readonly description: string;\n readonly inputSchema: Json;\n readonly run: (args: Params, ctx: McpContext, runners: Runners) => Promise<ToolResult>;\n}\n\nconst engineNames = Object.keys(provers);\nconst proversSchema: Json = {\n type: \"array\",\n items: { type: \"string\", enum: engineNames },\n description: `Proof engines for the PROVEN rung: ${engineNames.join(\", \")}`,\n};\n\nconst asResult = (structured: Json, isError = false): ToolResult => ({\n structured,\n text: JSON.stringify(structured, null, 2),\n ...(isError ? { isError: true } : {}),\n});\n\nexport const tools: readonly Tool[] = [\n {\n name: \"check\",\n title: \"Check a scenario\",\n description:\n \"Run a scenario file (*.sim.ts) in the simulator and return the JSON report: the verdict (BOUNDED, VIOLATED with the shrunk schedule, or UNSUPPORTED), the spec verdicts, and on a violation the path of the regression test written beside the scenario (regressionTest), and the errors nothing handled during a run whose verdict still stands (unhandledErrors). Exit code 1 is a violation or a refuted spec, not an error.\",\n inputSchema: {\n type: \"object\",\n properties: {\n scenario: {\n type: \"string\",\n description: \"Path of the scenario file, relative to the working directory\",\n },\n wrangler: {\n type: \"string\",\n description:\n \"Wrangler config path; default: the one the scenario names, else the one beside it\",\n },\n seed: { type: \"string\", description: \"Exploration seed; default: the scenario file name\" },\n maxRuns: { type: \"integer\", minimum: 1, description: \"Cap on exploration runs\" },\n budgetMs: {\n type: \"integer\",\n minimum: 1,\n description: \"Time budget in milliseconds, replacing the scenario's\",\n },\n exhaustive: { type: \"boolean\", description: \"Run every schedule within the bounds once\" },\n provers: proversSchema,\n regression: {\n type: \"boolean\",\n description: \"Write the regression test on a violation; default true\",\n },\n out: { type: \"string\", description: \"Where to write the regression test\" },\n },\n required: [\"scenario\"],\n additionalProperties: false,\n },\n async run(args, ctx, runners) {\n only(args, [\n \"scenario\",\n \"wrangler\",\n \"seed\",\n \"maxRuns\",\n \"budgetMs\",\n \"exhaustive\",\n \"provers\",\n \"regression\",\n \"out\",\n ]);\n const scenario = str(args, \"scenario\", true) as string;\n const wrangler = str(args, \"wrangler\");\n const seed = str(args, \"seed\");\n const maxRuns = positiveInt(args, \"maxRuns\");\n const budgetMs = positiveInt(args, \"budgetMs\");\n const engines = strings(args, \"provers\");\n const out = str(args, \"out\");\n const r = await capture((stdout, stderr) =>\n runners.check({\n scenario,\n cwd: ctx.cwd,\n ...(wrangler === undefined ? {} : { wrangler }),\n ...(seed === undefined ? {} : { seed }),\n ...(maxRuns === undefined ? {} : { maxRuns }),\n ...(budgetMs === undefined ? {} : { budgetMs }),\n exhaustive: bool(args, \"exhaustive\") === true,\n ...(engines === undefined ? {} : { provers: engines }),\n json: true,\n ...(out === undefined ? {} : { out }),\n noRegression: bool(args, \"regression\") === false,\n expectViolation: false,\n keep: false,\n stdout,\n stderr,\n }),\n );\n return asResult({ exitCode: r.code, report: reported(\"check\", r) });\n },\n },\n {\n name: \"report\",\n title: \"Report on the spec files\",\n description:\n \"Run every spec file (*.props.ts) under a directory through the TESTED rung and, with engines named, the PROVEN rung; return the JSON report of spec verdicts. Exit code 1 is a refuted or conflicting spec, not an error.\",\n inputSchema: {\n type: \"object\",\n properties: {\n dir: { type: \"string\", description: \"Directory to search; default: the working directory\" },\n provers: proversSchema,\n seed: { type: \"string\", description: \"Seed for the TESTED rung; default report\" },\n },\n additionalProperties: false,\n },\n async run(args, ctx, runners) {\n only(args, [\"dir\", \"provers\", \"seed\"]);\n const dir = str(args, \"dir\");\n const engines = strings(args, \"provers\");\n const seed = str(args, \"seed\");\n const r = await capture((stdout, stderr) =>\n runners.report({\n cwd: ctx.cwd,\n ...(dir === undefined ? {} : { dir }),\n ...(engines === undefined ? {} : { provers: engines }),\n ...(seed === undefined ? {} : { seed }),\n json: true,\n stdout,\n stderr,\n }),\n );\n return asResult({ exitCode: r.code, report: reported(\"report\", r) });\n },\n },\n {\n name: \"goals\",\n title: \"List the open proof goals\",\n description:\n \"Run the Lean engine on every spec file under a directory and list the properties it could not prove, each with the statement it tried; write each module's open goals beside its spec file as <spec>.goals.lean, a proof file with every proof open (copy it to <spec>.lean, add lemmas and tactics, then call prove). Needs the lean engine installed.\",\n inputSchema: {\n type: \"object\",\n properties: {\n dir: { type: \"string\", description: \"Directory to search; default: the working directory\" },\n },\n additionalProperties: false,\n },\n async run(args, ctx, runners) {\n only(args, [\"dir\"]);\n const dir = str(args, \"dir\");\n const r = await capture((stdout, stderr) =>\n runners.report({\n cwd: ctx.cwd,\n ...(dir === undefined ? {} : { dir }),\n provers: [\"lean\"],\n goals: true,\n json: true,\n stdout,\n stderr,\n }),\n );\n return asResult({ exitCode: r.code, report: reported(\"goals\", r) });\n },\n },\n {\n name: \"prove\",\n title: \"Check the proofs supplied for a spec file\",\n description:\n \"Run the Lean engine on one module, the one whose spec file (*.props.ts) is given, with the proofs supplied beside it in <spec>.lean, and return its spec verdicts: PROVEN where a proof closes (Lean's kernel checked it against the statement Eutaxy emitted), UNKNOWN with the reason where it does not, or where the proof file is stale (written for another version of the module or the spec).\",\n inputSchema: {\n type: \"object\",\n properties: {\n spec: {\n type: \"string\",\n description: \"Path of the spec file, relative to the working directory\",\n },\n },\n required: [\"spec\"],\n additionalProperties: false,\n },\n async run(args, ctx, runners) {\n only(args, [\"spec\"]);\n const spec = str(args, \"spec\", true) as string;\n const r = await capture((stdout, stderr) =>\n runners.report({\n cwd: ctx.cwd,\n dir: dirname(spec),\n only: spec,\n provers: [\"lean\"],\n json: true,\n stdout,\n stderr,\n }),\n );\n return asResult({ exitCode: r.code, report: reported(\"prove\", r) });\n },\n },\n {\n name: \"draft\",\n title: \"Draft a scenario\",\n description:\n \"Draft a scenario (*.sim.ts) from a wrangler config (JSON or JSONC) and the Worker module it names: the bindings become setup steps (a service binding whose Worker's config is found under the directory becomes a callee), the Worker's handlers the drive, the hosts its code fetches the externals; the invariants and the drive's events are holes marked TODO for you to fill before calling check. Returns the source, the draft as data and its notes (bindings not modelled, guesses made); with out, also writes the file, never over an existing one. Nothing is imported or run.\",\n inputSchema: {\n type: \"object\",\n properties: {\n config: {\n type: \"string\",\n description:\n \"Wrangler config path, relative to the working directory; default: wrangler.jsonc or wrangler.json there\",\n },\n worker: {\n type: \"string\",\n description: \"The Worker module; default: the config's main\",\n },\n out: {\n type: \"string\",\n description:\n \"Where to write the scenario; paths in it are relative to its directory. Default: not written\",\n },\n },\n additionalProperties: false,\n },\n async run(args, ctx) {\n only(args, [\"config\", \"worker\", \"out\"]);\n const config = str(args, \"config\");\n const worker = str(args, \"worker\");\n const out = str(args, \"out\");\n let stdout = \"\";\n let stderr = \"\";\n const code = runDraft({\n cwd: ctx.cwd,\n ...(config === undefined ? {} : { config }),\n ...(worker === undefined ? {} : { worker }),\n ...(out === undefined ? {} : { out }),\n json: true,\n stdout: (t) => {\n stdout += t;\n },\n stderr: (t) => {\n stderr += t;\n },\n });\n if (code !== 0) throw new ToolError(stderr.trim() || `draft exited ${code}`);\n return asResult(JSON.parse(stdout) as Json);\n },\n },\n {\n name: \"prover_status\",\n title: \"Which proof engines are installed\",\n description:\n \"For each proof engine (lean, smt): whether its pinned toolchain is installed and its version, or why not and how to install it (eutaxy prover install <name>).\",\n inputSchema: { type: \"object\", additionalProperties: false },\n async run(args, _ctx, runners) {\n only(args, []);\n return asResult(await runners.status());\n },\n },\n];\n\ninterface Response {\n readonly jsonrpc: \"2.0\";\n readonly id: string | number | null;\n readonly result?: Json;\n readonly error?: { readonly code: number; readonly message: string; readonly data?: Json };\n}\n\nconst errorResponse = (\n id: string | number | null,\n code: number,\n message: string,\n data?: Json,\n): Response => ({\n jsonrpc: \"2.0\",\n id,\n error: { code, message, ...(data === undefined ? {} : { data }) },\n});\n\n/** A result in the requester's era: the stateless one carries `resultType` and the server's identity. */\nconst resultResponse = (req: Request, result: { [key: string]: Json }): Response => ({\n jsonrpc: \"2.0\",\n id: req.id,\n result: req.modern\n ? { resultType: \"complete\", ...result, _meta: { [serverInfoKey]: serverInfo } }\n : result,\n});\n\nconst toolListing = (): Json =>\n tools.map((t) => ({\n name: t.name,\n title: t.title,\n description: t.description,\n inputSchema: t.inputSchema,\n }));\n\nasync function callTool(req: Request, ctx: McpContext): Promise<Response> {\n const name = req.params[\"name\"];\n const tool = tools.find((t) => t.name === name);\n if (typeof name !== \"string\" || !tool)\n return errorResponse(req.id, -32602, `Unknown tool: ${String(name)}`);\n const args = req.params[\"arguments\"] ?? {};\n if (typeof args !== \"object\" || args === null || Array.isArray(args))\n return errorResponse(req.id, -32602, \"arguments must be an object\");\n const runners: Runners = { ...realRunners, ...ctx.runners };\n let result: ToolResult;\n try {\n result = await tool.run(args as Params, ctx, runners);\n } catch (err) {\n // The tool itself failed: an execution error the model can act on, not a protocol error.\n const message = err instanceof Error ? err.message : String(err);\n result = { structured: { error: message }, text: message, isError: true };\n }\n return resultResponse(req, {\n content: [{ type: \"text\", text: result.text }],\n structuredContent: result.structured,\n isError: result.isError === true,\n });\n}\n\n/**\n * One line in, at most one line out: the response to a request, nothing\n * for a notification. A request of the stateless era whose version is not\n * served gets the `UnsupportedProtocolVersion` error with what is.\n */\nexport async function handleLine(line: string, ctx: McpContext): Promise<string | undefined> {\n let message: unknown;\n try {\n message = JSON.parse(line);\n } catch {\n return JSON.stringify(errorResponse(null, -32700, \"Parse error\"));\n }\n if (Array.isArray(message))\n return JSON.stringify(\n errorResponse(null, -32600, \"Invalid Request: batches are not supported\"),\n );\n if (typeof message !== \"object\" || message === null)\n return JSON.stringify(errorResponse(null, -32600, \"Invalid Request\"));\n const m = message as Record<string, unknown>;\n const id = m[\"id\"];\n const idOk = typeof id === \"string\" || typeof id === \"number\";\n if (m[\"jsonrpc\"] !== \"2.0\" || typeof m[\"method\"] !== \"string\")\n return JSON.stringify(\n errorResponse(idOk ? (id as string | number) : null, -32600, \"Invalid Request\"),\n );\n if (id === undefined) return undefined; // a notification: initialized, cancelled, progress; nothing to answer\n if (!idOk)\n return JSON.stringify(\n errorResponse(null, -32600, \"Invalid Request: id must be a string or a number\"),\n );\n const params = (\n typeof m[\"params\"] === \"object\" && m[\"params\"] !== null ? m[\"params\"] : {}\n ) as Params;\n const meta = (\n typeof params[\"_meta\"] === \"object\" && params[\"_meta\"] !== null ? params[\"_meta\"] : {}\n ) as Params;\n const requested = meta[protocolVersionKey];\n const req: Request = {\n id: id as string | number,\n method: m[\"method\"],\n params,\n modern: typeof requested === \"string\",\n };\n if (req.modern) {\n if (!modernVersions.includes(requested as string))\n return JSON.stringify(\n errorResponse(req.id, -32022, \"Unsupported protocol version\", {\n supported: [...modernVersions],\n requested: requested as string,\n }),\n );\n if (typeof meta[clientCapabilitiesKey] !== \"object\" || meta[clientCapabilitiesKey] === null)\n return JSON.stringify(\n errorResponse(req.id, -32602, `Invalid params: _meta.${clientCapabilitiesKey} is required`),\n );\n }\n let response: Response;\n try {\n response = await dispatch(req, ctx);\n } catch (err) {\n response = errorResponse(\n req.id,\n -32603,\n `Internal error: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n return JSON.stringify(response);\n}\n\nasync function dispatch(req: Request, ctx: McpContext): Promise<Response> {\n switch (req.method) {\n case \"initialize\": {\n const asked = req.params[\"protocolVersion\"];\n const version =\n typeof asked === \"string\" && legacyVersions.includes(asked)\n ? asked\n : (legacyVersions[0] as string);\n return resultResponse(req, {\n protocolVersion: version,\n capabilities: { tools: {} },\n serverInfo,\n instructions,\n });\n }\n case \"ping\":\n return resultResponse(req, {});\n case \"server/discover\":\n return resultResponse(req, {\n supportedVersions: [...modernVersions],\n capabilities: { tools: {} },\n instructions,\n });\n case \"tools/list\":\n return resultResponse(req, { tools: toolListing() });\n case \"tools/call\":\n return callTool(req, ctx);\n default:\n return errorResponse(req.id, -32601, `Method not found: ${req.method}`);\n }\n}\n\n/** Serve on the process's standard streams until stdin closes. Requests are answered one at a time, in order. */\nexport async function serveStdio(ctx: McpContext): Promise<number> {\n const lines = createInterface({ input: process.stdin, crlfDelay: Number.POSITIVE_INFINITY });\n for await (const line of lines) {\n if (line.trim().length === 0) continue;\n const out = await handleLine(line, ctx);\n if (out !== undefined) process.stdout.write(`${out}\\n`);\n }\n return exitCodes.BOUNDED;\n}\n","import { parseArgs } from \"./args.ts\";\nimport { exitCodes, runCheck } from \"./check.ts\";\nimport { runDraft } from \"./draft.ts\";\nimport { type Engine, engines, runInstall } from \"./install.ts\";\nimport { serveStdio } from \"./mcp.ts\";\nimport { runReport } from \"./report.ts\";\n\nconst usage = `eutaxy — deterministic simulation checks and spec verdicts for Cloudflare Workers\n\nUsage:\n eutaxy check <scenario.sim.ts> [options]\n eutaxy draft [wrangler config] [--worker <module>] [--out <file>] [--json]\n eutaxy report [dir] [--prover <names>] [--seed <seed>] [--json]\n eutaxy prover install <lean|smt> [--from <url or directory>] [--json]\n eutaxy mcp\n\ncheck options:\n --wrangler <path> wrangler config (default: the one the scenario names, else\n wrangler.jsonc/json/toml beside the scenario)\n --seed <seed> exploration seed (default: the scenario file name)\n --max-runs <n> cap on exploration runs in addition to the scenario's time budget\n --budget-ms <n> replace the scenario's time budget (with --max-runs, the run cap decides)\n --exhaustive run every schedule within the bounds once (with partial-order reduction)\n --prover <names> also run the PROVEN rung with these engines on the scenario's specs\n (comma-separated; known: lean, smt)\n --json print the versioned JSON report instead of text\n --out <path> where to write the regression test on a violation\n --no-regression do not write a regression test\n --expect-violation write a regression test that asserts the violation (for corpora)\n --keep keep the generated .eutaxy/ files\n\ndraft writes a scenario skeleton from a wrangler config (JSON or JSONC; default:\nwrangler.jsonc or wrangler.json in the current directory) and the Worker module it names\n(--worker to name another): the bindings become setup steps (a service binding whose\nWorker's config is found under the directory becomes a callee), the handlers the drive,\nthe hosts the code fetches the externals; the invariants and the events are left as holes\nmarked TODO. It prints the scenario, or writes it to --out (never over an existing file);\nnothing is imported or run.\n\nreport runs every spec file (*.props.ts) under dir (default: the current directory)\nthrough the TESTED rung, on inputs drawn from the parameter types with the seed\n(default: report), and the PROVEN rung with --prover. No scenario runs, so nothing\nis CHECKED.\n\nprover install smt puts the pinned Z3 for this platform in Eutaxy's cache\n(EUTAXY_CACHE_DIR, else the platform's user cache), where --prover finds it first:\ndownloaded from the upstream GitHub release, or from a mirror or offline directory\nholding the same file (--from), and checked against its SHA-256 before the solver is\ntaken from it. prover install lean installs the pinned Lean through elan: the machine's\nelan, else elan put in Eutaxy's cache from its pinned installer (the PATH and the\nshell's profile untouched); the toolchain's files are checked against the pinned\ndigest. Nothing is downloaded at any other time.\n\nreport options: --goals writes each module's open Lean goals beside its spec file as\n<spec>.goals.lean (a proof file with every proof open) and lists them; needs --prover lean.\n\nmcp serves the Model Context Protocol over stdio (one JSON-RPC message per line, logs on\nstderr) for a coding agent: tools check, report, goals, prove and prover_status, each\nreturning the JSON report, and draft, returning the drafted scenario. Point the agent's\nMCP configuration at \"eutaxy mcp\".\n\nExit codes: 0 BOUNDED, 1 VIOLATED or a REFUTED or CONFLICT spec, 2 UNSUPPORTED, 3 error.\nreport: 0, or 1 for a REFUTED or CONFLICT spec, 3 error. prover install: 0, or 3.\n`;\n\nexport interface Io {\n readonly cwd: string;\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n}\n\nexport async function main(argv: readonly string[], io: Io): Promise<number> {\n const { positionals, flags } = parseArgs(argv, [\n \"json\",\n \"no-regression\",\n \"expect-violation\",\n \"keep\",\n \"help\",\n \"exhaustive\",\n \"goals\",\n ]);\n const command = positionals[0];\n if (!command || command === \"help\" || flags[\"help\"] === true) {\n io.stdout(usage);\n return command ? exitCodes.BOUNDED : exitCodes.error;\n }\n // A value flag given without one would otherwise read as absent: `--prover` alone must not quietly\n // skip the PROVEN rung.\n for (const k of [\"wrangler\", \"seed\", \"max-runs\", \"budget-ms\", \"prover\", \"out\", \"from\", \"worker\"])\n if (flags[k] === true) {\n io.stderr(`--${k} needs a value\\n`);\n return exitCodes.error;\n }\n const str = (k: string): string | undefined =>\n typeof flags[k] === \"string\" ? (flags[k] as string) : undefined;\n const provers = (str(\"prover\") ?? \"\")\n .split(\",\")\n .map((n) => n.trim())\n .filter((n) => n.length > 0);\n if (command === \"mcp\") {\n if (positionals.length !== 1 || Object.keys(flags).length > 0) {\n io.stderr(`mcp takes no arguments\\n\\n${usage}`);\n return exitCodes.error;\n }\n return serveStdio({ cwd: io.cwd, log: io.stderr });\n }\n if (command === \"prover\") {\n const names = engines.join(\"|\");\n if (positionals[1] !== \"install\" || positionals.length !== 3) {\n io.stderr(`prover takes: install <${names}>\\n\\n${usage}`);\n return exitCodes.error;\n }\n const other = Object.keys(flags).find((k) => ![\"from\", \"json\"].includes(k));\n if (other !== undefined) {\n io.stderr(`prover install does not take --${other}\\n`);\n return exitCodes.error;\n }\n const engine = positionals[2] as Engine;\n if (!engines.includes(engine)) {\n io.stderr(\n `unknown engine ${positionals[2]}; the engines are ${names.replaceAll(\"|\", \", \")}\\n`,\n );\n return exitCodes.error;\n }\n return runInstall({\n engine,\n from: str(\"from\"),\n json: flags[\"json\"] === true,\n stdout: io.stdout,\n stderr: io.stderr,\n });\n }\n if (command === \"report\") {\n if (positionals.length > 2) {\n io.stderr(`report takes one directory\\n\\n${usage}`);\n return exitCodes.error;\n }\n const other = Object.keys(flags).find((k) => ![\"prover\", \"seed\", \"json\", \"goals\"].includes(k));\n if (other !== undefined) {\n io.stderr(`report does not take --${other}\\n`);\n return exitCodes.error;\n }\n const dir = positionals[1];\n return runReport({\n cwd: io.cwd,\n ...(dir === undefined ? {} : { dir }),\n ...(provers.length > 0 ? { provers } : {}),\n ...(str(\"seed\") ? { seed: str(\"seed\") as string } : {}),\n ...(flags[\"goals\"] === true ? { goals: true } : {}),\n json: flags[\"json\"] === true,\n stdout: io.stdout,\n stderr: io.stderr,\n });\n }\n if (command === \"draft\") {\n if (positionals.length > 2) {\n io.stderr(`draft takes one wrangler config\\n\\n${usage}`);\n return exitCodes.error;\n }\n const other = Object.keys(flags).find((k) => ![\"worker\", \"out\", \"json\"].includes(k));\n if (other !== undefined) {\n io.stderr(`draft does not take --${other}\\n`);\n return exitCodes.error;\n }\n const config = positionals[1];\n const worker = str(\"worker\");\n const out = str(\"out\");\n return runDraft({\n cwd: io.cwd,\n ...(config === undefined ? {} : { config }),\n ...(worker === undefined ? {} : { worker }),\n ...(out === undefined ? {} : { out }),\n json: flags[\"json\"] === true,\n stdout: io.stdout,\n stderr: io.stderr,\n });\n }\n if (command !== \"check\") {\n io.stderr(`unknown command ${command}\\n\\n${usage}`);\n return exitCodes.error;\n }\n const scenario = positionals[1];\n if (!scenario) {\n io.stderr(`check needs a scenario file\\n\\n${usage}`);\n return exitCodes.error;\n }\n if (positionals.length > 2) {\n io.stderr(`check takes one scenario file\\n\\n${usage}`);\n return exitCodes.error;\n }\n const checkFlags = [\n \"wrangler\",\n \"seed\",\n \"max-runs\",\n \"budget-ms\",\n \"exhaustive\",\n \"prover\",\n \"json\",\n \"out\",\n \"no-regression\",\n \"expect-violation\",\n \"keep\",\n ];\n const unknownFlag = Object.keys(flags).find((k) => !checkFlags.includes(k));\n if (unknownFlag !== undefined) {\n io.stderr(`check does not take --${unknownFlag}\\n`);\n return exitCodes.error;\n }\n const maxRunsText = str(\"max-runs\");\n const maxRuns = maxRunsText === undefined ? undefined : Number(maxRunsText);\n if (maxRuns !== undefined && !(Number.isInteger(maxRuns) && maxRuns > 0)) {\n io.stderr(`--max-runs must be a positive integer, got ${JSON.stringify(maxRunsText)}\\n`);\n return exitCodes.error;\n }\n const budgetText = str(\"budget-ms\");\n const budgetMs = budgetText === undefined ? undefined : Number(budgetText);\n if (budgetMs !== undefined && !(Number.isInteger(budgetMs) && budgetMs > 0)) {\n io.stderr(`--budget-ms must be a positive integer, got ${JSON.stringify(budgetText)}\\n`);\n return exitCodes.error;\n }\n return runCheck({\n scenario,\n cwd: io.cwd,\n ...(provers.length > 0 ? { provers } : {}),\n ...(str(\"wrangler\") ? { wrangler: str(\"wrangler\") as string } : {}),\n ...(str(\"seed\") ? { seed: str(\"seed\") as string } : {}),\n ...(maxRuns === undefined ? {} : { maxRuns }),\n ...(budgetMs === undefined ? {} : { budgetMs }),\n exhaustive: flags[\"exhaustive\"] === true,\n json: flags[\"json\"] === true,\n ...(str(\"out\") ? { out: str(\"out\") as string } : {}),\n noRegression: flags[\"no-regression\"] === true,\n expectViolation: flags[\"expect-violation\"] === true,\n keep: flags[\"keep\"] === true,\n stdout: io.stdout,\n stderr: io.stderr,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,eAAsB,OACpB,OACA,OACA,MACc;CACd,MAAM,UAAU,IAAI,MAAS,MAAM,MAAM;CACzC,IAAI,OAAO;CAEX,IAAI,SAAS;CACb,MAAM,SAAS,YAA2B;EACxC,OAAO,OAAO,MAAM,UAAU,CAAC,QAAQ;GACrC,MAAM,IAAI;GACV,IAAI;IACF,QAAQ,KAAK,MAAM,KAAK,MAAM,IAAS,CAAC;GAC1C,SAAS,KAAK;IACZ,SAAS;IACT,MAAM;GACR;EACF;CACF;CACA,MAAM,UAAU,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC;CACrE,MAAM,QAAQ,IAAI,MAAM,KAAK,EAAE,QAAQ,QAAQ,GAAG,MAAM,CAAC;CACzD,OAAO;AACT;;;;;;;AAQA,eAAsB,SACpB,OACA,MACA,MACc;CACd,MAAM,IAAI,KAAK,IAAI,GAAG,KAAK,MAAM,IAAI,CAAC;CACtC,MAAM,WAAW,MAAM,UAAU,KAAK;CACtC,IAAI,WAAW;CACf,IAAI,SAAS;CACb,MAAM,0BAAU,IAAI,IAAwB;CAC5C,OAAO,OAAO,OAAO,GAAG,OAAO,MAAM,MAAM;EACzC,IAAI,KAAK,WAAW,GAAG,MAAM,IAAI,SAAe,OAAO,QAAQ,IAAI,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