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

Resolving and Binding:静态作用域与变量解析

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

Crafting Interpreters:Resolving and Binding

本章在 interpreter 运行前增加 resolver pass,计算每个变量引用对应的 lexical scope 距离,并修复 closure 中的绑定语义。

TL;DR

  • lexical scope 由 source code 的嵌套结构决定,不能依赖运行时 Environment 链的偶然形状。
  • Resolver 是 semantic analysis pass:它不执行 expression,而是遍历 AST 并记录每个 variable expression 的静态距离。
  • declaration 有 declared 与 defined 两个状态,用来拒绝 initializer 中读取尚未完成声明的变量。
  • Interpreter 按 resolver 记录的距离访问 Environment,避免每次从当前 scope 逐层向外搜索。
  • function declaration 会创建新的 resolver scope;return 只能出现在 function body 内。

目录

章节内容
Static scopelexical scope 与 environment
Semantic analysisresolver pass
Resolver class遍历 AST 并维护 scope stack
Interpreting resolved variables按距离访问 binding
Resolution errors静态错误
Challenges扩展练习

Static scope

Lexical scope 的目标是:变量引用绑定到 source code 中最近的、可见的 declaration。仅靠 interpreter 在运行时沿 Environment 链查找,无法准确表达 closure 创建前后发生 declaration 的情况。

典型例子是同一个函数体中的变量引用。函数 declaration 在一个 scope 中创建,但 function body 可能稍后在另一个 scope 中调用。若 lookup 只沿调用时的 environment 链进行,结果会随调用位置变化,违反 lexical scope。

environment 1

Scopes and mutable environments

最直接的修复是让每个 variable expression 在 resolver 中记录 scope distance。运行时知道应该向 enclosing 链走几层,就能准确找到 lexical binding。

如果 resolver 直接修改共享的 mutable Environment,变量 declaration 前后的环境状态可能互相影响。尤其是 closure 捕获了 environment 后,后续声明会改变同一个 map 的内容:

environment 2

Persistent environments

另一种思路是使用 persistent environment:每次加入 binding 都创建新环境,旧环境保持不变。这样 closure 看到的是 declaration 时的 environment snapshot。

split

本书的实现继续使用 mutable Environment,但通过 resolver 在静态阶段计算 binding,并在运行时按距离访问,从而保持实现简单且语义正确。

Semantic analysis

Resolver 是 interpreter 之前的一次 AST traversal。它维护一个 scope stack,每个 scope 是 name 到“是否已定义”的 map。

遇到 var declaration 时,先 declare name,再 resolve initializer,最后 define name。这样 initializer 中读取同名变量会被诊断为“不能在自己的 initializer 中读取变量”。

遇到 variable expression 时,resolver 从内层 scope 向外查找 name,计算它距离当前 scope 的层数,并调用 interpreter.resolve(expression, distance)。global variable 如果不在 scope stack 中,则保留为 global lookup。

Resolver class

Resolver 实现 Expr.Visitor<Void> 和 Stmt.Visitor<Void>。beginScope() 压入新 map,endScope() 弹出 map。resolveLocal() 从 scope stack 的内层向外搜索,找到后记录 distance。

environment 3

block statement 创建 scope,解析其中 declarations 和 statements,再恢复外层 scope。嵌套 block 会产生多层 scope:

environment 4

function declaration 保存自己的 name,随后以 FUNCTION 类型进入新的 function scope,并把 parameters 标记为已定义,再解析 body。解析结束后恢复原来的 function context,避免嵌套函数的 return 状态泄漏。

environment 5

Interpreting resolved variables

Interpreter 为每个 Expr.Variable 和 Expr.Assign 节点保存 resolver 给出的 distance。读取时调用 Environment.getAt(distance, name),赋值时调用 assignAt(distance, name, value)。

global variable 没有静态 distance,继续使用 globals.get(name)。局部变量则直接跳到目标 Environment;这既正确处理 shadowing,也把 lookup 从运行时的重复链式搜索变成一次确定的访问。

Resolver 必须在 interpreter 开始执行前运行:

text
Scanner → Parser → Resolver → Interpreter

Resolution errors

Resolver 可以在运行前发现一类语义错误。return 出现在顶层时没有 enclosing function,应立即报告;return value 也可以根据当前 function 类型检查。

其他错误包括 initializer 中提前读取变量、重复声明同一 scope 的 name,以及未来 classes 章节中的 super/this 使用位置错误。将这些检查集中在 resolver 中,能让 interpreter 保持关注运行时行为。

Challenges

1. Persistent environments

实现 persistent Environment,并比较它与距离解析方案在内存占用、closure 语义和实现复杂度上的差异。

2. Resolution diagnostics

为 resolver 增加重复 declaration、未使用变量或不可达代码的诊断;说明哪些属于语言必需错误,哪些只是 lint。

3. Dynamic lookup

实现一个动态 scope 版本的 Lox,对比同一个 closure 程序在 lexical scope 和 dynamic scope 下的输出。

参考资料

Code block 1

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

Code block 2

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

Code block 3

text
{
  console.log(a);
  var a = "value";
}

Code block 4

text
{
  var a; // Hoist.
  console.log(a);
  a = "value";
}

Code block 5

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

Code block 6

text
var a = "global";
{
  fun showA() {
    print a;
  }

  showA();
  var a = "block";
  showA();
}

Code block 7

text
global
block

Code block 8

text
{
  var a;
  // 1.
  var b;
  // 2.
}

Code block 9

java
package com.craftinginterpreters.lox;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

class Resolver implements Expr.Visitor<Void>, Stmt.Visitor<Void> {
  private final Interpreter interpreter;

  Resolver(Interpreter interpreter) {
    this.interpreter = interpreter;
  }
}

Code block 10

java
  @Override
  public Void visitBlockStmt(Stmt.Block stmt) {
    beginScope();
    resolve(stmt.statements);
    endScope();
    return null;
  }

Code block 11

java
  void resolve(List<Stmt> statements) {
    for (Stmt statement : statements) {
      resolve(statement);
    }
  }

Code block 12

java
  private void resolve(Stmt stmt) {
    stmt.accept(this);
  }

Code block 13

java
  private void resolve(Expr expr) {
    expr.accept(this);
  }

Code block 14

java
  private void beginScope() {
    scopes.push(new HashMap<String, Boolean>());
  }

Code block 15

java
  private final Interpreter interpreter;

Code block 16

java
  private final Stack<Map<String, Boolean>> scopes = new Stack<>();

Code block 17

java
  Resolver(Interpreter interpreter) {

Code block 18

java
  private void endScope() {
    scopes.pop();
  }

Code block 19

java
  @Override
  public Void visitVarStmt(Stmt.Var stmt) {
    declare(stmt.name);
    if (stmt.initializer != null) {
      resolve(stmt.initializer);
    }
    define(stmt.name);
    return null;
  }

Code block 20

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

Code block 21

text
var temp = a; // Run the initializer.
var a;        // Declare the variable.
a = temp;     // Initialize it.

Code block 22

text
var a; // Define the variable.
a = a; // Run the initializer.

Code block 23

java
  private void declare(Token name) {
    if (scopes.isEmpty()) return;

    Map<String, Boolean> scope = scopes.peek();
    scope.put(name.lexeme, false);
  }

Code block 24

java
  private void define(Token name) {
    if (scopes.isEmpty()) return;
    scopes.peek().put(name.lexeme, true);
  }

Code block 25

java
  @Override
  public Void visitVariableExpr(Expr.Variable expr) {
    if (!scopes.isEmpty() &&
        scopes.peek().get(expr.name.lexeme) == Boolean.FALSE) {
      Lox.error(expr.name,
          "Can't read local variable in its own initializer.");
    }

    resolveLocal(expr, expr.name);
    return null;
  }

Code block 26

java
  private void resolveLocal(Expr expr, Token name) {
    for (int i = scopes.size() - 1; i >= 0; i--) {
      if (scopes.get(i).containsKey(name.lexeme)) {
        interpreter.resolve(expr, scopes.size() - 1 - i);
        return;
      }
    }
  }

Code block 27

java
  @Override
  public Void visitAssignExpr(Expr.Assign expr) {
    resolve(expr.value);
    resolveLocal(expr, expr.name);
    return null;
  }

Code block 28

java
  @Override
  public Void visitFunctionStmt(Stmt.Function stmt) {
    declare(stmt.name);
    define(stmt.name);

    resolveFunction(stmt);
    return null;
  }

Code block 29

java
  private void resolveFunction(Stmt.Function function) {
    beginScope();
    for (Token param : function.params) {
      declare(param);
      define(param);
    }
    resolve(function.body);
    endScope();
  }

Code block 30

java
  @Override
  public Void visitExpressionStmt(Stmt.Expression stmt) {
    resolve(stmt.expression);
    return null;
  }

Code block 31

java
  @Override
  public Void visitIfStmt(Stmt.If stmt) {
    resolve(stmt.condition);
    resolve(stmt.thenBranch);
    if (stmt.elseBranch != null) resolve(stmt.elseBranch);
    return null;
  }

Code block 32

java
  @Override
  public Void visitPrintStmt(Stmt.Print stmt) {
    resolve(stmt.expression);
    return null;
  }

Code block 33

java
  @Override
  public Void visitReturnStmt(Stmt.Return stmt) {
    if (stmt.value != null) {
      resolve(stmt.value);
    }

    return null;
  }

Code block 34

java
  @Override
  public Void visitWhileStmt(Stmt.While stmt) {
    resolve(stmt.condition);
    resolve(stmt.body);
    return null;
  }

Code block 35

java
  @Override
  public Void visitBinaryExpr(Expr.Binary expr) {
    resolve(expr.left);
    resolve(expr.right);
    return null;
  }

Code block 36

java
  @Override
  public Void visitCallExpr(Expr.Call expr) {
    resolve(expr.callee);

    for (Expr argument : expr.arguments) {
      resolve(argument);
    }

    return null;
  }

Code block 37

java
  @Override
  public Void visitGroupingExpr(Expr.Grouping expr) {
    resolve(expr.expression);
    return null;
  }

Code block 38

java
  @Override
  public Void visitLiteralExpr(Expr.Literal expr) {
    return null;
  }

Code block 39

java
  @Override
  public Void visitLogicalExpr(Expr.Logical expr) {
    resolve(expr.left);
    resolve(expr.right);
    return null;
  }

Code block 40

java
  @Override
  public Void visitUnaryExpr(Expr.Unary expr) {
    resolve(expr.right);
    return null;
  }

Code block 41

java
  void resolve(Expr expr, int depth) {
    locals.put(expr, depth);
  }

Code block 42

java
  private Environment environment = globals;

Code block 43

java
  private final Map<Expr, Integer> locals = new HashMap<>();

Code block 44

text
  Interpreter() {

Code block 45

java
import java.util.ArrayList;

Code block 46

java
import java.util.HashMap;

Code block 47

java
import java.util.List;

Code block 48

java
import java.util.List;

Code block 49

java
import java.util.Map;

Code block 50

java
class Interpreter implements Expr.Visitor<Object>,

Code block 51

java
  public Object visitVariableExpr(Expr.Variable expr) {

Code block 52

java
    return lookUpVariable(expr.name, expr);

Code block 53

text
  }

Code block 54

java
  private Object lookUpVariable(Token name, Expr expr) {
    Integer distance = locals.get(expr);
    if (distance != null) {
      return environment.getAt(distance, name.lexeme);
    } else {
      return globals.get(name);
    }
  }

Code block 55

java
  Object getAt(int distance, String name) {
    return ancestor(distance).values.get(name);
  }

Code block 56

java
  Environment ancestor(int distance) {
    Environment environment = this;
    for (int i = 0; i < distance; i++) {
      environment = environment.enclosing; 
    }

    return environment;
  }

Code block 57

java
  public Object visitAssignExpr(Expr.Assign expr) {
    Object value = evaluate(expr.value);

Code block 58

java
    Integer distance = locals.get(expr);
    if (distance != null) {
      environment.assignAt(distance, expr.name, value);
    } else {
      globals.assign(expr.name, value);
    }

Code block 59

java
    return value;

Code block 60

java
  void assignAt(int distance, Token name, Object value) {
    ancestor(distance).values.put(name.lexeme, value);
  }

Code block 61

java
    // Stop if there was a syntax error.
    if (hadError) return;

Code block 62

java
    Resolver resolver = new Resolver(interpreter);
    resolver.resolve(statements);

Code block 63

text
    interpreter.interpret(statements);

Code block 64

text
fun bad() {
  var a = "first";
  var a = "second";
}

Code block 65

java
    Map<String, Boolean> scope = scopes.peek();

Code block 66

java
    if (scope.containsKey(name.lexeme)) {
      Lox.error(name,
          "Already a variable with this name in this scope.");
    }

Code block 67

text
    scope.put(name.lexeme, false);

Code block 68

java
return "at top level";

Code block 69

java
  private final Stack<Map<String, Boolean>> scopes = new Stack<>();

Code block 70

java
  private FunctionType currentFunction = FunctionType.NONE;

Code block 71

java
  Resolver(Interpreter interpreter) {

Code block 72

java
  private enum FunctionType {
    NONE,
    FUNCTION
  }

Code block 73

text
    define(stmt.name);

Code block 74

java
    resolveFunction(stmt, FunctionType.FUNCTION);

Code block 75

java
    return null;

Code block 76

java
  private void resolveFunction(
      Stmt.Function function, FunctionType type) {
    FunctionType enclosingFunction = currentFunction;
    currentFunction = type;

Code block 77

text
    beginScope();

Code block 78

text
    endScope();

Code block 79

text
    currentFunction = enclosingFunction;

Code block 80

text
  }

Code block 81

java
  public Void visitReturnStmt(Stmt.Return stmt) {

Code block 82

java
    if (currentFunction == FunctionType.NONE) {
      Lox.error(stmt.keyword, "Can't return from top-level code.");
    }

Code block 83

java
    if (stmt.value != null) {

Code block 84

text
    resolver.resolve(statements);

Code block 85

java
    // Stop if there was a resolution error.
    if (hadError) return;

Code block 86

text
    interpreter.interpret(statements);

Code block 87

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

参考资料

← 返回列表
← 上一篇 Functions:调用、返回与 closure 下一篇 → Classes:对象、方法与 this 绑定

评论 (0)

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