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

Local Variables:stack slot 与局部作用域

发布于 2026-09-16 19:20 · 最后编辑于 2026-09-17 22:07 · 版本 v2 · 字数 2,941 · 预计阅读 6 分钟 👁 14 次阅读

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 variableslocal slot
Block statementsscope depth
Declaring local variablesdeclaration 生命周期
Using localsget/set local
Challenges扩展练习

Representing local variables

global variable 使用 hash table,便于运行时按 name 查找;local variable 的生命周期和调用 stack 紧密相关。compiler 可以在编译期知道一个 local 在当前 scope 中的位置,把它直接编码为 slot index。

scopes

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 清理它们。

block

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 标记为可读取。

declaration

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

local slots

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

phases

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

text
} ParseRule;

Code block 2

c
typedef struct {
  Local locals[UINT8_COUNT];
  int localCount;
  int scopeDepth;
} Compiler;

Code block 3

text
Parser parser;

Code block 4

c
#define DEBUG_TRACE_EXECUTION

Code block 5

c
#define UINT8_COUNT (UINT8_MAX + 1)

Code block 6

text
#endif

Code block 7

text
} ParseRule;

Code block 8

c
typedef struct {
  Token name;
  int depth;
} Local;

Code block 9

c
typedef struct {

Code block 10

text
Parser parser;

Code block 11

c
Compiler* current = NULL;

Code block 12

c
Chunk* compilingChunk;

Code block 13

c
static void initCompiler(Compiler* compiler) {
  compiler->localCount = 0;
  compiler->scopeDepth = 0;
  current = compiler;
}

Code block 14

text
  initScanner(source);

Code block 15

c
  Compiler compiler;
  initCompiler(&compiler);

Code block 16

c
  compilingChunk = chunk;

Code block 17

text
statement      → exprStmt
               | printStmt
               | block ;

block          → "{" declaration* "}" ;

Code block 18

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

Code block 19

c
  } else if (match(TOKEN_LEFT_BRACE)) {
    beginScope();
    block();
    endScope();

Code block 20

text
  } else {

Code block 21

c
static void block() {
  while (!check(TOKEN_RIGHT_BRACE) && !check(TOKEN_EOF)) {
    declaration();
  }

  consume(TOKEN_RIGHT_BRACE, "Expect '}' after block.");
}

Code block 22

c
static void beginScope() {
  current->scopeDepth++;
}

Code block 23

c
static void endScope() {
  current->scopeDepth--;
}

Code block 24

c
  consume(TOKEN_IDENTIFIER, errorMessage);

Code block 25

c
  declareVariable();
  if (current->scopeDepth > 0) return 0;

Code block 26

c
  return identifierConstant(&parser.previous);

Code block 27

c
static void defineVariable(uint8_t global) {

Code block 28

c
  if (current->scopeDepth > 0) {
    return;
  }

Code block 29

c
  emitBytes(OP_DEFINE_GLOBAL, global);

Code block 30

c
static void declareVariable() {
  if (current->scopeDepth == 0) return;

  Token* name = &parser.previous;
  addLocal(*name);
}

Code block 31

c
static void addLocal(Token name) {
  Local* local = &current->locals[current->localCount++];
  local->name = name;
  local->depth = current->scopeDepth;
}

Code block 32

c
static void addLocal(Token name) {

Code block 33

c
  if (current->localCount == UINT8_COUNT) {
    error("Too many local variables in function.");
    return;
  }

Code block 34

c
  Local* local = &current->locals[current->localCount++];

Code block 35

text
{
  var a = "first";
  var a = "second";
}

Code block 36

text
{
  var a = "outer";
  {
    var a = "inner";
  }
}

Code block 37

text
  Token* name = &parser.previous;

Code block 38

c
  for (int i = current->localCount - 1; i >= 0; i--) {
    Local* local = &current->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

c
  addLocal(*name);
}

Code block 40

c
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

c
#include <stdlib.h>

Code block 42

c
#include <string.h>

Code block 43

c
#include "common.h"

Code block 44

text
  current->scopeDepth--;

Code block 45

c
  while (current->localCount > 0 &&
         current->locals[current->localCount - 1].depth >
            current->scopeDepth) {
    emitByte(OP_POP);
    current->localCount--;
  }

Code block 46

text
}

Code block 47

c
static void namedVariable(Token name, bool canAssign) {

Code block 48

c
  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

c
  if (canAssign && match(TOKEN_EQUAL)) {

Code block 50

c
  if (canAssign && match(TOKEN_EQUAL)) {
    expression();

Code block 51

text
    emitBytes(setOp, (uint8_t)arg);

Code block 52

text
  } else {

Code block 53

text
    emitBytes(setOp, (uint8_t)arg);
  } else {

Code block 54

text
    emitBytes(getOp, (uint8_t)arg);

Code block 55

text
  }

Code block 56

c
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

c
  OP_POP,

Code block 58

c
  OP_GET_LOCAL,

Code block 59

c
  OP_GET_GLOBAL,

Code block 60

c
      case OP_POP: pop(); break;

Code block 61

c
      case OP_GET_LOCAL: {
        uint8_t slot = READ_BYTE();
        push(vm.stack[slot]); 
        break;
      }

Code block 62

c
      case OP_GET_GLOBAL: {

Code block 63

c
  OP_GET_LOCAL,

Code block 64

c
  OP_SET_LOCAL,

Code block 65

c
  OP_GET_GLOBAL,

Code block 66

text
      }

Code block 67

c
      case OP_SET_LOCAL: {
        uint8_t slot = READ_BYTE();
        vm.stack[slot] = peek(0);
        break;
      }

Code block 68

c
      case OP_GET_GLOBAL: {

Code block 69

c
      return simpleInstruction("OP_POP", offset);

Code block 70

c
    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

c
    case OP_GET_GLOBAL:

Code block 72

c
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

text
{
  var a = "outer";
  {
    var a = a;
  }
}

Code block 74

text
  local->name = name;

Code block 75

text
  local->depth = -1;

Code block 76

text
}

Code block 77

c
  if (current->scopeDepth > 0) {

Code block 78

text
    markInitialized();

Code block 79

text
    return;
  }

Code block 80

c
static void markInitialized() {
  current->locals[current->localCount - 1].depth =
      current->scopeDepth;
}

Code block 81

c
    if (identifiersEqual(name, &local->name)) {

Code block 82

c
      if (local->depth == -1) {
        error("Can't read local variable in its own initializer.");
      }

Code block 83

c
      return i;

Code block 84

text
var a = a;

参考资料

← 返回列表
← 上一篇 Global Variables:声明、读取与 assignment 下一篇 → Jumping Back and Forth:bytecode 控制流与 backpatching

评论 (0)

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