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

Jumping Back and Forth:bytecode 控制流与 backpatching

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

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 statementsconditional jump
Logical operatorsshort-circuit bytecode
While statementsbackward jump
For statementsloop compilation
Challenges扩展练习
Design Note:Considering Goto Harmful结构化控制流

If statements

if statement 的 bytecode 先编译 condition,再发出 OP_JUMP_IF_FALSE。该 instruction 携带一个暂时未知的 offset;then branch 编译完成后,compiler 才知道跳过多少 bytes。

if without else

Else clauses

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

bad else

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

if else

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

full if else

Logical operators

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

and

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

or

jump instruction 只改变 instruction pointer,不创建额外 AST 或 runtime object。短路也保证未执行的右侧 expression 不产生副作用。

While statements

while 保存 condition 的起始 offset。先编译 condition,再发出 OP_JUMP_IF_FALSE 跳到 loop 之后;body 编译完成后发出 OP_LOOP,回到起点:

while

OP_LOOP 与 forward jump 相反,它的 operand 表示向后跳的距离。编译器必须检查 offset 是否能放入 operand 宽度,并在超限时报告 compile error。

For statements

for 的 initializer 在进入 loop 前执行;condition 位于每轮开始;body 后是 increment,再跳回 condition 或起点:

for

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

c
if (condition) print("condition was truthy");

Code block 2

c
  if (match(TOKEN_PRINT)) {
    printStatement();

Code block 3

c
  } else if (match(TOKEN_IF)) {
    ifStatement();

Code block 4

c
  } else if (match(TOKEN_LEFT_BRACE)) {

Code block 5

c
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

text
if condition) print("looks weird");

Code block 7

c
static int emitJump(uint8_t instruction) {
  emitByte(instruction);
  emitByte(0xff);
  emitByte(0xff);
  return currentChunk()->count - 2;
}

Code block 8

c
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

c
  OP_PRINT,

Code block 10

c
  OP_JUMP_IF_FALSE,

Code block 11

c
  OP_RETURN,

Code block 12

text
        break;
      }

Code block 13

c
      case OP_JUMP_IF_FALSE: {
        uint16_t offset = READ_SHORT();
        if (isFalsey(peek(0))) vm.ip += offset;
        break;
      }

Code block 14

c
      case OP_RETURN: {

Code block 15

c
#define READ_CONSTANT() (vm.chunk->constants.values[READ_BYTE()])

Code block 16

c
#define READ_SHORT() \
    (vm.ip += 2, (uint16_t)((vm.ip[-2] << 8) | vm.ip[-1]))

Code block 17

c
#define READ_STRING() AS_STRING(READ_CONSTANT())

Code block 18

text
#undef READ_BYTE

Code block 19

text
#undef READ_SHORT

Code block 20

text
#undef READ_CONSTANT

Code block 21

c
case OP_JUMP_IF_FALSE: {
  uint16_t offset = READ_SHORT();
  vm.ip += falsey() * offset;
  break;
}

Code block 22

c
  patchJump(thenJump);

Code block 23

c
  if (match(TOKEN_ELSE)) statement();

Code block 24

text
}

Code block 25

text
  statement();

Code block 26

c
  int elseJump = emitJump(OP_JUMP);

Code block 27

c
  patchJump(thenJump);

Code block 28

c
  if (match(TOKEN_ELSE)) statement();

Code block 29

c
  patchJump(elseJump);

Code block 30

text
}

Code block 31

c
  OP_PRINT,

Code block 32

c
  OP_JUMP,

Code block 33

c
  OP_JUMP_IF_FALSE,

Code block 34

text
        break;
      }

Code block 35

c
      case OP_JUMP: {
        uint16_t offset = READ_SHORT();
        vm.ip += offset;
        break;
      }

Code block 36

c
      case OP_JUMP_IF_FALSE: {

Code block 37

c
  int thenJump = emitJump(OP_JUMP_IF_FALSE);

Code block 38

c
  emitByte(OP_POP);

Code block 39

text
  statement();

Code block 40

c
  patchJump(thenJump);

Code block 41

c
  emitByte(OP_POP);

Code block 42

c
  if (match(TOKEN_ELSE)) statement();

Code block 43

c
      return simpleInstruction("OP_PRINT", offset);

Code block 44

c
    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

c
    case OP_RETURN:

Code block 46

c
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

text
  [TOKEN_NUMBER]        = {number,   NULL,   PREC_NONE},

Code block 48

text
  [TOKEN_AND]           = {NULL,     and_,   PREC_AND},

Code block 49

text
  [TOKEN_CLASS]         = {NULL,     NULL,   PREC_NONE},

Code block 50

c
static void and_(bool canAssign) {
  int endJump = emitJump(OP_JUMP_IF_FALSE);

  emitByte(OP_POP);
  parsePrecedence(PREC_AND);

  patchJump(endJump);
}

Code block 51

text
  [TOKEN_NIL]           = {literal,  NULL,   PREC_NONE},

Code block 52

text
  [TOKEN_OR]            = {NULL,     or_,    PREC_OR},

Code block 53

text
  [TOKEN_PRINT]         = {NULL,     NULL,   PREC_NONE},

Code block 54

c
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

text
    ifStatement();

Code block 56

c
  } else if (match(TOKEN_WHILE)) {
    whileStatement();

Code block 57

c
  } else if (match(TOKEN_LEFT_BRACE)) {

Code block 58

c
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

text
  statement();

Code block 60

c
  emitLoop(loopStart);

Code block 61

c
  patchJump(exitJump);

Code block 62

c
static void whileStatement() {

Code block 63

c
  int loopStart = currentChunk()->count;

Code block 64

text
  consume(TOKEN_LEFT_PAREN, "Expect '(' after 'while'.");

Code block 65

c
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

c
  OP_JUMP_IF_FALSE,

Code block 67

c
  OP_LOOP,

Code block 68

c
  OP_RETURN,

Code block 69

text
      }

Code block 70

c
      case OP_LOOP: {
        uint16_t offset = READ_SHORT();
        vm.ip -= offset;
        break;
      }

Code block 71

c
      case OP_RETURN: {

Code block 72

c
      return jumpInstruction("OP_JUMP_IF_FALSE", 1, chunk, offset);

Code block 73

c
    case OP_LOOP:
      return jumpInstruction("OP_LOOP", -1, chunk, offset);

Code block 74

c
    case OP_RETURN:

Code block 75

text
    printStatement();

Code block 76

c
  } else if (match(TOKEN_FOR)) {
    forStatement();

Code block 77

c
  } else if (match(TOKEN_IF)) {

Code block 78

c
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

text
  consume(TOKEN_LEFT_PAREN, "Expect '(' after 'for'.");

Code block 80

c
  if (match(TOKEN_SEMICOLON)) {
    // No initializer.
  } else if (match(TOKEN_VAR)) {
    varDeclaration();
  } else {
    expressionStatement();
  }

Code block 81

c
  int loopStart = currentChunk()->count;

Code block 82

c
static void forStatement() {

Code block 83

text
  beginScope();

Code block 84

text
  consume(TOKEN_LEFT_PAREN, "Expect '(' after 'for'.");

Code block 85

c
  emitLoop(loopStart);

Code block 86

text
  endScope();

Code block 87

text
}

Code block 88

c
  int loopStart = currentChunk()->count;

Code block 89

c
  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

text
  consume(TOKEN_RIGHT_PAREN, "Expect ')' after for clauses.");

Code block 91

c
  emitLoop(loopStart);

Code block 92

c
  if (exitJump != -1) {
    patchJump(exitJump);
    emitByte(OP_POP); // Condition.
  }

Code block 93

text
  endScope();
}

Code block 94

text
  }

Code block 95

c
  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

text
  statement();

Code block 97

text
switchStmt     → "switch" "(" expression ")"
                 "{" switchCase* defaultCase? "}" ;
switchCase     → "case" expression ":" statement* ;
defaultCase    → "default" ":" statement* ;

Code block 98

text
continueStmt   → "continue" ";" ;

Code block 99

c
// 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

c
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:

参考资料

← 返回列表
← 上一篇 Local Variables:stack slot 与局部作用域 下一篇 → Calls and Functions:call frame 与函数调用栈

评论 (0)

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