Resolving and Binding:静态作用域与变量解析
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 scope | lexical scope 与 environment |
| Semantic analysis | resolver 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。

Scopes and mutable environments
最直接的修复是让每个 variable expression 在 resolver 中记录 scope distance。运行时知道应该向 enclosing 链走几层,就能准确找到 lexical binding。
如果 resolver 直接修改共享的 mutable Environment,变量 declaration 前后的环境状态可能互相影响。尤其是 closure 捕获了 environment 后,后续声明会改变同一个 map 的内容:

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

本书的实现继续使用 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。

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

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

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 开始执行前运行:
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
var a = "outer";
{
var a = "inner";
print a;
}
Code block 2
var a = "outer";
{
print a;
var a = "inner";
}
Code block 3
{
console.log(a);
var a = "value";
}
Code block 4
{
var a; // Hoist.
console.log(a);
a = "value";
}
Code block 5
var a = "outer";
{
var a = "inner";
print a;
}
Code block 6
var a = "global";
{
fun showA() {
print a;
}
showA();
var a = "block";
showA();
}
Code block 7
global
block
Code block 8
{
var a;
// 1.
var b;
// 2.
}
Code block 9
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
@Override
public Void visitBlockStmt(Stmt.Block stmt) {
beginScope();
resolve(stmt.statements);
endScope();
return null;
}
Code block 11
void resolve(List<Stmt> statements) {
for (Stmt statement : statements) {
resolve(statement);
}
}
Code block 12
private void resolve(Stmt stmt) {
stmt.accept(this);
}
Code block 13
private void resolve(Expr expr) {
expr.accept(this);
}
Code block 14
private void beginScope() {
scopes.push(new HashMap<String, Boolean>());
}
Code block 15
private final Interpreter interpreter;
Code block 16
private final Stack<Map<String, Boolean>> scopes = new Stack<>();
Code block 17
Resolver(Interpreter interpreter) {
Code block 18
private void endScope() {
scopes.pop();
}
Code block 19
@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
var a = "outer";
{
var a = a;
}
Code block 21
var temp = a; // Run the initializer.
var a; // Declare the variable.
a = temp; // Initialize it.
Code block 22
var a; // Define the variable.
a = a; // Run the initializer.
Code block 23
private void declare(Token name) {
if (scopes.isEmpty()) return;
Map<String, Boolean> scope = scopes.peek();
scope.put(name.lexeme, false);
}
Code block 24
private void define(Token name) {
if (scopes.isEmpty()) return;
scopes.peek().put(name.lexeme, true);
}
Code block 25
@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
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
@Override
public Void visitAssignExpr(Expr.Assign expr) {
resolve(expr.value);
resolveLocal(expr, expr.name);
return null;
}
Code block 28
@Override
public Void visitFunctionStmt(Stmt.Function stmt) {
declare(stmt.name);
define(stmt.name);
resolveFunction(stmt);
return null;
}
Code block 29
private void resolveFunction(Stmt.Function function) {
beginScope();
for (Token param : function.params) {
declare(param);
define(param);
}
resolve(function.body);
endScope();
}
Code block 30
@Override
public Void visitExpressionStmt(Stmt.Expression stmt) {
resolve(stmt.expression);
return null;
}
Code block 31
@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
@Override
public Void visitPrintStmt(Stmt.Print stmt) {
resolve(stmt.expression);
return null;
}
Code block 33
@Override
public Void visitReturnStmt(Stmt.Return stmt) {
if (stmt.value != null) {
resolve(stmt.value);
}
return null;
}
Code block 34
@Override
public Void visitWhileStmt(Stmt.While stmt) {
resolve(stmt.condition);
resolve(stmt.body);
return null;
}
Code block 35
@Override
public Void visitBinaryExpr(Expr.Binary expr) {
resolve(expr.left);
resolve(expr.right);
return null;
}
Code block 36
@Override
public Void visitCallExpr(Expr.Call expr) {
resolve(expr.callee);
for (Expr argument : expr.arguments) {
resolve(argument);
}
return null;
}
Code block 37
@Override
public Void visitGroupingExpr(Expr.Grouping expr) {
resolve(expr.expression);
return null;
}
Code block 38
@Override
public Void visitLiteralExpr(Expr.Literal expr) {
return null;
}
Code block 39
@Override
public Void visitLogicalExpr(Expr.Logical expr) {
resolve(expr.left);
resolve(expr.right);
return null;
}
Code block 40
@Override
public Void visitUnaryExpr(Expr.Unary expr) {
resolve(expr.right);
return null;
}
Code block 41
void resolve(Expr expr, int depth) {
locals.put(expr, depth);
}
Code block 42
private Environment environment = globals;
Code block 43
private final Map<Expr, Integer> locals = new HashMap<>();
Code block 44
Interpreter() {
Code block 45
import java.util.ArrayList;
Code block 46
import java.util.HashMap;
Code block 47
import java.util.List;
Code block 48
import java.util.List;
Code block 49
import java.util.Map;
Code block 50
class Interpreter implements Expr.Visitor<Object>,
Code block 51
public Object visitVariableExpr(Expr.Variable expr) {
Code block 52
return lookUpVariable(expr.name, expr);
Code block 53
}
Code block 54
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
Object getAt(int distance, String name) {
return ancestor(distance).values.get(name);
}
Code block 56
Environment ancestor(int distance) {
Environment environment = this;
for (int i = 0; i < distance; i++) {
environment = environment.enclosing;
}
return environment;
}
Code block 57
public Object visitAssignExpr(Expr.Assign expr) {
Object value = evaluate(expr.value);
Code block 58
Integer distance = locals.get(expr);
if (distance != null) {
environment.assignAt(distance, expr.name, value);
} else {
globals.assign(expr.name, value);
}
Code block 59
return value;
Code block 60
void assignAt(int distance, Token name, Object value) {
ancestor(distance).values.put(name.lexeme, value);
}
Code block 61
// Stop if there was a syntax error.
if (hadError) return;
Code block 62
Resolver resolver = new Resolver(interpreter);
resolver.resolve(statements);
Code block 63
interpreter.interpret(statements);
Code block 64
fun bad() {
var a = "first";
var a = "second";
}
Code block 65
Map<String, Boolean> scope = scopes.peek();
Code block 66
if (scope.containsKey(name.lexeme)) {
Lox.error(name,
"Already a variable with this name in this scope.");
}
Code block 67
scope.put(name.lexeme, false);
Code block 68
return "at top level";
Code block 69
private final Stack<Map<String, Boolean>> scopes = new Stack<>();
Code block 70
private FunctionType currentFunction = FunctionType.NONE;
Code block 71
Resolver(Interpreter interpreter) {
Code block 72
private enum FunctionType {
NONE,
FUNCTION
}
Code block 73
define(stmt.name);
Code block 74
resolveFunction(stmt, FunctionType.FUNCTION);
Code block 75
return null;
Code block 76
private void resolveFunction(
Stmt.Function function, FunctionType type) {
FunctionType enclosingFunction = currentFunction;
currentFunction = type;
Code block 77
beginScope();
Code block 78
endScope();
Code block 79
currentFunction = enclosingFunction;
Code block 80
}
Code block 81
public Void visitReturnStmt(Stmt.Return stmt) {
Code block 82
if (currentFunction == FunctionType.NONE) {
Lox.error(stmt.keyword, "Can't return from top-level code.");
}
Code block 83
if (stmt.value != null) {
Code block 84
resolver.resolve(statements);
Code block 85
// Stop if there was a resolution error.
if (hadError) return;
Code block 86
interpreter.interpret(statements);
Code block 87
var a = "outer";
{
var a = a;
}
参考资料
- 原文:Resolving and Binding
- 系列索引
- Robert Nystrom, Crafting Interpreters,© 2015–2021
评论 (0)