Statements and State:变量、环境与 lexical scope
Crafting Interpreters:Statements and State
本章让 Lox 从只能计算 expression,扩展为能执行 statements、保存变量状态,并支持 assignment、block 和 lexical scope。
TL;DR
- Expression 产生 value,statement 产生 effect;AST 因此需要独立的 Stmt hierarchy。
- Environment 用一个从 name 到 value 的 map 表示 scope,并通过 enclosing 链连接嵌套 scope。
- var declaration、assignment 和 variable access 都必须在 parser、AST、interpreter 三层同时接入。
- block 创建临时 Environment;离开 block 后恢复旧 environment,从而实现 lexical scope 和 shadowing。
- assignment 不是新的 declaration:它沿 enclosing 链寻找已有 binding,找不到时报告运行时错误。
目录
| 章节 | 内容 |
|---|---|
| Statements | statement AST、parsing 与 execution |
| Global Variables | declaration 与 global environment |
| Environments | binding 的保存与查找 |
| Assignment | 更新已有变量 |
| Scope | block、嵌套与 shadowing |
| Challenges | 扩展练习 |
| Design Note:Implicit Variable Declaration | 隐式声明的语言设计 |
Statements
到目前为止,Lox 程序只有一个 expression。我们现在加入 statement:它通常不产生需要嵌套到其他 expression 中的 value,而是改变状态或触发行为。因此需要为 statements 建立独立的 syntax tree hierarchy,并让 parser 返回一组 statements。
Expression node 通过 Visitor 返回 Object;statement visitor 则返回 void。这样类型层面就能表达两者的不同语义。

最简单的 statement 是 expression statement:解析一个 expression,然后要求分号。执行时 evaluate 它并丢弃结果。print statement 则计算 expression 并把结果格式化后输出。
Parser 的入口从 parse single expression 改成循环读取 declarations,直到 EOF。每一次读取 declaration 都返回一个 Stmt;syntax error 时进入 panic mode,synchronize 到下一个 statement 边界,然后继续 parsing。
Global Variables
变量需要三个部分:声明、读取和更新。var declaration 可以没有 initializer,此时初始值为 nil;有 initializer 时先解析并计算它。

Global environment 是一个 Environment 实例,保存顶层 name/value bindings。解释 variable expression 时,在 environment 中按 token.lexeme 查找;解释 var statement 时,计算 initializer 后定义 binding。
变量名本身在 parser 中只是 identifier token。真正的 name resolution 发生在 interpreter 的 environment lookup 中,因此本章的变量是 dynamic lookup,后续章节再优化 lexical resolution。
Environments
Environment 内部使用 map:
class Environment {
private final Map<String, Object> values = new HashMap<>();
final Environment enclosing;
Environment() {
enclosing = null;
}
Environment(Environment enclosing) {
this.enclosing = enclosing;
}
}
define 直接写入当前 map。get 先查询当前 environment;找不到时递归查询 enclosing;到达 null 仍找不到,就抛出 RuntimeError。这样嵌套 scope 能看到外层变量,但外层 scope 看不到内层 binding。

Assignment
assignment expression 既要计算右值,也要把结果写回变量。它和 declaration 的关键区别是:assignment 必须找到已经存在的 binding;不能因为 assignment 自动创建变量。
Parser 先解析普通 expression。如果发现等号,就把左侧解析结果转换为 assignment target。Lox 当前只有 variable target,因此左侧必须是 Variable expression;否则报告 invalid assignment target。
Interpreter 先 evaluate value,再调用 environment.assign(name, value)。assign 和 get 使用同一条 enclosing 链。如果当前 scope 和外层都没有该变量,就报告 undefined variable。
Scope
Scope 是变量可见性的规则。最外层是 global scope;block 会创建一个新 scope。执行 block 时保存旧 environment,把 interpreter.environment 切换为新的 Environment;执行结束后用 finally 恢复旧值,确保 runtime error 也不会污染后续状态。

嵌套 block 通过 enclosing 链形成 scope chain:
current block → enclosing block → global
声明同名变量时,内层 binding 会 shadow 外层 binding。读取变量从 current environment 开始,所以先命中最近的 declaration。离开内层 block 后,外层变量仍保持原值。

这里的 scope 是 lexical scope:可见性由 source code 的嵌套结构决定,而不是由函数调用时的动态路径决定。后续函数章节会进一步展示为什么需要 resolver,把每个 variable expression 绑定到静态距离。
Challenges
1. Initializer self-reference
决定 var a = a; 应如何处理。实现一致的规则并写出测试:是读取旧的 outer binding,还是报告变量尚未初始化?
2. Block result
为 block 增加一个 value,使其可以作为 expression 使用。需要明确空 block、多条 statement 和最后一条 statement 的语义。
3. Environment operations
为 Environment 增加删除 binding、枚举当前 scope 和检查当前 scope 是否包含 name 的操作,并说明哪些操作可能破坏 shadowing 语义。
Design Note:Implicit Variable Declaration
有些语言允许对未声明变量直接赋值,并把它当作 declaration;另一些语言要求显式 var、let 或其他声明语法。
隐式 declaration 可以减少样板代码,让小脚本写起来更快,但拼写错误会悄悄创建新变量:
counter = 0
conter = conter + 1
如果语言允许隐式声明,第二行可能不会立即报错,而是产生一个错误的新 binding。显式 declaration 则会把这类问题更早暴露出来,但要求用户记住更多语法。
选择哪种设计,取决于语言定位。交互式 scripting 可能偏好便利;大型程序通常更需要拼写错误能快速失败。重要的是让 scope、assignment 和 declaration 的规则彼此一致,并在错误位置给出清晰诊断。
原文代码片段
本节按官方页面顺序保留本章所有 grammar、Java 和测试代码片段,便于与上文译文逐段对照。
参考资料
Code block 1
program → statement* EOF ;
statement → exprStmt
| printStmt ;
exprStmt → expression ";" ;
printStmt → "print" expression ";" ;
Code block 2
"Unary : Token operator, Expr right"
));
Code block 3
defineAst(outputDir, "Stmt", Arrays.asList(
"Expression : Expr expression",
"Print : Expr expression"
));
Code block 4
}
Code block 5
List<Stmt> parse() {
List<Stmt> statements = new ArrayList<>();
while (!isAtEnd()) {
statements.add(statement());
}
return statements;
}
Code block 6
package com.craftinginterpreters.lox;
Code block 7
import java.util.ArrayList;
Code block 8
import java.util.List;
Code block 9
private Stmt statement() {
if (match(PRINT)) return printStatement();
return expressionStatement();
}
Code block 10
private Stmt printStatement() {
Expr value = expression();
consume(SEMICOLON, "Expect ';' after value.");
return new Stmt.Print(value);
}
Code block 11
private Stmt expressionStatement() {
Expr expr = expression();
consume(SEMICOLON, "Expect ';' after expression.");
return new Stmt.Expression(expr);
}
Code block 12
class Interpreter implements Expr.Visitor<Object>,
Stmt.Visitor<Void> {
Code block 13
void interpret(Expr expression) {
Code block 14
@Override
public Void visitExpressionStmt(Stmt.Expression stmt) {
evaluate(stmt.expression);
return null;
}
Code block 15
@Override
public Void visitPrintStmt(Stmt.Print stmt) {
Object value = evaluate(stmt.expression);
System.out.println(stringify(value));
return null;
}
Code block 16
void interpret(List<Stmt> statements) {
try {
for (Stmt statement : statements) {
execute(statement);
}
} catch (RuntimeError error) {
Lox.runtimeError(error);
}
}
Code block 17
private void execute(Stmt stmt) {
stmt.accept(this);
}
Code block 18
package com.craftinginterpreters.lox;
Code block 19
import java.util.List;
Code block 20
class Interpreter implements Expr.Visitor<Object>,
Code block 21
Parser parser = new Parser(tokens);
Code block 22
List<Stmt> statements = parser.parse();
Code block 23
// Stop if there was a syntax error.
Code block 24
if (hadError) return;
Code block 25
interpreter.interpret(statements);
Code block 26
}
Code block 27
print "one";
print true;
print 2 + 1;
Code block 28
var beverage = "espresso";
Code block 29
print beverage; // "espresso".
Code block 30
if (monday) print "Ugh, already?";
Code block 31
if (monday) var beverage = "espresso";
Code block 32
program → declaration* EOF ;
declaration → varDecl
| statement ;
statement → exprStmt
| printStmt ;
Code block 33
varDecl → "var" IDENTIFIER ( "=" expression )? ";" ;
Code block 34
primary → "true" | "false" | "nil"
| NUMBER | STRING
| "(" expression ")"
| IDENTIFIER ;
Code block 35
"Expression : Expr expression",
Code block 36
"Print : Expr expression",
Code block 37
"Var : Token name, Expr initializer"
Code block 38
));
Code block 39
"Literal : Object value",
Code block 40
"Unary : Token operator, Expr right",
Code block 41
"Variable : Token name"
Code block 42
));
Code block 43
List<Stmt> parse() {
List<Stmt> statements = new ArrayList<>();
while (!isAtEnd()) {
Code block 44
statements.add(declaration());
Code block 45
}
return statements;
}
Code block 46
private Stmt declaration() {
try {
if (match(VAR)) return varDeclaration();
return statement();
} catch (ParseError error) {
synchronize();
return null;
}
}
Code block 47
private Stmt varDeclaration() {
Token name = consume(IDENTIFIER, "Expect variable name.");
Expr initializer = null;
if (match(EQUAL)) {
initializer = expression();
}
consume(SEMICOLON, "Expect ';' after variable declaration.");
return new Stmt.Var(name, initializer);
}
Code block 48
return new Expr.Literal(previous().literal);
}
Code block 49
if (match(IDENTIFIER)) {
return new Expr.Variable(previous());
}
Code block 50
if (match(LEFT_PAREN)) {
Code block 51
package com.craftinginterpreters.lox;
import java.util.HashMap;
import java.util.Map;
class Environment {
private final Map<String, Object> values = new HashMap<>();
}
Code block 52
void define(String name, Object value) {
values.put(name, value);
}
Code block 53
var a = "before";
print a; // "before".
var a = "after";
print a; // "after".
Code block 54
class Environment {
private final Map<String, Object> values = new HashMap<>();
Code block 55
Object get(Token name) {
if (values.containsKey(name.lexeme)) {
return values.get(name.lexeme);
}
throw new RuntimeError(name,
"Undefined variable '" + name.lexeme + "'.");
}
Code block 56
void define(String name, Object value) {
Code block 57
fun isOdd(n) {
if (n == 0) return false;
return isEven(n - 1);
}
fun isEven(n) {
if (n == 0) return true;
return isOdd(n - 1);
}
Code block 58
print a;
var a = "too late!";
Code block 59
class Interpreter implements Expr.Visitor<Object>,
Stmt.Visitor<Void> {
Code block 60
private Environment environment = new Environment();
Code block 61
void interpret(List<Stmt> statements) {
Code block 62
@Override
public Void visitVarStmt(Stmt.Var stmt) {
Object value = null;
if (stmt.initializer != null) {
value = evaluate(stmt.initializer);
}
environment.define(stmt.name.lexeme, value);
return null;
}
Code block 63
var a;
print a; // "nil".
Code block 64
@Override
public Object visitVariableExpr(Expr.Variable expr) {
return environment.get(expr.name);
}
Code block 65
var a = 1;
var b = 2;
print a + b;
Code block 66
expression → assignment ;
assignment → IDENTIFIER "=" assignment
| equality ;
Code block 67
instance.field = "value";
Code block 68
defineAst(outputDir, "Expr", Arrays.asList(
Code block 69
"Assign : Token name, Expr value",
Code block 70
"Binary : Expr left, Token operator, Expr right",
Code block 71
private Expr expression() {
Code block 72
return assignment();
Code block 73
}
Code block 74
var a = "before";
a = "value";
Code block 75
makeList().head.next = node;
Code block 76
private Expr assignment() {
Expr expr = equality();
if (match(EQUAL)) {
Token equals = previous();
Expr value = assignment();
if (expr instanceof Expr.Variable) {
Token name = ((Expr.Variable)expr).name;
return new Expr.Assign(name, value);
}
error(equals, "Invalid assignment target.");
}
return expr;
}
Code block 77
newPoint(x + 2, 0).y = 3;
Code block 78
newPoint(x + 2, 0).y;
Code block 79
a + b = c;
Code block 80
a = 3; // OK.
(a) = 3; // Error.
Code block 81
@Override
public Object visitAssignExpr(Expr.Assign expr) {
Object value = evaluate(expr.value);
environment.assign(expr.name, value);
return value;
}
Code block 82
void assign(Token name, Object value) {
if (values.containsKey(name.lexeme)) {
values.put(name.lexeme, value);
return;
}
throw new RuntimeError(name,
"Undefined variable '" + name.lexeme + "'.");
}
Code block 83
var a = 1;
print a = 2; // "2".
Code block 84
{
var a = "first";
print a; // "first".
}
{
var a = "second";
print a; // "second".
}
Code block 85
class Saxophone {
play() {
print "Careless Whisper";
}
}
class GolfClub {
play() {
print "Fore!";
}
}
fun playIt(thing) {
thing.play();
}
Code block 86
{
var a = "in block";
}
print a; // Error! No more "a".
Code block 87
// How loud?
var volume = 11;
// Silence.
volume = 0;
// Calculate size of 3x4x5 cuboid.
{
var volume = 3 * 4 * 5;
print volume;
}
Code block 88
var global = "outside";
{
var local = "inside";
print global + local;
}
Code block 89
class Environment {
Code block 90
final Environment enclosing;
Code block 91
private final Map<String, Object> values = new HashMap<>();
Code block 92
Environment() {
enclosing = null;
}
Environment(Environment enclosing) {
this.enclosing = enclosing;
}
Code block 93
return values.get(name.lexeme);
}
Code block 94
if (enclosing != null) return enclosing.get(name);
Code block 95
throw new RuntimeError(name,
"Undefined variable '" + name.lexeme + "'.");
Code block 96
values.put(name.lexeme, value);
return;
}
Code block 97
if (enclosing != null) {
enclosing.assign(name, value);
return;
}
Code block 98
throw new RuntimeError(name,
Code block 99
statement → exprStmt
| printStmt
| block ;
block → "{" declaration* "}" ;
Code block 100
defineAst(outputDir, "Stmt", Arrays.asList(
Code block 101
"Block : List<Stmt> statements",
Code block 102
"Expression : Expr expression",
Code block 103
if (match(PRINT)) return printStatement();
Code block 104
if (match(LEFT_BRACE)) return new Stmt.Block(block());
Code block 105
return expressionStatement();
Code block 106
private List<Stmt> block() {
List<Stmt> statements = new ArrayList<>();
while (!check(RIGHT_BRACE) && !isAtEnd()) {
statements.add(declaration());
}
consume(RIGHT_BRACE, "Expect '}' after block.");
return statements;
}
Code block 107
@Override
public Void visitBlockStmt(Stmt.Block stmt) {
executeBlock(stmt.statements, new Environment(environment));
return null;
}
Code block 108
void executeBlock(List<Stmt> statements,
Environment environment) {
Environment previous = this.environment;
try {
this.environment = environment;
for (Stmt statement : statements) {
execute(statement);
}
} finally {
this.environment = previous;
}
}
Code block 109
var a = "global a";
var b = "global b";
var c = "global c";
{
var a = "outer a";
var b = "outer b";
{
var a = "inner a";
print a;
print b;
print c;
}
print a;
print b;
print c;
}
print a;
print b;
print c;
Code block 110
// No initializers.
var a;
var b;
a = "assigned";
print a; // OK, was assigned first.
print b; // Error!
Code block 111
var a = 1;
{
var a = a + 2;
print a;
}
参考资料
- 原文:Statements and State
- 系列索引
- Robert Nystrom, Crafting Interpreters,© 2015–2021
评论 (0)