目录
正在加载目录…
正在阅读专栏 Crafting Interpreters:手写解释器 第 20 篇 · 共 35 篇 · 57%

Compiling Expressions:Pratt parser 与 bytecode 生成

发布于 2026-09-16 19:15 · 最后编辑于 2026-09-17 22:07 · 版本 v2 · 字数 4,851 · 预计阅读 10 分钟 👁 15 次阅读

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 compilationcompiler 在 pipeline 中的位置
Parsing tokenstoken 与错误处理
Emitting bytecodeinstruction 输出
Prefix expressionsliterals、grouping、unary
Infix expressionsbinary operators
A Pratt parserprecedence table
Dumping chunks调试输出
Challenges扩展练习
Design Note:It’s Just Parsingparser 的边界

Single-pass compilation

之前的 pipeline 是 scanner → compiler → bytecode → VM:

pipeline

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。

keyhole

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 则按同样宽度解码。

mystery

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 的绑定强度。

connections

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。

calls

points to

A Pratt parser

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

connections

这套机制把 grammar 中大量相似的 binary rules 压缩为一个通用循环,同时保留每个 operator 的 precedence。新增 operator 通常只需增加 token type、ParseRule 和 compiler function,并在 VM 中加入相应 opcode。

Dumping chunks

编译结束后调用 disassembleChunk(),确认生成的 instruction、constant index 和 source line。编译器开发中的常见调试顺序是:

  1. scanner 是否返回正确 token;
  2. ParseRule 是否选中了正确 prefix/infix function;
  3. bytecode 是否体现预期 precedence;
  4. 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

text
InterpretResult interpret(const char* source) {

Code block 2

c
  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

text
}

Code block 4

c
#define clox_compiler_h

Code block 5

c
#include "vm.h"

bool compile(const char* source, Chunk* chunk);

Code block 6

text
#endif

Code block 7

c
#include "scanner.h"

Code block 8

text
bool compile(const char* source, Chunk* chunk) {

Code block 9

text
  initScanner(source);

Code block 10

text
  initScanner(source);

Code block 11

c
  advance();
  expression();
  consume(TOKEN_EOF, "Expect end of expression.");

Code block 12

text
}

Code block 13

c
#include "scanner.h"

Code block 14

c
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

c
#include "scanner.h"

Code block 16

c
typedef struct {
  Token current;
  Token previous;
} Parser;

Parser parser;

Code block 17

c
static void advance() {

Code block 18

c
static void errorAtCurrent(const char* message) {
  errorAt(&parser.current, message);
}

Code block 19

c
static void error(const char* message) {
  errorAt(&parser.previous, message);
}

Code block 20

c
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

c
  Token previous;

Code block 22

text
  bool hadError;

Code block 23

text
} Parser;

Code block 24

c
  consume(TOKEN_EOF, "Expect end of expression.");

Code block 25

c
  return !parser.hadError;

Code block 26

text
}

Code block 27

text
  bool hadError;

Code block 28

text
  bool panicMode;

Code block 29

text
} Parser;

Code block 30

c
static void errorAt(Token* token, const char* message) {

Code block 31

c
  parser.panicMode = true;

Code block 32

c
  fprintf(stderr, "[line %d] Error", token->line);

Code block 33

c
static void errorAt(Token* token, const char* message) {

Code block 34

c
  if (parser.panicMode) return;

Code block 35

c
  parser.panicMode = true;

Code block 36

text
  initScanner(source);

Code block 37

c
  parser.hadError = false;
  parser.panicMode = false;

Code block 38

text
  advance();

Code block 39

c
#include <stdio.h>

Code block 40

c
#include <stdlib.h>

Code block 41

c
#include "common.h"

Code block 42

c
static void consume(TokenType type, const char* message) {
  if (parser.current.type == type) {
    advance();
    return;
  }

  errorAtCurrent(message);
}

Code block 43

c
static void emitByte(uint8_t byte) {
  writeChunk(currentChunk(), byte, parser.previous.line);
}

Code block 44

c
Parser parser;

Code block 45

c
Chunk* compilingChunk;

static Chunk* currentChunk() {
  return compilingChunk;
}

Code block 46

c
static void errorAt(Token* token, const char* message) {

Code block 47

text
bool compile(const char* source, Chunk* chunk) {
  initScanner(source);

Code block 48

text
  compilingChunk = chunk;

Code block 49

c
  parser.hadError = false;

Code block 50

c
  consume(TOKEN_EOF, "Expect end of expression.");

Code block 51

c
  endCompiler();

Code block 52

c
  return !parser.hadError;

Code block 53

c
static void endCompiler() {
  emitReturn();
}

Code block 54

c
static void emitReturn() {
  emitByte(OP_RETURN);
}

Code block 55

c
static void emitBytes(uint8_t byte1, uint8_t byte2) {
  emitByte(byte1);
  emitByte(byte2);
}

Code block 56

c
static void expression() {
  // What goes here?
}

Code block 57

c
static void number() {
  double value = strtod(parser.previous.start, NULL);
  emitConstant(value);
}

Code block 58

c
static void emitConstant(Value value) {
  emitBytes(OP_CONSTANT, makeConstant(value));
}

Code block 59

c
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

c
static void grouping() {
  expression();
  consume(TOKEN_RIGHT_PAREN, "Expect ')' after expression.");
}

Code block 61

c
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

c
print -
  true;

Code block 63

text
-a.b + c;

Code block 64

c
static void parsePrecedence(Precedence precedence) {
  // What goes here?
}

Code block 65

text
} Parser;

Code block 66

c
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

c
Parser parser;

Code block 68

text
-a.b + c

Code block 69

c
static void expression() {

Code block 70

c
  parsePrecedence(PREC_ASSIGNMENT);

Code block 71

text
}

Code block 72

text
  // Compile the operand.

Code block 73

c
  parsePrecedence(PREC_UNARY);

Code block 74

text
  // Emit the operator instruction.

Code block 75

text
1 + 2

Code block 76

c
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

text
2 * 3 + 4

Code block 78

text
1 + 2 + 3 + 4

Code block 79

text
((1 + 2) + 3) + 4

Code block 80

text
a = b = c = d

Code block 81

text
a = (b = (c = d))

Code block 82

c
} Precedence;

Code block 83

c
typedef struct {
  ParseFn prefix;
  ParseFn infix;
  Precedence precedence;
} ParseRule;

Code block 84

c
Parser parser;

Code block 85

c
} Precedence;

Code block 86

c
typedef void (*ParseFn)();

Code block 87

c
typedef struct {

Code block 88

c
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

c
static ParseRule* getRule(TokenType type) {
  return &rules[type];
}

Code block 90

c
  emitReturn();
}

Code block 91

c
static void expression();
static ParseRule* getRule(TokenType type);
static void parsePrecedence(Precedence precedence);

Code block 92

c
static void binary() {

Code block 93

c
static void parsePrecedence(Precedence precedence) {

Code block 94

c
  advance();
  ParseFn prefixRule = getRule(parser.previous.type)->prefix;
  if (prefixRule == NULL) {
    error("Expect expression.");
    return;
  }

  prefixRule();

Code block 95

text
}

Code block 96

text
  prefixRule();

Code block 97

c
  while (precedence <= getRule(parser.current.type)->precedence) {
    advance();
    ParseFn infixRule = getRule(parser.previous.type)->infix;
    infixRule();
  }

Code block 98

text
}

Code block 99

c
#include <stdint.h>

Code block 100

c
#define DEBUG_PRINT_CODE

Code block 101

c
#define DEBUG_TRACE_EXECUTION

Code block 102

c
  emitReturn();

Code block 103

c
#ifdef DEBUG_PRINT_CODE
  if (!parser.hadError) {
    disassembleChunk(currentChunk(), "code");
  }
#endif

Code block 104

text
}

Code block 105

c
#include "scanner.h"

Code block 106

c
#ifdef DEBUG_PRINT_CODE
#include "debug.h"
#endif

Code block 107

c
typedef struct {

Code block 108

text
(-1 + 2) * 3 - -4

参考资料

← 返回列表
← 上一篇 Scanning on Demand:clox 的按需词法扫描 下一篇 → Types of Values:tagged union 与动态值表示

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论