Jumping Back and Forth:bytecode 控制流与 backpatching
Crafting Interpreters:Jumping Back and Forth
本章在 clox bytecode 中实现控制流:使用 jump instruction、backpatching 和 loop back edges 编译 if、logical operators、while 与 for。
TL;DR
- bytecode 控制流通过修改 instruction pointer 实现,conditional jump 根据 stack top 决定是否跳过一段 instruction。
- 编译前无法知道未来 jump target 的 offset,因此先写占位 operand,生成目标代码后再 backpatch。
- if/else 需要正确处理 then 分支跳过 else;condition value 在两条路径上都必须清理。
- while 保存 loop 起点,并用 OP_LOOP 跳回;for 是 initializer、condition、body、increment 的组合。
- logical and/or 使用 jump 实现 short-circuit,不必为每个逻辑运算引入新的运行时 value。
目录
| 章节 | 内容 |
|---|---|
| If statements | conditional jump |
| Logical operators | short-circuit bytecode |
| While statements | backward jump |
| For statements | loop compilation |
| Challenges | 扩展练习 |
| Design Note:Considering Goto Harmful | 结构化控制流 |
If statements
if statement 的 bytecode 先编译 condition,再发出 OP_JUMP_IF_FALSE。该 instruction 携带一个暂时未知的 offset;then branch 编译完成后,compiler 才知道跳过多少 bytes。

Else clauses
没有 else 时,then branch 执行完直接继续。若不插入跳转,then branch 会落入 else branch:

因此在 then branch 结束处还要发出无条件 OP_JUMP,跳过 else:

condition 留在 stack 上时,两条路径都需要发出 OP_POP:

Logical operators
logical and 在左值为 false 时跳过右侧;否则弹出左值并继续编译右侧:

logical or 在左值为 true 时跳过右侧;否则继续:

jump instruction 只改变 instruction pointer,不创建额外 AST 或 runtime object。短路也保证未执行的右侧 expression 不产生副作用。
While statements
while 保存 condition 的起始 offset。先编译 condition,再发出 OP_JUMP_IF_FALSE 跳到 loop 之后;body 编译完成后发出 OP_LOOP,回到起点:

OP_LOOP 与 forward jump 相反,它的 operand 表示向后跳的距离。编译器必须检查 offset 是否能放入 operand 宽度,并在超限时报告 compile error。
For statements
for 的 initializer 在进入 loop 前执行;condition 位于每轮开始;body 后是 increment,再跳回 condition 或起点:

Initializer clause
initializer 可以是 var declaration、expression statement 或空。若声明了 local,整个 for 应包在隐含 block 中,让变量的 scope 只覆盖 loop。
Condition clause
省略 condition 等同于 true,不需要发出额外 condition bytecode。否则编译 condition,并用 OP_JUMP_IF_FALSE 跳出。
Increment clause
increment 必须在 body 后执行。compiler 可以先编译 condition 和 body,再暂存或调整 loop start,使 backward jump 指向 increment 的开头,increment 完成后再跳回 condition。
Challenges
1. Break and continue
实现 break、continue 的 jump patching;处理嵌套 loop 和 continue 在 for 中应跳到 increment 的问题。
2. Switch
用 jump table 或线性比较实现 switch,并比较 code size 与 dispatch 成本。
3. Loop optimization
识别永真条件、空 body 和可合并 jump,说明优化如何保持 source line 与 debug 信息。
原文代码片段
本节按官方页面顺序保留本章所有 grammar、C 和测试代码片段,便于与上文译文逐段对照。
Design Note:Considering Goto Harmful
结构化 control flow 用 if、while 和 for 表达常见的执行关系,让代码的跳转边界能够从语法中看出来。任意 goto 虽然表达能力更强,却容易产生难以追踪的 control-flow graph;除非底层实现或极特殊的性能路径确实需要,否则结构化语句通常更容易验证和维护。
参考资料
Code block 1
if (condition) print("condition was truthy");
Code block 2
if (match(TOKEN_PRINT)) {
printStatement();
Code block 3
} else if (match(TOKEN_IF)) {
ifStatement();
Code block 4
} else if (match(TOKEN_LEFT_BRACE)) {
Code block 5
static void ifStatement() {
consume(TOKEN_LEFT_PAREN, "Expect '(' after 'if'.");
expression();
consume(TOKEN_RIGHT_PAREN, "Expect ')' after condition.");
int thenJump = emitJump(OP_JUMP_IF_FALSE);
statement();
patchJump(thenJump);
}
Code block 6
if condition) print("looks weird");
Code block 7
static int emitJump(uint8_t instruction) {
emitByte(instruction);
emitByte(0xff);
emitByte(0xff);
return currentChunk()->count - 2;
}
Code block 8
static void patchJump(int offset) {
// -2 to adjust for the bytecode for the jump offset itself.
int jump = currentChunk()->count - offset - 2;
if (jump > UINT16_MAX) {
error("Too much code to jump over.");
}
currentChunk()->code[offset] = (jump >> 8) & 0xff;
currentChunk()->code[offset + 1] = jump & 0xff;
}
Code block 9
OP_PRINT,
Code block 10
OP_JUMP_IF_FALSE,
Code block 11
OP_RETURN,
Code block 12
break;
}
Code block 13
case OP_JUMP_IF_FALSE: {
uint16_t offset = READ_SHORT();
if (isFalsey(peek(0))) vm.ip += offset;
break;
}
Code block 14
case OP_RETURN: {
Code block 15
#define READ_CONSTANT() (vm.chunk->constants.values[READ_BYTE()])
Code block 16
#define READ_SHORT() \
(vm.ip += 2, (uint16_t)((vm.ip[-2] << 8) | vm.ip[-1]))
Code block 17
#define READ_STRING() AS_STRING(READ_CONSTANT())
Code block 18
#undef READ_BYTE
Code block 19
#undef READ_SHORT
Code block 20
#undef READ_CONSTANT
Code block 21
case OP_JUMP_IF_FALSE: {
uint16_t offset = READ_SHORT();
vm.ip += falsey() * offset;
break;
}
Code block 22
patchJump(thenJump);
Code block 23
if (match(TOKEN_ELSE)) statement();
Code block 24
}
Code block 25
statement();
Code block 26
int elseJump = emitJump(OP_JUMP);
Code block 27
patchJump(thenJump);
Code block 28
if (match(TOKEN_ELSE)) statement();
Code block 29
patchJump(elseJump);
Code block 30
}
Code block 31
OP_PRINT,
Code block 32
OP_JUMP,
Code block 33
OP_JUMP_IF_FALSE,
Code block 34
break;
}
Code block 35
case OP_JUMP: {
uint16_t offset = READ_SHORT();
vm.ip += offset;
break;
}
Code block 36
case OP_JUMP_IF_FALSE: {
Code block 37
int thenJump = emitJump(OP_JUMP_IF_FALSE);
Code block 38
emitByte(OP_POP);
Code block 39
statement();
Code block 40
patchJump(thenJump);
Code block 41
emitByte(OP_POP);
Code block 42
if (match(TOKEN_ELSE)) statement();
Code block 43
return simpleInstruction("OP_PRINT", offset);
Code block 44
case OP_JUMP:
return jumpInstruction("OP_JUMP", 1, chunk, offset);
case OP_JUMP_IF_FALSE:
return jumpInstruction("OP_JUMP_IF_FALSE", 1, chunk, offset);
Code block 45
case OP_RETURN:
Code block 46
static int jumpInstruction(const char* name, int sign,
Chunk* chunk, int offset) {
uint16_t jump = (uint16_t)(chunk->code[offset + 1] << 8);
jump |= chunk->code[offset + 2];
printf("%-16s %4d -> %d\n", name, offset,
offset + 3 + sign * jump);
return offset + 3;
}
Code block 47
[TOKEN_NUMBER] = {number, NULL, PREC_NONE},
Code block 48
[TOKEN_AND] = {NULL, and_, PREC_AND},
Code block 49
[TOKEN_CLASS] = {NULL, NULL, PREC_NONE},
Code block 50
static void and_(bool canAssign) {
int endJump = emitJump(OP_JUMP_IF_FALSE);
emitByte(OP_POP);
parsePrecedence(PREC_AND);
patchJump(endJump);
}
Code block 51
[TOKEN_NIL] = {literal, NULL, PREC_NONE},
Code block 52
[TOKEN_OR] = {NULL, or_, PREC_OR},
Code block 53
[TOKEN_PRINT] = {NULL, NULL, PREC_NONE},
Code block 54
static void or_(bool canAssign) {
int elseJump = emitJump(OP_JUMP_IF_FALSE);
int endJump = emitJump(OP_JUMP);
patchJump(elseJump);
emitByte(OP_POP);
parsePrecedence(PREC_OR);
patchJump(endJump);
}
Code block 55
ifStatement();
Code block 56
} else if (match(TOKEN_WHILE)) {
whileStatement();
Code block 57
} else if (match(TOKEN_LEFT_BRACE)) {
Code block 58
static void whileStatement() {
consume(TOKEN_LEFT_PAREN, "Expect '(' after 'while'.");
expression();
consume(TOKEN_RIGHT_PAREN, "Expect ')' after condition.");
int exitJump = emitJump(OP_JUMP_IF_FALSE);
emitByte(OP_POP);
statement();
patchJump(exitJump);
emitByte(OP_POP);
}
Code block 59
statement();
Code block 60
emitLoop(loopStart);
Code block 61
patchJump(exitJump);
Code block 62
static void whileStatement() {
Code block 63
int loopStart = currentChunk()->count;
Code block 64
consume(TOKEN_LEFT_PAREN, "Expect '(' after 'while'.");
Code block 65
static void emitLoop(int loopStart) {
emitByte(OP_LOOP);
int offset = currentChunk()->count - loopStart + 2;
if (offset > UINT16_MAX) error("Loop body too large.");
emitByte((offset >> 8) & 0xff);
emitByte(offset & 0xff);
}
Code block 66
OP_JUMP_IF_FALSE,
Code block 67
OP_LOOP,
Code block 68
OP_RETURN,
Code block 69
}
Code block 70
case OP_LOOP: {
uint16_t offset = READ_SHORT();
vm.ip -= offset;
break;
}
Code block 71
case OP_RETURN: {
Code block 72
return jumpInstruction("OP_JUMP_IF_FALSE", 1, chunk, offset);
Code block 73
case OP_LOOP:
return jumpInstruction("OP_LOOP", -1, chunk, offset);
Code block 74
case OP_RETURN:
Code block 75
printStatement();
Code block 76
} else if (match(TOKEN_FOR)) {
forStatement();
Code block 77
} else if (match(TOKEN_IF)) {
Code block 78
static void forStatement() {
consume(TOKEN_LEFT_PAREN, "Expect '(' after 'for'.");
consume(TOKEN_SEMICOLON, "Expect ';'.");
int loopStart = currentChunk()->count;
consume(TOKEN_SEMICOLON, "Expect ';'.");
consume(TOKEN_RIGHT_PAREN, "Expect ')' after for clauses.");
statement();
emitLoop(loopStart);
}
Code block 79
consume(TOKEN_LEFT_PAREN, "Expect '(' after 'for'.");
Code block 80
if (match(TOKEN_SEMICOLON)) {
// No initializer.
} else if (match(TOKEN_VAR)) {
varDeclaration();
} else {
expressionStatement();
}
Code block 81
int loopStart = currentChunk()->count;
Code block 82
static void forStatement() {
Code block 83
beginScope();
Code block 84
consume(TOKEN_LEFT_PAREN, "Expect '(' after 'for'.");
Code block 85
emitLoop(loopStart);
Code block 86
endScope();
Code block 87
}
Code block 88
int loopStart = currentChunk()->count;
Code block 89
int exitJump = -1;
if (!match(TOKEN_SEMICOLON)) {
expression();
consume(TOKEN_SEMICOLON, "Expect ';' after loop condition.");
// Jump out of the loop if the condition is false.
exitJump = emitJump(OP_JUMP_IF_FALSE);
emitByte(OP_POP); // Condition.
}
Code block 90
consume(TOKEN_RIGHT_PAREN, "Expect ')' after for clauses.");
Code block 91
emitLoop(loopStart);
Code block 92
if (exitJump != -1) {
patchJump(exitJump);
emitByte(OP_POP); // Condition.
}
Code block 93
endScope();
}
Code block 94
}
Code block 95
if (!match(TOKEN_RIGHT_PAREN)) {
int bodyJump = emitJump(OP_JUMP);
int incrementStart = currentChunk()->count;
expression();
emitByte(OP_POP);
consume(TOKEN_RIGHT_PAREN, "Expect ')' after for clauses.");
emitLoop(loopStart);
loopStart = incrementStart;
patchJump(bodyJump);
}
Code block 96
statement();
Code block 97
switchStmt → "switch" "(" expression ")"
"{" switchCase* defaultCase? "}" ;
switchCase → "case" expression ":" statement* ;
defaultCase → "default" ":" statement* ;
Code block 98
continueStmt → "continue" ";" ;
Code block 99
// See if the matrix contains a zero.
bool found = false;
for (int x = 0; x < xSize; x++) {
for (int y = 0; y < ySize; y++) {
for (int z = 0; z < zSize; z++) {
if (matrix[x][y][z] == 0) {
printf("found");
found = true;
break;
}
}
if (found) break;
}
if (found) break;
}
Code block 100
for (int x = 0; x < xSize; x++) {
for (int y = 0; y < ySize; y++) {
for (int z = 0; z < zSize; z++) {
if (matrix[x][y][z] == 0) {
printf("found");
goto done;
}
}
}
}
done:
参考资料
- 原文:Jumping Back and Forth
- 系列索引
- Robert Nystrom, Crafting Interpreters,© 2015–2021
评论 (0)