递归下降解析器
07 把 EBNF 摆出来,最直接的实现就是把每条产生式翻译成一个函数——parseIfStmt 解析 if,parseFnDecl 解析 fn,递归到底。这就是递归下降(recursive descent)。简单到让人怀疑:这就是 rustc / Go / V8 / Swift / TypeScript 的同款方案?是的,工业级也就这一套,只不过错误恢复更聪明、增量解析做得更细。
一句话先记住:递归下降 = 一条产生式 → 一个函数 + peek/advance/match/consume 四件套 + panic mode 错误恢复。简单到看一眼就懂,强大到能写下 Rust/Go/Swift 的全部语法,这就是为什么所有现代主流语言都选它。
一、自顶向下:一条产生式 = 一个函数
EBNF 函数
program = decl* EOF → parseProgram()
decl = letDecl | varDecl | ... → parseDecl()
ifStmt = "if" expr block ... → parseIfStmt()
expr = ... → parseExpr()执行顺序自上而下:从 program 开始,根据当前 token 决定调用哪个子函数——每个函数知道自己要"从输入开始,消耗一段 token,产出对应 AST 节点",调用栈深度 = 产生式嵌套深度。
二、四件套:peek / advance / match / consume
任何递归下降解析器都靠这四个工具:
class Parser {
tokens: Token[]; pos = 0;
peek(): Token { return this.tokens[this.pos] }
previous(): Token { return this.tokens[this.pos - 1] }
advance(): Token { return this.tokens[this.pos++] }
isAtEnd(): boolean { return this.peek().type === EOF }
check(t: TokenType): boolean { return this.peek().type === t }
// 当前 token 是这些之一?是就吃掉返回 true,否则不动
match(...types: TokenType[]): boolean {
if (types.includes(this.peek().type)) { this.advance(); return true }
return false
}
// 当前 token 必须是这种,否则抛错
consume(type: TokenType, msg: string): Token {
if (this.check(type)) return this.advance()
throw this.error(this.peek(), msg)
}
}四个动作:peek 不前进、advance 前进、match 试探(成功就前进)、consume 强制(失败就报错)。覆盖所有解析行为。
三、Mochi 解析器骨架
parseProgram(): Program {
const decls: Decl[] = []
while (!this.isAtEnd()) decls.push(this.parseDecl())
return { type: "Program", decls }
}
parseDecl(): Decl {
if (this.match(LET)) return this.parseLetDecl()
if (this.match(VAR)) return this.parseVarDecl()
if (this.match(FN)) return this.parseFnDecl()
if (this.match(CLASS)) return this.parseClassDecl()
return this.parseStmt()
}
parseLetDecl(): LetDecl {
const name = this.consume(IDENT, "expected variable name").lexeme
this.consume(EQ, "expected '=' after let name")
return { type: "Let", name, value: this.parseExpr() }
}
parseStmt(): Stmt {
if (this.match(IF)) return this.parseIfStmt()
if (this.match(WHILE)) return this.parseWhileStmt()
if (this.check(LBRACE)) return this.parseBlock()
return { type: "ExprStmt", expr: this.parseExpr() }
}
parseIfStmt(): IfStmt {
const cond = this.parseExpr()
const then = this.parseBlock()
let elseB: Stmt | null = null
if (this.match(ELSE)) // else if 链:不开新块,直接接 parseIfStmt
elseB = this.match(IF) ? this.parseIfStmt() : this.parseBlock()
return { type: "If", cond, then, else: elseB }
}
parseBlock(): Block {
this.consume(LBRACE, "expected '{'")
const stmts: Decl[] = []
while (!this.check(RBRACE) && !this.isAtEnd()) stmts.push(this.parseDecl())
this.consume(RBRACE, "expected '}'")
return { type: "Block", stmts }
}70 行覆盖 let / var / fn / if / while / block / 表达式语句。parseExpr 留到 09 篇——递归下降做表达式那 10 层楼梯太丑,Pratt 替掉。
四、panic mode 错误恢复
最朴素的错误处理:遇错抛异常,catch 后跳过 token 到下一个语句边界——这就是 panic mode。
parse(): Program {
const decls: Decl[] = []
while (!this.isAtEnd()) {
try { decls.push(this.parseDecl()) }
catch (e) { this.errors.push(e); this.synchronize() }
}
return { type: "Program", decls }
}
synchronize() {
this.advance() // 错误 token 先吃掉
while (!this.isAtEnd()) {
if (this.previous().type === SEMI) return // 分号后就是新语句
switch (this.peek().type) {
case LET: case VAR: case FN: case CLASS:
case IF: case WHILE: case FOR: case RETURN: return // 关键字开头肯定是新语句
}
this.advance()
}
}"同步点(synchronization point)" = 分号后、右大括号后、或声明 / 控制流关键字。效果:let x = 1 + 这行错,有 panic mode 报 1 个错就同步到下一条 let y,后续正常解析;没有 panic mode 一个错连锁报 30 个——用户体验差距巨大。
五、为什么工业级都用它
| 优势 | 说明 |
|---|---|
| 错误信息好 | 每个函数知道在解析什么,可以说"expected { after if condition" |
| 易调试 | 直接下断点到 parseIfStmt,调用栈就是产生式嵌套 |
| 上下文敏感 | "class 内部 init 是关键字、其他地方是标识符"?加个布尔字段 |
| 增量解析 | LSP / IDE 改一个函数只重解析一小段,手写控制流容易做 |
| 性能可控 | 无自动机状态爆炸,常量分发,JIT 友好 |
自动生成器(yacc / bison / ANTLR) 在这些维度全部败北——生成代码黑盒、调试要去看 .y 文件、错误信息全靠 hack——工业级一致放弃。
六、工业指针
| 项目 | 文件 |
|---|---|
| rustc | compiler/rustc_parse/src/parser/mod.rs(主)、item.rs、stmt.rs、expr.rs |
| Go | src/go/parser/parser.go 全手写,单文件 2700+ 行 |
| V8 | src/parsing/parser-base.h 模板基类、parser.cc 实现 |
| TypeScript | src/compiler/parser.ts 单文件 9000+ 行,几乎所有 TS 神功都在这里 |
| Zig | src/parse.zig 手写,单文件 4000+ 行 |
| Crafting Interpreters | "Parsing Expressions" + "Statements and State" 章 |
打开 src/go/parser/parser.go 搜 parseIfStmt——你会发现跟上面 60 行骨架几乎一样,只是多了 token 位置信息和注释挂载。
七、Mochi 这里偷懒了
- 错误恢复只做 panic mode:不做"incremental recovery"——rustc 会在错处插入虚拟 token、继续严格解析,产出"这里其实想写什么"的诊断
- 没有 trivia 保留:注释、空白在解析阶段被丢弃,不挂在 AST 上——这样代码格式化工具就写不了。rust-analyzer 的 rowan 树会把每个空格保留
- 无"期待集"诊断:rustc 报错列"expected one of
let,if, ..."——需要在 parser 状态里维护 first set,Mochi 只报单 token 期待
八、跟 PEG / parser combinator 对比一句
| 方案 | 优点 | 缺点 |
|---|---|---|
| 手写递归下降 | 错误信息好、易调试、能加上下文 | 表达式那段丑(09 篇 Pratt 治) |
| PEG | 文法可执行、有序选择 / 消歧 | 错误信息天生差(回溯掉过的路径不记录) |
| Parser combinator | 类型安全、函数式优雅(parsec / nom) | 性能差、栈深、错误恢复几乎没办法做 |
手写递归下降胜在工程实用性——不优雅,但每一行都能改。
下一篇:09-Pratt解析器.md,专治表达式那一段 10 层楼梯——把 + - * / ( ) f(args) a[i] a.b ?: 全部统一进一个 30 行循环,1973 年 Vaughan Pratt 在 POPL 上发表的 4 页论文,过去 50 年没人超过它。