Functions:调用、返回与 closure
Crafting Interpreters:Functions
本章为 Lox 加入 function call、function declaration、return 和 closure 的基础,让代码可以封装、复用并递归调用。
TL;DR
- Function call 是一种 expression:先求值 callee,再求值 arguments,最后执行调用。
- Function declaration 把 name、parameters 和 body 保存为 function object;调用时为每次 invocation 创建独立 Environment。
- Arity 是 function contract 的一部分,调用参数数量不匹配必须报告 runtime error。
- return 需要从任意深度的 function body 中立即跳出,使用专门的 Return exception 可以自然实现这一控制转移。
- Closure 会同时捕获 function code 和 declaration 时的 Environment,为后续 lexical resolver 奠定基础。
目录
| 章节 | 内容 |
|---|---|
| Function calls | callee、arguments 与 arity |
| Function declarations | 声明语法与 function object |
| Return statements | 从调用中返回 |
| Closures | function 与 enclosing environment |
| Challenges | 扩展练习 |
Function calls
Function call 的 syntax 是一个 primary expression 后跟括号和零个或多个 arguments。parser 先解析 callee,再循环解析 arguments,最后构造 Call expression。arguments 的最大数量通常受实现限制;限制应在 parser 中尽早报告。

Interpreter 处理 Call expression 时,先 evaluate callee,再按从左到右的顺序 evaluate arguments。只有 callee 是 LoxCallable 才能调用;否则报告 “Can only call functions and classes.” 之类的 runtime error。
LoxCallable 提供 call(interpreter, arguments) 和 arity()。interpreter 通过 arity 检查参数数量,再调用 function object。先求值 callee 和 arguments 很重要:它定义了副作用的顺序,也避免未调用的分支提前执行。

内建 clock function 是 native function 的例子。它把宿主 Java 的当前时间暴露给 Lox,但仍通过相同的 callable interface 接入。
Function declarations
Function declaration 包含 name、parameter list 和 body statements。parser 读取 fun、name、参数和 block body,生成 Stmt.Function。函数声明执行时并不运行 body,而是创建 LoxFunction 并在当前 Environment 中定义 name。

调用函数时,为本次 invocation 创建新的 Environment,并把每个 argument value 绑定到对应 parameter。body 在这个新 environment 中执行;因此递归调用的每一层都有独立的 locals:

函数 declaration 的 environment 和 call environment 不是一回事。前者决定函数创建时可见的外层 binding,后者保存当前调用的 parameters 与 locals。
Return statements
return 是 statement,但它会把 value 传回调用者。return expression 先被 evaluate,然后从 function body 的任意嵌套 block 中跳出。
直接让每一层 visitor 返回“是否继续”会污染所有 statement 的返回类型。更简单的实现是抛出一个只在 interpreter 内部使用的 Return exception;LoxFunction.call 捕获它,取出 value,然后正常恢复调用者。
如果 return 没有 expression,返回 nil。Return exception 不能被普通 runtime error handler 当作用户错误打印。
Closures
Function 是 closure 的基础:它不仅保存 declaration 中的 code,还保存 declaration 时的 Environment。这样函数体引用外层变量时,即使函数稍后在别处调用,也能沿正确的 environment chain 查找。

当函数在另一个函数内部声明时,closure 捕获当前局部 environment:

返回内部函数后,创建它的外层调用可能已经结束,但被 closure 捕获的 Environment 仍然存活:

这正是 lexical closure 的语义:函数携带它定义位置的环境,而不是调用位置的环境。当前实现通过 Java object references 保持 environment chain;后续章节会加入 resolver,避免每次运行时从链头逐层查找。
Challenges
1. Anonymous functions
允许 function declaration 没有 name,把 function literal 作为 expression。需要决定如何打印、比较和存储匿名 function。
2. First-class functions
让 function 可以赋给变量、作为 argument 传递并从 function 返回。检查现有 callable interface 是否已经足够。
3. Native functions
添加更多 native function,并明确宿主异常如何转换为 Lox runtime error。
4. Function equality
决定两个 function object 何时相等:按 identity,还是按 declaration 内容比较。说明选择对 closure state 的影响。
原文代码片段
本节按官方页面顺序保留本章所有 grammar、Java 和测试代码片段,便于与上文译文逐段对照。
参考资料
Code block 1
average(1, 2);
Code block 2
getCallback()();
Code block 3
unary → ( "!" | "-" ) unary | call ;
call → primary ( "(" arguments? ")" )* ;
Code block 4
arguments → expression ( "," expression )* ;
Code block 5
"Binary : Expr left, Token operator, Expr right",
Code block 6
"Call : Expr callee, Token paren, List<Expr> arguments",
Code block 7
"Grouping : Expr expression",
Code block 8
return new Expr.Unary(operator, right);
}
Code block 9
return call();
Code block 10
}
Code block 11
private Expr call() {
Expr expr = primary();
while (true) {
if (match(LEFT_PAREN)) {
expr = finishCall(expr);
} else {
break;
}
}
return expr;
}
Code block 12
private Expr finishCall(Expr callee) {
List<Expr> arguments = new ArrayList<>();
if (!check(RIGHT_PAREN)) {
do {
arguments.add(expression());
} while (match(COMMA));
}
Token paren = consume(RIGHT_PAREN,
"Expect ')' after arguments.");
return new Expr.Call(callee, paren, arguments);
}
Code block 13
do {
Code block 14
if (arguments.size() >= 255) {
error(peek(), "Can't have more than 255 arguments.");
}
Code block 15
arguments.add(expression());
Code block 16
import java.util.ArrayList;
Code block 17
import java.util.List;
Code block 18
@Override
public Object visitCallExpr(Expr.Call expr) {
Object callee = evaluate(expr.callee);
List<Object> arguments = new ArrayList<>();
for (Expr argument : expr.arguments) {
arguments.add(evaluate(argument));
}
LoxCallable function = (LoxCallable)callee;
return function.call(this, arguments);
}
Code block 19
package com.craftinginterpreters.lox;
import java.util.List;
interface LoxCallable {
Object call(Interpreter interpreter, List<Object> arguments);
}
Code block 20
"totally not a function"();
Code block 21
}
Code block 22
if (!(callee instanceof LoxCallable)) {
throw new RuntimeError(expr.paren,
"Can only call functions and classes.");
}
Code block 23
LoxCallable function = (LoxCallable)callee;
Code block 24
fun add(a, b, c) {
print a + b + c;
}
Code block 25
add(1, 2, 3, 4); // Too many.
add(1, 2); // Too few.
Code block 26
LoxCallable function = (LoxCallable)callee;
Code block 27
if (arguments.size() != function.arity()) {
throw new RuntimeError(expr.paren, "Expected " +
function.arity() + " arguments but got " +
arguments.size() + ".");
}
Code block 28
return function.call(this, arguments);
Code block 29
interface LoxCallable {
Code block 30
int arity();
Code block 31
Object call(Interpreter interpreter, List<Object> arguments);
Code block 32
class Interpreter implements Expr.Visitor<Object>,
Stmt.Visitor<Void> {
Code block 33
final Environment globals = new Environment();
private Environment environment = globals;
Code block 34
void interpret(List<Stmt> statements) {
Code block 35
private Environment environment = globals;
Code block 36
Interpreter() {
globals.define("clock", new LoxCallable() {
@Override
public int arity() { return 0; }
@Override
public Object call(Interpreter interpreter,
List<Object> arguments) {
return (double)System.currentTimeMillis() / 1000.0;
}
@Override
public String toString() { return "<native fn>"; }
});
}
Code block 37
void interpret(List<Stmt> statements) {
Code block 38
var add = fun (a, b) {
print a + b;
};
Code block 39
declaration → funDecl
| varDecl
| statement ;
Code block 40
funDecl → "fun" function ;
function → IDENTIFIER "(" parameters? ")" block ;
Code block 41
parameters → IDENTIFIER ( "," IDENTIFIER )* ;
Code block 42
"Expression : Expr expression",
Code block 43
"Function : Token name, List<Token> params," +
" List<Stmt> body",
Code block 44
"If : Expr condition, Stmt thenBranch," +
Code block 45
try {
Code block 46
if (match(FUN)) return function("function");
Code block 47
if (match(VAR)) return varDeclaration();
Code block 48
private Stmt.Function function(String kind) {
Token name = consume(IDENTIFIER, "Expect " + kind + " name.");
}
Code block 49
Token name = consume(IDENTIFIER, "Expect " + kind + " name.");
Code block 50
consume(LEFT_PAREN, "Expect '(' after " + kind + " name.");
List<Token> parameters = new ArrayList<>();
if (!check(RIGHT_PAREN)) {
do {
if (parameters.size() >= 255) {
error(peek(), "Can't have more than 255 parameters.");
}
parameters.add(
consume(IDENTIFIER, "Expect parameter name."));
} while (match(COMMA));
}
consume(RIGHT_PAREN, "Expect ')' after parameters.");
Code block 51
}
Code block 52
consume(RIGHT_PAREN, "Expect ')' after parameters.");
Code block 53
consume(LEFT_BRACE, "Expect '{' before " + kind + " body.");
List<Stmt> body = block();
return new Stmt.Function(name, parameters, body);
Code block 54
}
Code block 55
package com.craftinginterpreters.lox;
import java.util.List;
class LoxFunction implements LoxCallable {
private final Stmt.Function declaration;
LoxFunction(Stmt.Function declaration) {
this.declaration = declaration;
}
}
Code block 56
@Override
public Object call(Interpreter interpreter,
List<Object> arguments) {
Environment environment = new Environment(interpreter.globals);
for (int i = 0; i < declaration.params.size(); i++) {
environment.define(declaration.params.get(i).lexeme,
arguments.get(i));
}
interpreter.executeBlock(declaration.body, environment);
return null;
}
Code block 57
fun count(n) {
if (n > 1) count(n - 1);
print n;
}
count(3);
Code block 58
fun add(a, b, c) {
print a + b + c;
}
add(1, 2, 3);
Code block 59
@Override
public int arity() {
return declaration.params.size();
}
Code block 60
@Override
public String toString() {
return "<fn " + declaration.name.lexeme + ">";
}
Code block 61
fun add(a, b) {
print a + b;
}
print add; // "<fn add>".
Code block 62
@Override
public Void visitFunctionStmt(Stmt.Function stmt) {
LoxFunction function = new LoxFunction(stmt);
environment.define(stmt.name.lexeme, function);
return null;
}
Code block 63
fun sayHi(first, last) {
print "Hi, " + first + " " + last + "!";
}
sayHi("Dear", "Reader");
Code block 64
statement → exprStmt
| forStmt
| ifStmt
| printStmt
| returnStmt
| whileStmt
| block ;
returnStmt → "return" expression? ";" ;
Code block 65
fun procedure() {
print "don't return anything";
}
var result = procedure();
print result; // ?
Code block 66
return nil;
Code block 67
"Print : Expr expression",
Code block 68
"Return : Token keyword, Expr value",
Code block 69
"Var : Token name, Expr initializer",
Code block 70
if (match(PRINT)) return printStatement();
Code block 71
if (match(RETURN)) return returnStatement();
Code block 72
if (match(WHILE)) return whileStatement();
Code block 73
private Stmt returnStatement() {
Token keyword = previous();
Expr value = null;
if (!check(SEMICOLON)) {
value = expression();
}
consume(SEMICOLON, "Expect ';' after return value.");
return new Stmt.Return(keyword, value);
}
Code block 74
fun count(n) {
while (n < 100) {
if (n == 3) return n; // <--
print n;
n = n + 1;
}
}
count(1);
Code block 75
Interpreter.visitReturnStmt()
Interpreter.visitIfStmt()
Interpreter.executeBlock()
Interpreter.visitBlockStmt()
Interpreter.visitWhileStmt()
Interpreter.executeBlock()
LoxFunction.call()
Interpreter.visitCallExpr()
Code block 76
@Override
public Void visitReturnStmt(Stmt.Return stmt) {
Object value = null;
if (stmt.value != null) value = evaluate(stmt.value);
throw new Return(value);
}
Code block 77
package com.craftinginterpreters.lox;
class Return extends RuntimeException {
final Object value;
Return(Object value) {
super(null, null, false, false);
this.value = value;
}
}
Code block 78
arguments.get(i));
}
Code block 79
try {
interpreter.executeBlock(declaration.body, environment);
} catch (Return returnValue) {
return returnValue.value;
}
Code block 80
return null;
Code block 81
fun fib(n) {
if (n <= 1) return n;
return fib(n - 2) + fib(n - 1);
}
for (var i = 0; i < 20; i = i + 1) {
print fib(i);
}
Code block 82
fun makeCounter() {
var i = 0;
fun count() {
i = i + 1;
print i;
}
return count;
}
var counter = makeCounter();
counter(); // "1".
counter(); // "2".
Code block 83
private final Stmt.Function declaration;
Code block 84
private final Environment closure;
Code block 85
LoxFunction(Stmt.Function declaration) {
Code block 86
LoxFunction(Stmt.Function declaration, Environment closure) {
this.closure = closure;
Code block 87
this.declaration = declaration;
Code block 88
public Void visitFunctionStmt(Stmt.Function stmt) {
Code block 89
LoxFunction function = new LoxFunction(stmt, environment);
Code block 90
environment.define(stmt.name.lexeme, function);
Code block 91
List<Object> arguments) {
Code block 92
Environment environment = new Environment(closure);
Code block 93
for (int i = 0; i < declaration.params.size(); i++) {
Code block 94
fun thrice(fn) {
for (var i = 1; i <= 3; i = i + 1) {
fn(i);
}
}
thrice(fun (a) {
print a;
});
// "1".
// "2".
// "3".
Code block 95
fun () {};
Code block 96
fun scope(a) {
var a = "local";
}
参考资料
- 原文:Functions
- 系列索引
- Robert Nystrom, Crafting Interpreters,© 2015–2021
评论 (0)