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

Methods and Initializers:bound method 与 init

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

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 declarationsmethod object 与编译
Method referencesbound method
Thisreceiver 绑定
Instance initializersinit()
Optimized invocationsinvoke opcode
Challenges扩展练习
Design Note:Novelty Budget新特性的成本

Method declarations

class body 中的 method 不需要 fun keyword。compiler 为每个 method 创建 function object,编译完成后发出 OP_METHOD,把 name 和 closure 放入当前 class:

method instructions

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:

bind method

随后把 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 留给参数:

closure slot

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。

party hat

Instance initializers

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

init call frame

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

c
typedef struct {
  Obj obj;
  ObjString* name;

Code block 2

c
  Table methods;

Code block 3

c
} ObjClass;

Code block 4

text
  klass->name = name;

Code block 5

c
  initTable(&klass->methods);

Code block 6

c
  return klass;

Code block 7

text
    case OBJ_CLASS: {

Code block 8

c
      ObjClass* klass = (ObjClass*)object;
      freeTable(&klass->methods);

Code block 9

c
      FREE(ObjClass, object);

Code block 10

text
      markObject((Obj*)klass->name);

Code block 11

c
      markTable(&klass->methods);

Code block 12

text
      break;

Code block 13

text
  consume(TOKEN_LEFT_BRACE, "Expect '{' before class body.");

Code block 14

c
  while (!check(TOKEN_RIGHT_BRACE) && !check(TOKEN_EOF)) {
    method();
  }

Code block 15

text
  consume(TOKEN_RIGHT_BRACE, "Expect '}' after class body.");

Code block 16

c
static void method() {
  consume(TOKEN_IDENTIFIER, "Expect method name.");
  uint8_t constant = identifierConstant(&parser.previous);
  emitBytes(OP_METHOD, constant);
}

Code block 17

text
  uint8_t constant = identifierConstant(&parser.previous);

Code block 18

text
  FunctionType type = TYPE_FUNCTION;
  function(type);

Code block 19

c
  emitBytes(OP_METHOD, constant);

Code block 20

text
  consume(TOKEN_IDENTIFIER, "Expect class name.");

Code block 21

text
  Token className = parser.previous;

Code block 22

text
  uint8_t nameConstant = identifierConstant(&parser.previous);

Code block 23

text
  defineVariable(nameConstant);

Code block 24

text
  namedVariable(className, false);

Code block 25

text
  consume(TOKEN_LEFT_BRACE, "Expect '{' before class body.");

Code block 26

text
  consume(TOKEN_RIGHT_BRACE, "Expect '}' after class body.");

Code block 27

c
  emitByte(OP_POP);

Code block 28

text
}

Code block 29

text
class Brunch {
  bacon() {}
  eggs() {}
}

Code block 30

c
  OP_CLASS,

Code block 31

c
  OP_METHOD

Code block 32

text
} OpCode;

Code block 33

c
    case OP_CLASS:
      return constantInstruction("OP_CLASS", chunk, offset);

Code block 34

c
    case OP_METHOD:
      return constantInstruction("OP_METHOD", chunk, offset);

Code block 35

text
    default:

Code block 36

text
        break;

Code block 37

c
      case OP_METHOD:
        defineMethod(READ_STRING());
        break;

Code block 38

text
    }

Code block 39

c
static void defineMethod(ObjString* name) {
  Value method = peek(0);
  ObjClass* klass = AS_CLASS(peek(1));
  tableSet(&klass->methods, name, method);
  pop();
}

Code block 40

text
instance.method(argument);

Code block 41

text
var closure = instance.method;
closure(argument);

Code block 42

text
class Person {
  sayName() {
    print this.name;
  }
}

var jane = Person();
jane.name = "Jane";

var method = jane.sayName;
method(); // ?

Code block 43

c
} ObjInstance;

Code block 44

c
typedef struct {
  Obj obj;
  Value receiver;
  ObjClosure* method;
} ObjBoundMethod;

Code block 45

c
ObjClass* newClass(ObjString* name);

Code block 46

c
typedef enum {

Code block 47

text
  OBJ_BOUND_METHOD,

Code block 48

text
  OBJ_CLASS,

Code block 49

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

Code block 50

c
#define IS_BOUND_METHOD(value) isObjType(value, OBJ_BOUND_METHOD)

Code block 51

c
#define IS_CLASS(value)        isObjType(value, OBJ_CLASS)

Code block 52

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

Code block 53

c
#define AS_BOUND_METHOD(value) ((ObjBoundMethod*)AS_OBJ(value))

Code block 54

c
#define AS_CLASS(value)        ((ObjClass*)AS_OBJ(value))

Code block 55

c
} ObjBoundMethod;

Code block 56

c
ObjBoundMethod* newBoundMethod(Value receiver,
                               ObjClosure* method);

Code block 57

c
ObjClass* newClass(ObjString* name);

Code block 58

c
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

text
  switch (object->type) {

Code block 60

c
    case OBJ_BOUND_METHOD:
      FREE(ObjBoundMethod, object);
      break;

Code block 61

text
    case OBJ_CLASS: {

Code block 62

text
  switch (object->type) {

Code block 63

c
    case OBJ_BOUND_METHOD: {
      ObjBoundMethod* bound = (ObjBoundMethod*)object;
      markValue(bound->receiver);
      markObject((Obj*)bound->method);
      break;
    }

Code block 64

text
    case OBJ_CLASS: {

Code block 65

text
  switch (OBJ_TYPE(value)) {

Code block 66

text
    case OBJ_BOUND_METHOD:
      printFunction(AS_BOUND_METHOD(value)->method->function);
      break;

Code block 67

text
    case OBJ_CLASS:

Code block 68

text
          pop(); // Instance.
          push(value);
          break;
        }

Code block 69

c
        if (!bindMethod(instance->klass, name)) {
          return INTERPRET_RUNTIME_ERROR;
        }
        break;

Code block 70

text
      }

Code block 71

c
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

text
class Brunch {
  eggs() {}
}

var brunch = Brunch();
var eggs = brunch.eggs;

Code block 73

text
    switch (OBJ_TYPE(callee)) {

Code block 74

c
      case OBJ_BOUND_METHOD: {
        ObjBoundMethod* bound = AS_BOUND_METHOD(callee);
        return call(bound->method, argCount);
      }

Code block 75

text
      case OBJ_CLASS: {

Code block 76

text
class Scone {
  topping(first, second) {
    print "scone with " + first + " and " + second;
  }
}

var scone = Scone();
scone.topping("berries", "cream");

Code block 77

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

Code block 78

text
  [TOKEN_THIS]          = {this_,    NULL,   PREC_NONE},

Code block 79

text
  [TOKEN_TRUE]          = {literal,  NULL,   PREC_NONE},

Code block 80

c
static void this_(bool canAssign) {
  variable(false);
}

Code block 81

text
  local->isCaptured = false;

Code block 82

c
  if (type != TYPE_FUNCTION) {
    local->name.start = "this";
    local->name.length = 4;
  } else {
    local->name.start = "";
    local->name.length = 0;
  }

Code block 83

text
}

Code block 84

text
class Nested {
  method() {
    fun function() {
      print this;
    }

    function();
  }
}

Nested().method();

Code block 85

text
  TYPE_FUNCTION,

Code block 86

text
  TYPE_METHOD,

Code block 87

text
  TYPE_SCRIPT

Code block 88

text
  uint8_t constant = identifierConstant(&parser.previous);

Code block 89

text
  FunctionType type = TYPE_METHOD;

Code block 90

text
  function(type);

Code block 91

c
      case OBJ_BOUND_METHOD: {
        ObjBoundMethod* bound = AS_BOUND_METHOD(callee);

Code block 92

text
        vm.stackTop[-argCount - 1] = bound->receiver;

Code block 93

c
        return call(bound->method, argCount);
      }

Code block 94

text
scone.topping("berries", "cream");

Code block 95

c
print this; // At top level.

fun notMethod() {
  print this; // In a function.
}

Code block 96

c
Compiler* current = NULL;

Code block 97

c
ClassCompiler* currentClass = NULL;

Code block 98

c
static Chunk* currentChunk() {

Code block 99

c
} Compiler;

Code block 100

c
typedef struct ClassCompiler {
  struct ClassCompiler* enclosing;
} ClassCompiler;

Code block 101

text
Parser parser;

Code block 102

text
  defineVariable(nameConstant);

Code block 103

c
  ClassCompiler classCompiler;
  classCompiler.enclosing = currentClass;
  currentClass = &classCompiler;

Code block 104

text
  namedVariable(className, false);

Code block 105

c
  emitByte(OP_POP);

Code block 106

text
  currentClass = currentClass->enclosing;

Code block 107

text
}

Code block 108

c
static void this_(bool canAssign) {

Code block 109

c
  if (currentClass == NULL) {
    error("Can't use 'this' outside of a class.");
    return;
  }

Code block 110

text
  variable(false);

Code block 111

c
fun create(klass) {
  var obj = newInstance(klass);
  obj.init();
  return obj;
}

Code block 112

text
        vm.stackTop[-argCount - 1] = OBJ_VAL(newInstance(klass));

Code block 113

c
        Value initializer;
        if (tableGet(&klass->methods, vm.initString,
                     &initializer)) {
          return call(AS_CLOSURE(initializer), argCount);
        }

Code block 114

c
        return true;

Code block 115

text
class Brunch {
  init(food, drink) {}
}

Brunch("eggs", "coffee");

Code block 116

c
          return call(AS_CLOSURE(initializer), argCount);

Code block 117

c
        } else if (argCount != 0) {
          runtimeError("Expected 0 arguments but got %d.",
                       argCount);
          return false;

Code block 118

text
        }

Code block 119

c
  Table strings;

Code block 120

text
  ObjString* initString;

Code block 121

text
  ObjUpvalue* openUpvalues;

Code block 122

c
  initTable(&vm.strings);

Code block 123

text
  vm.initString = copyString("init", 4);

Code block 124

text
  defineNative("clock", clockNative);

Code block 125

c
  markCompilerRoots();

Code block 126

text
  markObject((Obj*)vm.initString);

Code block 127

text
}

Code block 128

c
  initTable(&vm.strings);

Code block 129

text
  vm.initString = NULL;

Code block 130

text
  vm.initString = copyString("init", 4);

Code block 131

c
  freeTable(&vm.strings);

Code block 132

text
  vm.initString = NULL;

Code block 133

text
  freeObjects();

Code block 134

text
  FunctionType type = TYPE_METHOD;

Code block 135

c
  if (parser.previous.length == 4 &&
      memcmp(parser.previous.start, "init", 4) == 0) {
    type = TYPE_INITIALIZER;
  }

Code block 136

text
  function(type);

Code block 137

text
  TYPE_FUNCTION,

Code block 138

text
  TYPE_INITIALIZER,

Code block 139

text
  TYPE_METHOD,

Code block 140

c
static void emitReturn() {

Code block 141

c
  if (current->type == TYPE_INITIALIZER) {
    emitBytes(OP_GET_LOCAL, 0);
  } else {
    emitByte(OP_NIL);
  }

Code block 142

c
  emitByte(OP_RETURN);

Code block 143

c
  if (match(TOKEN_SEMICOLON)) {
    emitReturn();
  } else {

Code block 144

c
    if (current->type == TYPE_INITIALIZER) {
      error("Can't return a value from an initializer.");
    }

Code block 145

text
    expression();

Code block 146

text
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

c
  if (canAssign && match(TOKEN_EQUAL)) {
    expression();
    emitBytes(OP_SET_PROPERTY, name);

Code block 148

c
  } else if (match(TOKEN_LEFT_PAREN)) {
    uint8_t argCount = argumentList();
    emitBytes(OP_INVOKE, name);
    emitByte(argCount);

Code block 149

text
  } else {

Code block 150

c
  OP_CALL,

Code block 151

c
  OP_INVOKE,

Code block 152

c
  OP_CLOSURE,

Code block 153

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

Code block 154

c
    case OP_INVOKE:
      return invokeInstruction("OP_INVOKE", chunk, offset);

Code block 155

c
    case OP_CLOSURE: {

Code block 156

c
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

text
      }

Code block 158

c
      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

c
      case OP_CLOSURE: {

Code block 160

c
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

c
  Value receiver = peek(argCount);

Code block 162

c
  if (!IS_INSTANCE(receiver)) {
    runtimeError("Only instances have methods.");
    return false;
  }

Code block 163

c
  ObjInstance* instance = AS_INSTANCE(receiver);

Code block 164

c
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

text
class Oops {
  init() {
    fun f() {
      print "not a method";
    }

    this.field = f;
  }
}

var oops = Oops();
oops.field();

Code block 166

c
  ObjInstance* instance = AS_INSTANCE(receiver);

Code block 167

c
  Value value;
  if (tableGet(&instance->fields, name, &value)) {
    vm.stackTop[-argCount - 1] = value;
    return callValue(value, argCount);
  }

Code block 168

c
  return invokeFromClass(instance->klass, name, argCount);

参考资料

← 返回列表
← 上一篇 Classes and Instances:clox 对象与属性访问 下一篇 → Superclasses:super lookup 与继承调用

评论 (0)

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