Compiling Expressions:Pratt parser 与 bytecode 生成
Crafting Interpreters:Compiling Expressions
本章实现 clox compiler 的 expression compilation:扫描 token、使用 Pratt parser 处理 precedence,并发出 bytecode。
TL;DR
- compiler 位于 scanner 与 VM 之间,把 source token 直接 lowering 为 bytecode chunk。
- clox 使用 single-pass compiler:parser 识别语法的同时立即生成 instruction,不构造完整 AST。
- prefix/infix parser 与 precedence table 结合,形成 Pratt parser,能简洁处理 unary、binary 和 grouping。
- 每个 token type 关联 prefix function、infix function 以及 precedence;parsePrecedence 驱动整个 expression parser。
- 编译器和 VM 必须共享 opcode、constant、stack 与 source-line 的契约,disassembler 是验证这种契约的工具。
目录
| 章节 | 内容 |
|---|---|
| Single-pass compilation | compiler 在 pipeline 中的位置 |
| Parsing tokens | token 与错误处理 |
| Emitting bytecode | instruction 输出 |
| Prefix expressions | literals、grouping、unary |
| Infix expressions | binary operators |
| A Pratt parser | precedence table |
| Dumping chunks | 调试输出 |
| Challenges | 扩展练习 |
| Design Note:It’s Just Parsing | parser 的边界 |
Single-pass compilation
之前的 pipeline 是 scanner → compiler → bytecode → VM:

jlox 先生成 AST,再由 interpreter 遍历;clox compiler 在读取 token 时直接发出 bytecode。这样避免了 AST object allocation,也让编译器和执行器之间的表示更紧凑。
Single-pass 不代表没有 grammar 或 precedence。它只是把 parsing 和 code generation 合并在一个 pass 中:parser 知道足够多的上下文后,立即把对应 instruction 写入 chunk。
Parsing tokens
compiler 使用 scanner 的 scanToken() 按需获得 token,并保存 current 与 previous。advance() 读取下一个 token,consume() 要求特定 token type,否则进入 error state。

Handling syntax errors
compiler 需要分别处理 scanner error 与 parser error。panic mode 下应同步到明确的 token 边界;在 expression-only 的初版中,遇到错误可以停止编译并返回失败状态。重要的是不要继续生成可能被 VM 误执行的残缺 bytecode。
Emitting bytecode
emitByte() 把 opcode 写入当前 chunk,emitBytes() 连续写入 opcode 和 operand。emitConstant() 先把 value 加入 constants,再发出 OP_CONSTANT 与 index。
compiler 与 VM 共享 instruction encoding。例如 OP_CONSTANT 消费后一个 byte 作为 constant index;compiler 必须检查 index 是否超出 operand 可表达的范围,VM 则按同样宽度解码。

Prefix expressions
prefix expression 由一个 token 开头,后续结构取决于 token 类型。number 和 string 发出 constant;true、false、nil 发出对应常量 opcode;左括号编译内部 expression 并消费右括号;minus 和 bang 编译 operand 后发出 unary opcode。
Parsers for tokens
每个 token type 对应一个 ParseRule:
- prefix function 处理 token 位于 expression 开头的情况;
- infix function 处理 token 位于已有左 expression 之后的情况;
- precedence 指示该 operator 的绑定强度。

Parentheses for grouping
grouping 不需要专用 runtime instruction。compiler 消费左括号,递归编译内部 expression,再消费右括号;括号只改变 parsing 时的 precedence。
Unary negation
编译 unary operator 时先编译 operand,再发出 OP_NEGATE。因为 operand 的编译可能继续递归进入 unary 或 grouping,生成的 bytecode 会按正确的 evaluation order 排列。
Infix expressions
infix parser 接收已经编译好的 left expression。对于 binary operator,它按当前 precedence 递归调用 parsePrecedence(precedence + 1) 编译 right expression,然后发出 operator instruction。
使用更高一级 precedence 编译右侧,使同一 precedence 的 operators left-associative。例如 a - b - c 会先完成 a - b,再把结果作为外层 operator 的 left operand。


A Pratt parser
Pratt parser 通过 prefix/infix parse functions 和 precedence table 处理 expression。parsePrecedence() 先消费一个 prefix token,得到左表达式;只要当前 token 的 precedence 不低于传入级别,就消费 infix token,调用对应 infix function 继续扩展左表达式。

这套机制把 grammar 中大量相似的 binary rules 压缩为一个通用循环,同时保留每个 operator 的 precedence。新增 operator 通常只需增加 token type、ParseRule 和 compiler function,并在 VM 中加入相应 opcode。
Dumping chunks
编译结束后调用 disassembleChunk(),确认生成的 instruction、constant index 和 source line。编译器开发中的常见调试顺序是:
- scanner 是否返回正确 token;
- ParseRule 是否选中了正确 prefix/infix function;
- bytecode 是否体现预期 precedence;
- VM 是否按 operand encoding 执行。
Challenges
1. Ternary operator
为 Pratt parser 添加 ?:,处理它的 precedence、right-associativity 和跳转 instruction。
2. Error recovery
在单 pass compiler 中实现更好的 panic-mode synchronization,尽量在一次编译中报告多个独立错误。
3. Constant operands
支持宽 constant operand,比较多个 opcode、two-byte operand 与 constant pool 分层的设计。
Design Note:It’s Just Parsing
Pratt parser 看起来像一套特殊算法,但它本质上仍然是在把 token 序列映射到 grammar 结构。prefix/infix callbacks 对应 grammar 中不同位置的 production;precedence table 则显式编码了 binding rules。
算法的价值不在于神秘,而在于它把 language design 中真正重要的规则——哪些 token 能开始 expression、哪些 token 能继续 expression、谁绑定得更紧——集中到一张可检查的表中。理解这一点后,扩展 parser 就是增加明确的 grammar 与 code-generation 规则,而不是盲目修改递归。
原文代码片段
本节按官方页面顺序保留本章所有 grammar、C 和测试代码片段,便于与上文译文逐段对照。
参考资料
Code block 1
InterpretResult interpret(const char* source) {
Code block 2
Chunk chunk;
initChunk(&chunk);
if (!compile(source, &chunk)) {
freeChunk(&chunk);
return INTERPRET_COMPILE_ERROR;
}
vm.chunk = &chunk;
vm.ip = vm.chunk->code;
InterpretResult result = run();
freeChunk(&chunk);
return result;
Code block 3
}
Code block 4
#define clox_compiler_h
Code block 5
#include "vm.h"
bool compile(const char* source, Chunk* chunk);
Code block 6
#endif
Code block 7
#include "scanner.h"
Code block 8
bool compile(const char* source, Chunk* chunk) {
Code block 9
initScanner(source);
Code block 10
initScanner(source);
Code block 11
advance();
expression();
consume(TOKEN_EOF, "Expect end of expression.");
Code block 12
}
Code block 13
#include "scanner.h"
Code block 14
static void advance() {
parser.previous = parser.current;
for (;;) {
parser.current = scanToken();
if (parser.current.type != TOKEN_ERROR) break;
errorAtCurrent(parser.current.start);
}
}
Code block 15
#include "scanner.h"
Code block 16
typedef struct {
Token current;
Token previous;
} Parser;
Parser parser;
Code block 17
static void advance() {
Code block 18
static void errorAtCurrent(const char* message) {
errorAt(&parser.current, message);
}
Code block 19
static void error(const char* message) {
errorAt(&parser.previous, message);
}
Code block 20
static void errorAt(Token* token, const char* message) {
fprintf(stderr, "[line %d] Error", token->line);
if (token->type == TOKEN_EOF) {
fprintf(stderr, " at end");
} else if (token->type == TOKEN_ERROR) {
// Nothing.
} else {
fprintf(stderr, " at '%.*s'", token->length, token->start);
}
fprintf(stderr, ": %s\n", message);
parser.hadError = true;
}
Code block 21
Token previous;
Code block 22
bool hadError;
Code block 23
} Parser;
Code block 24
consume(TOKEN_EOF, "Expect end of expression.");
Code block 25
return !parser.hadError;
Code block 26
}
Code block 27
bool hadError;
Code block 28
bool panicMode;
Code block 29
} Parser;
Code block 30
static void errorAt(Token* token, const char* message) {
Code block 31
parser.panicMode = true;
Code block 32
fprintf(stderr, "[line %d] Error", token->line);
Code block 33
static void errorAt(Token* token, const char* message) {
Code block 34
if (parser.panicMode) return;
Code block 35
parser.panicMode = true;
Code block 36
initScanner(source);
Code block 37
parser.hadError = false;
parser.panicMode = false;
Code block 38
advance();
Code block 39
#include <stdio.h>
Code block 40
#include <stdlib.h>
Code block 41
#include "common.h"
Code block 42
static void consume(TokenType type, const char* message) {
if (parser.current.type == type) {
advance();
return;
}
errorAtCurrent(message);
}
Code block 43
static void emitByte(uint8_t byte) {
writeChunk(currentChunk(), byte, parser.previous.line);
}
Code block 44
Parser parser;
Code block 45
Chunk* compilingChunk;
static Chunk* currentChunk() {
return compilingChunk;
}
Code block 46
static void errorAt(Token* token, const char* message) {
Code block 47
bool compile(const char* source, Chunk* chunk) {
initScanner(source);
Code block 48
compilingChunk = chunk;
Code block 49
parser.hadError = false;
Code block 50
consume(TOKEN_EOF, "Expect end of expression.");
Code block 51
endCompiler();
Code block 52
return !parser.hadError;
Code block 53
static void endCompiler() {
emitReturn();
}
Code block 54
static void emitReturn() {
emitByte(OP_RETURN);
}
Code block 55
static void emitBytes(uint8_t byte1, uint8_t byte2) {
emitByte(byte1);
emitByte(byte2);
}
Code block 56
static void expression() {
// What goes here?
}
Code block 57
static void number() {
double value = strtod(parser.previous.start, NULL);
emitConstant(value);
}
Code block 58
static void emitConstant(Value value) {
emitBytes(OP_CONSTANT, makeConstant(value));
}
Code block 59
static uint8_t makeConstant(Value value) {
int constant = addConstant(currentChunk(), value);
if (constant > UINT8_MAX) {
error("Too many constants in one chunk.");
return 0;
}
return (uint8_t)constant;
}
Code block 60
static void grouping() {
expression();
consume(TOKEN_RIGHT_PAREN, "Expect ')' after expression.");
}
Code block 61
static void unary() {
TokenType operatorType = parser.previous.type;
// Compile the operand.
expression();
// Emit the operator instruction.
switch (operatorType) {
case TOKEN_MINUS: emitByte(OP_NEGATE); break;
default: return; // Unreachable.
}
}
Code block 62
print -
true;
Code block 63
-a.b + c;
Code block 64
static void parsePrecedence(Precedence precedence) {
// What goes here?
}
Code block 65
} Parser;
Code block 66
typedef enum {
PREC_NONE,
PREC_ASSIGNMENT, // =
PREC_OR, // or
PREC_AND, // and
PREC_EQUALITY, // == !=
PREC_COMPARISON, // < > <= >=
PREC_TERM, // + -
PREC_FACTOR, // * /
PREC_UNARY, // ! -
PREC_CALL, // . ()
PREC_PRIMARY
} Precedence;
Code block 67
Parser parser;
Code block 68
-a.b + c
Code block 69
static void expression() {
Code block 70
parsePrecedence(PREC_ASSIGNMENT);
Code block 71
}
Code block 72
// Compile the operand.
Code block 73
parsePrecedence(PREC_UNARY);
Code block 74
// Emit the operator instruction.
Code block 75
1 + 2
Code block 76
static void binary() {
TokenType operatorType = parser.previous.type;
ParseRule* rule = getRule(operatorType);
parsePrecedence((Precedence)(rule->precedence + 1));
switch (operatorType) {
case TOKEN_PLUS: emitByte(OP_ADD); break;
case TOKEN_MINUS: emitByte(OP_SUBTRACT); break;
case TOKEN_STAR: emitByte(OP_MULTIPLY); break;
case TOKEN_SLASH: emitByte(OP_DIVIDE); break;
default: return; // Unreachable.
}
}
Code block 77
2 * 3 + 4
Code block 78
1 + 2 + 3 + 4
Code block 79
((1 + 2) + 3) + 4
Code block 80
a = b = c = d
Code block 81
a = (b = (c = d))
Code block 82
} Precedence;
Code block 83
typedef struct {
ParseFn prefix;
ParseFn infix;
Precedence precedence;
} ParseRule;
Code block 84
Parser parser;
Code block 85
} Precedence;
Code block 86
typedef void (*ParseFn)();
Code block 87
typedef struct {
Code block 88
ParseRule rules[] = {
[TOKEN_LEFT_PAREN] = {grouping, NULL, PREC_NONE},
[TOKEN_RIGHT_PAREN] = {NULL, NULL, PREC_NONE},
[TOKEN_LEFT_BRACE] = {NULL, NULL, PREC_NONE},
[TOKEN_RIGHT_BRACE] = {NULL, NULL, PREC_NONE},
[TOKEN_COMMA] = {NULL, NULL, PREC_NONE},
[TOKEN_DOT] = {NULL, NULL, PREC_NONE},
[TOKEN_MINUS] = {unary, binary, PREC_TERM},
[TOKEN_PLUS] = {NULL, binary, PREC_TERM},
[TOKEN_SEMICOLON] = {NULL, NULL, PREC_NONE},
[TOKEN_SLASH] = {NULL, binary, PREC_FACTOR},
[TOKEN_STAR] = {NULL, binary, PREC_FACTOR},
[TOKEN_BANG] = {NULL, NULL, PREC_NONE},
[TOKEN_BANG_EQUAL] = {NULL, NULL, PREC_NONE},
[TOKEN_EQUAL] = {NULL, NULL, PREC_NONE},
[TOKEN_EQUAL_EQUAL] = {NULL, NULL, PREC_NONE},
[TOKEN_GREATER] = {NULL, NULL, PREC_NONE},
[TOKEN_GREATER_EQUAL] = {NULL, NULL, PREC_NONE},
[TOKEN_LESS] = {NULL, NULL, PREC_NONE},
[TOKEN_LESS_EQUAL] = {NULL, NULL, PREC_NONE},
[TOKEN_IDENTIFIER] = {NULL, NULL, PREC_NONE},
[TOKEN_STRING] = {NULL, NULL, PREC_NONE},
[TOKEN_NUMBER] = {number, NULL, PREC_NONE},
[TOKEN_AND] = {NULL, NULL, PREC_NONE},
[TOKEN_CLASS] = {NULL, NULL, PREC_NONE},
[TOKEN_ELSE] = {NULL, NULL, PREC_NONE},
[TOKEN_FALSE] = {NULL, NULL, PREC_NONE},
[TOKEN_FOR] = {NULL, NULL, PREC_NONE},
[TOKEN_FUN] = {NULL, NULL, PREC_NONE},
[TOKEN_IF] = {NULL, NULL, PREC_NONE},
[TOKEN_NIL] = {NULL, NULL, PREC_NONE},
[TOKEN_OR] = {NULL, NULL, PREC_NONE},
[TOKEN_PRINT] = {NULL, NULL, PREC_NONE},
[TOKEN_RETURN] = {NULL, NULL, PREC_NONE},
[TOKEN_SUPER] = {NULL, NULL, PREC_NONE},
[TOKEN_THIS] = {NULL, NULL, PREC_NONE},
[TOKEN_TRUE] = {NULL, NULL, PREC_NONE},
[TOKEN_VAR] = {NULL, NULL, PREC_NONE},
[TOKEN_WHILE] = {NULL, NULL, PREC_NONE},
[TOKEN_ERROR] = {NULL, NULL, PREC_NONE},
[TOKEN_EOF] = {NULL, NULL, PREC_NONE},
};
Code block 89
static ParseRule* getRule(TokenType type) {
return &rules[type];
}
Code block 90
emitReturn();
}
Code block 91
static void expression();
static ParseRule* getRule(TokenType type);
static void parsePrecedence(Precedence precedence);
Code block 92
static void binary() {
Code block 93
static void parsePrecedence(Precedence precedence) {
Code block 94
advance();
ParseFn prefixRule = getRule(parser.previous.type)->prefix;
if (prefixRule == NULL) {
error("Expect expression.");
return;
}
prefixRule();
Code block 95
}
Code block 96
prefixRule();
Code block 97
while (precedence <= getRule(parser.current.type)->precedence) {
advance();
ParseFn infixRule = getRule(parser.previous.type)->infix;
infixRule();
}
Code block 98
}
Code block 99
#include <stdint.h>
Code block 100
#define DEBUG_PRINT_CODE
Code block 101
#define DEBUG_TRACE_EXECUTION
Code block 102
emitReturn();
Code block 103
#ifdef DEBUG_PRINT_CODE
if (!parser.hadError) {
disassembleChunk(currentChunk(), "code");
}
#endif
Code block 104
}
Code block 105
#include "scanner.h"
Code block 106
#ifdef DEBUG_PRINT_CODE
#include "debug.h"
#endif
Code block 107
typedef struct {
Code block 108
(-1 + 2) * 3 - -4
参考资料
- 原文:Compiling Expressions
- 系列索引
- Robert Nystrom, Crafting Interpreters,© 2015–2021
评论 (0)