#!/usr/bin/env node import { type ChildProcess, spawn } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { parseArgs } from "node:util"; import { killGroup } from "./kill.ts"; import { shortName } from "./lean/ir.ts"; import { messageOf } from "./run.ts"; const USAGE = `Usage: statechart SPEC.tla [--config FILE] [--view FILE] [--out DIR] statechart FILE.lean THEOREM [--view FILE] [--tactics] [--out DIR] Checks SPEC.tla with TLC and draws its state graph as Mermaid, or elaborates FILE.lean and compiles THEOREM's lemma dependency graph and proof tree to Mermaid flowcharts. --config FILE TLC config (TLA+ only). Default: SPEC.cfg beside the spec. --view FILE A module supplying plain-English labels, titles, and grouping. TLA+ exports: state(vars), step(action, from, to), group(vars), colors, title. state() returns a string for a flat chart, an array for parent states, or an object for regions. colors gives each group blue, orange, purple, yellow, teal, tan, or pink. Lean exports: title, lemma(info), group(info), branch(info), caseLabel(tag, info). --tactics Show raw Lean tactic lines inside proof-tree boxes (Lean only). --out DIR Output folder (must be new or empty). TLA+ default: SPEC-chart. Lean default: -proof beside FILE.lean. Exit code: 0 when every rule holds or the proof is clean, 1 when a rule breaks or the proof has an audit finding (sorry, error, open goal, native computation, or non-standard axiom), 2 on tool/check error, 130 or 143 on SIGINT or SIGTERM. Only exits 0 and 1 write output.`; let stop: NodeJS.Signals | undefined; const stopped = new Promise((resolve) => { for (const name of ["SIGINT", "SIGTERM"] as const) process.on(name, () => { stop ??= name; resolve(); }); }); type ParsedCommand = | { mode: "tla"; specFile: string; configFile: string; viewFile: string | undefined; out: string; } | { mode: "lean"; leanFile: string; theorem: string; viewFile: string | undefined; tactics: boolean; out: string; }; const sanitizeDirName = (name: string) => name.replace(/[^A-Za-z0-9._-]+/g, "_"); let command: ParsedCommand; try { const args = parseArgs({ allowPositionals: true, options: { config: { type: "string" }, view: { type: "string" }, out: { type: "string" }, tactics: { type: "boolean" }, }, }); const flags = args.values; const first = args.positionals[0]; const isLean = first !== undefined && first.endsWith(".lean"); if (isLean) { if (flags.config !== undefined) throw new Error("--config applies only to TLA+ specs."); if (args.positionals.length !== 2) throw new Error("Give FILE.lean and THEOREM."); const [leanFile, theorem] = args.positionals; const out = flags.out ?? path.join(path.dirname(leanFile), `${sanitizeDirName(shortName(theorem))}-proof`); command = { mode: "lean", leanFile, theorem, viewFile: flags.view, tactics: flags.tactics === true, out, }; } else { if (flags.tactics === true) throw new Error("--tactics applies only to Lean files."); if (args.positionals.length !== 1) throw new Error("Give one SPEC.tla."); const [specFile] = args.positionals; const configFile = flags.config ?? specFile.replace(/\.tla$/, ".cfg"); const out = flags.out ?? specFile.replace(/\.tla$/, "-chart"); command = { mode: "tla", specFile, configFile, viewFile: flags.view, out }; } } catch (error) { console.error(`${messageOf(error)}\n\n${USAGE}`); process.exit(2); } const codeOf = (error: unknown) => error instanceof Error && "code" in error ? error.code : undefined; try { if (command.mode === "tla" && !fs.existsSync(command.configFile)) throw new Error(`Cannot find the TLC config ${command.configFile}. Pass --config FILE.`); if ( command.mode === "lean" && !process.env.STATECHART_LEAN_REPLAY && !fs.existsSync(command.leanFile) ) throw new Error(`Cannot find Lean file ${command.leanFile}.`); if (command.mode === "lean" && command.viewFile && !fs.existsSync(command.viewFile)) throw new Error(`Cannot find the view file ${command.viewFile}.`); const { out } = command; let entries: string[] = []; let dest: string; try { entries = fs.readdirSync(out); dest = fs.realpathSync(out); } catch (error) { if (codeOf(error) !== "ENOENT") throw new Error( `${out} cannot be the output folder. ${messageOf(error)}. Pass --out with a new folder.`, { cause: error }, ); if (fs.lstatSync(out, { throwIfNoEntry: false })) throw new Error( `${out} cannot be the output folder. It is a broken link. Pass --out with a new folder.`, { cause: error }, ); dest = path.resolve(out); } if (entries.length) throw new Error( `${out} is not empty. It has ${entries.sort()[0]}. The command writes only to a new or empty folder. Pass --out with a new folder.`, ); let base = path.dirname(dest); while (!fs.existsSync(base)) base = path.dirname(base); const stage = fs.mkdtempSync(path.join(base, `.${path.basename(dest)}.statechart-`)); const done = path.join(stage, "done"); let tmp: string | undefined; let janitor: ChildProcess | undefined; let exitCode: number; try { tmp = fs.mkdtempSync(path.join(os.tmpdir(), "statechart-")); const runtime = process.versions.deno ? [ "run", "--quiet", "--no-prompt", "--allow-read", "--allow-write", "--allow-run", "--allow-env", ] : process.execArgv; const workerArgs = command.mode === "lean" ? [ "lean", stage, command.leanFile, command.theorem, command.tactics ? "1" : "0", ...(command.viewFile ? [command.viewFile] : []), ] : [ "tla", stage, command.specFile, command.configFile, ...(command.viewFile ? [command.viewFile] : []), ]; const worker = spawn( process.execPath, [...runtime, path.join(import.meta.dirname, "worker.ts"), ...workerArgs], { detached: true, stdio: ["ignore", "inherit", "inherit"], env: { ...process.env, TMPDIR: tmp, TEMP: tmp, TMP: tmp }, }, ); janitor = spawn( process.execPath, [...runtime, path.join(import.meta.dirname, "janitor.ts"), String(worker.pid), stage, tmp], { detached: true, stdio: ["pipe", "ignore", "ignore"] }, ); const toJanitor = janitor.stdin; toJanitor?.on("error", () => {}); const exited = new Promise((resolve) => worker.on("exit", (code) => { toJanitor?.write("exited\n"); resolve(code ?? 2); }), ); await Promise.race([stopped, exited]); const running = worker.exitCode === null && worker.signalCode === null; const groupOutlivesWorker = process.platform !== "win32"; if (worker.pid !== undefined && (running || groupOutlivesWorker)) await killGroup(worker.pid); const verdict = await exited; if (stop) { console.error(`${stop} stopped the check, so the command wrote nothing.`); exitCode = 128 + os.constants.signals[stop]; } else if (worker.signalCode) { console.error(`${worker.signalCode} killed the check, so the command wrote nothing.`); exitCode = 2; } else if ((verdict === 0 || verdict === 1) && fs.existsSync(done)) { fs.mkdirSync(path.dirname(dest), { recursive: true }); try { fs.renameSync(done, dest); } catch (error) { if (codeOf(error) !== "ENOTEMPTY" && codeOf(error) !== "EEXIST") throw error; throw new Error( `${path.join(out, fs.readdirSync(dest).sort()[0])} appeared while the check ran, so the command wrote nothing. Pass --out with a new folder.`, { cause: error }, ); } process.stdout.write(fs.readFileSync(path.join(dest, "report.md"))); console.log(`\nWrote ${out}`); exitCode = verdict; } else exitCode = 2; } finally { fs.rmSync(stage, { recursive: true, force: true }); if (tmp) fs.rmSync(tmp, { recursive: true, force: true }); janitor?.kill("SIGKILL"); } process.exit(exitCode); } catch (error) { console.error(messageOf(error)); process.exit(2); }