Local Variables:stack slot 与局部作用域
Crafting Interpreters:Local Variables
本章把 global variables 之外的局部变量放入 VM stack,通过 compiler 在编译期分配 local slot,实现高效的 lexical scope。
TL;DR
- local variable 不需要 hash table lookup;compiler 把它解析成当前 function 的 stack slot。
- compiler 用 Local 数组维护 name、depth 和初始化状态,按作用域嵌套管理 slot。
- block 结束时,超出作用域的 local 通过 OP_POP 或 OP_CLOSE_UPVALUE 清理。
- initializer 的结果直接留在变量对应 slot 中,避免额外移动 value。
- 变量 declaration 在 initializer 完成前处于 declared-but-uninitialized 状态,防止读取自身。
目录
| 章节 | 内容 |
|---|---|
| Representing local variables | local slot |
| Block statements | scope depth |
| Declaring local variables | declaration 生命周期 |
| Using locals | get/set local |
| Challenges | 扩展练习 |
Representing local variables
global variable 使用 hash table,便于运行时按 name 查找;local variable 的生命周期和调用 stack 紧密相关。compiler 可以在编译期知道一个 local 在当前 scope 中的位置,把它直接编码为 slot index。

VM 的 stack 中,local value 由 slot 保存。访问 local 只需要从 stack frame 的起点加上 slot offset,不需要 string hash、比较或 table lookup。
Block statements
进入 block 时 compiler 增加 scopeDepth;离开时减少。声明 local 时记录当前 depth。block 结束时,所有 depth 大于当前值的 locals 都离开 scope,compiler 发出 POP 清理它们。

scope depth 是 compile-time 概念,运行时只执行生成的 stack cleanup instruction。嵌套 block 可以复用已经释放的 slots,只要不会让仍可见的 local 被覆盖。
Declaring local variables
varDeclaration() 先解析 identifier,再把 Local 加入 locals array,状态为 declared。若有 initializer,编译 expression;否则发出 OP_NIL。最后 markInitialized,把 local 标记为可读取。

initializer 的结果天然位于刚声明 local 的 slot:

如果 initializer 内再次读取同名 local,compiler 应报错。global declaration 可以有不同规则,但 local variable 必须避免未初始化读取:

Using locals
编译 variable expression 时,从 locals 数组的末尾向前搜索最近同名 local。找到后发出 OP_GET_LOCAL 和 slot index;assignment 则发出 OP_SET_LOCAL。搜索失败时回退到 global variable。
local name 的解析发生在 compile-time,因此 shadowing 遵循 source code 的 lexical nesting。slot index 是 bytecode operand,VM 不需要知道变量名。
退出 scope 时,compiler 按逆序清理 locals。当前 value 仍在 stack 上时,应保证 POP 数量和 local 数量一致;未来加入 closure 后,被捕获的 local 不能直接 POP,而要转换为 closed-over upvalue。
Challenges
1. Local slot limits
支持超过单 byte slot index 的 locals,并比较更宽 operand、多个 opcode 和 function frame 分段的实现。
2. Unused locals
为未使用 local 添加 warning;说明 compiler 如何区分“用户明确忽略”与“可能是 bug”。
3. Destructuring
为 tuple 或多返回值添加 destructuring declaration,明确多个 local slot 的初始化顺序和失败行为。
原文代码片段
本节按官方页面顺序保留本章所有 grammar、C 和测试代码片段,便于与上文译文逐段对照。
参考资料
Code block 1
} ParseRule;
Code block 2
typedef struct {
Local locals[UINT8_COUNT];
int localCount;
int scopeDepth;
} Compiler;
Code block 3
Parser parser;
Code block 4
#define DEBUG_TRACE_EXECUTION
Code block 5
#define UINT8_COUNT (UINT8_MAX + 1)
Code block 6
#endif
Code block 7
} ParseRule;
Code block 8
typedef struct {
Token name;
int depth;
} Local;
Code block 9
typedef struct {
Code block 10
Parser parser;
Code block 11
Compiler* current = NULL;
Code block 12
Chunk* compilingChunk;
Code block 13
static void initCompiler(Compiler* compiler) {
compiler->localCount = 0;
compiler->scopeDepth = 0;
current = compiler;
}
Code block 14
initScanner(source);
Code block 15
Compiler compiler;
initCompiler(&compiler);
Code block 16
compilingChunk = chunk;
Code block 17
statement → exprStmt
| printStmt
| block ;
block → "{" declaration* "}" ;
Code block 18
if (match(TOKEN_PRINT)) {
printStatement();
Code block 19
} else if (match(TOKEN_LEFT_BRACE)) {
beginScope();
block();
endScope();
Code block 20
} else {
Code block 21
static void block() {
while (!check(TOKEN_RIGHT_BRACE) && !check(TOKEN_EOF)) {
declaration();
}
consume(TOKEN_RIGHT_BRACE, "Expect '}' after block.");
}
Code block 22
static void beginScope() {
current->scopeDepth++;
}
Code block 23
static void endScope() {
current->scopeDepth--;
}
Code block 24
consume(TOKEN_IDENTIFIER, errorMessage);
Code block 25
declareVariable();
if (current->scopeDepth > 0) return 0;
Code block 26
return identifierConstant(&parser.previous);
Code block 27
static void defineVariable(uint8_t global) {
Code block 28
if (current->scopeDepth > 0) {
return;
}
Code block 29
emitBytes(OP_DEFINE_GLOBAL, global);
Code block 30
static void declareVariable() {
if (current->scopeDepth == 0) return;
Token* name = &parser.previous;
addLocal(*name);
}
Code block 31
static void addLocal(Token name) {
Local* local = ¤t->locals[current->localCount++];
local->name = name;
local->depth = current->scopeDepth;
}
Code block 32
static void addLocal(Token name) {
Code block 33
if (current->localCount == UINT8_COUNT) {
error("Too many local variables in function.");
return;
}
Code block 34
Local* local = ¤t->locals[current->localCount++];
Code block 35
{
var a = "first";
var a = "second";
}
Code block 36
{
var a = "outer";
{
var a = "inner";
}
}
Code block 37
Token* name = &parser.previous;
Code block 38
for (int i = current->localCount - 1; i >= 0; i--) {
Local* local = ¤t->locals[i];
if (local->depth != -1 && local->depth < current->scopeDepth) {
break;
}
if (identifiersEqual(name, &local->name)) {
error("Already a variable with this name in this scope.");
}
}
Code block 39
addLocal(*name);
}
Code block 40
static bool identifiersEqual(Token* a, Token* b) {
if (a->length != b->length) return false;
return memcmp(a->start, b->start, a->length) == 0;
}
Code block 41
#include <stdlib.h>
Code block 42
#include <string.h>
Code block 43
#include "common.h"
Code block 44
current->scopeDepth--;
Code block 45
while (current->localCount > 0 &&
current->locals[current->localCount - 1].depth >
current->scopeDepth) {
emitByte(OP_POP);
current->localCount--;
}
Code block 46
}
Code block 47
static void namedVariable(Token name, bool canAssign) {
Code block 48
uint8_t getOp, setOp;
int arg = resolveLocal(current, &name);
if (arg != -1) {
getOp = OP_GET_LOCAL;
setOp = OP_SET_LOCAL;
} else {
arg = identifierConstant(&name);
getOp = OP_GET_GLOBAL;
setOp = OP_SET_GLOBAL;
}
Code block 49
if (canAssign && match(TOKEN_EQUAL)) {
Code block 50
if (canAssign && match(TOKEN_EQUAL)) {
expression();
Code block 51
emitBytes(setOp, (uint8_t)arg);
Code block 52
} else {
Code block 53
emitBytes(setOp, (uint8_t)arg);
} else {
Code block 54
emitBytes(getOp, (uint8_t)arg);
Code block 55
}
Code block 56
static int resolveLocal(Compiler* compiler, Token* name) {
for (int i = compiler->localCount - 1; i >= 0; i--) {
Local* local = &compiler->locals[i];
if (identifiersEqual(name, &local->name)) {
return i;
}
}
return -1;
}
Code block 57
OP_POP,
Code block 58
OP_GET_LOCAL,
Code block 59
OP_GET_GLOBAL,
Code block 60
case OP_POP: pop(); break;
Code block 61
case OP_GET_LOCAL: {
uint8_t slot = READ_BYTE();
push(vm.stack[slot]);
break;
}
Code block 62
case OP_GET_GLOBAL: {
Code block 63
OP_GET_LOCAL,
Code block 64
OP_SET_LOCAL,
Code block 65
OP_GET_GLOBAL,
Code block 66
}
Code block 67
case OP_SET_LOCAL: {
uint8_t slot = READ_BYTE();
vm.stack[slot] = peek(0);
break;
}
Code block 68
case OP_GET_GLOBAL: {
Code block 69
return simpleInstruction("OP_POP", offset);
Code block 70
case OP_GET_LOCAL:
return byteInstruction("OP_GET_LOCAL", chunk, offset);
case OP_SET_LOCAL:
return byteInstruction("OP_SET_LOCAL", chunk, offset);
Code block 71
case OP_GET_GLOBAL:
Code block 72
static int byteInstruction(const char* name, Chunk* chunk,
int offset) {
uint8_t slot = chunk->code[offset + 1];
printf("%-16s %4d\n", name, slot);
return offset + 2;
}
Code block 73
{
var a = "outer";
{
var a = a;
}
}
Code block 74
local->name = name;
Code block 75
local->depth = -1;
Code block 76
}
Code block 77
if (current->scopeDepth > 0) {
Code block 78
markInitialized();
Code block 79
return;
}
Code block 80
static void markInitialized() {
current->locals[current->localCount - 1].depth =
current->scopeDepth;
}
Code block 81
if (identifiersEqual(name, &local->name)) {
Code block 82
if (local->depth == -1) {
error("Can't read local variable in its own initializer.");
}
Code block 83
return i;
Code block 84
var a = a;
参考资料
- 原文:Local Variables
- 系列索引
- Robert Nystrom, Crafting Interpreters,© 2015–2021
评论 (0)