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

Global Variables:声明、读取与 assignment

发布于 2026-09-16 19:19 · 最后编辑于 2026-09-17 22:07 · 版本 v2 · 字数 3,818 · 预计阅读 8 分钟 👁 18 次阅读

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 就假定它已经存在。

目录

章节内容
Statementsstatement compiler 与同步
Variable declarationsglobal declaration
Reading variablesOP_GET_GLOBAL
AssignmentOP_SET_GLOBAL 与赋值表达式
Challenges扩展练习

Statements

compiler 的入口从 compile 一个 expression 改成循环读取 declaration,直到 EOF。每种 statement 或 declaration 消费自己的 token,并发出相应 bytecode。

Print statements

print statement 编译 expression,再发出 OP_PRINT。VM 从 stack 弹出 value 并调用 printValue:

stack effect

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。

setter

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

ast good

ast bad

编译 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

c
fun showVariable() {
  print global;
}

var global = "after";
showVariable();

Code block 2

c
if (monday) var croissant = "yes"; // Error.

Code block 3

text
statement      → exprStmt
               | forStmt
               | ifStmt
               | printStmt
               | returnStmt
               | whileStmt
               | block ;

Code block 4

text
declaration    → classDecl
               | funDecl
               | varDecl
               | statement ;

Code block 5

text
statement      → exprStmt
               | printStmt ;

declaration    → varDecl
               | statement ;

Code block 6

text
  advance();

Code block 7

c
  while (!match(TOKEN_EOF)) {
    declaration();
  }

Code block 8

c
  endCompiler();

Code block 9

c
static void declaration() {
  statement();
}

Code block 10

c
static void statement() {
  if (match(TOKEN_PRINT)) {
    printStatement();
  }
}

Code block 11

c
static void expression();

Code block 12

c
static void statement();
static void declaration();

Code block 13

c
static ParseRule* getRule(TokenType type);

Code block 14

c
static bool match(TokenType type) {
  if (!check(type)) return false;
  advance();
  return true;
}

Code block 15

c
static bool check(TokenType type) {
  return parser.current.type == type;
}

Code block 16

c
static void printStatement() {
  expression();
  consume(TOKEN_SEMICOLON, "Expect ';' after value.");
  emitByte(OP_PRINT);
}

Code block 17

c
  OP_NEGATE,

Code block 18

c
  OP_PRINT,

Code block 19

c
  OP_RETURN,

Code block 20

text
        break;

Code block 21

c
      case OP_PRINT: {
        printValue(pop());
        printf("\n");
        break;
      }

Code block 22

c
      case OP_RETURN: {

Code block 23

c
      case OP_RETURN: {

Code block 24

text
        // Exit interpreter.

Code block 25

c
        return INTERPRET_OK;

Code block 26

c
      return simpleInstruction("OP_NEGATE", offset);

Code block 27

c
    case OP_PRINT:
      return simpleInstruction("OP_PRINT", offset);

Code block 28

c
    case OP_RETURN:

Code block 29

c
print 1 + 2;
print 3 * 4;

Code block 30

text
    printStatement();

Code block 31

text
  } else {
    expressionStatement();

Code block 32

text
  }

Code block 33

c
static void expressionStatement() {
  expression();
  consume(TOKEN_SEMICOLON, "Expect ';' after expression.");
  emitByte(OP_POP);
}

Code block 34

text
brunch = "quiche";
eat(brunch);

Code block 35

c
  OP_FALSE,

Code block 36

c
  OP_POP,

Code block 37

c
  OP_EQUAL,

Code block 38

c
      case OP_FALSE: push(BOOL_VAL(false)); break;

Code block 39

c
      case OP_POP: pop(); break;

Code block 40

c
      case OP_EQUAL: {

Code block 41

c
      return simpleInstruction("OP_FALSE", offset);

Code block 42

c
    case OP_POP:
      return simpleInstruction("OP_POP", offset);

Code block 43

c
    case OP_EQUAL:

Code block 44

text
  statement();

Code block 45

c
  if (parser.panicMode) synchronize();

Code block 46

text
}

Code block 47

c
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

c
static void declaration() {

Code block 49

c
  if (match(TOKEN_VAR)) {
    varDeclaration();
  } else {
    statement();
  }

Code block 50

c
  if (parser.panicMode) synchronize();

Code block 51

c
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

text
var a;

Code block 53

text
var a = nil;

Code block 54

c
static void parsePrecedence(Precedence precedence);

Code block 55

c
static uint8_t parseVariable(const char* errorMessage) {
  consume(TOKEN_IDENTIFIER, errorMessage);
  return identifierConstant(&parser.previous);
}

Code block 56

c
static void parsePrecedence(Precedence precedence);

Code block 57

c
static uint8_t identifierConstant(Token* name) {
  return makeConstant(OBJ_VAL(copyString(name->start,
                                         name->length)));
}

Code block 58

c
static void defineVariable(uint8_t global) {
  emitBytes(OP_DEFINE_GLOBAL, global);
}

Code block 59

c
  OP_POP,

Code block 60

c
  OP_DEFINE_GLOBAL,

Code block 61

c
  OP_EQUAL,

Code block 62

c
      case OP_POP: pop(); break;

Code block 63

c
      case OP_DEFINE_GLOBAL: {
        ObjString* name = READ_STRING();
        tableSet(&vm.globals, name, peek(0));
        pop();
        break;
      }

Code block 64

c
      case OP_EQUAL: {

Code block 65

c
#define READ_CONSTANT() (vm.chunk->constants.values[READ_BYTE()])

Code block 66

c
#define READ_STRING() AS_STRING(READ_CONSTANT())

Code block 67

c
#define BINARY_OP(valueType, op) \

Code block 68

text
#undef READ_CONSTANT

Code block 69

text
#undef READ_STRING

Code block 70

text
#undef BINARY_OP

Code block 71

c
  Value* stackTop;

Code block 72

c
  Table globals;

Code block 73

text
  Table strings;

Code block 74

text
  vm.objects = NULL;

Code block 75

c
  initTable(&vm.globals);

Code block 76

text
  initTable(&vm.strings);

Code block 77

c
void freeVM() {

Code block 78

c
  freeTable(&vm.globals);

Code block 79

text
  freeTable(&vm.strings);

Code block 80

c
      return simpleInstruction("OP_POP", offset);

Code block 81

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

Code block 82

c
    case OP_EQUAL:

Code block 83

text
  [TOKEN_LESS_EQUAL]    = {NULL,     binary, PREC_COMPARISON},

Code block 84

text
  [TOKEN_IDENTIFIER]    = {variable, NULL,   PREC_NONE},

Code block 85

text
  [TOKEN_STRING]        = {string,   NULL,   PREC_NONE},

Code block 86

c
static void variable() {
  namedVariable(parser.previous);
}

Code block 87

c
static void namedVariable(Token name) {
  uint8_t arg = identifierConstant(&name);
  emitBytes(OP_GET_GLOBAL, arg);
}

Code block 88

c
  OP_POP,

Code block 89

c
  OP_GET_GLOBAL,

Code block 90

c
  OP_DEFINE_GLOBAL,

Code block 91

c
      case OP_POP: pop(); break;

Code block 92

c
      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

c
      case OP_DEFINE_GLOBAL: {

Code block 94

c
      return simpleInstruction("OP_POP", offset);

Code block 95

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

Code block 96

c
    case OP_DEFINE_GLOBAL:

Code block 97

c
var beverage = "cafe au lait";
var breakfast = "beignets with " + beverage;
print breakfast;

Code block 98

text
menu.brunch(sunday).beverage = "mimosa";

Code block 99

text
  uint8_t arg = identifierConstant(&name);

Code block 100

c
  if (match(TOKEN_EQUAL)) {
    expression();
    emitBytes(OP_SET_GLOBAL, arg);
  } else {
    emitBytes(OP_GET_GLOBAL, arg);
  }

Code block 101

text
}

Code block 102

c
  OP_DEFINE_GLOBAL,

Code block 103

c
  OP_SET_GLOBAL,

Code block 104

c
  OP_EQUAL,

Code block 105

text
      }

Code block 106

c
      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

c
      case OP_EQUAL: {

Code block 108

c
      return constantInstruction("OP_DEFINE_GLOBAL", chunk,
                                 offset);

Code block 109

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

Code block 110

c
    case OP_EQUAL:

Code block 111

text
a * b = c + d;

Code block 112

text
    error("Expect expression.");
    return;
  }

Code block 113

text
  bool canAssign = precedence <= PREC_ASSIGNMENT;
  prefixRule(canAssign);

Code block 114

c
  while (precedence <= getRule(parser.current.type)->precedence) {

Code block 115

c
static void variable(bool canAssign) {
  namedVariable(parser.previous, canAssign);
}

Code block 116

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

Code block 117

text
  uint8_t arg = identifierConstant(&name);

Code block 118

text
  uint8_t arg = identifierConstant(&name);

Code block 119

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

Code block 120

text
    expression();

Code block 121

text
    infixRule();
  }

Code block 122

c
  if (canAssign && match(TOKEN_EQUAL)) {
    error("Invalid assignment target.");
  }

Code block 123

text
}

Code block 124

text
    ParseFn infixRule = getRule(parser.previous.type)->infix;

Code block 125

text
    infixRule(canAssign);

Code block 126

text
  }

Code block 127

text
} Precedence;

Code block 128

c
typedef void (*ParseFn)(bool canAssign);

Code block 129

c
typedef struct {

Code block 130

c
static void binary(bool canAssign) {

Code block 131

c
  TokenType operatorType = parser.previous.type;

Code block 132

c
static void literal(bool canAssign) {

Code block 133

text
  switch (parser.previous.type) {

Code block 134

c
static void grouping(bool canAssign) {

Code block 135

text
  expression();

Code block 136

c
static void number(bool canAssign) {

Code block 137

text
  double value = strtod(parser.previous.start, NULL);

Code block 138

c
static void string(bool canAssign) {

Code block 139

text
  emitConstant(OBJ_VAL(copyString(parser.previous.start + 1,

Code block 140

c
static void unary(bool canAssign) {

Code block 141

c
  TokenType operatorType = parser.previous.type;

Code block 142

c
var breakfast = "beignets";
var beverage = "cafe au lait";
breakfast = "beignets with " + beverage;

print breakfast;

Code block 143

c
fun useVar() {
  print oops;
}

var ooops = "too many o's!";

参考资料

← 返回列表
← 上一篇 Hash Tables:open addressing、tombstone 与 interning 下一篇 → Local Variables:stack slot 与局部作用域

评论 (0)

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