import { BLOCK_HYPS, BLOCK_LINES, branchStatusOf, type BudgetedBlocks, byText, type CheckedLeanView, clipLine, type DoubtKind, type Drawn, type Facts, type Flow, type FlowEdge, type FlowNode, type FlowShape, type Goal, type GoalId, hasSubtreeMark, humanCaseTag, type Hyp, isSyntheticNativeAx, type LemmaGraph, LINE_WIDTH, type Script, shortName, type Step, type StepId, stripCasePrefix, } from "../ir.ts"; const hypSig = (h: Hyp): string => (h.value !== undefined ? `${h.type} := ${h.value}` : h.type); const isTypeBinder = (h: Hyp): boolean => h.type === "Type" || h.type.startsWith("Type ") || h.type === "Sort" || h.type.startsWith("Sort "); const hypLine = (prefix: string, h: Hyp): string => { const raw = h.value !== undefined ? `${prefix}${h.name} : ${h.type} := ${h.value}` : `${prefix}${h.name} : ${h.type}`; return clipLine(raw, LINE_WIDTH); }; function newAssumptions(input: { entryGoal: Goal; parentLastGoal: Goal | undefined; hyps: readonly Hyp[]; }): Hyp[] { const { entryGoal, parentLastGoal, hyps } = input; if (!parentLastGoal) return []; const parentMap = new Map(); for (const hid of parentLastGoal.hyps) { const h = hyps[hid]; if (h) parentMap.set(h.name, hypSig(h)); } const added: Hyp[] = []; for (const hid of entryGoal.hyps) { const h = hyps[hid]; if (!h || isTypeBinder(h)) continue; const prev = parentMap.get(h.name); if (prev === undefined || prev !== hypSig(h)) added.push(h); } return added; } function orderHypsForDisplay(hyps: readonly Hyp[]): Hyp[] { const named: Hyp[] = []; const inaccessible: Hyp[] = []; for (const h of hyps) { if (h.name.includes("✝")) inaccessible.push(h); else named.push(h); } return [...named, ...inaccessible]; } function midBoxAssumptions(input: { entryGoal: Goal; lastGoal: Goal | undefined; entryAdded: readonly Hyp[]; hyps: readonly Hyp[]; }): Hyp[] { const { entryGoal, lastGoal, entryAdded, hyps } = input; if (!lastGoal || lastGoal.id === entryGoal.id) return []; const entryAddedNames = new Set(entryAdded.map((h) => h.name)); const raw = newAssumptions({ entryGoal: lastGoal, parentLastGoal: entryGoal, hyps }); return orderHypsForDisplay(raw.filter((h) => !entryAddedNames.has(h.name))); } function tacticLines(block: Drawn, stepById: ReadonlyMap): string[] { const raw: string[] = []; for (const sid of block.steps) { const step = stepById.get(sid); if (!step) continue; const inl = block.inlined.get(sid)?.filter((t) => !step.text.includes(t)); const full = inl && inl.length > 0 ? `${step.text} [${inl.join("; ")}]` : step.text; raw.push(clipLine(full, LINE_WIDTH)); } if (raw.length > BLOCK_LINES) { const kept = raw.slice(0, BLOCK_LINES - 1); kept.push(`… +${raw.length - (BLOCK_LINES - 1)} steps`); raw.length = 0; raw.push(...kept); } if (block.errorLabel !== undefined) { raw.push(clipLine(`error: ${block.errorLabel}`, LINE_WIDTH)); } return raw; } function invokedLemmas(input: { block: Drawn; stepById: ReadonlyMap; graph: LemmaGraph; }): string[] { const targetUser = input.graph.lemmas.get(input.graph.target)?.decl.userName ?? input.graph.target; const dot = targetUser.indexOf("."); const prefix = dot === -1 ? "" : targetUser.slice(0, dot + 1); const collectFromSteps = (steps: readonly StepId[]): Set => { const found = new Set(); for (const sid of steps) { const step = input.stepById.get(sid); if (!step) continue; for (const name of step.names) { if (name === input.graph.target) continue; if (isSyntheticNativeAx(name)) continue; const lemma = input.graph.lemmas.get(name); if (!lemma) continue; const u = lemma.decl.userName; const display = prefix && u.startsWith(prefix) ? u.slice(prefix.length) : u; found.add(display); } } return found; }; if (input.block.differentGoals && input.block.foldedEntries.length > 1) { const sets = input.block.foldedEntries.map((e) => collectFromSteps(e.steps)); const common = [...sets[0]].filter((name) => sets.every((s) => s.has(name))); return common.sort(byText); } return [...collectFromSteps(input.block.steps)].sort(byText); } function restsOnBadge(kinds: ReadonlySet | undefined): string { if (!kinds || kinds.size === 0) return "Depends on unproven gap"; const parts: string[] = []; if (kinds.has("sorry")) parts.push("unproven gap"); if (kinds.has("error")) parts.push("failing step"); if (kinds.has("axiom")) parts.push("custom axiom"); if (kinds.has("native")) parts.push("native_decide"); if (parts.length === 0) return "Depends on unproven gap"; return `Depends on ${parts.join(" / ")}`; } function trustBadgeOf(block: Drawn): string | undefined { if (block.marks.has("error")) { return block.errorLabel ? clipLine(`Failing step: ${block.errorLabel}`, LINE_WIDTH) : "Failing step"; } if (block.marks.has("sorry")) return "Unproven gap (sorry)"; if (block.marks.has("open")) return "Open goal"; if (block.marks.has("restsOn")) return restsOnBadge(block.restsOnKinds); return undefined; } export function buildProofChart(input: { budgeted: BudgetedBlocks; script: Script; facts: Facts; graph: LemmaGraph; targetClean?: boolean; allowProven?: boolean; tactics?: boolean; view?: CheckedLeanView; }): Flow { const { budgeted, script, facts, graph, targetClean = true, allowProven = true, tactics = false, view, } = input; const goalById = new Map(); for (const g of script.goals) goalById.set(g.id, g); const stepById = new Map(); for (const s of script.steps) stepById.set(s.id, s); const isPartial = script.partial === true || budgeted.roots.some((r) => r.root.where === "term"); const nodes: FlowNode[] = []; const edges: FlowEdge[] = []; const groups: { title: string; nodes: string[] }[] = []; const usedClasses = new Set(); const usedRestsOnKinds = new Set(); let anyDifferentGoalFold = false; let nextId = 0; const emitBlock = (ctx: { block: Drawn; stableId: string; parentId: string | undefined; parentLastGoal: Goal | undefined; ancestorRawTags: readonly string[]; ancestorTainted: boolean; depth: number; isRoot: boolean; rootWhere: "body" | "term" | "termination"; groupNodes: string[]; }): void => { const { block, stableId, parentId, parentLastGoal, ancestorRawTags, ancestorTainted, depth, isRoot, rootWhere, groupNodes, } = ctx; const id = `b${nextId++}`; groupNodes.push(id); const entryGoal = goalById.get(block.entry); const lastGoal = goalById.get(block.last); const status = branchStatusOf(block.marks); const isLeaf = block.into.length === 0; const blockAllowProven = allowProven && !ancestorTainted; const rawPrimaryTag = block.tags[0]; const strippedPrimaryTag = rawPrimaryTag !== undefined ? stripCasePrefix({ rawTag: rawPrimaryTag, ancestorTags: ancestorRawTags }) : undefined; const humanPrimaryTag = strippedPrimaryTag !== undefined ? humanCaseTag(strippedPrimaryTag) : undefined; if (block.times > 1 && block.differentGoals) anyDifferentGoalFold = true; if (block.marks.has("restsOn") && block.restsOnKinds) { for (const k of block.restsOnKinds) usedRestsOnKinds.add(k); } const lines: string[] = []; if (block.hidden) { if (block.times > 1) lines.push(`×${block.times}`); const suffix = targetClean && blockAllowProven ? ", all proven" : ""; lines.push( `${block.hidden.steps} ${block.hidden.steps === 1 ? "step" : "steps"}, ${block.hidden.cases} ${block.hidden.cases === 1 ? "case" : "cases"}${suffix}`, ); usedClasses.add("stub"); nodes.push({ id, lines, shape: "stub", classes: ["stub"] }); } else { const entryAdded = entryGoal && !block.differentGoals ? orderHypsForDisplay(newAssumptions({ entryGoal, parentLastGoal, hyps: script.hyps })) : []; const midAdded = entryGoal && !block.differentGoals ? midBoxAssumptions({ entryGoal, lastGoal, entryAdded, hyps: script.hyps }) : []; const allAdded = [...entryAdded, ...midAdded]; const usedLemmas = invokedLemmas({ block, stepById, graph }); const rawStepTexts = block.steps .map((sid) => stepById.get(sid)?.text) .filter((t): t is string => t !== undefined); const branchView = view?.branch?.({ id: stableId, goal: block.differentGoals ? "" : (entryGoal?.target ?? ""), newHyps: allAdded.map((h) => ({ ...h })), tactics: [...rawStepTexts], lemmas: [...usedLemmas], status, caseTag: humanPrimaryTag, rawCaseTag: rawPrimaryTag, depth, isRoot, isLeaf, times: block.times, }); const badge = trustBadgeOf(block); if (branchView !== undefined) { if (block.times > 1) lines.push(`×${block.times}`); lines.push(clipLine(branchView.label, 120)); if (branchView.detail !== undefined) { lines.push("────────"); lines.push(clipLine(branchView.detail, 120)); } if (badge !== undefined) lines.push(badge); } else if (tactics) { if (block.times > 1) { const foldedTags = block.tags .map((t) => humanCaseTag(stripCasePrefix({ rawTag: t, ancestorTags: ancestorRawTags }))) .join(", "); lines.push( clipLine(`×${block.times}${foldedTags ? ` (${foldedTags})` : ""}`, LINE_WIDTH), ); } const goalLines: string[] = []; if (!block.differentGoals) { const shownEntry = entryAdded.slice(0, BLOCK_HYPS).map((h) => hypLine("+ ", h)); const remainingBudget = Math.max(0, BLOCK_HYPS - shownEntry.length); const shownMid = midAdded.slice(0, remainingBudget).map((h) => hypLine("+ ", h)); const omittedHyps = allAdded.length - shownEntry.length - shownMid.length; for (const hl of shownEntry) goalLines.push(hl); if (entryGoal && (!parentLastGoal || entryGoal.target !== parentLastGoal.target)) { goalLines.push(clipLine(`⊢ ${entryGoal.target}`, LINE_WIDTH)); } for (const hl of shownMid) goalLines.push(hl); if (omittedHyps > 0) { goalLines.push( `+${omittedHyps} more ${omittedHyps === 1 ? "assumption" : "assumptions"}`, ); } } for (const gl of goalLines) lines.push(gl); const tLines = tacticLines(block, stepById); if (goalLines.length > 0 && tLines.length > 0) lines.push("────────"); for (const tl of tLines) lines.push(tl); if (badge !== undefined) lines.push(badge); if (lines.length === 0) lines.push("Goal"); } else { if (block.times > 1) { const foldedTags = block.tags .map((t) => humanCaseTag(stripCasePrefix({ rawTag: t, ancestorTags: ancestorRawTags }))) .join(", "); lines.push( clipLine(`×${block.times}${foldedTags ? ` (${foldedTags})` : ""}`, LINE_WIDTH), ); } const summaryLines: string[] = []; if (usedLemmas.length > 0) { const shown = usedLemmas.slice(0, 3).join(", "); const extra = usedLemmas.length > 3 ? ` (+${usedLemmas.length - 3})` : ""; summaryLines.push(clipLine(`uses ${shown}${extra}`, LINE_WIDTH)); } if (badge !== undefined) { summaryLines.push(badge); } else if (isLeaf && blockAllowProven) { summaryLines.push("Proven"); } const claimLines: string[] = []; if (!block.differentGoals) { const shownEntry = entryAdded.slice(0, BLOCK_HYPS).map((h) => hypLine("+ ", h)); const remainingBudget = Math.max(0, BLOCK_HYPS - shownEntry.length); const shownMid = midAdded.slice(0, remainingBudget).map((h) => hypLine("+ ", h)); const omittedHyps = allAdded.length - shownEntry.length - shownMid.length; for (const hl of shownEntry) claimLines.push(hl); if ( entryGoal && (isRoot || !parentLastGoal || entryGoal.target !== parentLastGoal.target || (shownEntry.length === 0 && shownMid.length === 0 && summaryLines.length === 0)) ) { claimLines.push(clipLine(entryGoal.target, LINE_WIDTH)); } for (const hl of shownMid) claimLines.push(hl); if (omittedHyps > 0) { claimLines.push( `+${omittedHyps} more ${omittedHyps === 1 ? "assumption" : "assumptions"}`, ); } } for (const cl of claimLines) lines.push(cl); if ((claimLines.length > 0 || block.times > 1) && summaryLines.length > 0) { lines.push("────────"); } for (const sl of summaryLines) lines.push(sl); if (lines.length === 0) lines.push(isLeaf ? (blockAllowProven ? "Proven" : "Unverified") : "Subcase"); } const classes: string[] = []; if (isRoot) { if (rootWhere === "termination") classes.push("termRoot"); else classes.push(isPartial || rootWhere === "term" ? "subRoot" : "goalRoot"); } if (block.marks.has("error")) classes.push("error"); else if (block.marks.has("sorry")) classes.push("sorry"); else if (block.marks.has("open")) classes.push("open"); else if (block.marks.has("restsOn")) classes.push("restsOn"); else if (block.times > 1) classes.push("folded"); else if (isLeaf && !isRoot && blockAllowProven) classes.push("closed"); for (const cls of classes) usedClasses.add(cls); const shape: FlowShape = block.marks.has("error") || block.marks.has("sorry") || block.marks.has("open") ? "hexagon" : isRoot || (isLeaf && block.marks.size === 0) ? "round" : "box"; nodes.push({ id, lines, shape, classes }); } if (parentId !== undefined) { let edgeLabel: string | undefined; if (block.tags.length > 0) { const rendered = block.tags.map((rawTag) => { const stripped = stripCasePrefix({ rawTag, ancestorTags: ancestorRawTags }); const custom = view?.caseLabel?.(stripped, { id: stableId, rawTag, parentTag: ancestorRawTags[ancestorRawTags.length - 1], goal: entryGoal?.target ?? "", status, isLeaf, }); return custom ?? humanCaseTag(stripped); }); const hasCustom = view?.caseLabel !== undefined; edgeLabel = clipLine(rendered.join(", "), hasCustom ? 64 : 36); } const thick = hasSubtreeMark(block) || block.errorLabel !== undefined; edges.push({ from: parentId, to: id, label: edgeLabel, dotted: false, thick }); } const nextAncestors = rawPrimaryTag !== undefined ? [...ancestorRawTags, rawPrimaryTag] : ancestorRawTags; const nextAncestorTainted = ancestorTainted || block.marks.size > 0 || block.errorLabel !== undefined; for (const [ci, child] of block.into.entries()) { emitBlock({ block: child, stableId: `${stableId}.${ci}`, parentId: id, parentLastGoal: lastGoal ?? entryGoal, ancestorRawTags: nextAncestors, ancestorTainted: nextAncestorTainted, depth: depth + 1, isRoot: false, rootWhere, groupNodes, }); } }; for (const [i, entry] of budgeted.roots.entries()) { const groupNodes: string[] = []; const rootStableId = budgeted.roots.length === 1 ? "root" : `root${i}`; emitBlock({ block: entry.block, stableId: rootStableId, parentId: undefined, parentLastGoal: undefined, ancestorRawTags: [], ancestorTainted: false, depth: 0, isRoot: true, rootWhere: entry.root.where, groupNodes, }); if (budgeted.roots.length > 1) { const title = entry.root.where === "termination" ? "Termination proof" : entry.root.where === "term" ? `Sub-proof ${i + 1}` : `Case ${i + 1}`; groups.push({ title, nodes: groupNodes }); } } const restsOnLegend = restsOnBadge(usedRestsOnKinds); const foldedLegend = anyDifferentGoalFold ? "Folded branches (same steps)" : "Repeated identical branches"; const legendSpecs: [string, string][] = [ ["Theorem", "goalRoot"], ["Sub-proof root", "subRoot"], ["Termination goal", "termRoot"], ["Proven", "closed"], ["Unproven gap (sorry)", "sorry"], ["Failing step", "error"], ["Open goal", "open"], [restsOnLegend, "restsOn"], [foldedLegend, "folded"], ["Hidden details", "stub"], ]; const legend = legendSpecs .filter(([, cls]) => usedClasses.has(cls)) .map(([text, cls]) => ({ text, cls })); if (isPartial) { legend.push({ text: "Partial proof: term-mode parts omitted", cls: "note" }); } const defaultTitle = `${shortName(facts.target)} - proof`; return { title: view?.title?.proof ?? defaultTitle, nodes, edges, groups, legend, }; }