Methods and Initializers:bound method 与 init
Crafting Interpreters:Methods and Initializers
本章把 class method 真正接入 clox,完成 method declaration、bound method、this、initializer 和优化后的 invocation。
TL;DR
- method declaration 编译为 function object,再通过 OP_METHOD 写入 class 的 method table。
- 访问 method 不立即调用,而是创建绑定了 receiver 的 ObjBoundMethod。
- bound method 同时保存 receiver 和 method closure,调用时把 receiver 放入预期的 slot。
- this 通过 method closure 中的局部绑定实现;它与普通 local 一样可被 lexical resolver 处理。
- init() 永远返回 instance,且 method invocation 可以通过专用 opcode 避免不必要的临时 bound-method object。
目录
| 章节 | 内容 |
|---|---|
| Method declarations | method object 与编译 |
| Method references | bound method |
| This | receiver 绑定 |
| Instance initializers | init() |
| Optimized invocations | invoke opcode |
| Challenges | 扩展练习 |
| Design Note:Novelty Budget | 新特性的成本 |
Method declarations
class body 中的 method 不需要 fun keyword。compiler 为每个 method 创建 function object,编译完成后发出 OP_METHOD,把 name 和 closure 放入当前 class:

Representing methods
method 与 function 使用相同的 ObjFunction 表示,但 function type 区分 TYPE_FUNCTION、TYPE_METHOD 和 TYPE_INITIALIZER。class 的 methods table 保存 method name 到 function 的映射。
Compiling method declarations
编译 class body 时,compiler 逐个读取 method name 和 parameters。每个 method 有独立 locals 与 bytecode chunk;编译完恢复 enclosing compiler,再发出 OP_METHOD。
Executing method declarations
class declaration 运行时创建 LoxClass。OP_METHOD 从 stack 取 closure 和 name,写入 methods table。method declaration 本身不执行 body。
Method references
读取 instance.method 时,VM 先查 fields;如果没有 field,再从 class 找到 method。返回 method reference 时需要记住 receiver,否则稍后调用无法知道 this。
Bound methods
bindMethod() 创建 ObjBoundMethod,保存 receiver 与 method closure:

随后把 bound method 作为普通 callable 返回。它是一个完整的 runtime object,可以存入变量、传递给 function 或延迟调用。
Accessing methods
field lookup 优先于 method lookup。这样 instance field 可以 shadow method;删除 field 后,同一 property access 又可能解析为 method。
Calling methods
调用 bound method 时,VM 把 receiver 放入 call frame 的 slot zero,把剩余 slots 留给参数:

function body 中的 this 就是这个 slot zero。这样 method 可以像普通 closure 一样执行,而 receiver 绑定在调用前已经确定。
This
this 是 method 中的隐式 local。编译 method 时 compiler 将 this 放在 local slot zero;resolver/VM 不需要为每次 this access 做全局查找。
非法 this 使用(例如顶层 script 或普通 function)应在 resolver/compiler 阶段报告。nested function 是否捕获 this,取决于它是否从 enclosing method scope 引用了该 local。

Instance initializers
名为 init 的 method 是 initializer。class call 找到 initializer 后,创建 instance 并转发调用:

Invoking initializers
initializer 的 closure 中保存 instance。class call 把新 instance 放到 slot zero,再运行 init body。即使 initializer 没有显式 return,隐含 return 也返回该 instance。
Initializer return values
init() 的返回值固定是 receiver,而不是 body 中的任意 return expression。这保证 Brunch() 和 obj.init() 都返回同一个 instance。
Incorrect returns in initializers
compiler 可以拒绝 initializer 中带 value 的 return;或者编译它但在 VM 层忽略显式 value。无论选择哪种实现,语言语义都必须保持“initializer 返回 instance”。
Optimized invocations
如果先创建 bound method 再立即调用,会产生不必要的临时 object。OP_INVOKE 可以同时编码 method name 和 argument count:VM 直接从 receiver 的 class 查找 method、设置 frame,并开始执行。
Invoking fields
若 property name 对应 field 而不是 method,invoke 必须回退到 field value 的普通 call。这样优化不能改变 field shadowing 或 callable error 的行为。
Challenges
1. Method decorators
添加 method decorator 或 metadata,明确它是在 class 创建时还是调用时执行。
2. Super invocation
设计专用 OP_SUPER_INVOKE,比较它和普通 super property access 的 stack/lookup 成本。
3. Method caching
为 method lookup 添加 cache,处理 class method table 修改和继承关系变化时的失效。
Design Note:Novelty Budget
语言每增加一个新机制,用户都要学习新的 syntax、runtime semantics 和错误边界。method invocation、initializer、super call 等特性各自合理,但组合起来会产生更多规则。
设计时应把 novelty budget 花在能显著改善表达能力、且与已有模型一致的特性上。若一项语法只是把两步已有操作缩短,却引入独立的 edge cases,就可能不值得加入。
原文代码片段
本节按官方页面顺序保留本章所有 grammar、C 和测试代码片段,便于与上文译文逐段对照。
参考资料
Code block 1
typedef struct {
Obj obj;
ObjString* name;
Code block 2
Table methods;
Code block 3
} ObjClass;
Code block 4
klass->name = name;
Code block 5
initTable(&klass->methods);
Code block 6
return klass;
Code block 7
case OBJ_CLASS: {
Code block 8
ObjClass* klass = (ObjClass*)object;
freeTable(&klass->methods);
Code block 9
FREE(ObjClass, object);
Code block 10
markObject((Obj*)klass->name);
Code block 11
markTable(&klass->methods);
Code block 12
break;
Code block 13
consume(TOKEN_LEFT_BRACE, "Expect '{' before class body.");
Code block 14
while (!check(TOKEN_RIGHT_BRACE) && !check(TOKEN_EOF)) {
method();
}
Code block 15
consume(TOKEN_RIGHT_BRACE, "Expect '}' after class body.");
Code block 16
static void method() {
consume(TOKEN_IDENTIFIER, "Expect method name.");
uint8_t constant = identifierConstant(&parser.previous);
emitBytes(OP_METHOD, constant);
}
Code block 17
uint8_t constant = identifierConstant(&parser.previous);
Code block 18
FunctionType type = TYPE_FUNCTION;
function(type);
Code block 19
emitBytes(OP_METHOD, constant);
Code block 20
consume(TOKEN_IDENTIFIER, "Expect class name.");
Code block 21
Token className = parser.previous;
Code block 22
uint8_t nameConstant = identifierConstant(&parser.previous);
Code block 23
defineVariable(nameConstant);
Code block 24
namedVariable(className, false);
Code block 25
consume(TOKEN_LEFT_BRACE, "Expect '{' before class body.");
Code block 26
consume(TOKEN_RIGHT_BRACE, "Expect '}' after class body.");
Code block 27
emitByte(OP_POP);
Code block 28
}
Code block 29
class Brunch {
bacon() {}
eggs() {}
}
Code block 30
OP_CLASS,
Code block 31
OP_METHOD
Code block 32
} OpCode;
Code block 33
case OP_CLASS:
return constantInstruction("OP_CLASS", chunk, offset);
Code block 34
case OP_METHOD:
return constantInstruction("OP_METHOD", chunk, offset);
Code block 35
default:
Code block 36
break;
Code block 37
case OP_METHOD:
defineMethod(READ_STRING());
break;
Code block 38
}
Code block 39
static void defineMethod(ObjString* name) {
Value method = peek(0);
ObjClass* klass = AS_CLASS(peek(1));
tableSet(&klass->methods, name, method);
pop();
}
Code block 40
instance.method(argument);
Code block 41
var closure = instance.method;
closure(argument);
Code block 42
class Person {
sayName() {
print this.name;
}
}
var jane = Person();
jane.name = "Jane";
var method = jane.sayName;
method(); // ?
Code block 43
} ObjInstance;
Code block 44
typedef struct {
Obj obj;
Value receiver;
ObjClosure* method;
} ObjBoundMethod;
Code block 45
ObjClass* newClass(ObjString* name);
Code block 46
typedef enum {
Code block 47
OBJ_BOUND_METHOD,
Code block 48
OBJ_CLASS,
Code block 49
#define OBJ_TYPE(value) (AS_OBJ(value)->type)
Code block 50
#define IS_BOUND_METHOD(value) isObjType(value, OBJ_BOUND_METHOD)
Code block 51
#define IS_CLASS(value) isObjType(value, OBJ_CLASS)
Code block 52
#define IS_STRING(value) isObjType(value, OBJ_STRING)
Code block 53
#define AS_BOUND_METHOD(value) ((ObjBoundMethod*)AS_OBJ(value))
Code block 54
#define AS_CLASS(value) ((ObjClass*)AS_OBJ(value))
Code block 55
} ObjBoundMethod;
Code block 56
ObjBoundMethod* newBoundMethod(Value receiver,
ObjClosure* method);
Code block 57
ObjClass* newClass(ObjString* name);
Code block 58
ObjBoundMethod* newBoundMethod(Value receiver,
ObjClosure* method) {
ObjBoundMethod* bound = ALLOCATE_OBJ(ObjBoundMethod,
OBJ_BOUND_METHOD);
bound->receiver = receiver;
bound->method = method;
return bound;
}
Code block 59
switch (object->type) {
Code block 60
case OBJ_BOUND_METHOD:
FREE(ObjBoundMethod, object);
break;
Code block 61
case OBJ_CLASS: {
Code block 62
switch (object->type) {
Code block 63
case OBJ_BOUND_METHOD: {
ObjBoundMethod* bound = (ObjBoundMethod*)object;
markValue(bound->receiver);
markObject((Obj*)bound->method);
break;
}
Code block 64
case OBJ_CLASS: {
Code block 65
switch (OBJ_TYPE(value)) {
Code block 66
case OBJ_BOUND_METHOD:
printFunction(AS_BOUND_METHOD(value)->method->function);
break;
Code block 67
case OBJ_CLASS:
Code block 68
pop(); // Instance.
push(value);
break;
}
Code block 69
if (!bindMethod(instance->klass, name)) {
return INTERPRET_RUNTIME_ERROR;
}
break;
Code block 70
}
Code block 71
static bool bindMethod(ObjClass* klass, ObjString* name) {
Value method;
if (!tableGet(&klass->methods, name, &method)) {
runtimeError("Undefined property '%s'.", name->chars);
return false;
}
ObjBoundMethod* bound = newBoundMethod(peek(0),
AS_CLOSURE(method));
pop();
push(OBJ_VAL(bound));
return true;
}
Code block 72
class Brunch {
eggs() {}
}
var brunch = Brunch();
var eggs = brunch.eggs;
Code block 73
switch (OBJ_TYPE(callee)) {
Code block 74
case OBJ_BOUND_METHOD: {
ObjBoundMethod* bound = AS_BOUND_METHOD(callee);
return call(bound->method, argCount);
}
Code block 75
case OBJ_CLASS: {
Code block 76
class Scone {
topping(first, second) {
print "scone with " + first + " and " + second;
}
}
var scone = Scone();
scone.topping("berries", "cream");
Code block 77
[TOKEN_SUPER] = {NULL, NULL, PREC_NONE},
Code block 78
[TOKEN_THIS] = {this_, NULL, PREC_NONE},
Code block 79
[TOKEN_TRUE] = {literal, NULL, PREC_NONE},
Code block 80
static void this_(bool canAssign) {
variable(false);
}
Code block 81
local->isCaptured = false;
Code block 82
if (type != TYPE_FUNCTION) {
local->name.start = "this";
local->name.length = 4;
} else {
local->name.start = "";
local->name.length = 0;
}
Code block 83
}
Code block 84
class Nested {
method() {
fun function() {
print this;
}
function();
}
}
Nested().method();
Code block 85
TYPE_FUNCTION,
Code block 86
TYPE_METHOD,
Code block 87
TYPE_SCRIPT
Code block 88
uint8_t constant = identifierConstant(&parser.previous);
Code block 89
FunctionType type = TYPE_METHOD;
Code block 90
function(type);
Code block 91
case OBJ_BOUND_METHOD: {
ObjBoundMethod* bound = AS_BOUND_METHOD(callee);
Code block 92
vm.stackTop[-argCount - 1] = bound->receiver;
Code block 93
return call(bound->method, argCount);
}
Code block 94
scone.topping("berries", "cream");
Code block 95
print this; // At top level.
fun notMethod() {
print this; // In a function.
}
Code block 96
Compiler* current = NULL;
Code block 97
ClassCompiler* currentClass = NULL;
Code block 98
static Chunk* currentChunk() {
Code block 99
} Compiler;
Code block 100
typedef struct ClassCompiler {
struct ClassCompiler* enclosing;
} ClassCompiler;
Code block 101
Parser parser;
Code block 102
defineVariable(nameConstant);
Code block 103
ClassCompiler classCompiler;
classCompiler.enclosing = currentClass;
currentClass = &classCompiler;
Code block 104
namedVariable(className, false);
Code block 105
emitByte(OP_POP);
Code block 106
currentClass = currentClass->enclosing;
Code block 107
}
Code block 108
static void this_(bool canAssign) {
Code block 109
if (currentClass == NULL) {
error("Can't use 'this' outside of a class.");
return;
}
Code block 110
variable(false);
Code block 111
fun create(klass) {
var obj = newInstance(klass);
obj.init();
return obj;
}
Code block 112
vm.stackTop[-argCount - 1] = OBJ_VAL(newInstance(klass));
Code block 113
Value initializer;
if (tableGet(&klass->methods, vm.initString,
&initializer)) {
return call(AS_CLOSURE(initializer), argCount);
}
Code block 114
return true;
Code block 115
class Brunch {
init(food, drink) {}
}
Brunch("eggs", "coffee");
Code block 116
return call(AS_CLOSURE(initializer), argCount);
Code block 117
} else if (argCount != 0) {
runtimeError("Expected 0 arguments but got %d.",
argCount);
return false;
Code block 118
}
Code block 119
Table strings;
Code block 120
ObjString* initString;
Code block 121
ObjUpvalue* openUpvalues;
Code block 122
initTable(&vm.strings);
Code block 123
vm.initString = copyString("init", 4);
Code block 124
defineNative("clock", clockNative);
Code block 125
markCompilerRoots();
Code block 126
markObject((Obj*)vm.initString);
Code block 127
}
Code block 128
initTable(&vm.strings);
Code block 129
vm.initString = NULL;
Code block 130
vm.initString = copyString("init", 4);
Code block 131
freeTable(&vm.strings);
Code block 132
vm.initString = NULL;
Code block 133
freeObjects();
Code block 134
FunctionType type = TYPE_METHOD;
Code block 135
if (parser.previous.length == 4 &&
memcmp(parser.previous.start, "init", 4) == 0) {
type = TYPE_INITIALIZER;
}
Code block 136
function(type);
Code block 137
TYPE_FUNCTION,
Code block 138
TYPE_INITIALIZER,
Code block 139
TYPE_METHOD,
Code block 140
static void emitReturn() {
Code block 141
if (current->type == TYPE_INITIALIZER) {
emitBytes(OP_GET_LOCAL, 0);
} else {
emitByte(OP_NIL);
}
Code block 142
emitByte(OP_RETURN);
Code block 143
if (match(TOKEN_SEMICOLON)) {
emitReturn();
} else {
Code block 144
if (current->type == TYPE_INITIALIZER) {
error("Can't return a value from an initializer.");
}
Code block 145
expression();
Code block 146
class CoffeeMaker {
init(coffee) {
this.coffee = coffee;
}
brew() {
print "Enjoy your cup of " + this.coffee;
// No reusing the grounds!
this.coffee = nil;
}
}
var maker = CoffeeMaker("coffee and chicory");
maker.brew();
Code block 147
if (canAssign && match(TOKEN_EQUAL)) {
expression();
emitBytes(OP_SET_PROPERTY, name);
Code block 148
} else if (match(TOKEN_LEFT_PAREN)) {
uint8_t argCount = argumentList();
emitBytes(OP_INVOKE, name);
emitByte(argCount);
Code block 149
} else {
Code block 150
OP_CALL,
Code block 151
OP_INVOKE,
Code block 152
OP_CLOSURE,
Code block 153
case OP_CALL:
return byteInstruction("OP_CALL", chunk, offset);
Code block 154
case OP_INVOKE:
return invokeInstruction("OP_INVOKE", chunk, offset);
Code block 155
case OP_CLOSURE: {
Code block 156
static int invokeInstruction(const char* name, Chunk* chunk,
int offset) {
uint8_t constant = chunk->code[offset + 1];
uint8_t argCount = chunk->code[offset + 2];
printf("%-16s (%d args) %4d '", name, argCount, constant);
printValue(chunk->constants.values[constant]);
printf("'\n");
return offset + 3;
}
Code block 157
}
Code block 158
case OP_INVOKE: {
ObjString* method = READ_STRING();
int argCount = READ_BYTE();
if (!invoke(method, argCount)) {
return INTERPRET_RUNTIME_ERROR;
}
frame = &vm.frames[vm.frameCount - 1];
break;
}
Code block 159
case OP_CLOSURE: {
Code block 160
static bool invoke(ObjString* name, int argCount) {
Value receiver = peek(argCount);
ObjInstance* instance = AS_INSTANCE(receiver);
return invokeFromClass(instance->klass, name, argCount);
}
Code block 161
Value receiver = peek(argCount);
Code block 162
if (!IS_INSTANCE(receiver)) {
runtimeError("Only instances have methods.");
return false;
}
Code block 163
ObjInstance* instance = AS_INSTANCE(receiver);
Code block 164
static bool invokeFromClass(ObjClass* klass, ObjString* name,
int argCount) {
Value method;
if (!tableGet(&klass->methods, name, &method)) {
runtimeError("Undefined property '%s'.", name->chars);
return false;
}
return call(AS_CLOSURE(method), argCount);
}
Code block 165
class Oops {
init() {
fun f() {
print "not a method";
}
this.field = f;
}
}
var oops = Oops();
oops.field();
Code block 166
ObjInstance* instance = AS_INSTANCE(receiver);
Code block 167
Value value;
if (tableGet(&instance->fields, name, &value)) {
vm.stackTop[-argCount - 1] = value;
return callValue(value, argCount);
}
Code block 168
return invokeFromClass(instance->klass, name, argCount);
参考资料
- 原文:Methods and Initializers
- 系列索引
- Robert Nystrom, Crafting Interpreters,© 2015–2021
评论 (0)