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

Calls and Functions:call frame 与函数调用栈

发布于 2026-09-16 19:23 · 最后编辑于 2026-09-17 22:07 · 版本 v2 · 字数 5,749 · 预计阅读 12 分钟 👁 22 次阅读

Crafting Interpreters:Calls and Functions

本章把 Lox function 编译成独立 function object,并用 call frame 管理参数、局部变量、返回地址和嵌套调用。

TL;DR

  • function object 保存 function 的 bytecode chunk、name 和 arity。
  • call frame 是 VM 对一次 function invocation 的记录:function、instruction pointer 和 slots 起点。
  • 每个 function 有自己的 compiler;编译嵌套 function 时用 compiler stack 保存外层上下文。
  • 参数和局部变量都位于当前 frame 的 slots 中,多个 frame 可以共享同一条 value stack。
  • return 恢复 caller frame,并把返回值放回调用者预期的 stack slot;native function 也遵循 callable contract。

目录

章节内容
Function objectsfunction runtime representation
Compiling to function objects独立 chunk
Call framesframe、slots 与 return address
Function declarations嵌套 compiler
Function calls参数与调用
Return statements返回流程
Native functions宿主函数
Challenges扩展练习

Function objects

之前只有一个 top-level chunk。现在每个 Lox function 都需要自己的 ObjFunction 和 Chunk,并保存 name、arity 与编译所得 instructions。function declaration 编译为创建 function object 的常量,再由 OP_CLOSURE 或相应 opcode 放入运行时。

Compiling to function objects

Creating functions at compile time

compiler 当前指向正在生成 bytecode 的 function。编译 function declaration 时创建新的 Compiler,设置 function type 和 name,编译 body,最后发出隐含 return,取出 ObjFunction。

函数代码不能直接在 declaration 执行;它要等到 call 时在自己的 frame 中运行。这样 declaration 只建立 object,调用才产生参数和局部状态。

Call frames

call frame 保存:

  • function:被调用的 ObjFunction;
  • ip:当前要执行的 instruction;
  • slots:该 invocation 在 value stack 中的起点。

calls

Allocating local variables

参数和 locals 不需要每次单独 malloc。它们直接放在共享 value stack 的 frame window 中:

window

多个 frame 的 window 可以重叠但不会互相覆盖,因为每个 frame 的 slots 起点不同:

overlapping windows

Return addresses

每个 frame 的 ip 指向当前 function 的 instruction。return 时恢复 caller frame 的 ip;因此不需要把 return address 作为普通 Lox value 压入 stack。

The call stack

嵌套 function call 会向 call stack 添加 frame。frame 数量受 VM 最大深度限制;超过限制时报告 stack overflow,不能让 C 的递归调用栈失控。

Function declarations

编译 function declaration 时,当前 compiler 需要暂时切换到新 function 的 compiler。

A stack of compilers

外层 compiler 保存于 enclosing 指针;endCompiler() 完成内层 function 后恢复 enclosing。每个 compiler 都有自己的 locals、scope depth、function object 和 loop state。

Function parameters

参数在 function body 开始时已经位于 frame slots 中,因此 compiler 只需把它们登记为 locals,并把 function arity 设为参数数量:

parameter window

Function calls

call expression 先编译 callee,再按 source 顺序编译 arguments,最后发出 OP_CALL 和 argument count。编译结果的 stack 形状类似:

argument stack

Binding arguments to parameters

VM 通过 argCount 找到 callee 与参数,并设置新 frame 的 slots,使 parameter slot 直接指向 argument value。调用 function 后,执行从该 function chunk 的 instruction zero 开始。

arithmetic

Runtime error checking

call 前检查 callee 是否为 callable,以及 argCount 是否等于 function arity。错误包括“只能调用函数”和参数数量不匹配。检查必须发生在创建 frame 前。

Printing stack traces

Runtime error 应沿 call frames 从当前 frame 向外打印 function name 和 source line,形成 stack trace。每个 frame 的 ip 要回退一个 instruction 才能定位触发错误的 opcode。

Returning from functions

return value 位于当前 frame 的 stack 顶部。VM 取出它,丢弃当前 frame 的 slots,恢复 caller frame,再把 value 放回 caller 继续执行的位置:

return

Return statements

return expression 编译 expression 后发出 OP_RETURN;没有 expression 时先发 OP_NIL。顶层 script 也需要隐含 return,保证 VM 总能结束。

function 返回时只能恢复 frame,不应继续执行当前 function 的后续 instructions。所有控制路径最终都应产生一个返回值,未显式返回时使用 nil。

Native functions

native function 用 C function pointer 实现 LoxCallable。它有自己的 arity,并从 VM stack 读取 arguments,返回一个 Value。native call 仍通过 OP_CALL 的统一路径执行,只是 VM 在识别 native object 后调用 C 函数。

Challenges

1. Variadic functions

支持可变参数,设计 arity 检查与参数在 slots 中的布局。

2. Tail calls

识别 tail position 的 call,复用当前 frame,比较递归深度和 stack trace 的变化。

3. First-class native functions

让 native function 能保存为变量、传递和比较,并明确宿主资源异常如何转成 Lox error。

原文代码片段

本节按官方页面顺序保留本章所有 grammar、C 和测试代码片段,便于与上文译文逐段对照。

参考资料

Code block 1

c
  struct Obj* next;
};

Code block 2

c
typedef struct {
  Obj obj;
  int arity;
  Chunk chunk;
  ObjString* name;
} ObjFunction;

Code block 3

c
struct ObjString {

Code block 4

c
#include "common.h"

Code block 5

c
#include "chunk.h"

Code block 6

c
#include "value.h"

Code block 7

text
  uint32_t hash;
};

Code block 8

c
ObjFunction* newFunction();

Code block 9

c
ObjString* takeString(char* chars, int length);

Code block 10

c
ObjFunction* newFunction() {
  ObjFunction* function = ALLOCATE_OBJ(ObjFunction, OBJ_FUNCTION);
  function->arity = 0;
  function->name = NULL;
  initChunk(&function->chunk);
  return function;
}

Code block 11

c
typedef enum {

Code block 12

text
  OBJ_FUNCTION,

Code block 13

text
  OBJ_STRING,
} ObjType;

Code block 14

text
  switch (object->type) {

Code block 15

c
    case OBJ_FUNCTION: {
      ObjFunction* function = (ObjFunction*)object;
      freeChunk(&function->chunk);
      FREE(ObjFunction, object);
      break;
    }

Code block 16

text
    case OBJ_STRING: {

Code block 17

text
  switch (OBJ_TYPE(value)) {

Code block 18

c
    case OBJ_FUNCTION:
      printFunction(AS_FUNCTION(value));
      break;

Code block 19

text
    case OBJ_STRING:

Code block 20

c
static void printFunction(ObjFunction* function) {
  printf("<fn %s>", function->name->chars);
}

Code block 21

c
#define OBJ_TYPE(value)        (AS_OBJ(value)->type)

Code block 22

c
#define IS_FUNCTION(value)     isObjType(value, OBJ_FUNCTION)

Code block 23

c
#define IS_STRING(value)       isObjType(value, OBJ_STRING)

Code block 24

c
#define IS_STRING(value)       isObjType(value, OBJ_STRING)

Code block 25

c
#define AS_FUNCTION(value)     ((ObjFunction*)AS_OBJ(value))

Code block 26

c
#define AS_STRING(value)       ((ObjString*)AS_OBJ(value))

Code block 27

c
typedef struct {

Code block 28

c
  ObjFunction* function;
  FunctionType type;

Code block 29

text
  Local locals[UINT8_COUNT];

Code block 30

c
typedef enum {
  TYPE_FUNCTION,
  TYPE_SCRIPT
} FunctionType;

Code block 31

c
Compiler* current = NULL;

Code block 32

c
static Chunk* currentChunk() {
  return &current->function->chunk;
}

Code block 33

c
static void errorAt(Token* token, const char* message) {

Code block 34

c
  Compiler compiler;

Code block 35

c
  initCompiler(&compiler, TYPE_SCRIPT);

Code block 36

text
  parser.hadError = false;

Code block 37

c
static void initCompiler(Compiler* compiler, FunctionType type) {
  compiler->function = NULL;
  compiler->type = type;

Code block 38

text
  compiler->localCount = 0;

Code block 39

text
  compiler->scopeDepth = 0;

Code block 40

c
  compiler->function = newFunction();

Code block 41

text
  current = compiler;

Code block 42

text
  current = compiler;

Code block 43

text
  Local* local = &current->locals[current->localCount++];
  local->depth = 0;
  local->name.start = "";
  local->name.length = 0;

Code block 44

text
}

Code block 45

c
static ObjFunction* endCompiler() {

Code block 46

text
  emitReturn();

Code block 47

text
  emitReturn();

Code block 48

c
  ObjFunction* function = current->function;

Code block 49

text
#ifdef DEBUG_PRINT_CODE

Code block 50

text
#endif

Code block 51

c
  return function;

Code block 52

text
}

Code block 53

c
#ifdef DEBUG_PRINT_CODE
  if (!parser.hadError) {

Code block 54

text
    disassembleChunk(currentChunk(), function->name != NULL
        ? function->name->chars : "<script>");

Code block 55

text
  }
#endif

Code block 56

c
static void printFunction(ObjFunction* function) {

Code block 57

c
  if (function->name == NULL) {
    printf("<script>");
    return;
  }

Code block 58

c
  printf("<fn %s>", function->name->chars);

Code block 59

c
#include "vm.h"

Code block 60

c
ObjFunction* compile(const char* source);

Code block 61

text
#endif

Code block 62

c
ObjFunction* compile(const char* source) {

Code block 63

text
  initScanner(source);

Code block 64

c
  while (!match(TOKEN_EOF)) {
    declaration();
  }

Code block 65

c
  ObjFunction* function = endCompiler();
  return parser.hadError ? NULL : function;

Code block 66

text
}

Code block 67

text
fun first() {
  var a = 1;
  second();
  var b = 2;
}

fun second() {
  var c = 3;
  var d = 4;
}

first();

Code block 68

text
fun first() {
  var a = 1;
  second();
  var b = 2;
  second();
}

fun second() {
  var c = 3;
  var d = 4;
}

first();

Code block 69

c
#define STACK_MAX 256

Code block 70

c
typedef struct {
  ObjFunction* function;
  uint8_t* ip;
  Value* slots;
} CallFrame;

Code block 71

c
typedef struct {

Code block 72

c
typedef struct {

Code block 73

c
  CallFrame frames[FRAMES_MAX];
  int frameCount;

Code block 74

c
  Value stack[STACK_MAX];

Code block 75

c
#include "value.h"

Code block 76

c
#define FRAMES_MAX 64
#define STACK_MAX (FRAMES_MAX * UINT8_COUNT)

Code block 77

c
typedef struct {

Code block 78

text
  vm.stackTop = vm.stack;

Code block 79

text
  vm.frameCount = 0;

Code block 80

text
}

Code block 81

c
#define clox_vm_h

Code block 82

c
#include "object.h"

Code block 83

c
#include "table.h"

Code block 84

c
static InterpretResult run() {

Code block 85

c
  CallFrame* frame = &vm.frames[vm.frameCount - 1];

#define READ_BYTE() (*frame->ip++)

#define READ_SHORT() \
    (frame->ip += 2, \
    (uint16_t)((frame->ip[-2] << 8) | frame->ip[-1]))

#define READ_CONSTANT() \
    (frame->function->chunk.constants.values[READ_BYTE()])

Code block 86

c
#define READ_STRING() AS_STRING(READ_CONSTANT())

Code block 87

c
      case OP_GET_LOCAL: {
        uint8_t slot = READ_BYTE();

Code block 88

text
        push(frame->slots[slot]);

Code block 89

text
        break;

Code block 90

c
      case OP_SET_LOCAL: {
        uint8_t slot = READ_BYTE();

Code block 91

text
        frame->slots[slot] = peek(0);

Code block 92

text
        break;

Code block 93

c
      case OP_JUMP: {
        uint16_t offset = READ_SHORT();

Code block 94

text
        frame->ip += offset;

Code block 95

text
        break;

Code block 96

c
      case OP_JUMP_IF_FALSE: {
        uint16_t offset = READ_SHORT();

Code block 97

c
        if (isFalsey(peek(0))) frame->ip += offset;

Code block 98

text
        break;

Code block 99

c
      case OP_LOOP: {
        uint16_t offset = READ_SHORT();

Code block 100

text
        frame->ip -= offset;

Code block 101

text
        break;

Code block 102

c
    printf("\n");

Code block 103

text
    disassembleInstruction(&frame->function->chunk,
        (int)(frame->ip - frame->function->chunk.code));

Code block 104

text
#endif

Code block 105

text
InterpretResult interpret(const char* source) {

Code block 106

c
  ObjFunction* function = compile(source);
  if (function == NULL) return INTERPRET_COMPILE_ERROR;

  push(OBJ_VAL(function));
  CallFrame* frame = &vm.frames[vm.frameCount++];
  frame->function = function;
  frame->ip = function->chunk.code;
  frame->slots = vm.stack;

Code block 107

text
  InterpretResult result = run();

Code block 108

text
  frame->slots = vm.stack;

Code block 109

c
  return run();

Code block 110

text
}

Code block 111

text
  fputs("\n", stderr);

Code block 112

c
  CallFrame* frame = &vm.frames[vm.frameCount - 1];
  size_t instruction = frame->ip - frame->function->chunk.code - 1;
  int line = frame->function->chunk.lines[instruction];

Code block 113

c
  fprintf(stderr, "[line %d] in script\n", line);

Code block 114

c
static void declaration() {

Code block 115

c
  if (match(TOKEN_FUN)) {
    funDeclaration();
  } else if (match(TOKEN_VAR)) {

Code block 116

text
    varDeclaration();

Code block 117

c
static void funDeclaration() {
  uint8_t global = parseVariable("Expect function name.");
  markInitialized();
  function(TYPE_FUNCTION);
  defineVariable(global);
}

Code block 118

c
static void markInitialized() {

Code block 119

c
  if (current->scopeDepth == 0) return;

Code block 120

text
  current->locals[current->localCount - 1].depth =

Code block 121

c
static void function(FunctionType type) {
  Compiler compiler;
  initCompiler(&compiler, type);
  beginScope(); 

  consume(TOKEN_LEFT_PAREN, "Expect '(' after function name.");
  consume(TOKEN_RIGHT_PAREN, "Expect ')' after parameters.");
  consume(TOKEN_LEFT_BRACE, "Expect '{' before function body.");
  block();

  ObjFunction* function = endCompiler();
  emitBytes(OP_CONSTANT, makeConstant(OBJ_VAL(function)));
}

Code block 122

c
} FunctionType;

Code block 123

c
typedef struct Compiler {
  struct Compiler* enclosing;

Code block 124

c
  ObjFunction* function;

Code block 125

c
static void initCompiler(Compiler* compiler, FunctionType type) {

Code block 126

text
  compiler->enclosing = current;

Code block 127

text
  compiler->function = NULL;

Code block 128

text
#endif

Code block 129

text
  current = current->enclosing;

Code block 130

c
  return function;

Code block 131

text
  consume(TOKEN_LEFT_PAREN, "Expect '(' after function name.");

Code block 132

c
  if (!check(TOKEN_RIGHT_PAREN)) {
    do {
      current->function->arity++;
      if (current->function->arity > 255) {
        errorAtCurrent("Can't have more than 255 parameters.");
      }
      uint8_t constant = parseVariable("Expect parameter name.");
      defineVariable(constant);
    } while (match(TOKEN_COMMA));
  }

Code block 133

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

Code block 134

text
  current = compiler;

Code block 135

c
  if (type != TYPE_SCRIPT) {
    current->function->name = copyString(parser.previous.start,
                                         parser.previous.length);
  }

Code block 136

text
  Local* local = &current->locals[current->localCount++];

Code block 137

c
fun areWeHavingItYet() {
  print "Yes we are!";
}

print areWeHavingItYet;

Code block 138

text
ParseRule rules[] = {

Code block 139

text
  [TOKEN_LEFT_PAREN]    = {grouping, call,   PREC_CALL},

Code block 140

text
  [TOKEN_RIGHT_PAREN]   = {NULL,     NULL,   PREC_NONE},

Code block 141

c
static void call(bool canAssign) {
  uint8_t argCount = argumentList();
  emitBytes(OP_CALL, argCount);
}

Code block 142

c
static uint8_t argumentList() {
  uint8_t argCount = 0;
  if (!check(TOKEN_RIGHT_PAREN)) {
    do {
      expression();
      argCount++;
    } while (match(TOKEN_COMMA));
  }
  consume(TOKEN_RIGHT_PAREN, "Expect ')' after arguments.");
  return argCount;
}

Code block 143

text
      expression();

Code block 144

c
      if (argCount == 255) {
        error("Can't have more than 255 arguments.");
      }

Code block 145

text
      argCount++;

Code block 146

c
  OP_LOOP,

Code block 147

c
  OP_CALL,

Code block 148

c
  OP_RETURN,

Code block 149

c
fun sum(a, b, c) {
  return a + b + c;
}

print 4 + sum(5, 6, 7);

Code block 150

text
      }

Code block 151

c
      case OP_CALL: {
        int argCount = READ_BYTE();
        if (!callValue(peek(argCount), argCount)) {
          return INTERPRET_RUNTIME_ERROR;
        }
        break;
      }

Code block 152

c
      case OP_RETURN: {

Code block 153

c
          return INTERPRET_RUNTIME_ERROR;
        }

Code block 154

text
        frame = &vm.frames[vm.frameCount - 1];

Code block 155

text
        break;

Code block 156

c
static bool callValue(Value callee, int argCount) {
  if (IS_OBJ(callee)) {
    switch (OBJ_TYPE(callee)) {
      case OBJ_FUNCTION: 
        return call(AS_FUNCTION(callee), argCount);
      default:
        break; // Non-callable object type.
    }
  }
  runtimeError("Can only call functions and classes.");
  return false;
}

Code block 157

c
var notAFunction = 123;
notAFunction();

Code block 158

c
static bool call(ObjFunction* function, int argCount) {
  CallFrame* frame = &vm.frames[vm.frameCount++];
  frame->function = function;
  frame->ip = function->chunk.code;
  frame->slots = vm.stackTop - argCount - 1;
  return true;
}

Code block 159

c
      return jumpInstruction("OP_LOOP", -1, chunk, offset);

Code block 160

c
    case OP_CALL:
      return byteInstruction("OP_CALL", chunk, offset);

Code block 161

c
    case OP_RETURN:

Code block 162

text
  push(OBJ_VAL(function));

Code block 163

text
  call(function, 0);

Code block 164

c
  return run();

Code block 165

c
static bool call(ObjFunction* function, int argCount) {

Code block 166

c
  if (argCount != function->arity) {
    runtimeError("Expected %d arguments but got %d.",
        function->arity, argCount);
    return false;
  }

Code block 167

c
  CallFrame* frame = &vm.frames[vm.frameCount++];

Code block 168

text
  }

Code block 169

c
  if (vm.frameCount == FRAMES_MAX) {
    runtimeError("Stack overflow.");
    return false;
  }

Code block 170

c
  CallFrame* frame = &vm.frames[vm.frameCount++];

Code block 171

text
  fputs("\n", stderr);

Code block 172

c
  for (int i = vm.frameCount - 1; i >= 0; i--) {
    CallFrame* frame = &vm.frames[i];
    ObjFunction* function = frame->function;
    size_t instruction = frame->ip - function->chunk.code - 1;
    fprintf(stderr, "[line %d] in ", 
            function->chunk.lines[instruction]);
    if (function->name == NULL) {
      fprintf(stderr, "script\n");
    } else {
      fprintf(stderr, "%s()\n", function->name->chars);
    }
  }

Code block 173

text
  resetStack();
}

Code block 174

text
fun a() { b(); }
fun b() { c(); }
fun c() {
  c("too", "many");
}

a();

Code block 175

text
Expected 0 arguments but got 2.
[line 4] in c()
[line 2] in b()
[line 1] in a()
[line 7] in script

Code block 176

c
      case OP_RETURN: {

Code block 177

c
        Value result = pop();
        vm.frameCount--;
        if (vm.frameCount == 0) {
          pop();
          return INTERPRET_OK;
        }

        vm.stackTop = frame->slots;
        push(result);
        frame = &vm.frames[vm.frameCount - 1];
        break;

Code block 178

text
      }

Code block 179

c
fun noReturn() {
  print "Do stuff";
  // No return here.
}

print noReturn(); // ???

Code block 180

c
static void emitReturn() {

Code block 181

c
  emitByte(OP_NIL);

Code block 182

c
  emitByte(OP_RETURN);
}

Code block 183

text
    ifStatement();

Code block 184

c
  } else if (match(TOKEN_RETURN)) {
    returnStatement();

Code block 185

c
  } else if (match(TOKEN_WHILE)) {

Code block 186

c
static void returnStatement() {
  if (match(TOKEN_SEMICOLON)) {
    emitReturn();
  } else {
    expression();
    consume(TOKEN_SEMICOLON, "Expect ';' after return value.");
    emitByte(OP_RETURN);
  }
}

Code block 187

c
return "What?!";

Code block 188

c
static void returnStatement() {

Code block 189

c
  if (current->type == TYPE_SCRIPT) {
    error("Can't return from top-level code.");
  }

Code block 190

c
  if (match(TOKEN_SEMICOLON)) {

Code block 191

c
} ObjFunction;

Code block 192

c
typedef Value (*NativeFn)(int argCount, Value* args);

typedef struct {
  Obj obj;
  NativeFn function;
} ObjNative;

Code block 193

c
struct ObjString {

Code block 194

c
ObjFunction* newFunction();

Code block 195

text
ObjNative* newNative(NativeFn function);

Code block 196

c
ObjString* takeString(char* chars, int length);

Code block 197

c
ObjNative* newNative(NativeFn function) {
  ObjNative* native = ALLOCATE_OBJ(ObjNative, OBJ_NATIVE);
  native->function = function;
  return native;
}

Code block 198

c
typedef enum {
  OBJ_FUNCTION,

Code block 199

text
  OBJ_NATIVE,

Code block 200

text
  OBJ_STRING,
} ObjType;

Code block 201

text
    }

Code block 202

text
    case OBJ_NATIVE:
      FREE(ObjNative, object);
      break;

Code block 203

text
    case OBJ_STRING: {

Code block 204

text
      break;

Code block 205

c
    case OBJ_NATIVE:
      printf("<native fn>");
      break;

Code block 206

text
    case OBJ_STRING:

Code block 207

c
#define IS_FUNCTION(value)     isObjType(value, OBJ_FUNCTION)

Code block 208

c
#define IS_NATIVE(value)       isObjType(value, OBJ_NATIVE)

Code block 209

c
#define IS_STRING(value)       isObjType(value, OBJ_STRING)

Code block 210

c
#define AS_FUNCTION(value)     ((ObjFunction*)AS_OBJ(value))

Code block 211

c
#define AS_NATIVE(value) \
    (((ObjNative*)AS_OBJ(value))->function)

Code block 212

c
#define AS_STRING(value)       ((ObjString*)AS_OBJ(value))

Code block 213

c
      case OBJ_FUNCTION: 
        return call(AS_FUNCTION(callee), argCount);

Code block 214

c
      case OBJ_NATIVE: {
        NativeFn native = AS_NATIVE(callee);
        Value result = native(argCount, vm.stackTop - argCount);
        vm.stackTop -= argCount + 1;
        push(result);
        return true;
      }

Code block 215

text
      default:

Code block 216

c
static void defineNative(const char* name, NativeFn function) {
  push(OBJ_VAL(copyString(name, (int)strlen(name))));
  push(OBJ_VAL(newNative(function)));
  tableSet(&vm.globals, AS_STRING(vm.stack[0]), vm.stack[1]);
  pop();
  pop();
}

Code block 217

c
static Value clockNative(int argCount, Value* args) {
  return NUMBER_VAL((double)clock() / CLOCKS_PER_SEC);
}

Code block 218

text
  initTable(&vm.strings);

Code block 219

text
  defineNative("clock", clockNative);

Code block 220

text
}

Code block 221

c
#include <string.h>

Code block 222

c
#include <time.h>

Code block 223

c
#include "common.h"

Code block 224

c
fun fib(n) {
  if (n < 2) return n;
  return fib(n - 2) + fib(n - 1);
}

var start = clock();
print fib(35);
print clock() - start;

参考资料

← 返回列表
← 上一篇 Jumping Back and Forth:bytecode 控制流与 backpatching 下一篇 → Closures:upvalue 捕获与生命周期

评论 (0)

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