Chunks of Bytecode:指令、常量与反汇编
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 started | clox 项目初始化 |
| Chunks of instructions | instruction array |
| Disassembling chunks | 反汇编 |
| Constants | value 与 constant table |
| Line information | source 行号 |
| Challenges | 扩展练习 |
| Design Note:Test Your Language | 测试策略 |
Bytecode
jlox 直接 walking AST。AST 由许多 Java objects 组成,每次执行都要经过 visitor dispatch:

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

直接编译成 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 中的索引:

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

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

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
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
#include "common.h"
int main(int argc, const char* argv[]) {
return 0;
}
Code block 3
#ifndef clox_common_h
#define clox_common_h
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#endif
Code block 4
#ifndef clox_chunk_h
#define clox_chunk_h
#include "common.h"
#endif
Code block 5
#include "common.h"
Code block 6
typedef enum {
OP_RETURN,
} OpCode;
Code block 7
#endif
Code block 8
} OpCode;
Code block 9
typedef struct {
uint8_t* code;
} Chunk;
Code block 10
#endif
Code block 11
typedef struct {
Code block 12
int count;
int capacity;
Code block 13
uint8_t* code;
} Chunk;
Code block 14
} Chunk;
Code block 15
void initChunk(Chunk* chunk);
Code block 16
#endif
Code block 17
#include <stdlib.h>
#include "chunk.h"
void initChunk(Chunk* chunk) {
chunk->count = 0;
chunk->capacity = 0;
chunk->code = NULL;
}
Code block 18
void initChunk(Chunk* chunk);
Code block 19
void writeChunk(Chunk* chunk, uint8_t byte);
Code block 20
#endif
Code block 21
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
#include "chunk.h"
Code block 23
#include "memory.h"
Code block 24
void initChunk(Chunk* chunk) {
Code block 25
#ifndef clox_memory_h
#define clox_memory_h
#include "common.h"
#define GROW_CAPACITY(capacity) \
((capacity) < 8 ? 8 : (capacity) * 2)
#endif
Code block 26
#define GROW_CAPACITY(capacity) \
((capacity) < 8 ? 8 : (capacity) * 2)
Code block 27
#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
#endif
Code block 29
#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
void* result = realloc(pointer, newSize);
Code block 31
if (result == NULL) exit(1);
Code block 32
return result;
Code block 33
void initChunk(Chunk* chunk);
Code block 34
void freeChunk(Chunk* chunk);
Code block 35
void writeChunk(Chunk* chunk, uint8_t byte);
Code block 36
void freeChunk(Chunk* chunk) {
FREE_ARRAY(uint8_t, chunk->code, chunk->capacity);
initChunk(chunk);
}
Code block 37
#define GROW_ARRAY(type, pointer, oldCount, newCount) \
(type*)reallocate(pointer, sizeof(type) * (oldCount), \
sizeof(type) * (newCount))
Code block 38
#define FREE_ARRAY(type, pointer, oldCount) \
reallocate(pointer, sizeof(type) * (oldCount), 0)
Code block 39
void* reallocate(void* pointer, size_t oldSize, size_t newSize);
Code block 40
int main(int argc, const char* argv[]) {
Code block 41
Chunk chunk;
initChunk(&chunk);
writeChunk(&chunk, OP_RETURN);
freeChunk(&chunk);
Code block 42
return 0;
Code block 43
#include "common.h"
Code block 44
#include "chunk.h"
Code block 45
int main(int argc, const char* argv[]) {
Code block 46
initChunk(&chunk);
writeChunk(&chunk, OP_RETURN);
Code block 47
disassembleChunk(&chunk, "test chunk");
Code block 48
freeChunk(&chunk);
Code block 49
#include "chunk.h"
Code block 50
#include "debug.h"
Code block 51
int main(int argc, const char* argv[]) {
Code block 52
#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
#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
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
static int simpleInstruction(const char* name, int offset) {
printf("%s\n", name);
return offset + 1;
}
Code block 56
== test chunk ==
0000 OP_RETURN
Code block 57
1 + 2;
Code block 58
#ifndef clox_value_h
#define clox_value_h
#include "common.h"
typedef double Value;
#endif
Code block 59
typedef double Value;
Code block 60
typedef struct {
int capacity;
int count;
Value* values;
} ValueArray;
Code block 61
#endif
Code block 62
} ValueArray;
Code block 63
void initValueArray(ValueArray* array);
void writeValueArray(ValueArray* array, Value value);
void freeValueArray(ValueArray* array);
Code block 64
#endif
Code block 65
#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
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
void freeValueArray(ValueArray* array) {
FREE_ARRAY(Value, array->values, array->capacity);
initValueArray(array);
}
Code block 68
uint8_t* code;
Code block 69
ValueArray constants;
Code block 70
} Chunk;
Code block 71
#include "common.h"
Code block 72
#include "value.h"
Code block 73
typedef enum {
Code block 74
chunk->code = NULL;
Code block 75
initValueArray(&chunk->constants);
Code block 76
}
Code block 77
FREE_ARRAY(uint8_t, chunk->code, chunk->capacity);
Code block 78
freeValueArray(&chunk->constants);
Code block 79
initChunk(chunk);
Code block 80
void writeChunk(Chunk* chunk, uint8_t byte);
Code block 81
int addConstant(Chunk* chunk, Value value);
Code block 82
#endif
Code block 83
int addConstant(Chunk* chunk, Value value) {
writeValueArray(&chunk->constants, value);
return chunk->constants.count - 1;
}
Code block 84
print 1;
print 2;
Code block 85
typedef enum {
Code block 86
OP_CONSTANT,
Code block 87
OP_RETURN,
Code block 88
initChunk(&chunk);
Code block 89
int constant = addConstant(&chunk, 1.2);
writeChunk(&chunk, OP_CONSTANT);
writeChunk(&chunk, constant);
Code block 90
writeChunk(&chunk, OP_RETURN);
Code block 91
switch (instruction) {
Code block 92
case OP_CONSTANT:
return constantInstruction("OP_CONSTANT", chunk, offset);
Code block 93
case OP_RETURN:
Code block 94
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
#include "debug.h"
Code block 96
#include "value.h"
Code block 97
void disassembleChunk(Chunk* chunk, const char* name) {
Code block 98
void freeValueArray(ValueArray* array);
Code block 99
void printValue(Value value);
Code block 100
#endif
Code block 101
void printValue(Value value) {
printf("%g", value);
}
Code block 102
printf("'\n");
Code block 103
return offset + 2;
Code block 104
}
Code block 105
uint8_t* code;
Code block 106
int* lines;
Code block 107
ValueArray constants;
Code block 108
chunk->code = NULL;
Code block 109
chunk->lines = NULL;
Code block 110
initValueArray(&chunk->constants);
Code block 111
FREE_ARRAY(uint8_t, chunk->code, chunk->capacity);
Code block 112
FREE_ARRAY(int, chunk->lines, chunk->capacity);
Code block 113
freeValueArray(&chunk->constants);
Code block 114
void freeChunk(Chunk* chunk);
Code block 115
void writeChunk(Chunk* chunk, uint8_t byte, int line);
Code block 116
int addConstant(Chunk* chunk, Value value);
Code block 117
void writeChunk(Chunk* chunk, uint8_t byte, int line) {
Code block 118
if (chunk->capacity < chunk->count + 1) {
Code block 119
chunk->code = GROW_ARRAY(uint8_t, chunk->code,
oldCapacity, chunk->capacity);
Code block 120
chunk->lines = GROW_ARRAY(int, chunk->lines,
oldCapacity, chunk->capacity);
Code block 121
}
Code block 122
chunk->code[chunk->count] = byte;
Code block 123
chunk->lines[chunk->count] = line;
Code block 124
chunk->count++;
Code block 125
int constant = addConstant(&chunk, 1.2);
Code block 126
writeChunk(&chunk, OP_CONSTANT, 123);
writeChunk(&chunk, constant, 123);
writeChunk(&chunk, OP_RETURN, 123);
Code block 127
disassembleChunk(&chunk, "test chunk");
Code block 128
int disassembleInstruction(Chunk* chunk, int offset) {
printf("%04d ", offset);
Code block 129
if (offset > 0 &&
chunk->lines[offset] == chunk->lines[offset - 1]) {
printf(" | ");
} else {
printf("%4d ", chunk->lines[offset]);
}
Code block 130
uint8_t instruction = chunk->code[offset];
Code block 131
== test chunk ==
0000 123 OP_CONSTANT 0 '1.2'
0002 | OP_RETURN
Code block 132
void writeConstant(Chunk* chunk, Value value, int line) {
// Implement me...
}
参考资料
- 原文:Chunks of Bytecode
- 系列索引
- Robert Nystrom, Crafting Interpreters,© 2015–2021
评论 (0)