Global Variables:声明、读取与 assignment
Crafting Interpreters:Global Variables
本章把 clox 从只能编译 expression 扩展为能够编译 statements、声明 global variables,并在 VM 中读取和更新它们。
TL;DR
- compiler 需要从 expression-only 进入 declaration/statement parsing,并在遇到 EOF 前持续编译。
- global variable name 可以作为 constant string 存入 constant table,opcode 携带它的 index。
- 读取变量用 OP_GET_GLOBAL,声明/赋值分别用 OP_DEFINE_GLOBAL 与 OP_SET_GLOBAL。
- assignment 是 expression,因此必须在 Pratt parser 中正确区分普通 expression 和可赋值 target。
- 未定义变量属于 runtime error;编译器不能因为看到 identifier 就假定它已经存在。
目录
| 章节 | 内容 |
|---|---|
| Statements | statement compiler 与同步 |
| Variable declarations | global declaration |
| Reading variables | OP_GET_GLOBAL |
| Assignment | OP_SET_GLOBAL 与赋值表达式 |
| Challenges | 扩展练习 |
Statements
compiler 的入口从 compile 一个 expression 改成循环读取 declaration,直到 EOF。每种 statement 或 declaration 消费自己的 token,并发出相应 bytecode。
Print statements
print statement 编译 expression,再发出 OP_PRINT。VM 从 stack 弹出 value 并调用 printValue:

Expression statements
expression statement 编译 expression,再发出 OP_POP,丢弃结果。这样一个 expression 的临时 value 不会污染后续 statement 的 stack。
Error synchronization
遇到 compile error 后进入 panic mode,跳过 token 直到 statement boundary。同步点包括分号以及 class、fun、var、for、if、while、print、return 等 declaration/statement 开始 token。
Variable declarations
var declaration 读取 identifier name,可选 initializer;没有 initializer 时发出 OP_NIL。编译 initializer 后,global name 作为 string constant 写入 constant table,再发出 OP_DEFINE_GLOBAL。
define opcode 在 VM 中从 stack 取 value,并把 name/value 写入 globals table。注意 value 的栈生命周期:opcode 执行前 initializer result 必须仍在 stack 上。
Reading variables
variable expression 将 identifier name 编译为 constant string,发出 OP_GET_GLOBAL 和 name index。VM 从 globals table 查找 key;找到后压入 value,找不到则报告 “Undefined variable”。
由于 global lookup 发生在 runtime,变量可以引用稍后才执行的 declaration,只要运行到读取点时 binding 已存在。
Assignment
assignment 也是 expression。Parser 先用 Pratt parser 编译左侧;若随后看到等号,就回退到 target 语义,编译右侧,并发出 OP_SET_GLOBAL。set opcode 更新已有 global,同时保留 value 在 stack 上,因为 assignment expression 需要产生该 value。

左侧必须是可赋值的 variable。像 (a * b) = c + d 这样的输入应报告 invalid assignment target,而不是把等号错误地嵌入右侧:


编译 assignment 时要注意 precedence 和 associativity;连续 assignment 应从右向左结合。
Challenges
1. Global declaration timing
决定 var a = a; 的 bytecode 和运行时行为,编写测试覆盖已有 outer binding 与未定义 binding 两种情况。
2. Global deletion
添加删除 global 的语法和 opcode,并说明 closure、引用旧值和 table tombstone 的影响。
3. Immutable globals
增加 const declaration,在 compiler 和 VM 中阻止后续 assignment。
原文代码片段
本节按官方页面顺序保留本章所有 grammar、C 和测试代码片段,便于与上文译文逐段对照。
参考资料
Code block 1
fun showVariable() {
print global;
}
var global = "after";
showVariable();
Code block 2
if (monday) var croissant = "yes"; // Error.
Code block 3
statement → exprStmt
| forStmt
| ifStmt
| printStmt
| returnStmt
| whileStmt
| block ;
Code block 4
declaration → classDecl
| funDecl
| varDecl
| statement ;
Code block 5
statement → exprStmt
| printStmt ;
declaration → varDecl
| statement ;
Code block 6
advance();
Code block 7
while (!match(TOKEN_EOF)) {
declaration();
}
Code block 8
endCompiler();
Code block 9
static void declaration() {
statement();
}
Code block 10
static void statement() {
if (match(TOKEN_PRINT)) {
printStatement();
}
}
Code block 11
static void expression();
Code block 12
static void statement();
static void declaration();
Code block 13
static ParseRule* getRule(TokenType type);
Code block 14
static bool match(TokenType type) {
if (!check(type)) return false;
advance();
return true;
}
Code block 15
static bool check(TokenType type) {
return parser.current.type == type;
}
Code block 16
static void printStatement() {
expression();
consume(TOKEN_SEMICOLON, "Expect ';' after value.");
emitByte(OP_PRINT);
}
Code block 17
OP_NEGATE,
Code block 18
OP_PRINT,
Code block 19
OP_RETURN,
Code block 20
break;
Code block 21
case OP_PRINT: {
printValue(pop());
printf("\n");
break;
}
Code block 22
case OP_RETURN: {
Code block 23
case OP_RETURN: {
Code block 24
// Exit interpreter.
Code block 25
return INTERPRET_OK;
Code block 26
return simpleInstruction("OP_NEGATE", offset);
Code block 27
case OP_PRINT:
return simpleInstruction("OP_PRINT", offset);
Code block 28
case OP_RETURN:
Code block 29
print 1 + 2;
print 3 * 4;
Code block 30
printStatement();
Code block 31
} else {
expressionStatement();
Code block 32
}
Code block 33
static void expressionStatement() {
expression();
consume(TOKEN_SEMICOLON, "Expect ';' after expression.");
emitByte(OP_POP);
}
Code block 34
brunch = "quiche";
eat(brunch);
Code block 35
OP_FALSE,
Code block 36
OP_POP,
Code block 37
OP_EQUAL,
Code block 38
case OP_FALSE: push(BOOL_VAL(false)); break;
Code block 39
case OP_POP: pop(); break;
Code block 40
case OP_EQUAL: {
Code block 41
return simpleInstruction("OP_FALSE", offset);
Code block 42
case OP_POP:
return simpleInstruction("OP_POP", offset);
Code block 43
case OP_EQUAL:
Code block 44
statement();
Code block 45
if (parser.panicMode) synchronize();
Code block 46
}
Code block 47
static void synchronize() {
parser.panicMode = false;
while (parser.current.type != TOKEN_EOF) {
if (parser.previous.type == TOKEN_SEMICOLON) return;
switch (parser.current.type) {
case TOKEN_CLASS:
case TOKEN_FUN:
case TOKEN_VAR:
case TOKEN_FOR:
case TOKEN_IF:
case TOKEN_WHILE:
case TOKEN_PRINT:
case TOKEN_RETURN:
return;
default:
; // Do nothing.
}
advance();
}
}
Code block 48
static void declaration() {
Code block 49
if (match(TOKEN_VAR)) {
varDeclaration();
} else {
statement();
}
Code block 50
if (parser.panicMode) synchronize();
Code block 51
static void varDeclaration() {
uint8_t global = parseVariable("Expect variable name.");
if (match(TOKEN_EQUAL)) {
expression();
} else {
emitByte(OP_NIL);
}
consume(TOKEN_SEMICOLON,
"Expect ';' after variable declaration.");
defineVariable(global);
}
Code block 52
var a;
Code block 53
var a = nil;
Code block 54
static void parsePrecedence(Precedence precedence);
Code block 55
static uint8_t parseVariable(const char* errorMessage) {
consume(TOKEN_IDENTIFIER, errorMessage);
return identifierConstant(&parser.previous);
}
Code block 56
static void parsePrecedence(Precedence precedence);
Code block 57
static uint8_t identifierConstant(Token* name) {
return makeConstant(OBJ_VAL(copyString(name->start,
name->length)));
}
Code block 58
static void defineVariable(uint8_t global) {
emitBytes(OP_DEFINE_GLOBAL, global);
}
Code block 59
OP_POP,
Code block 60
OP_DEFINE_GLOBAL,
Code block 61
OP_EQUAL,
Code block 62
case OP_POP: pop(); break;
Code block 63
case OP_DEFINE_GLOBAL: {
ObjString* name = READ_STRING();
tableSet(&vm.globals, name, peek(0));
pop();
break;
}
Code block 64
case OP_EQUAL: {
Code block 65
#define READ_CONSTANT() (vm.chunk->constants.values[READ_BYTE()])
Code block 66
#define READ_STRING() AS_STRING(READ_CONSTANT())
Code block 67
#define BINARY_OP(valueType, op) \
Code block 68
#undef READ_CONSTANT
Code block 69
#undef READ_STRING
Code block 70
#undef BINARY_OP
Code block 71
Value* stackTop;
Code block 72
Table globals;
Code block 73
Table strings;
Code block 74
vm.objects = NULL;
Code block 75
initTable(&vm.globals);
Code block 76
initTable(&vm.strings);
Code block 77
void freeVM() {
Code block 78
freeTable(&vm.globals);
Code block 79
freeTable(&vm.strings);
Code block 80
return simpleInstruction("OP_POP", offset);
Code block 81
case OP_DEFINE_GLOBAL:
return constantInstruction("OP_DEFINE_GLOBAL", chunk,
offset);
Code block 82
case OP_EQUAL:
Code block 83
[TOKEN_LESS_EQUAL] = {NULL, binary, PREC_COMPARISON},
Code block 84
[TOKEN_IDENTIFIER] = {variable, NULL, PREC_NONE},
Code block 85
[TOKEN_STRING] = {string, NULL, PREC_NONE},
Code block 86
static void variable() {
namedVariable(parser.previous);
}
Code block 87
static void namedVariable(Token name) {
uint8_t arg = identifierConstant(&name);
emitBytes(OP_GET_GLOBAL, arg);
}
Code block 88
OP_POP,
Code block 89
OP_GET_GLOBAL,
Code block 90
OP_DEFINE_GLOBAL,
Code block 91
case OP_POP: pop(); break;
Code block 92
case OP_GET_GLOBAL: {
ObjString* name = READ_STRING();
Value value;
if (!tableGet(&vm.globals, name, &value)) {
runtimeError("Undefined variable '%s'.", name->chars);
return INTERPRET_RUNTIME_ERROR;
}
push(value);
break;
}
Code block 93
case OP_DEFINE_GLOBAL: {
Code block 94
return simpleInstruction("OP_POP", offset);
Code block 95
case OP_GET_GLOBAL:
return constantInstruction("OP_GET_GLOBAL", chunk, offset);
Code block 96
case OP_DEFINE_GLOBAL:
Code block 97
var beverage = "cafe au lait";
var breakfast = "beignets with " + beverage;
print breakfast;
Code block 98
menu.brunch(sunday).beverage = "mimosa";
Code block 99
uint8_t arg = identifierConstant(&name);
Code block 100
if (match(TOKEN_EQUAL)) {
expression();
emitBytes(OP_SET_GLOBAL, arg);
} else {
emitBytes(OP_GET_GLOBAL, arg);
}
Code block 101
}
Code block 102
OP_DEFINE_GLOBAL,
Code block 103
OP_SET_GLOBAL,
Code block 104
OP_EQUAL,
Code block 105
}
Code block 106
case OP_SET_GLOBAL: {
ObjString* name = READ_STRING();
if (tableSet(&vm.globals, name, peek(0))) {
tableDelete(&vm.globals, name);
runtimeError("Undefined variable '%s'.", name->chars);
return INTERPRET_RUNTIME_ERROR;
}
break;
}
Code block 107
case OP_EQUAL: {
Code block 108
return constantInstruction("OP_DEFINE_GLOBAL", chunk,
offset);
Code block 109
case OP_SET_GLOBAL:
return constantInstruction("OP_SET_GLOBAL", chunk, offset);
Code block 110
case OP_EQUAL:
Code block 111
a * b = c + d;
Code block 112
error("Expect expression.");
return;
}
Code block 113
bool canAssign = precedence <= PREC_ASSIGNMENT;
prefixRule(canAssign);
Code block 114
while (precedence <= getRule(parser.current.type)->precedence) {
Code block 115
static void variable(bool canAssign) {
namedVariable(parser.previous, canAssign);
}
Code block 116
static void namedVariable(Token name, bool canAssign) {
Code block 117
uint8_t arg = identifierConstant(&name);
Code block 118
uint8_t arg = identifierConstant(&name);
Code block 119
if (canAssign && match(TOKEN_EQUAL)) {
Code block 120
expression();
Code block 121
infixRule();
}
Code block 122
if (canAssign && match(TOKEN_EQUAL)) {
error("Invalid assignment target.");
}
Code block 123
}
Code block 124
ParseFn infixRule = getRule(parser.previous.type)->infix;
Code block 125
infixRule(canAssign);
Code block 126
}
Code block 127
} Precedence;
Code block 128
typedef void (*ParseFn)(bool canAssign);
Code block 129
typedef struct {
Code block 130
static void binary(bool canAssign) {
Code block 131
TokenType operatorType = parser.previous.type;
Code block 132
static void literal(bool canAssign) {
Code block 133
switch (parser.previous.type) {
Code block 134
static void grouping(bool canAssign) {
Code block 135
expression();
Code block 136
static void number(bool canAssign) {
Code block 137
double value = strtod(parser.previous.start, NULL);
Code block 138
static void string(bool canAssign) {
Code block 139
emitConstant(OBJ_VAL(copyString(parser.previous.start + 1,
Code block 140
static void unary(bool canAssign) {
Code block 141
TokenType operatorType = parser.previous.type;
Code block 142
var breakfast = "beignets";
var beverage = "cafe au lait";
breakfast = "beignets with " + beverage;
print breakfast;
Code block 143
fun useVar() {
print oops;
}
var ooops = "too many o's!";
参考资料
- 原文:Global Variables
- 系列索引
- Robert Nystrom, Crafting Interpreters,© 2015–2021
评论 (0)