ethos/src/middle.ts
2026-03-10 23:21:42 +01:00

342 lines
10 KiB
TypeScript

import * as ast from "./ast.ts";
import { Checker, ResolveMap } from "./front.ts";
import { Ty } from "./ty.ts";
export class MiddleLowerer {
private fns = new Map<number, Fn>();
constructor(
private resols: ResolveMap,
private checker: Checker,
) {}
lowerFn(stmt: ast.FnStmt): Fn {
if (this.fns.has(stmt.id)) {
return this.fns.get(stmt.id)!;
}
const fn = new FnLowerer(this, this.resols, this.checker, stmt).lower();
this.fns.set(stmt.id, fn);
return fn;
}
}
class FnLowerer {
private bbs: BasicBlock[] = [new BasicBlock([])];
private localMap = new Map<number, Inst>();
constructor(
private lowerer: MiddleLowerer,
private resols: ResolveMap,
private checker: Checker,
private stmt: ast.FnStmt,
) {}
lower(): Fn {
const ty = this.checker.check(this.stmt);
this.lowerBlock(this.stmt.kind.body.as("Block"));
this.pushInst(Ty.Void, "Return", { source: this.makeVoid() });
return new Fn(this.stmt, ty, this.bbs);
}
private lowerBlock(block: ast.Block) {
for (const stmt of block.kind.stmts) {
this.lowerStmt(stmt);
}
}
private lowerStmt(stmt: ast.Node) {
if (stmt.is("LetStmt")) {
const ty = this.checker.check(stmt.kind.param);
const expr = this.lowerExpr(stmt.kind.expr);
const local = this.pushInst(ty, "AllocLocal", {});
this.pushInst(Ty.Void, "LocalStore", {
target: local,
source: expr,
});
this.localMap.set(stmt.kind.param.id, local);
return;
}
if (stmt.is("ReturnStmt")) {
const source = stmt.kind.expr
? this.lowerExpr(stmt.kind.expr)
: this.makeVoid();
this.pushInst(Ty.Void, "Return", { source });
return;
}
if (stmt.is("AssignStmt")) {
const source = this.lowerExpr(stmt.kind.expr);
const target = this.lowerAssignPlace(stmt.kind.place);
this.pushInst(Ty.Void, "LocalStore", { target, source });
return;
}
if (stmt.is("ExprStmt")) {
this.lowerExpr(stmt.kind.expr);
return;
}
throw new Error(`'${stmt.kind.tag}' not handled`);
}
private lowerAssignPlace(place: ast.Node): Inst {
if (place.is("IdentExpr")) {
const sym = this.resols.get(place);
if (sym.tag === "Let") {
const local = this.localMap.get(sym.param.id);
if (!local) {
throw new Error();
}
return local;
}
throw new Error(`'${sym.tag}' not handled`);
}
throw new Error(`'${place.kind.tag}' not handled`);
}
private lowerExpr(expr: ast.Node): Inst {
if (expr.is("IdentExpr")) {
const sym = this.resols.get(expr);
if (sym.tag === "Fn") {
const fn = this.lowerer.lowerFn(sym.stmt);
return this.pushInst(fn.ty, "Fn", { fn });
}
if (sym.tag === "FnParam") {
const ty = this.checker.check(sym.param);
return this.pushInst(ty, "Param", { idx: sym.idx });
}
if (sym.tag === "Builtin") {
throw new Error("handle elsewhere");
}
if (sym.tag === "Let") {
const local = this.localMap.get(sym.param.id);
if (!local) {
throw new Error();
}
return this.pushInst(local.ty, "LocalLoad", { source: local });
}
throw new Error(`'${sym.tag}' not handled`);
}
if (expr.is("IntExpr")) {
return this.pushInst(Ty.Int, "Int", { value: expr.kind.value });
}
if (expr.is("CallExpr")) {
const ty = this.checker.check(expr);
const args = expr.kind.args
.map((arg) => this.lowerExpr(arg));
if (expr.kind.expr.is("IdentExpr")) {
const sym = this.resols.get(expr.kind.expr);
if (sym.tag === "Builtin") {
if (sym.id === "__add") {
const [left, right] = args;
return this.pushInst(ty, "Add", { left, right });
}
if (sym.id === "print_int") {
return this.pushInst(ty, "DebugPrint", { args });
}
throw new Error(`builtin '${sym.id}' not handled`);
}
}
const callee = this.lowerExpr(expr.kind.expr);
return this.pushInst(ty, "Call", { callee, args });
}
if (expr.is("BinaryExpr")) {
const ty = this.checker.check(expr);
const binaryOp = binaryOpPatterns
.find((pat) =>
expr.kind.op === pat.op && ty.compatibleWith(pat.ty)
);
if (!binaryOp) {
throw new Error();
}
const left = this.lowerExpr(expr.kind.left);
const right = this.lowerExpr(expr.kind.right);
return this.pushInst(ty, binaryOp.tag, { left, right });
}
throw new Error(`'${expr.kind.tag}' not handled`);
}
private makeVoid(): Inst {
return this.pushInst(Ty.Void, "Void", {});
}
private pushInst<
Tag extends InstKind["tag"],
>(
ty: Ty,
tag: Tag,
kind: Omit<InstKind & { tag: Tag }, "tag">,
): Inst {
const inst = new Inst(ty, { tag, ...kind } as InstKind);
this.bbs.at(-1)!.insts.push(inst);
return inst;
}
}
type BinaryOpPattern = {
op: ast.BinaryOp;
ty: Ty;
tag: BinaryOp;
};
const binaryOpPatterns: BinaryOpPattern[] = [
{ op: "Add", ty: Ty.Int, tag: "Add" },
{ op: "Subtract", ty: Ty.Int, tag: "Sub" },
];
export class Fn {
constructor(
public stmt: ast.FnStmt,
public ty: Ty,
public bbs: BasicBlock[],
) {}
pretty(): string {
const fnTy = this.ty.isKind("FnStmt") && this.ty.kind.ty.isKind("Fn")
? this.ty.kind.ty
: null;
if (!fnTy) {
throw new Error();
}
const cx = new PrettyCx();
return `fn ${this.stmt.kind.ident}(${
fnTy.kind.params
.map((ty, idx) => `${idx}: ${ty.pretty()}`)
.join(", ")
}) -> ${fnTy.kind.retTy.pretty()}\n{\n${
this.bbs
.map((bb) => bb.pretty(cx))
.join("\n")
}\n}`;
}
}
class IdMap<T> {
private map = new Map<T, number>();
private counter = 0;
id(val: T): number {
if (!this.map.has(val)) {
this.map.set(val, this.counter++);
}
return this.map.get(val)!;
}
}
class PrettyCx {
private bbIds = new IdMap<BasicBlock>();
private regIds = new IdMap<Inst>();
bbId(bb: BasicBlock): number {
return this.bbIds.id(bb);
}
regId(reg: Inst): number {
return this.regIds.id(reg);
}
}
export class BasicBlock {
constructor(
public insts: Inst[],
) {}
pretty(cx: PrettyCx): string {
return `bb${cx.bbId(this)}:\n${
this.insts
.map((inst) => inst.pretty(cx))
.map((line) => ` ${line}`)
.join("\n")
}`;
}
}
export class Inst {
constructor(
public ty: Ty,
public kind: InstKind,
) {}
pretty(cx: PrettyCx): string {
const r = (v: Inst) => `_${cx.regId(v)}`;
return `${r(this)}: ${this.ty.pretty()} = ${this.kind.tag}${
(() => {
const k = this.kind;
switch (k.tag) {
case "Error":
return "";
case "Void":
return "";
case "Int":
return ` ${k.value}`;
case "Fn":
return ` ${k.fn.stmt.kind.ident}`;
case "Param":
return ` ${k.idx}`;
case "Call":
return ` ${r(k.callee)} (${k.args.map(r).join(", ")})`;
case "AllocLocal":
return "";
case "LocalLoad":
return ` ${r(k.source)}`;
case "LocalStore":
return ` ${r(k.target)}, ${r(k.source)}`;
case "Return":
return ` ${r(k.source)}`;
case "Eq":
case "Ne":
case "Lt":
case "Gt":
case "Lte":
case "Gte":
case "BitOr":
case "BitXor":
case "BitAnd":
case "Shl":
case "Shr":
case "Add":
case "Sub":
case "Mul":
case "Div":
case "Rem":
return ` ${r(k.left)} ${r(k.right)}`;
case "DebugPrint":
return ` ${k.args.map(r).join(", ")}`;
}
const _: never = k;
})()
}`;
}
}
export type InstKind =
| { tag: "Error" }
| { tag: "Void" }
| { tag: "Int"; value: number }
| { tag: "Fn"; fn: Fn }
| { tag: "Param"; idx: number }
| { tag: "Call"; callee: Inst; args: Inst[] }
| { tag: "AllocLocal" }
| { tag: "LocalLoad"; source: Inst }
| { tag: "LocalStore"; target: Inst; source: Inst }
| { tag: "Return"; source: Inst }
| { tag: BinaryOp; left: Inst; right: Inst }
| { tag: "DebugPrint"; args: Inst[] };
export type BinaryOp =
| "Eq"
| "Ne"
| "Lt"
| "Gt"
| "Lte"
| "Gte"
| "BitOr"
| "BitXor"
| "BitAnd"
| "Shl"
| "Shr"
| "Add"
| "Sub"
| "Mul"
| "Div"
| "Rem";