Evaluating Expressions:实现 Lox expression interpreter
Crafting Interpreters:Evaluating Expressions
本章为 Lox expression tree 添加 interpreter:从 Literal、Grouping、Unary 到 Binary,递归求值并处理 runtime error。
TL;DR
- Interpreter 直接访问 syntax tree;每种 Expr 节点在 Visitor 中对应一个 evaluate 方法。
- Lox 使用 Java 的 Object 表示运行时值,number、string、boolean 和 nil 都共享同一个宿主类型。
- evaluation 的顺序是语法语义的一部分;binary expression 先计算左侧,再计算右侧。
- Truthiness、equality、comparison 和 arithmetic 必须由语言自己定义,不能无意中继承 Java 的规则。
- Runtime error 应在解释器边界被捕获并报告,同时保留 source token 的位置。
目录
| 章节 | 内容 |
|---|---|
| Representing values | Lox 运行时值 |
| The interpreter | Visitor 驱动的递归求值 |
| Runtime errors | 运行时错误与诊断 |
| Hooking up the interpreter | 接入 Lox 主流程 |
| Challenges | 扩展练习 |
| Design Note:Static and Dynamic Typing | 类型检查时机 |
Representing values
现在 parser 已经能把 source 变成 syntax tree,下一步是执行它。Interpreter 不需要把树重新转换成另一种形式,而是遍历每个节点,在访问节点时计算它的值。
Lox 的运行时值先用 Java 的 Object 表示。这样一个字段可以保存 Double、String、Boolean 或 null。Lox 的 nil 对应 Java 的 null。这个选择简化了第一版 interpreter,但也意味着之后需要集中处理 Java null,避免空指针错误泄漏到 Lox 用户面前。
The interpreter
Interpreter 实现 Expr.Visitor<Object>。每个 visit 方法接收一个 AST node,并返回该表达式在 Lox 中产生的值:
class Interpreter implements Expr.Visitor<Object> {
Object evaluate(Expr expr) {
return expr.accept(this);
}
}
Evaluating literals
Literal 节点已经保存了 scanner 产生的 Java value,因此直接返回 node.literal:
public Object visitLiteralExpr(Expr.Literal expr) {
return expr.value;
}
Evaluating parentheses
Grouping 节点的语义就是计算内部 expression:
public Object visitGroupingExpr(Expr.Grouping expr) {
return evaluate(expr.expression);
}

Evaluating unary expressions
Unary expression 先递归计算 operand,再依据 operator 应用对应操作。minus 要求 operand 为 number;bang 使用 Lox 的 truthiness 规则。
public Object visitUnaryExpr(Expr.Unary expr) {
Object right = evaluate(expr.right);
switch (expr.operator.type) {
case MINUS:
checkNumberOperand(expr.operator, right);
return -(double)right;
case BANG:
return !isTruthy(right);
}
return null;
}

Truthiness and falsiness
Lox 的 truthiness 很简单:只有 false 和 nil 是 falsey,其他值都是真值,包括 0 和空字符串。这与 Java、JavaScript 或 Python 的默认规则都不完全相同,所以必须显式写出:
private boolean isTruthy(Object object) {
if (object == null) return false;
if (object instanceof Boolean) return (boolean)object;
return true;
}
Evaluating binary operators
Binary expression 先求值左 operand,再求值右 operand,然后根据 operator 分支。加法既支持两个 number,也支持两个 string;其他类型组合报告 runtime error。比较运算要求两个 number,equality 则允许任意类型并使用语言定义的 isEqual。

Runtime errors
Parser 的 syntax error 发生在 code 还没有形成合法 AST 时;runtime error 则发生在 AST 合法、但执行时操作数不满足语义要求的情况下。例如:
-"hello"
3 + true
这些错误不能由 parser 解决。Interpreter 在执行具体 operator 前检查 operand 类型,发现问题就抛出 RuntimeError。异常携带 token,因此错误报告可以指出 source 中的准确位置。
Runtime error 不应让 Java exception stack trace 直接暴露给 Lox 用户。Lox 主流程捕获 RuntimeError,打印 token 行号与 message,并设置 hadRuntimeError,最终以非零状态退出。
Hooking up the interpreter
Lox 的执行管线变成:
source → Scanner → tokens → Parser → Expr → Interpreter → result
主类在扫描和 parsing 成功后调用 interpreter.interpret(expression)。如果 parser 设置了 hadError,就跳过解释;如果 interpreter 捕获 runtime error,则按语言约定报告并退出。
完成后,输入 expression 就能看到真正的运行结果,而不是 AST 的括号表示。此时 Lox 已经具备一个完整的、可执行的 expression evaluator。
Challenges
1. String concatenation
目前加法只允许两个 number 或两个 string。扩展它,使 number 与 string 的组合也有明确行为;同时说明为什么隐式转换可能给语言用户带来惊喜。
2. Division by zero
决定 Lox 对除以零的行为。IEEE 754 floating point 会产生 Infinity 或 NaN;语言是否应保留这种行为,还是报告 runtime error?
3. Native operators
为更多 number operator 添加实现,并保证 operand 校验、错误位置和结果类型一致。
Design Note:Static and Dynamic Typing
Lox 是 dynamically typed language:变量和表达式本身不需要预先声明类型,类型检查在运行时进行。这样可以快速开始,也让语言保持轻量,但错误会推迟到执行相关代码路径时才出现。
Static typing 则在运行前检查类型,能够更早发现一类错误,也允许 compiler 根据类型信息优化代码;代价是语言规则、类型推断和错误信息都会更复杂。
这里没有脱离语言目标的绝对优劣。小型 scripting language 可能更看重交互速度和表达自由;大型工程可能更看重 refactoring 工具、接口约束和尽早反馈。关键是明确哪些错误应由 parser、static checker 或 runtime 负责。
原文代码片段
本节按官方页面顺序保留本章所有 grammar、Java 和测试代码片段,便于与上文译文逐段对照。
参考资料
Code block 1
package com.craftinginterpreters.lox;
class Interpreter implements Expr.Visitor<Object> {
}
Code block 2
@Override
public Object visitLiteralExpr(Expr.Literal expr) {
return expr.value;
}
Code block 3
@Override
public Object visitGroupingExpr(Expr.Grouping expr) {
return evaluate(expr.expression);
}
Code block 4
private Object evaluate(Expr expr) {
return expr.accept(this);
}
Code block 5
@Override
public Object visitUnaryExpr(Expr.Unary expr) {
Object right = evaluate(expr.right);
switch (expr.operator.type) {
case MINUS:
return -(double)right;
}
// Unreachable.
return null;
}
Code block 6
switch (expr.operator.type) {
Code block 7
case BANG:
return !isTruthy(right);
Code block 8
case MINUS:
Code block 9
private boolean isTruthy(Object object) {
if (object == null) return false;
if (object instanceof Boolean) return (boolean)object;
return true;
}
Code block 10
@Override
public Object visitBinaryExpr(Expr.Binary expr) {
Object left = evaluate(expr.left);
Object right = evaluate(expr.right);
switch (expr.operator.type) {
case MINUS:
return (double)left - (double)right;
case SLASH:
return (double)left / (double)right;
case STAR:
return (double)left * (double)right;
}
// Unreachable.
return null;
}
Code block 11
switch (expr.operator.type) {
case MINUS:
return (double)left - (double)right;
Code block 12
case PLUS:
if (left instanceof Double && right instanceof Double) {
return (double)left + (double)right;
}
if (left instanceof String && right instanceof String) {
return (String)left + (String)right;
}
break;
Code block 13
case SLASH:
Code block 14
switch (expr.operator.type) {
Code block 15
case GREATER:
return (double)left > (double)right;
case GREATER_EQUAL:
return (double)left >= (double)right;
case LESS:
return (double)left < (double)right;
case LESS_EQUAL:
return (double)left <= (double)right;
Code block 16
case MINUS:
Code block 17
case BANG_EQUAL: return !isEqual(left, right);
case EQUAL_EQUAL: return isEqual(left, right);
Code block 18
private boolean isEqual(Object a, Object b) {
if (a == null && b == null) return true;
if (a == null) return false;
return a.equals(b);
}
Code block 19
(0 / 0) == (0 / 0)
Code block 20
2 * (3 / -"muffin")
Code block 21
case MINUS:
Code block 22
checkNumberOperand(expr.operator, right);
Code block 23
return -(double)right;
Code block 24
private void checkNumberOperand(Token operator, Object operand) {
if (operand instanceof Double) return;
throw new RuntimeError(operator, "Operand must be a number.");
}
Code block 25
package com.craftinginterpreters.lox;
class RuntimeError extends RuntimeException {
final Token token;
RuntimeError(Token token, String message) {
super(message);
this.token = token;
}
}
Code block 26
case GREATER:
Code block 27
checkNumberOperands(expr.operator, left, right);
Code block 28
return (double)left > (double)right;
Code block 29
case GREATER_EQUAL:
Code block 30
checkNumberOperands(expr.operator, left, right);
Code block 31
return (double)left >= (double)right;
Code block 32
case LESS:
Code block 33
checkNumberOperands(expr.operator, left, right);
Code block 34
return (double)left < (double)right;
Code block 35
case LESS_EQUAL:
Code block 36
checkNumberOperands(expr.operator, left, right);
Code block 37
return (double)left <= (double)right;
Code block 38
case MINUS:
Code block 39
checkNumberOperands(expr.operator, left, right);
Code block 40
return (double)left - (double)right;
Code block 41
case SLASH:
Code block 42
checkNumberOperands(expr.operator, left, right);
Code block 43
return (double)left / (double)right;
Code block 44
case STAR:
Code block 45
checkNumberOperands(expr.operator, left, right);
Code block 46
return (double)left * (double)right;
Code block 47
private void checkNumberOperands(Token operator,
Object left, Object right) {
if (left instanceof Double && right instanceof Double) return;
throw new RuntimeError(operator, "Operands must be numbers.");
}
Code block 48
say("left") - say("right");
Code block 49
return (String)left + (String)right;
}
Code block 50
throw new RuntimeError(expr.operator,
"Operands must be two numbers or two strings.");
Code block 51
case SLASH:
Code block 52
void interpret(Expr expression) {
try {
Object value = evaluate(expression);
System.out.println(stringify(value));
} catch (RuntimeError error) {
Lox.runtimeError(error);
}
}
Code block 53
private String stringify(Object object) {
if (object == null) return "nil";
if (object instanceof Double) {
String text = object.toString();
if (text.endsWith(".0")) {
text = text.substring(0, text.length() - 2);
}
return text;
}
return object.toString();
}
Code block 54
static void runtimeError(RuntimeError error) {
System.err.println(error.getMessage() +
"\n[line " + error.token.line + "]");
hadRuntimeError = true;
}
Code block 55
static boolean hadError = false;
Code block 56
static boolean hadRuntimeError = false;
Code block 57
public static void main(String[] args) throws IOException {
Code block 58
run(new String(bytes, Charset.defaultCharset()));
// Indicate an error in the exit code.
if (hadError) System.exit(65);
Code block 59
if (hadRuntimeError) System.exit(70);
Code block 60
}
Code block 61
public class Lox {
Code block 62
private static final Interpreter interpreter = new Interpreter();
Code block 63
static boolean hadError = false;
Code block 64
// Stop if there was a syntax error.
if (hadError) return;
Code block 65
interpreter.interpret(expression);
Code block 66
}
Code block 67
Object[] stuff = new Integer[1];
stuff[0] = "not an int!";
参考资料
- 原文:Evaluating Expressions
- 系列索引
- Robert Nystrom, Crafting Interpreters,© 2015–2021
评论 (0)