import { type ChildProcess, spawn } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { parseFacts } from "./frontends/facts.ts"; import { type Facts, shortName, SUPPORTED_LEAN } from "./ir.ts"; import { assertSupportedLean, miseLeanTool, parseLeanToolchain, platformKeyOf, } from "./toolchain.ts"; type SpawnResult = { status: number | null; signal: NodeJS.Signals | null; stdout: string; stderr: string; error: Error | undefined; }; type RunChildInput = { file: string; args: string[]; cwd: string; env: NodeJS.ProcessEnv; signal: AbortSignal | undefined; }; function runChild(input: RunChildInput): Promise { return new Promise((resolve) => { if (input.signal?.aborted) { resolve({ status: null, signal: "SIGTERM", stdout: "", stderr: "", error: new Error("aborted"), }); return; } let child: ChildProcess; try { child = spawn(input.file, input.args, { cwd: input.cwd, env: input.env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true, }); } catch (error) { resolve({ status: null, signal: null, stdout: "", stderr: "", error: error instanceof Error ? error : new Error(String(error)), }); return; } const stdoutChunks: string[] = []; const stderrChunks: string[] = []; child.stdout?.setEncoding("utf8"); child.stderr?.setEncoding("utf8"); child.stdout?.on("data", (chunk: string) => stdoutChunks.push(chunk)); child.stderr?.on("data", (chunk: string) => stderrChunks.push(chunk)); let error: Error | undefined; let settled = false; const onAbort = () => { try { child.kill("SIGKILL"); } catch {} }; input.signal?.addEventListener("abort", onAbort, { once: true }); const finish = (status: number | null, signal: NodeJS.Signals | null) => { if (settled) return; settled = true; input.signal?.removeEventListener("abort", onAbort); resolve({ status, signal, stdout: stdoutChunks.join(""), stderr: stderrChunks.join(""), error, }); }; child.on("error", (err) => { error = err; if (child.pid === undefined) finish(null, null); }); child.on("close", (code, sig) => finish(code, sig)); }); } type PackageRoot = { dir: string; hasLakefile: boolean; toolchainFile: string | undefined; }; export function findPackageRoot(leanFile: string): PackageRoot { const start = path.dirname(path.resolve(leanFile)); let cur = start; let toolchainFile: string | undefined; for (;;) { const tc = path.join(cur, "lean-toolchain"); if (!toolchainFile && fs.existsSync(tc)) toolchainFile = tc; if ( fs.existsSync(path.join(cur, "lakefile.lean")) || fs.existsSync(path.join(cur, "lakefile.toml")) ) { return { dir: cur, hasLakefile: true, toolchainFile }; } const parent = path.dirname(cur); if (parent === cur) return { dir: start, hasLakefile: false, toolchainFile }; cur = parent; } } type Toolchain = { lean: string; lake: string; env: NodeJS.ProcessEnv; }; function binName(name: string): string { return process.platform === "win32" ? `${name}.exe` : name; } function withBinDir(binDir: string, baseEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv { const sep = process.platform === "win32" ? ";" : ":"; const prev = baseEnv.PATH ?? ""; return { ...baseEnv, PATH: prev ? `${binDir}${sep}${prev}` : binDir }; } function parseLeanVersionOutput(text: string): string | undefined { const m = text.match(/version\s+(\d+\.\d+\.\d+(?:-[A-Za-z0-9._-]+)?)/); return m ? `v${m[1]}` : undefined; } async function verifyLeanVersion(input: { lean: string; env: NodeJS.ProcessEnv; cwd: string; wanted: string; source: string; signal: AbortSignal | undefined; }): Promise { const probe = await runChild({ file: input.lean, args: ["--version"], cwd: input.cwd, env: input.env, signal: input.signal, }); if (probe.status !== 0 || probe.error) { throw new Error( `${input.source} failed \`lean --version\`: ${probe.stderr.trim() || probe.error?.message || `exit ${probe.status}`}`, ); } const found = parseLeanVersionOutput(probe.stdout); if (found !== input.wanted) { throw new Error( `${input.source} is Lean ${found ?? "unknown"}, but statechart requires ${input.wanted}.`, ); } } async function resolveToolchain(input: { pkgDir: string; pinnedVersion: string | undefined; signal: AbortSignal | undefined; }): Promise { const wanted = input.pinnedVersion ? assertSupportedLean(input.pinnedVersion) : SUPPORTED_LEAN; const sysroot = process.env.LEAN_SYSROOT; if (sysroot) { const binDir = path.join(sysroot, "bin"); const lean = path.join(binDir, binName("lean")); const lake = path.join(binDir, binName("lake")); if (!fs.existsSync(lean) || !fs.existsSync(lake)) { throw new Error(`LEAN_SYSROOT=${sysroot} is missing bin/lean or bin/lake.`); } const env = withBinDir(binDir, process.env); await verifyLeanVersion({ lean, env, cwd: input.pkgDir, wanted, source: `LEAN_SYSROOT=${sysroot}`, signal: input.signal, }); return { lean, lake, env }; } const probe = await runChild({ file: "lean", args: ["--version"], cwd: input.pkgDir, env: process.env, signal: input.signal, }); if (probe.status === 0 && !probe.error) { const found = parseLeanVersionOutput(probe.stdout); if (found !== wanted) { throw new Error( `Lean on PATH is ${found ?? "unknown"}, but statechart requires ${wanted}. Set LEAN_SYSROOT to a ${wanted} toolchain.`, ); } const lakeProbe = await runChild({ file: "lake", args: ["--version"], cwd: input.pkgDir, env: process.env, signal: input.signal, }); if (lakeProbe.status === 0 && !lakeProbe.error) { return { lean: "lean", lake: "lake", env: process.env }; } } const platform = platformKeyOf({ platform: process.platform, arch: process.arch }); const toolSpec = platform ? miseLeanTool({ version: wanted, platform }) : undefined; if (toolSpec) { const miseEnv = { ...process.env, MISE_CEILING_PATHS: input.pkgDir }; let where = await runChild({ file: "mise", args: ["where", toolSpec], cwd: input.pkgDir, env: miseEnv, signal: input.signal, }); if (where.status !== 0 && !where.error) { const installed = await runChild({ file: "mise", args: ["install", toolSpec], cwd: input.pkgDir, env: miseEnv, signal: input.signal, }); if (installed.status === 0) { where = await runChild({ file: "mise", args: ["where", toolSpec], cwd: input.pkgDir, env: miseEnv, signal: input.signal, }); } } if (where.status === 0 && !where.error) { const root = where.stdout.trim(); const candidates = [ path.join(root, "bin"), ...fs .readdirSync(root, { withFileTypes: true }) .filter((e) => e.isDirectory()) .map((e) => path.join(root, e.name, "bin")), ]; for (const binDir of candidates) { const lean = path.join(binDir, binName("lean")); const lake = path.join(binDir, binName("lake")); if (fs.existsSync(lean) && fs.existsSync(lake)) { const env = withBinDir(binDir, process.env); await verifyLeanVersion({ lean, env, cwd: input.pkgDir, wanted, source: `mise toolchain ${toolSpec}`, signal: input.signal, }); return { lean, lake, env }; } } } } throw new Error( [ `Cannot find Lean ${wanted}.`, "Install elan (https://github.com/leanprover/elan) or set LEAN_SYSROOT.", ].join("\n"), ); } function bareSetup(filePath: string): string { const stem = path.basename(filePath, path.extname(filePath)); return JSON.stringify({ name: stem, isModule: false, importArts: {}, dynlibs: [], plugins: [], options: {}, }); } export async function extractFactsBatch(input: { file: string; theorems: readonly string[]; signal?: AbortSignal; }): Promise { if (input.theorems.length === 0) return []; const absFile = path.resolve(input.file); if (!fs.existsSync(absFile)) throw new Error(`Cannot find Lean file ${input.file}.`); const pkg = findPackageRoot(absFile); const pinnedVersion = pkg.toolchainFile ? parseLeanToolchain(fs.readFileSync(pkg.toolchainFile, "utf8")) : undefined; if (pinnedVersion) assertSupportedLean(pinnedVersion); const toolchain = await resolveToolchain({ pkgDir: pkg.dir, pinnedVersion, signal: input.signal, }); let setupJson: string; if (pkg.hasLakefile) { const rel = path.relative(pkg.dir, absFile); const setupRes = await runChild({ file: toolchain.lake, args: ["setup-file", rel], cwd: pkg.dir, env: toolchain.env, signal: input.signal, }); if (setupRes.status !== 0) { const detail = setupRes.stderr.trim() || setupRes.stdout.trim() || setupRes.error?.message; throw new Error(`lake setup-file failed for ${rel} (exit ${setupRes.status}):\n${detail}`); } setupJson = setupRes.stdout.trim(); } else { setupJson = bareSetup(absFile); } const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "statechart-lean-")); try { const setupPath = path.join(tmpDir, "setup.json"); const outPath = path.join(tmpDir, "facts.ndjson"); fs.writeFileSync(setupPath, setupJson, "utf8"); const extractor = path.join(import.meta.dirname, "Extract.lean"); const relFile = path.relative(pkg.dir, absFile) || path.basename(absFile); const res = await runChild({ file: toolchain.lean, args: ["--run", extractor, setupPath, outPath, relFile, ...input.theorems], cwd: pkg.dir, env: toolchain.env, signal: input.signal, }); if (res.status !== 0) { const detail = res.stderr.trim() || res.stdout.trim() || res.error?.message; throw new Error(detail || `Extract.lean failed with exit ${res.status}.`); } const rawOut = fs.existsSync(outPath) ? fs.readFileSync(outPath, "utf8") : ""; const lines = rawOut .split(/\r?\n/) .map((line) => line.trim()) .filter((line) => line.length > 0); if (lines.length !== input.theorems.length) { throw new Error( `Extract.lean returned ${lines.length} results for ${input.theorems.length} theorems in ${relFile}.`, ); } return lines.map(parseFacts); } finally { fs.rmSync(tmpDir, { recursive: true, force: true }); } } export async function extractFacts(input: { file: string; theorem: string; signal?: AbortSignal; }): Promise { const replay = process.env.STATECHART_LEAN_REPLAY; if (replay) { const replayFile = fs.existsSync(replay) && fs.statSync(replay).isDirectory() ? path.join(replay, "facts.json") : replay; const facts = parseFacts(fs.readFileSync(replayFile, "utf8")); const targetMatches = facts.target === input.theorem || facts.target.endsWith(`.${input.theorem}`) || shortName(facts.target) === shortName(input.theorem); const fileMatches = path.basename(facts.file) === path.basename(input.file); if (!targetMatches || !fileMatches) { throw new Error( `STATECHART_LEAN_REPLAY facts (${facts.file} ${facts.target}) do not match requested ${path.basename(input.file)} ${input.theorem}.`, ); } return facts; } const absFile = path.resolve(input.file); if (!fs.existsSync(absFile)) throw new Error(`Cannot find Lean file ${input.file}.`); const pkg = findPackageRoot(absFile); const pinnedVersion = pkg.toolchainFile ? parseLeanToolchain(fs.readFileSync(pkg.toolchainFile, "utf8")) : undefined; if (pinnedVersion) assertSupportedLean(pinnedVersion); const customCmd = process.env.STATECHART_LEAN_EXTRACT_CMD; if (customCmd) { const res = await runChild({ file: process.execPath, args: [customCmd, absFile, input.theorem], cwd: pkg.dir, env: process.env, signal: input.signal, }); if (res.status !== 0) { throw new Error(res.stderr.trim() || `Extractor exited ${res.status}.`); } return parseFacts(res.stdout); } const [facts] = await extractFactsBatch({ file: absFile, theorems: [input.theorem], signal: input.signal, }); return facts; }