import { byText, type Doubt, doubtKey, isNativeAxiom, isStandardAxiom, type Lemma, type LemmaGraph, type Trust, } from "../ir.ts"; function dedupeDoubts(items: Iterable): Doubt[] { const seen = new Map(); for (const item of items) { const key = doubtKey(item); if (!seen.has(key)) seen.set(key, item); } return [...seen.entries()].sort(([a], [b]) => byText(a, b)).map(([, d]) => d); } function ownDoubtsOf(lemma: Lemma): Doubt[] { const out: Doubt[] = []; for (const s of lemma.sorries) { out.push({ kind: s.synthetic ? "error" : "sorry", in: s.in, at: s.at, }); } for (const ax of lemma.axioms) { if (ax === "sorryAx") { if (lemma.sorries.length === 0) out.push({ kind: "sorry", in: lemma.decl.userName, at: undefined }); continue; } if (isStandardAxiom(ax)) continue; if (isNativeAxiom(ax)) out.push({ kind: "native", name: ax }); else out.push({ kind: "axiom", name: ax }); } return dedupeDoubts(out); } export function analyzeTrust(graph: LemmaGraph): Trust { const own = new Map(); for (const [name, lemma] of graph.lemmas) own.set(name, ownDoubtsOf(lemma)); const below = new Map(); const resolveBelow = (name: string): Doubt[] => { const cached = below.get(name); if (cached) return cached; const acc: Doubt[] = [...(own.get(name) ?? [])]; const lemma = graph.lemmas.get(name); if (lemma) { for (const edge of lemma.to) { for (const d of resolveBelow(edge.name)) acc.push(d); } } const result = dedupeDoubts(acc); below.set(name, result); return result; }; for (const name of graph.lemmas.keys()) resolveBelow(name); const parent = new Map([[graph.target, undefined]]); const order: string[] = [graph.target]; let idx = 0; while (idx < order.length) { const cur = order[idx++]; const lemma = graph.lemmas.get(cur); if (!lemma) continue; const nextNames = lemma.to.map((e) => e.name).sort(byText); for (const next of nextNames) { if (parent.has(next)) continue; parent.set(next, cur); order.push(next); } } const pathTo = (node: string): string[] => { const rev: string[] = []; let cur: string | undefined = node; while (cur !== undefined) { rev.push(cur); cur = parent.get(cur); } return rev.reverse(); }; const seenPath = new Set(); const paths: { doubt: Doubt; path: string[] }[] = []; for (const node of order) { const doubts = own.get(node) ?? []; if (doubts.length === 0) continue; const path = pathTo(node); for (const doubt of doubts) { const key = doubtKey(doubt); if (seenPath.has(key)) continue; seenPath.add(key); paths.push({ doubt, path }); } } paths.sort( (a, b) => a.path.length - b.path.length || byText(doubtKey(a.doubt), doubtKey(b.doubt)), ); return { own, below, paths }; }