1. 降低到 IR
IR 把复杂 AST 降低 为更规则的指令序列。BasicBlock 表示连续执行的片段,labels 和 jumps 让 if 与 while 的 控制流 变得明确,emitJump() 则统一生成跳转边。
type IRInstruction =
| { op: "load"; target: string; value: string }
| { op: "jump"; label: string }
| { op: "jump_if_false"; condition: string; label: string };
type BasicBlock = { label: string; instructions: IRInstruction[] };
function lowerStatement(stmt: Stmt, blocks: BasicBlock[]): void {
if (stmt.kind === "if") emitJump(blocks, "jump_if_false", "else");
}
function emitJump(blocks: BasicBlock[], op: "jump" | "jump_if_false", label: string): void {
blocks.at(-1)?.instructions.push({ op, label, condition: "tmp" } as IRInstruction);
}
2. 循环示例
MiniLang 的 while (i < 3) { i = i + 1; } 会降低成入口块、循环体块和退出块。这样优化器和字节码生成器都不用重新理解 while 语法。
while (i < 3) { i = i + 1; }