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

Functions:调用、返回与 closure

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

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 callscallee、arguments 与 arity
Function declarations声明语法与 function object
Return statements从调用中返回
Closuresfunction 与 enclosing environment
Challenges扩展练习

Function calls

Function call 的 syntax 是一个 primary expression 后跟括号和零个或多个 arguments。parser 先解析 callee,再循环解析 arguments,最后构造 Call expression。arguments 的最大数量通常受实现限制;限制应在 parser 中尽早报告。

lambda

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 很重要:它定义了副作用的顺序,也避免未调用的分支提前执行。

foreign

内建 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。

binding

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

recursion

函数 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 查找。

global

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

body

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

closure

这正是 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

text
average(1, 2);

Code block 2

text
getCallback()();

Code block 3

text
unary          → ( "!" | "-" ) unary | call ;
call           → primary ( "(" arguments? ")" )* ;

Code block 4

text
arguments      → expression ( "," expression )* ;

Code block 5

java
      "Binary   : Expr left, Token operator, Expr right",

Code block 6

java
      "Call     : Expr callee, Token paren, List<Expr> arguments",

Code block 7

java
      "Grouping : Expr expression",

Code block 8

java
      return new Expr.Unary(operator, right);
    }

Code block 9

java
    return call();

Code block 10

text
  }

Code block 11

java
  private Expr call() {
    Expr expr = primary();

    while (true) { 
      if (match(LEFT_PAREN)) {
        expr = finishCall(expr);
      } else {
        break;
      }
    }

    return expr;
  }

Code block 12

java
  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

text
      do {

Code block 14

java
        if (arguments.size() >= 255) {
          error(peek(), "Can't have more than 255 arguments.");
        }

Code block 15

text
        arguments.add(expression());

Code block 16

java
import java.util.ArrayList;

Code block 17

java
import java.util.List;

Code block 18

java
  @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

java
package com.craftinginterpreters.lox;

import java.util.List;

interface LoxCallable {
  Object call(Interpreter interpreter, List<Object> arguments);
}

Code block 20

text
"totally not a function"();

Code block 21

text
    }

Code block 22

java
    if (!(callee instanceof LoxCallable)) {
      throw new RuntimeError(expr.paren,
          "Can only call functions and classes.");
    }

Code block 23

java
    LoxCallable function = (LoxCallable)callee;

Code block 24

text
fun add(a, b, c) {
  print a + b + c;
}

Code block 25

text
add(1, 2, 3, 4); // Too many.
add(1, 2);       // Too few.

Code block 26

java
    LoxCallable function = (LoxCallable)callee;

Code block 27

java
    if (arguments.size() != function.arity()) {
      throw new RuntimeError(expr.paren, "Expected " +
          function.arity() + " arguments but got " +
          arguments.size() + ".");
    }

Code block 28

java
    return function.call(this, arguments);

Code block 29

java
interface LoxCallable {

Code block 30

text
  int arity();

Code block 31

java
  Object call(Interpreter interpreter, List<Object> arguments);

Code block 32

java
class Interpreter implements Expr.Visitor<Object>,
                             Stmt.Visitor<Void> {

Code block 33

java
  final Environment globals = new Environment();
  private Environment environment = globals;

Code block 34

java
  void interpret(List<Stmt> statements) {

Code block 35

java
  private Environment environment = globals;

Code block 36

java
  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

java
  void interpret(List<Stmt> statements) {

Code block 38

text
var add = fun (a, b) {
  print a + b;
};

Code block 39

text
declaration    → funDecl
               | varDecl
               | statement ;

Code block 40

text
funDecl        → "fun" function ;
function       → IDENTIFIER "(" parameters? ")" block ;

Code block 41

text
parameters     → IDENTIFIER ( "," IDENTIFIER )* ;

Code block 42

java
      "Expression : Expr expression",

Code block 43

java
      "Function   : Token name, List<Token> params," +
                  " List<Stmt> body",

Code block 44

java
      "If         : Expr condition, Stmt thenBranch," +

Code block 45

text
    try {

Code block 46

java
      if (match(FUN)) return function("function");

Code block 47

java
      if (match(VAR)) return varDeclaration();

Code block 48

java
  private Stmt.Function function(String kind) {
    Token name = consume(IDENTIFIER, "Expect " + kind + " name.");
  }

Code block 49

java
    Token name = consume(IDENTIFIER, "Expect " + kind + " name.");

Code block 50

java
    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

text
  }

Code block 52

text
    consume(RIGHT_PAREN, "Expect ')' after parameters.");

Code block 53

java
    consume(LEFT_BRACE, "Expect '{' before " + kind + " body.");
    List<Stmt> body = block();
    return new Stmt.Function(name, parameters, body);

Code block 54

text
  }

Code block 55

java
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

java
  @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

java
fun count(n) {
  if (n > 1) count(n - 1);
  print n;
}

count(3);

Code block 58

text
fun add(a, b, c) {
  print a + b + c;
}

add(1, 2, 3);

Code block 59

java
  @Override
  public int arity() {
    return declaration.params.size();
  }

Code block 60

java
  @Override
  public String toString() {
    return "<fn " + declaration.name.lexeme + ">";
  }

Code block 61

text
fun add(a, b) {
  print a + b;
}

print add; // "<fn add>".

Code block 62

java
  @Override
  public Void visitFunctionStmt(Stmt.Function stmt) {
    LoxFunction function = new LoxFunction(stmt);
    environment.define(stmt.name.lexeme, function);
    return null;
  }

Code block 63

text
fun sayHi(first, last) {
  print "Hi, " + first + " " + last + "!";
}

sayHi("Dear", "Reader");

Code block 64

java
statement      → exprStmt
               | forStmt
               | ifStmt
               | printStmt
               | returnStmt
               | whileStmt
               | block ;

returnStmt     → "return" expression? ";" ;

Code block 65

java
fun procedure() {
  print "don't return anything";
}

var result = procedure();
print result; // ?

Code block 66

java
return nil;

Code block 67

java
      "Print      : Expr expression",

Code block 68

java
      "Return     : Token keyword, Expr value",

Code block 69

java
      "Var        : Token name, Expr initializer",

Code block 70

java
    if (match(PRINT)) return printStatement();

Code block 71

java
    if (match(RETURN)) return returnStatement();

Code block 72

java
    if (match(WHILE)) return whileStatement();

Code block 73

java
  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

java
fun count(n) {
  while (n < 100) {
    if (n == 3) return n; // <--
    print n;
    n = n + 1;
  }
}

count(1);

Code block 75

java
Interpreter.visitReturnStmt()
Interpreter.visitIfStmt()
Interpreter.executeBlock()
Interpreter.visitBlockStmt()
Interpreter.visitWhileStmt()
Interpreter.executeBlock()
LoxFunction.call()
Interpreter.visitCallExpr()

Code block 76

java
  @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

java
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

text
          arguments.get(i));
    }

Code block 79

java
    try {
      interpreter.executeBlock(declaration.body, environment);
    } catch (Return returnValue) {
      return returnValue.value;
    }

Code block 80

java
    return null;

Code block 81

java
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

java
fun makeCounter() {
  var i = 0;
  fun count() {
    i = i + 1;
    print i;
  }

  return count;
}

var counter = makeCounter();
counter(); // "1".
counter(); // "2".

Code block 83

java
  private final Stmt.Function declaration;

Code block 84

java
  private final Environment closure;

Code block 85

java
  LoxFunction(Stmt.Function declaration) {

Code block 86

java
  LoxFunction(Stmt.Function declaration, Environment closure) {
    this.closure = closure;

Code block 87

text
    this.declaration = declaration;

Code block 88

java
  public Void visitFunctionStmt(Stmt.Function stmt) {

Code block 89

java
    LoxFunction function = new LoxFunction(stmt, environment);

Code block 90

text
    environment.define(stmt.name.lexeme, function);

Code block 91

java
                     List<Object> arguments) {

Code block 92

java
    Environment environment = new Environment(closure);

Code block 93

text
    for (int i = 0; i < declaration.params.size(); i++) {

Code block 94

text
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

text
fun () {};

Code block 96

text
fun scope(a) {
  var a = "local";
}

参考资料

← 返回列表
← 上一篇 Control Flow:条件分支、逻辑短路与循环 下一篇 → Resolving and Binding:静态作用域与变量解析

评论 (0)

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