Calls and Functions:call frame 与函数调用栈
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 objects | function runtime representation |
| Compiling to function objects | 独立 chunk |
| Call frames | frame、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 中的起点。

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

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

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 设为参数数量:

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

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

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 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
struct Obj* next;
};
Code block 2
typedef struct {
Obj obj;
int arity;
Chunk chunk;
ObjString* name;
} ObjFunction;
Code block 3
struct ObjString {
Code block 4
#include "common.h"
Code block 5
#include "chunk.h"
Code block 6
#include "value.h"
Code block 7
uint32_t hash;
};
Code block 8
ObjFunction* newFunction();
Code block 9
ObjString* takeString(char* chars, int length);
Code block 10
ObjFunction* newFunction() {
ObjFunction* function = ALLOCATE_OBJ(ObjFunction, OBJ_FUNCTION);
function->arity = 0;
function->name = NULL;
initChunk(&function->chunk);
return function;
}
Code block 11
typedef enum {
Code block 12
OBJ_FUNCTION,
Code block 13
OBJ_STRING,
} ObjType;
Code block 14
switch (object->type) {
Code block 15
case OBJ_FUNCTION: {
ObjFunction* function = (ObjFunction*)object;
freeChunk(&function->chunk);
FREE(ObjFunction, object);
break;
}
Code block 16
case OBJ_STRING: {
Code block 17
switch (OBJ_TYPE(value)) {
Code block 18
case OBJ_FUNCTION:
printFunction(AS_FUNCTION(value));
break;
Code block 19
case OBJ_STRING:
Code block 20
static void printFunction(ObjFunction* function) {
printf("<fn %s>", function->name->chars);
}
Code block 21
#define OBJ_TYPE(value) (AS_OBJ(value)->type)
Code block 22
#define IS_FUNCTION(value) isObjType(value, OBJ_FUNCTION)
Code block 23
#define IS_STRING(value) isObjType(value, OBJ_STRING)
Code block 24
#define IS_STRING(value) isObjType(value, OBJ_STRING)
Code block 25
#define AS_FUNCTION(value) ((ObjFunction*)AS_OBJ(value))
Code block 26
#define AS_STRING(value) ((ObjString*)AS_OBJ(value))
Code block 27
typedef struct {
Code block 28
ObjFunction* function;
FunctionType type;
Code block 29
Local locals[UINT8_COUNT];
Code block 30
typedef enum {
TYPE_FUNCTION,
TYPE_SCRIPT
} FunctionType;
Code block 31
Compiler* current = NULL;
Code block 32
static Chunk* currentChunk() {
return ¤t->function->chunk;
}
Code block 33
static void errorAt(Token* token, const char* message) {
Code block 34
Compiler compiler;
Code block 35
initCompiler(&compiler, TYPE_SCRIPT);
Code block 36
parser.hadError = false;
Code block 37
static void initCompiler(Compiler* compiler, FunctionType type) {
compiler->function = NULL;
compiler->type = type;
Code block 38
compiler->localCount = 0;
Code block 39
compiler->scopeDepth = 0;
Code block 40
compiler->function = newFunction();
Code block 41
current = compiler;
Code block 42
current = compiler;
Code block 43
Local* local = ¤t->locals[current->localCount++];
local->depth = 0;
local->name.start = "";
local->name.length = 0;
Code block 44
}
Code block 45
static ObjFunction* endCompiler() {
Code block 46
emitReturn();
Code block 47
emitReturn();
Code block 48
ObjFunction* function = current->function;
Code block 49
#ifdef DEBUG_PRINT_CODE
Code block 50
#endif
Code block 51
return function;
Code block 52
}
Code block 53
#ifdef DEBUG_PRINT_CODE
if (!parser.hadError) {
Code block 54
disassembleChunk(currentChunk(), function->name != NULL
? function->name->chars : "<script>");
Code block 55
}
#endif
Code block 56
static void printFunction(ObjFunction* function) {
Code block 57
if (function->name == NULL) {
printf("<script>");
return;
}
Code block 58
printf("<fn %s>", function->name->chars);
Code block 59
#include "vm.h"
Code block 60
ObjFunction* compile(const char* source);
Code block 61
#endif
Code block 62
ObjFunction* compile(const char* source) {
Code block 63
initScanner(source);
Code block 64
while (!match(TOKEN_EOF)) {
declaration();
}
Code block 65
ObjFunction* function = endCompiler();
return parser.hadError ? NULL : function;
Code block 66
}
Code block 67
fun first() {
var a = 1;
second();
var b = 2;
}
fun second() {
var c = 3;
var d = 4;
}
first();
Code block 68
fun first() {
var a = 1;
second();
var b = 2;
second();
}
fun second() {
var c = 3;
var d = 4;
}
first();
Code block 69
#define STACK_MAX 256
Code block 70
typedef struct {
ObjFunction* function;
uint8_t* ip;
Value* slots;
} CallFrame;
Code block 71
typedef struct {
Code block 72
typedef struct {
Code block 73
CallFrame frames[FRAMES_MAX];
int frameCount;
Code block 74
Value stack[STACK_MAX];
Code block 75
#include "value.h"
Code block 76
#define FRAMES_MAX 64
#define STACK_MAX (FRAMES_MAX * UINT8_COUNT)
Code block 77
typedef struct {
Code block 78
vm.stackTop = vm.stack;
Code block 79
vm.frameCount = 0;
Code block 80
}
Code block 81
#define clox_vm_h
Code block 82
#include "object.h"
Code block 83
#include "table.h"
Code block 84
static InterpretResult run() {
Code block 85
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
#define READ_STRING() AS_STRING(READ_CONSTANT())
Code block 87
case OP_GET_LOCAL: {
uint8_t slot = READ_BYTE();
Code block 88
push(frame->slots[slot]);
Code block 89
break;
Code block 90
case OP_SET_LOCAL: {
uint8_t slot = READ_BYTE();
Code block 91
frame->slots[slot] = peek(0);
Code block 92
break;
Code block 93
case OP_JUMP: {
uint16_t offset = READ_SHORT();
Code block 94
frame->ip += offset;
Code block 95
break;
Code block 96
case OP_JUMP_IF_FALSE: {
uint16_t offset = READ_SHORT();
Code block 97
if (isFalsey(peek(0))) frame->ip += offset;
Code block 98
break;
Code block 99
case OP_LOOP: {
uint16_t offset = READ_SHORT();
Code block 100
frame->ip -= offset;
Code block 101
break;
Code block 102
printf("\n");
Code block 103
disassembleInstruction(&frame->function->chunk,
(int)(frame->ip - frame->function->chunk.code));
Code block 104
#endif
Code block 105
InterpretResult interpret(const char* source) {
Code block 106
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
InterpretResult result = run();
Code block 108
frame->slots = vm.stack;
Code block 109
return run();
Code block 110
}
Code block 111
fputs("\n", stderr);
Code block 112
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
fprintf(stderr, "[line %d] in script\n", line);
Code block 114
static void declaration() {
Code block 115
if (match(TOKEN_FUN)) {
funDeclaration();
} else if (match(TOKEN_VAR)) {
Code block 116
varDeclaration();
Code block 117
static void funDeclaration() {
uint8_t global = parseVariable("Expect function name.");
markInitialized();
function(TYPE_FUNCTION);
defineVariable(global);
}
Code block 118
static void markInitialized() {
Code block 119
if (current->scopeDepth == 0) return;
Code block 120
current->locals[current->localCount - 1].depth =
Code block 121
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
} FunctionType;
Code block 123
typedef struct Compiler {
struct Compiler* enclosing;
Code block 124
ObjFunction* function;
Code block 125
static void initCompiler(Compiler* compiler, FunctionType type) {
Code block 126
compiler->enclosing = current;
Code block 127
compiler->function = NULL;
Code block 128
#endif
Code block 129
current = current->enclosing;
Code block 130
return function;
Code block 131
consume(TOKEN_LEFT_PAREN, "Expect '(' after function name.");
Code block 132
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
consume(TOKEN_RIGHT_PAREN, "Expect ')' after parameters.");
Code block 134
current = compiler;
Code block 135
if (type != TYPE_SCRIPT) {
current->function->name = copyString(parser.previous.start,
parser.previous.length);
}
Code block 136
Local* local = ¤t->locals[current->localCount++];
Code block 137
fun areWeHavingItYet() {
print "Yes we are!";
}
print areWeHavingItYet;
Code block 138
ParseRule rules[] = {
Code block 139
[TOKEN_LEFT_PAREN] = {grouping, call, PREC_CALL},
Code block 140
[TOKEN_RIGHT_PAREN] = {NULL, NULL, PREC_NONE},
Code block 141
static void call(bool canAssign) {
uint8_t argCount = argumentList();
emitBytes(OP_CALL, argCount);
}
Code block 142
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
expression();
Code block 144
if (argCount == 255) {
error("Can't have more than 255 arguments.");
}
Code block 145
argCount++;
Code block 146
OP_LOOP,
Code block 147
OP_CALL,
Code block 148
OP_RETURN,
Code block 149
fun sum(a, b, c) {
return a + b + c;
}
print 4 + sum(5, 6, 7);
Code block 150
}
Code block 151
case OP_CALL: {
int argCount = READ_BYTE();
if (!callValue(peek(argCount), argCount)) {
return INTERPRET_RUNTIME_ERROR;
}
break;
}
Code block 152
case OP_RETURN: {
Code block 153
return INTERPRET_RUNTIME_ERROR;
}
Code block 154
frame = &vm.frames[vm.frameCount - 1];
Code block 155
break;
Code block 156
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
var notAFunction = 123;
notAFunction();
Code block 158
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
return jumpInstruction("OP_LOOP", -1, chunk, offset);
Code block 160
case OP_CALL:
return byteInstruction("OP_CALL", chunk, offset);
Code block 161
case OP_RETURN:
Code block 162
push(OBJ_VAL(function));
Code block 163
call(function, 0);
Code block 164
return run();
Code block 165
static bool call(ObjFunction* function, int argCount) {
Code block 166
if (argCount != function->arity) {
runtimeError("Expected %d arguments but got %d.",
function->arity, argCount);
return false;
}
Code block 167
CallFrame* frame = &vm.frames[vm.frameCount++];
Code block 168
}
Code block 169
if (vm.frameCount == FRAMES_MAX) {
runtimeError("Stack overflow.");
return false;
}
Code block 170
CallFrame* frame = &vm.frames[vm.frameCount++];
Code block 171
fputs("\n", stderr);
Code block 172
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
resetStack();
}
Code block 174
fun a() { b(); }
fun b() { c(); }
fun c() {
c("too", "many");
}
a();
Code block 175
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
case OP_RETURN: {
Code block 177
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
}
Code block 179
fun noReturn() {
print "Do stuff";
// No return here.
}
print noReturn(); // ???
Code block 180
static void emitReturn() {
Code block 181
emitByte(OP_NIL);
Code block 182
emitByte(OP_RETURN);
}
Code block 183
ifStatement();
Code block 184
} else if (match(TOKEN_RETURN)) {
returnStatement();
Code block 185
} else if (match(TOKEN_WHILE)) {
Code block 186
static void returnStatement() {
if (match(TOKEN_SEMICOLON)) {
emitReturn();
} else {
expression();
consume(TOKEN_SEMICOLON, "Expect ';' after return value.");
emitByte(OP_RETURN);
}
}
Code block 187
return "What?!";
Code block 188
static void returnStatement() {
Code block 189
if (current->type == TYPE_SCRIPT) {
error("Can't return from top-level code.");
}
Code block 190
if (match(TOKEN_SEMICOLON)) {
Code block 191
} ObjFunction;
Code block 192
typedef Value (*NativeFn)(int argCount, Value* args);
typedef struct {
Obj obj;
NativeFn function;
} ObjNative;
Code block 193
struct ObjString {
Code block 194
ObjFunction* newFunction();
Code block 195
ObjNative* newNative(NativeFn function);
Code block 196
ObjString* takeString(char* chars, int length);
Code block 197
ObjNative* newNative(NativeFn function) {
ObjNative* native = ALLOCATE_OBJ(ObjNative, OBJ_NATIVE);
native->function = function;
return native;
}
Code block 198
typedef enum {
OBJ_FUNCTION,
Code block 199
OBJ_NATIVE,
Code block 200
OBJ_STRING,
} ObjType;
Code block 201
}
Code block 202
case OBJ_NATIVE:
FREE(ObjNative, object);
break;
Code block 203
case OBJ_STRING: {
Code block 204
break;
Code block 205
case OBJ_NATIVE:
printf("<native fn>");
break;
Code block 206
case OBJ_STRING:
Code block 207
#define IS_FUNCTION(value) isObjType(value, OBJ_FUNCTION)
Code block 208
#define IS_NATIVE(value) isObjType(value, OBJ_NATIVE)
Code block 209
#define IS_STRING(value) isObjType(value, OBJ_STRING)
Code block 210
#define AS_FUNCTION(value) ((ObjFunction*)AS_OBJ(value))
Code block 211
#define AS_NATIVE(value) \
(((ObjNative*)AS_OBJ(value))->function)
Code block 212
#define AS_STRING(value) ((ObjString*)AS_OBJ(value))
Code block 213
case OBJ_FUNCTION:
return call(AS_FUNCTION(callee), argCount);
Code block 214
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
default:
Code block 216
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
static Value clockNative(int argCount, Value* args) {
return NUMBER_VAL((double)clock() / CLOCKS_PER_SEC);
}
Code block 218
initTable(&vm.strings);
Code block 219
defineNative("clock", clockNative);
Code block 220
}
Code block 221
#include <string.h>
Code block 222
#include <time.h>
Code block 223
#include "common.h"
Code block 224
fun fib(n) {
if (n < 2) return n;
return fib(n - 2) + fib(n - 1);
}
var start = clock();
print fib(35);
print clock() - start;
参考资料
- 原文:Calls and Functions
- 系列索引
- Robert Nystrom, Crafting Interpreters,© 2015–2021
评论 (0)