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

Superclasses:super lookup 与继承调用

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

Crafting Interpreters:Superclasses

本章把 inheritance 完整接入 clox:class 继承 superclass、method lookup 沿层次结构工作,并通过 super call 调用被覆盖的方法。

TL;DR

  • subclass declaration 编译并执行 inheritance,子类的 method table 仍只保存自身声明的方法。
  • method lookup 失败时沿 superclass 链搜索;super call 则从指定 superclass 开始搜索。
  • superclass 在运行时暂存在 stack/local slot 中,保证编译和执行期间对象可达。
  • OP_GET_SUPER 与 OP_SUPER_INVOKE 处理 super property access 和直接调用。
  • 完成后,clox VM 支持 Lox 的完整面向对象模型:fields、methods、this、initializers 和 inheritance。

目录

章节内容
Inheriting methods继承执行
Storing superclassessuperclass local
Super callssuper lookup 与调用
A complete VM语言能力汇总
Challenges扩展练习

Inheriting methods

LoxClass 保存 superclass pointer。查找 method 时先查当前 class 的 methods table,找不到再递归查 superclass:

jlox resolve

clox 也使用相同语义,但把查找和调用编译为 bytecode。class declaration 运行时把 subclass 与 superclass 连接起来:

inherit stack

Executing inheritance

compiler 编译 class name、superclass expression 和 method declarations。执行 OP_INHERIT 时,VM 从 stack 取得 subclass 和 superclass,把 superclass methods 复制或链接到正确的 class representation。

clox 通常让 subclass 持有 superclass pointer,而不是复制所有 method。这样 method 更新和内存占用更可控,lookup 也能沿链进行。

Invalid superclasses

继承目标必须是 class object。对 number、string、instance 或其他非-class value 使用 <,应在 runtime 报错。class 不能继承自身,否则 method lookup 会形成循环。

Storing superclasses

编译 subclass body 时,superclass 需要在当前 stack 上保持可达。compiler 可以把它作为隐含 local 保存,并创建一个专门的 scope:

clox resolve

A superclass local variable

super expression 的 resolver distance 指向这个 local。class method 的 closure 同时能访问 this 和 super;执行时 super local 指向 superclass,this local 指向当前 receiver。

这种布局使 nested method 和 closure 能正确捕获 class context,也让 GC 能从 stack/frame 找到 class hierarchy 中仍在使用的 object。

Super calls

super call 使用 super.method() 语法。compiler 发出 method name 和 super reference,VM 先取得 superclass,再查找 method,并绑定当前 this。

super instructions

Executing super accesses

OP_GET_SUPER 读取 superclass 与 method name,从 superclass method table 中查找 function,然后用 this 创建 bound method。它不会从当前 instance 的 fields 中查找,因为 super 明确指定了查找起点。

Faster super calls

如果 super property 之后立刻调用,可以发出 OP_SUPER_INVOKE,避免先创建 bound-method object:

super invoke

该 opcode 直接完成 superclass lookup、receiver binding 和 call frame 创建,同时保持 method 的 arity 与 runtime error 检查。

A complete VM

完成本章后,clox 已覆盖:

  • scanner 与 Pratt compiler;
  • constants、global/local variables;
  • if、while、for 和 jump;
  • functions、call frames、closures 和 upvalues;
  • classes、instances、fields、methods、this、initializers;
  • superclass、inheritance 和 super calls;
  • mark-sweep garbage collection。

monkey

这套实现仍有可优化之处,但语言语义已经闭合。接下来进入 optimization:在保持行为不变的前提下减少 instruction、内存和执行时间。

Challenges

1. Multiple inheritance

实现多个 superclass,并比较 linearization、method conflict 和 super semantics。

2. Sealed classes

加入 sealed class,使 compiler 可以检查继承关系是否封闭。

3. Method cache

为 superclass lookup 添加缓存,并处理 hierarchy 或 method table 变化时的失效。

原文代码片段

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

Design Note:Classical Inheritance

inheritance 可以表达稳定的“is-a”关系,但不是所有 code reuse 都适合用 subclass。若行为只需要组合或委托,composition 往往能避免深层 hierarchy 和脆弱的 base-class 依赖。

参考资料

Code block 1

text
class Doughnut {
  cook() {
    print "Dunk in the fryer.";
  }
}

class Cruller < Doughnut {
  finish() {
    print "Glaze with icing.";
  }
}

Code block 2

c
  currentClass = &classCompiler;

Code block 3

c
  if (match(TOKEN_LESS)) {
    consume(TOKEN_IDENTIFIER, "Expect superclass name.");
    variable(false);
    namedVariable(className, false);
    emitByte(OP_INHERIT);
  }

Code block 4

text
  namedVariable(className, false);

Code block 5

text
class Cruller < Doughnut {

Code block 6

text
    variable(false);

Code block 7

c
    if (identifiersEqual(&className, &parser.previous)) {
      error("A class can't inherit from itself.");
    }

Code block 8

text
    namedVariable(className, false);

Code block 9

c
  OP_CLASS,

Code block 10

c
  OP_INHERIT,

Code block 11

c
  OP_METHOD

Code block 12

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

Code block 13

c
    case OP_INHERIT:
      return simpleInstruction("OP_INHERIT", offset);

Code block 14

c
    case OP_METHOD:

Code block 15

text
        break;

Code block 16

c
      case OP_INHERIT: {
        Value superclass = peek(1);
        ObjClass* subclass = AS_CLASS(peek(0));
        tableAddAll(&AS_CLASS(superclass)->methods,
                    &subclass->methods);
        pop(); // Subclass.
        break;
      }

Code block 17

c
      case OP_METHOD:

Code block 18

text
var NotClass = "So not a class";
class OhNo < NotClass {}

Code block 19

c
        Value superclass = peek(1);

Code block 20

c
        if (!IS_CLASS(superclass)) {
          runtimeError("Superclass must be a class.");
          return INTERPRET_RUNTIME_ERROR;
        }

Code block 21

c
        ObjClass* subclass = AS_CLASS(peek(0));

Code block 22

c
class A {
  method() {
    print "A method";
  }
}

class B < A {
  method() {
    print "B method";
  }

  test() {
    super.method();
  }
}

class C < B {}

C().test();

Code block 23

c
class A {
  method() {
    print "A method";
  }
}

var Bs_super = A;
class B < A {
  method() {
    print "B method";
  }

  test() {
    runtimeSuperCall(Bs_super, "method");
  }
}

var Cs_super = B;
class C < B {}

C().test();

Code block 24

text
    }

Code block 25

c
    beginScope();
    addLocal(syntheticToken("super"));
    defineVariable(0);

Code block 26

c
    namedVariable(className, false);
    emitByte(OP_INHERIT);

Code block 27

c
static Token syntheticToken(const char* text) {
  Token token;
  token.start = text;
  token.length = (int)strlen(text);
  return token;
}

Code block 28

c
  emitByte(OP_POP);

Code block 29

c
  if (classCompiler.hasSuperclass) {
    endScope();
  }

Code block 30

text
  currentClass = currentClass->enclosing;

Code block 31

c
typedef struct ClassCompiler {
  struct ClassCompiler* enclosing;

Code block 32

text
  bool hasSuperclass;

Code block 33

c
} ClassCompiler;

Code block 34

c
  ClassCompiler classCompiler;

Code block 35

c
  classCompiler.hasSuperclass = false;

Code block 36

c
  classCompiler.enclosing = currentClass;

Code block 37

c
    emitByte(OP_INHERIT);

Code block 38

c
    classCompiler.hasSuperclass = true;

Code block 39

text
  }

Code block 40

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

Code block 41

c
  [TOKEN_SUPER]         = {super_,   NULL,   PREC_NONE},

Code block 42

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

Code block 43

c
static void super_(bool canAssign) {
  consume(TOKEN_DOT, "Expect '.' after 'super'.");
  consume(TOKEN_IDENTIFIER, "Expect superclass method name.");
  uint8_t name = identifierConstant(&parser.previous);
}

Code block 44

c
class A {
  method() {
    print "A";
  }
}

class B < A {
  method() {
    var closure = super.method;
    closure(); // Prints "A".
  }
}

Code block 45

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

Code block 46

c
  namedVariable(syntheticToken("this"), false);
  namedVariable(syntheticToken("super"), false);
  emitBytes(OP_GET_SUPER, name);

Code block 47

text
}

Code block 48

c
class Doughnut {
  cook() {
    print "Dunk in the fryer.";
    this.finish("sprinkles");
  }

  finish(ingredient) {
    print "Finish with " + ingredient;
  }
}

class Cruller < Doughnut {
  finish(ingredient) {
    // No sprinkles, always icing.
    super.finish("icing");
  }
}

Code block 49

c
static void super_(bool canAssign) {

Code block 50

c
  if (currentClass == NULL) {
    error("Can't use 'super' outside of a class.");
  } else if (!currentClass->hasSuperclass) {
    error("Can't use 'super' in a class with no superclass.");
  }

Code block 51

c
  consume(TOKEN_DOT, "Expect '.' after 'super'.");

Code block 52

c
  OP_SET_PROPERTY,

Code block 53

c
  OP_GET_SUPER,

Code block 54

c
  OP_EQUAL,

Code block 55

c
      return constantInstruction("OP_SET_PROPERTY", chunk, offset);

Code block 56

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

Code block 57

c
    case OP_EQUAL:

Code block 58

text
      }

Code block 59

c
      case OP_GET_SUPER: {
        ObjString* name = READ_STRING();
        ObjClass* superclass = AS_CLASS(pop());

        if (!bindMethod(superclass, name)) {
          return INTERPRET_RUNTIME_ERROR;
        }
        break;
      }

Code block 60

c
      case OP_EQUAL: {

Code block 61

text
  namedVariable(syntheticToken("this"), false);

Code block 62

c
  if (match(TOKEN_LEFT_PAREN)) {
    uint8_t argCount = argumentList();
    namedVariable(syntheticToken("super"), false);
    emitBytes(OP_SUPER_INVOKE, name);
    emitByte(argCount);
  } else {
    namedVariable(syntheticToken("super"), false);
    emitBytes(OP_GET_SUPER, name);
  }

Code block 63

text
}

Code block 64

c
  OP_INVOKE,

Code block 65

c
  OP_SUPER_INVOKE,

Code block 66

c
  OP_CLOSURE,

Code block 67

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

Code block 68

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

Code block 69

c
    case OP_CLOSURE: {

Code block 70

text
        break;
      }

Code block 71

c
      case OP_SUPER_INVOKE: {
        ObjString* method = READ_STRING();
        int argCount = READ_BYTE();
        ObjClass* superclass = AS_CLASS(pop());
        if (!invokeFromClass(superclass, method, argCount)) {
          return INTERPRET_RUNTIME_ERROR;
        }
        frame = &vm.frames[vm.frameCount - 1];
        break;
      }

Code block 72

c
      case OP_CLOSURE: {

Code block 73

text
class Doughnut {
  cook() {
    print "Fry until golden brown.";
    inner();
    print "Place in a nice box.";
  }
}

class BostonCream < Doughnut {
  cook() {
    print "Pipe full of custard and coat with chocolate.";
  }
}

BostonCream().cook();

Code block 74

text
Fry until golden brown.
Pipe full of custard and coat with chocolate.
Place in a nice box.

参考资料

← 返回列表
← 上一篇 Methods and Initializers:bound method 与 init 下一篇 → Optimization:性能测量、hash probing 与 NaN boxing

评论 (0)

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