import { byText, type Facts, type Goal, type GoalId, type LemmaGraph, type ProofTree, type Script, } from "../ir.ts"; export function checkAxioms(input: { facts: Facts; graph: LemmaGraph }): void { const { facts, graph } = input; const drawn = new Set(); const seen = new Set(); const stack = [graph.target]; while (stack.length > 0) { const name = stack.pop()!; if (seen.has(name)) continue; seen.add(name); const lemma = graph.lemmas.get(name); if (!lemma) continue; if (lemma.decl.kind === "axiom") drawn.add(lemma.decl.name); for (const ax of lemma.axioms) drawn.add(ax); for (const edge of lemma.to) stack.push(edge.name); } const expected = new Set(facts.axioms); const missing = [...expected].filter((ax) => !drawn.has(ax)).sort(byText); const extra = [...drawn].filter((ax) => !expected.has(ax)).sort(byText); if (missing.length > 0 || extra.length > 0) { const parts: string[] = []; if (missing.length > 0) parts.push(`missing [${missing.join(", ")}]`); if (extra.length > 0) parts.push(`extra [${extra.join(", ")}]`); throw new Error( `Axiom check failed for ${facts.target}: drawn lemma graph disagrees with Lean.collectAxioms (${parts.join("; ")}).`, ); } } export function checkTree(input: { script: Script; tree: ProofTree }): void { const { script, tree } = input; const goalById = new Map(); for (const g of script.goals) goalById.set(g.id, g); const parentOf = new Map(); const visiting = new Set(); const walk = (gid: GoalId, parent: GoalId | "root"): void => { const goal = goalById.get(gid); if (!goal) throw new Error(`Proof tree check failed: unknown goal ${gid}.`); if (goal.final === "gone") { throw new Error( `Proof tree check failed: reachable goal ${gid} is gone in the root MetavarContext.`, ); } if (visiting.has(gid)) { throw new Error(`Proof tree check failed: cycle through goal ${gid}.`); } const existing = parentOf.get(gid); if (existing !== undefined) { throw new Error( `Proof tree check failed: goal ${gid} has multiple parents (${String(existing)} and ${String(parent)}).`, ); } parentOf.set(gid, parent); const close = tree.closes.get(gid); if (close) { if (goal.final === "open") { throw new Error( `Proof tree check failed: goal ${gid} is closed by step ${close.step} but remains open in the root MetavarContext.`, ); } visiting.add(gid); for (const child of close.opens) walk(child, gid); visiting.delete(gid); } else if (goal.final === "assigned" && goal.closedBy === "proof") { throw new Error( `Proof tree check failed: leaf goal ${gid} is proved in the root MetavarContext but has no closing step.`, ); } }; for (const root of tree.roots) walk(root.goal, "root"); }