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

Chunks of Bytecode:指令、常量与反汇编

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

Crafting Interpreters:Chunks of Bytecode

本章为 clox 设计 bytecode chunk:用紧凑的 instruction、constant table 和 line information 表示可执行程序。

TL;DR

  • bytecode 是介于 source/AST 与 native machine code 之间的紧凑 instruction representation。
  • chunk 由 instruction bytes、constants 和 source line information 组成。
  • dynamic array 允许 chunk 在编译过程中增长;扩容时容量按比例增加以降低摊销成本。
  • disassembler 把不可读的 bytes 转回带 operand 的 instruction,既用于调试,也用于验证 compiler 输出。
  • constants 与 instruction 分离:OP_CONSTANT 后面的 byte 只是 constant table index。

目录

章节内容
Bytecode为什么选择 bytecode
Getting startedclox 项目初始化
Chunks of instructionsinstruction array
Disassembling chunks反汇编
Constantsvalue 与 constant table
Line informationsource 行号
Challenges扩展练习
Design Note:Test Your Language测试策略

Bytecode

jlox 直接 walking AST。AST 由许多 Java objects 组成,每次执行都要经过 visitor dispatch:

ast

这对教学很直观,但运行时需要频繁访问对象、调用方法和递归遍历。clox 先把程序编译成线性 bytecode,再由 VM 顺序取出 instruction 执行。

phases

直接编译成 native code 可以获得更高性能,但会引入目标平台、ABI、寄存器分配和机器码生成等复杂度。bytecode 保留了跨平台与实现简单之间的平衡。

Getting started

clox 使用 C standard library。项目先建立头文件、编译脚本和最小 main,再逐步加入 memory、value、chunk 与 debug 模块。每一步都保持程序可编译,避免在底层改动积累时失去反馈。

Chunks of instructions

instruction 是一个或多个 byte。最简单的 opcode 只有一个 byte;带 operand 的 instruction 则把数据放在后续 bytes 中。例如 OP_CONSTANT 后跟一个 byte,表示 constant table 中的索引:

format

chunk 需要保存 code array、当前 count 和 capacity。写入前检查 capacity;不足时分配更大的 array,再复制旧内容:

insert

容量增长通常采用固定增长因子。这样追加 n 个 instruction 的总复制成本是摊销线性的:

grow

Disassembling chunks

bytecode 对人不可读,因此 debug 模块提供 disassembleChunk 和 disassembleInstruction。disassembler 按 offset 读取 opcode,知道每种 instruction 的 operand 宽度后,打印名称、offset、行号和 operand。

它不是 interpreter 的必需组件,却是开发 compiler/VM 时最有价值的工具之一:当运行结果错误时,可以先确认 compiler 生成的 instruction 是否正确,再检查 VM 的执行逻辑。

Constants

number、string 等运行时 value 放在 constants array 中。OP_CONSTANT 只需要保存一个小索引,而不必把完整 value 塞进 instruction stream。

Representing values

初版 clox 用 Value 类型保存 number。之后扩展到 Boolean、nil 和 Obj 时,会把 Value 抽象成 tagged representation,让 VM 能在运行时识别实际类型。

Value arrays

ValueArray 与 Chunk 的 code array 使用类似的 dynamic-array 逻辑:初始化、写入、扩容和释放都集中在 value 模块中。统一内存策略可以减少模块间的不一致。

Constant instructions

编译一个常量时,先把 value 加入 constants,再发出 OP_CONSTANT 和返回的 index。index 的宽度决定单个 chunk 能引用多少 constants;当前实现使用一个 byte,因此需要检查上限并报告编译错误。

Line information

为了把 runtime error 和 disassembled instruction 映射回 source,chunk 还要记录每个 instruction 对应的 source line。最直接的做法是每个 byte 保存一个 line number;后续可以压缩连续相同的行号,减少重复数据。

line information 不改变执行语义,却显著改善错误报告和调试体验。底层表示应保留足够的 source mapping,而不是等到错误发生时再猜测位置。

Challenges

1. Constant limits

移除单 byte constant index 的限制,支持更大的 constant table,并比较宽 instruction 与多级 constant opcode 的取舍。

2. Compressed line information

实现压缩的 line table,在 disassembler 和 runtime error 中仍能 O(1) 或接近 O(1) 地查找行号。

3. Bytecode verifier

为 chunk 编写 verifier,检查未知 opcode、越界 constant index、截断 instruction 和非法 operand。

Design Note:Test Your Language

语言实现需要多层测试:scanner/parser 测试 grammar,compiler 测试生成的 bytecode,VM 测试执行结果,端到端测试则检查完整 pipeline。

disassembler 让 bytecode 测试更容易诊断。一个失败的输出不仅告诉我们结果不对,还能显示是哪条 instruction、哪个 operand 或哪个 source line 产生了偏差。测试不是项目完成后的装饰,而是设计 compiler 与 VM 时的反馈回路。

原文代码片段

本节按官方页面顺序保留本章所有 grammar、C 和测试代码片段,便于与上文译文逐段对照。

参考资料

Code block 1

c
fun fib(n) {
  if (n < 2) return n;
  return fib(n - 1) + fib(n - 2); 
}

var before = clock();
print fib(40);
var after = clock();
print after - before;

Code block 2

c
#include "common.h"

int main(int argc, const char* argv[]) {
  return 0;
}

Code block 3

c
#ifndef clox_common_h
#define clox_common_h

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>

#endif

Code block 4

c
#ifndef clox_chunk_h
#define clox_chunk_h

#include "common.h"

#endif

Code block 5

c
#include "common.h"

Code block 6

c
typedef enum {
  OP_RETURN,
} OpCode;

Code block 7

text
#endif

Code block 8

text
} OpCode;

Code block 9

c
typedef struct {
  uint8_t* code;
} Chunk;

Code block 10

text
#endif

Code block 11

c
typedef struct {

Code block 12

c
  int count;
  int capacity;

Code block 13

c
  uint8_t* code;
} Chunk;

Code block 14

c
} Chunk;

Code block 15

c
void initChunk(Chunk* chunk);

Code block 16

text
#endif

Code block 17

c
#include <stdlib.h>

#include "chunk.h"

void initChunk(Chunk* chunk) {
  chunk->count = 0;
  chunk->capacity = 0;
  chunk->code = NULL;
}

Code block 18

c
void initChunk(Chunk* chunk);

Code block 19

c
void writeChunk(Chunk* chunk, uint8_t byte);

Code block 20

text
#endif

Code block 21

c
void writeChunk(Chunk* chunk, uint8_t byte) {
  if (chunk->capacity < chunk->count + 1) {
    int oldCapacity = chunk->capacity;
    chunk->capacity = GROW_CAPACITY(oldCapacity);
    chunk->code = GROW_ARRAY(uint8_t, chunk->code,
        oldCapacity, chunk->capacity);
  }

  chunk->code[chunk->count] = byte;
  chunk->count++;
}

Code block 22

c
#include "chunk.h"

Code block 23

c
#include "memory.h"

Code block 24

c
void initChunk(Chunk* chunk) {

Code block 25

c
#ifndef clox_memory_h
#define clox_memory_h

#include "common.h"

#define GROW_CAPACITY(capacity) \
    ((capacity) < 8 ? 8 : (capacity) * 2)

#endif

Code block 26

c
#define GROW_CAPACITY(capacity) \
    ((capacity) < 8 ? 8 : (capacity) * 2)

Code block 27

c
#define GROW_ARRAY(type, pointer, oldCount, newCount) \
    (type*)reallocate(pointer, sizeof(type) * (oldCount), \
        sizeof(type) * (newCount))

void* reallocate(void* pointer, size_t oldSize, size_t newSize);

Code block 28

text
#endif

Code block 29

c
#include <stdlib.h>

#include "memory.h"

void* reallocate(void* pointer, size_t oldSize, size_t newSize) {
  if (newSize == 0) {
    free(pointer);
    return NULL;
  }

  void* result = realloc(pointer, newSize);
  return result;
}

Code block 30

text
  void* result = realloc(pointer, newSize);

Code block 31

c
  if (result == NULL) exit(1);

Code block 32

c
  return result;

Code block 33

c
void initChunk(Chunk* chunk);

Code block 34

c
void freeChunk(Chunk* chunk);

Code block 35

c
void writeChunk(Chunk* chunk, uint8_t byte);

Code block 36

c
void freeChunk(Chunk* chunk) {
  FREE_ARRAY(uint8_t, chunk->code, chunk->capacity);
  initChunk(chunk);
}

Code block 37

c
#define GROW_ARRAY(type, pointer, oldCount, newCount) \
    (type*)reallocate(pointer, sizeof(type) * (oldCount), \
        sizeof(type) * (newCount))

Code block 38

c
#define FREE_ARRAY(type, pointer, oldCount) \
    reallocate(pointer, sizeof(type) * (oldCount), 0)

Code block 39

text
void* reallocate(void* pointer, size_t oldSize, size_t newSize);

Code block 40

c
int main(int argc, const char* argv[]) {

Code block 41

c
  Chunk chunk;
  initChunk(&chunk);
  writeChunk(&chunk, OP_RETURN);
  freeChunk(&chunk);

Code block 42

c
  return 0;

Code block 43

c
#include "common.h"

Code block 44

c
#include "chunk.h"

Code block 45

c
int main(int argc, const char* argv[]) {

Code block 46

c
  initChunk(&chunk);
  writeChunk(&chunk, OP_RETURN);

Code block 47

c
  disassembleChunk(&chunk, "test chunk");

Code block 48

c
  freeChunk(&chunk);

Code block 49

c
#include "chunk.h"

Code block 50

c
#include "debug.h"

Code block 51

c
int main(int argc, const char* argv[]) {

Code block 52

c
#ifndef clox_debug_h
#define clox_debug_h

#include "chunk.h"

void disassembleChunk(Chunk* chunk, const char* name);
int disassembleInstruction(Chunk* chunk, int offset);

#endif

Code block 53

c
#include <stdio.h>

#include "debug.h"

void disassembleChunk(Chunk* chunk, const char* name) {
  printf("== %s ==\n", name);

  for (int offset = 0; offset < chunk->count;) {
    offset = disassembleInstruction(chunk, offset);
  }
}

Code block 54

c
int disassembleInstruction(Chunk* chunk, int offset) {
  printf("%04d ", offset);

  uint8_t instruction = chunk->code[offset];
  switch (instruction) {
    case OP_RETURN:
      return simpleInstruction("OP_RETURN", offset);
    default:
      printf("Unknown opcode %d\n", instruction);
      return offset + 1;
  }
}

Code block 55

c
static int simpleInstruction(const char* name, int offset) {
  printf("%s\n", name);
  return offset + 1;
}

Code block 56

c
== test chunk ==
0000 OP_RETURN

Code block 57

text
1 + 2;

Code block 58

c
#ifndef clox_value_h
#define clox_value_h

#include "common.h"

typedef double Value;

#endif

Code block 59

c
typedef double Value;

Code block 60

c
typedef struct {
  int capacity;
  int count;
  Value* values;
} ValueArray;

Code block 61

text
#endif

Code block 62

c
} ValueArray;

Code block 63

c
void initValueArray(ValueArray* array);
void writeValueArray(ValueArray* array, Value value);
void freeValueArray(ValueArray* array);

Code block 64

text
#endif

Code block 65

c
#include <stdio.h>

#include "memory.h"
#include "value.h"

void initValueArray(ValueArray* array) {
  array->values = NULL;
  array->capacity = 0;
  array->count = 0;
}

Code block 66

c
void writeValueArray(ValueArray* array, Value value) {
  if (array->capacity < array->count + 1) {
    int oldCapacity = array->capacity;
    array->capacity = GROW_CAPACITY(oldCapacity);
    array->values = GROW_ARRAY(Value, array->values,
                               oldCapacity, array->capacity);
  }

  array->values[array->count] = value;
  array->count++;
}

Code block 67

c
void freeValueArray(ValueArray* array) {
  FREE_ARRAY(Value, array->values, array->capacity);
  initValueArray(array);
}

Code block 68

c
  uint8_t* code;

Code block 69

c
  ValueArray constants;

Code block 70

c
} Chunk;

Code block 71

c
#include "common.h"

Code block 72

c
#include "value.h"

Code block 73

c
typedef enum {

Code block 74

text
  chunk->code = NULL;

Code block 75

c
  initValueArray(&chunk->constants);

Code block 76

text
}

Code block 77

c
  FREE_ARRAY(uint8_t, chunk->code, chunk->capacity);

Code block 78

c
  freeValueArray(&chunk->constants);

Code block 79

c
  initChunk(chunk);

Code block 80

c
void writeChunk(Chunk* chunk, uint8_t byte);

Code block 81

c
int addConstant(Chunk* chunk, Value value);

Code block 82

text
#endif

Code block 83

c
int addConstant(Chunk* chunk, Value value) {
  writeValueArray(&chunk->constants, value);
  return chunk->constants.count - 1;
}

Code block 84

c
print 1;
print 2;

Code block 85

c
typedef enum {

Code block 86

c
  OP_CONSTANT,

Code block 87

c
  OP_RETURN,

Code block 88

c
  initChunk(&chunk);

Code block 89

c
  int constant = addConstant(&chunk, 1.2);
  writeChunk(&chunk, OP_CONSTANT);
  writeChunk(&chunk, constant);

Code block 90

c
  writeChunk(&chunk, OP_RETURN);

Code block 91

text
  switch (instruction) {

Code block 92

c
    case OP_CONSTANT:
      return constantInstruction("OP_CONSTANT", chunk, offset);

Code block 93

c
    case OP_RETURN:

Code block 94

c
static int constantInstruction(const char* name, Chunk* chunk,
                               int offset) {
  uint8_t constant = chunk->code[offset + 1];
  printf("%-16s %4d '", name, constant);
  printValue(chunk->constants.values[constant]);
  printf("'\n");
}

Code block 95

c
#include "debug.h"

Code block 96

c
#include "value.h"

Code block 97

c
void disassembleChunk(Chunk* chunk, const char* name) {

Code block 98

c
void freeValueArray(ValueArray* array);

Code block 99

c
void printValue(Value value);

Code block 100

text
#endif

Code block 101

c
void printValue(Value value) {
  printf("%g", value);
}

Code block 102

c
  printf("'\n");

Code block 103

c
  return offset + 2;

Code block 104

text
}

Code block 105

c
  uint8_t* code;

Code block 106

text
  int* lines;

Code block 107

c
  ValueArray constants;

Code block 108

text
  chunk->code = NULL;

Code block 109

text
  chunk->lines = NULL;

Code block 110

c
  initValueArray(&chunk->constants);

Code block 111

c
  FREE_ARRAY(uint8_t, chunk->code, chunk->capacity);

Code block 112

text
  FREE_ARRAY(int, chunk->lines, chunk->capacity);

Code block 113

c
  freeValueArray(&chunk->constants);

Code block 114

c
void freeChunk(Chunk* chunk);

Code block 115

c
void writeChunk(Chunk* chunk, uint8_t byte, int line);

Code block 116

c
int addConstant(Chunk* chunk, Value value);

Code block 117

c
void writeChunk(Chunk* chunk, uint8_t byte, int line) {

Code block 118

c
  if (chunk->capacity < chunk->count + 1) {

Code block 119

c
    chunk->code = GROW_ARRAY(uint8_t, chunk->code,
        oldCapacity, chunk->capacity);

Code block 120

text
    chunk->lines = GROW_ARRAY(int, chunk->lines,
        oldCapacity, chunk->capacity);

Code block 121

text
  }

Code block 122

text
  chunk->code[chunk->count] = byte;

Code block 123

text
  chunk->lines[chunk->count] = line;

Code block 124

text
  chunk->count++;

Code block 125

c
  int constant = addConstant(&chunk, 1.2);

Code block 126

c
  writeChunk(&chunk, OP_CONSTANT, 123);
  writeChunk(&chunk, constant, 123);

  writeChunk(&chunk, OP_RETURN, 123);

Code block 127

c
  disassembleChunk(&chunk, "test chunk");

Code block 128

c
int disassembleInstruction(Chunk* chunk, int offset) {
  printf("%04d ", offset);

Code block 129

c
  if (offset > 0 &&
      chunk->lines[offset] == chunk->lines[offset - 1]) {
    printf("   | ");
  } else {
    printf("%4d ", chunk->lines[offset]);
  }

Code block 130

c
  uint8_t instruction = chunk->code[offset];

Code block 131

c
== test chunk ==
0000  123 OP_CONSTANT         0 '1.2'
0002    | OP_RETURN

Code block 132

c
void writeConstant(Chunk* chunk, Value value, int line) {
  // Implement me...
}

参考资料

← 返回列表
← 上一篇 A Bytecode Virtual Machine:从 jlox 到 clox 下一篇 → A Virtual Machine:stack、指令执行与算术

评论 (0)

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