import { type Block, type Goal, type GoalId, type RootBlock, type Script, spanStrictlyInside, type Step, type StepId, } from "../ir.ts"; export function inlineBlocks(input: { roots: RootBlock[]; script: Script }): RootBlock[] { const { roots, script } = 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 isSpawnedOneStep = (parentStep: Step, child: Block): string | undefined => { if (child.into.length !== 0) return undefined; if (child.steps.length !== 1) return undefined; if (child.marks.size !== 0 || child.errorLabel !== undefined) return undefined; const goal = goalById.get(child.last); if (goal && goal.closedBy !== "proof") return undefined; const childStep = stepById.get(child.steps[0]); if (!childStep) return undefined; if (!spanStrictlyInside(parentStep.span, childStep.span)) return undefined; return childStep.text; }; const isInsideParent = (parentStep: Step, child: Block): boolean => { if (child.steps.length === 0) return false; const first = stepById.get(child.steps[0]); return first !== undefined && spanStrictlyInside(parentStep.span, first.span); }; const transform = (raw: Block): Block => { const block: Block = { ...raw, steps: [...raw.steps], inlined: new Map(raw.inlined), marks: new Set(raw.marks), restsOnKinds: new Set(raw.restsOnKinds), into: raw.into.map(transform), }; while (block.steps.length > 0 && block.into.length > 1) { const lastStepId = block.steps[block.steps.length - 1]; const parentStep = stepById.get(lastStepId); if (!parentStep) break; const hasExternalContinuation = block.into.some( (child) => !isInsideParent(parentStep, child), ); if (!hasExternalContinuation) break; const remaining: Block[] = []; const foldedTexts: string[] = [...(block.inlined.get(lastStepId) ?? [])]; let didInline = false; for (const child of block.into) { const text = isSpawnedOneStep(parentStep, child); if (text !== undefined) { foldedTexts.push(text); didInline = true; } else { remaining.push(child); } } if (!didInline) break; block.inlined.set(lastStepId, foldedTexts); if (remaining.length === 1) { const cont = remaining[0]; for (const s of cont.steps) block.steps.push(s); for (const [k, v] of cont.inlined) { const prev = block.inlined.get(k); block.inlined.set(k, prev ? [...prev, ...v] : [...v]); } for (const m of cont.marks) block.marks.add(m); if (cont.restsOnKinds) { block.restsOnKinds ??= new Set(); for (const k of cont.restsOnKinds) block.restsOnKinds.add(k); } block.errorLabel = cont.errorLabel ?? block.errorLabel; block.last = cont.last; block.into = cont.into; } else { block.into = remaining; break; } } return block; }; return roots.map(({ root, block }) => ({ root, block: transform(block) })); }