import { edgeKey, type Lemma, type LemmaGraph, type Through, type Trust } from "../ir.ts"; function reachByKind(graph: LemmaGraph, kind: Through): Map> { const memo = new Map>(); const visit = (name: string): Set => { const cached = memo.get(name); if (cached) return cached; const out = new Set(); const lemma = graph.lemmas.get(name); if (lemma) { for (const edge of lemma.to) { if (edge.through !== kind) continue; out.add(edge.name); for (const sub of visit(edge.name)) out.add(sub); } } memo.set(name, out); return out; }; for (const name of graph.lemmas.keys()) visit(name); return memo; } export function reduceLemmas(input: { graph: LemmaGraph; trust: Trust }): LemmaGraph { const { graph, trust } = input; const protectedEdges = new Set(); for (const entry of trust.paths) { for (let i = 0; i + 1 < entry.path.length; i++) { protectedEdges.add(edgeKey({ from: entry.path[i], to: entry.path[i + 1] })); } } const reachProof = reachByKind(graph, "proof"); const reachDef = reachByKind(graph, "definition"); const lemmas = new Map(); let reducedEdges = graph.reducedEdges; for (const [name, lemma] of graph.lemmas) { const kept: { name: string; through: Through }[] = []; for (const edge of lemma.to) { if (protectedEdges.has(edgeKey({ from: name, to: edge.name }))) { kept.push(edge); continue; } const reach = edge.through === "proof" ? reachProof : reachDef; const redundant = lemma.to.some( (other) => other.through === edge.through && other.name !== edge.name && (reach.get(other.name)?.has(edge.name) ?? false), ); if (redundant) reducedEdges++; else kept.push(edge); } lemmas.set(name, { ...lemma, to: kept }); } return { target: graph.target, lemmas, reducedEdges }; }