1. AST 结构
AST 是 Parser 和语义检查之间的契约。Expr 描述表达式,Stmt 描述语句,CallExpr 表示函数调用,IfStmt 表示条件分支。赋值语句和 AST visitor shape 会决定后续检查器能否保持简单。
type CallExpr = { kind: "call"; callee: string; args: Expr[] };
type Expr =
| { kind: "literal"; value: number | string | boolean }
| { kind: "name"; name: string }
| { kind: "assign"; name: string; value: Expr }
| CallExpr;
type IfStmt = { kind: "if"; condition: Expr; thenBranch: Stmt[]; elseBranch?: Stmt[] };
type Stmt =
| { kind: "let"; name: string; value: Expr }
| { kind: "expr"; expr: Expr }
| IfStmt;
2. 语义遍历
visitor 不改写语法,只把节点分发给后续阶段。MiniLang 示例 if (score > 60) { print("pass"); } 会形成 IfStmt,条件是比较表达式,分支里是 CallExpr 包装的 print 调用。
if (score > 60) { print("pass"); }