Classes:对象、方法与 this 绑定
Crafting Interpreters:Classes
本章为 Lox 加入 classes、instances、fields、methods、this,以及构造器和 initializer。
TL;DR
- Class declaration 创建 class object;instance 保存 fields,class 保存 methods。
- Property access 先查找 instance field,再查找 class method;set expression 只写入 instance field。
- method 通过 closure 绑定 this,使同一个 method 在不同 instance 上调用时拥有不同接收者。
- init() 是特殊 initializer:调用后总是返回新建的 instance,即使函数体中显式 return。
- Class、instance、method 都实现统一的 callable 语义,constructor call 因而可以复用普通 function-call machinery。
目录
| 章节 | 内容 |
|---|---|
| OOP and classes | object model |
| Class declarations | 声明与 method |
| Creating instances | class call 与 instance |
| Properties on instances | get/set |
| Methods on classes | method lookup |
| This | receiver binding |
| Constructors and initializers | init() |
| Challenges | 扩展练习 |
| Design Note:Prototypes and Power | class 与 prototype |
OOP and classes
Object-oriented programming 把 data 与操作 data 的行为组织在一起。Lox 的 class 是一等 runtime value,可以存储在变量中、传给 function,也可以被调用来创建 instance。

Class object 保存 method;instance 保存 fields。调用 class 时创建 instance,调用 instance 上的 method 时再把 instance 作为 this 绑定到 method closure。
Class declarations
class declaration 读取 class name 和一组 method declarations。每个 method 类似 function,但保存为 LoxFunction,并放入 LoxClass 的 method map。class statement 执行时创建 class object,并在当前 environment 定义名称。
method 的语法树与 function body 类似,因此 parser 可以复用 parameters 和 block parsing。区别在于 method 不需要 fun keyword,而且 resolver 要知道当前是在 function 还是 class 中。
Creating instances
LoxClass 实现 LoxCallable。class 的 arity 由 init method 决定;调用 class 时先创建 LoxInstance,再调用 initializer(如果存在),最后返回 instance。
class call 的执行路径可以复用 function call:检查 arity、创建 call environment、绑定 arguments、执行 body。class 只是把 call 的结果改成 instance,并在初始化阶段运行 init。
Properties on instances
instance property access 使用 dot syntax。get expression 首先检查 instance.fields;如果没有该 field,再从 class 查找 method,并返回绑定后的 method。

set expression 要求左侧是 instance。它先求值 object,再求值右侧 value,最后写入 field:

字段 lookup 先于 method lookup,因此 instance field 可以 shadow 同名 method。对非-instance 值读取或写入 property 会产生 runtime error。
Methods on classes
LoxClass 的 findMethod(name) 在 method map 中查找。method 本身是 LoxFunction,返回前需要 bind(instance),把 this 放入一个新的 Environment。

同一个 method declaration 可以绑定到多个 instance,每次绑定都产生不同 closure:

This
this 是一个特殊的 variable expression。resolver 在 class scope 中把 this 标记为已定义;解释 class method 时,绑定 Environment 中的 this 让 method body 能访问接收者。

this 不能在 class 外部使用。nested function 是否能访问 this,取决于它是否通过 closure 捕获了 method 的环境;这也是 lexical scope 和 resolver 协作的地方。
Constructors and initializers
如果 class 有名为 init 的 method,它就是 initializer。class call 创建 instance 后调用 init,并把 instance 作为 this。无论 init 是否显式 return,最终结果都必须是 instance。

直接调用 obj.init() 也应返回 obj,而不是显式 return 的值。这样初始化方法的语义始终稳定,不会因为调用方式不同而改变。
Challenges
1. Class fields
允许 class declaration 直接声明默认 field,并决定默认值是在 class 创建时还是 instance 创建时计算。
2. Private properties
设计 private field 或 method。说明 parser、resolver 和 runtime lookup 需要怎样改变,以及继承章节如何处理可见性。
3. Static methods
添加 class-level static method,使 method 可以通过 class object 调用而不需要 instance。
4. Multiple constructors
支持多个构造器或 named constructors,并说明它们与统一的 callable/arity interface 如何协作。
Design Note:Prototypes and Power
Class-based object model 通过 class 描述 instance 的结构与行为;prototype-based model 则让对象直接委托给另一个对象。两者都能表达共享行为、覆盖属性和动态 dispatch。
Class 的优势是关系显式、工具容易展示;prototype 的优势是运行时组合灵活、无需先定义固定 class hierarchy。语言设计不应只追求最强表达能力:更强的动态能力也意味着 lookup、mutation 和错误诊断更难理解。
原文代码片段
本节按官方页面顺序保留本章所有 grammar、Java 和测试代码片段,便于与上文译文逐段对照。
参考资料
Code block 1
declaration → classDecl
| funDecl
| varDecl
| statement ;
classDecl → "class" IDENTIFIER "{" function* "}" ;
Code block 2
function → IDENTIFIER "(" parameters? ")" block ;
parameters → IDENTIFIER ( "," IDENTIFIER )* ;
Code block 3
class Breakfast {
cook() {
print "Eggs a-fryin'!";
}
serve(who) {
print "Enjoy your breakfast, " + who + ".";
}
}
Code block 4
"Block : List<Stmt> statements",
Code block 5
"Class : Token name, List<Stmt.Function> methods",
Code block 6
"Expression : Expr expression",
Code block 7
try {
Code block 8
if (match(CLASS)) return classDeclaration();
Code block 9
if (match(FUN)) return function("function");
Code block 10
private Stmt classDeclaration() {
Token name = consume(IDENTIFIER, "Expect class name.");
consume(LEFT_BRACE, "Expect '{' before class body.");
List<Stmt.Function> methods = new ArrayList<>();
while (!check(RIGHT_BRACE) && !isAtEnd()) {
methods.add(function("method"));
}
consume(RIGHT_BRACE, "Expect '}' after class body.");
return new Stmt.Class(name, methods);
}
Code block 11
@Override
public Void visitClassStmt(Stmt.Class stmt) {
declare(stmt.name);
define(stmt.name);
return null;
}
Code block 12
@Override
public Void visitClassStmt(Stmt.Class stmt) {
environment.define(stmt.name.lexeme, null);
LoxClass klass = new LoxClass(stmt.name.lexeme);
environment.assign(stmt.name, klass);
return null;
}
Code block 13
package com.craftinginterpreters.lox;
import java.util.List;
import java.util.Map;
class LoxClass {
final String name;
LoxClass(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
Code block 14
class DevonshireCream {
serveOn() {
return "Scones";
}
}
print DevonshireCream; // Prints "DevonshireCream".
Code block 15
class Bagel {}
Bagel();
Code block 16
import java.util.Map;
Code block 17
class LoxClass implements LoxCallable {
Code block 18
final String name;
Code block 19
@Override
public Object call(Interpreter interpreter,
List<Object> arguments) {
LoxInstance instance = new LoxInstance(this);
return instance;
}
@Override
public int arity() {
return 0;
}
Code block 20
package com.craftinginterpreters.lox;
import java.util.HashMap;
import java.util.Map;
class LoxInstance {
private LoxClass klass;
LoxInstance(LoxClass klass) {
this.klass = klass;
}
@Override
public String toString() {
return klass.name + " instance";
}
}
Code block 21
class Bagel {}
var bagel = Bagel();
print bagel; // Prints "Bagel instance".
Code block 22
someObject.someProperty
Code block 23
call → primary ( "(" arguments? ")" | "." IDENTIFIER )* ;
Code block 24
"Call : Expr callee, Token paren, List<Expr> arguments",
Code block 25
"Get : Expr object, Token name",
Code block 26
"Grouping : Expr expression",
Code block 27
while (true) {
if (match(LEFT_PAREN)) {
expr = finishCall(expr);
Code block 28
} else if (match(DOT)) {
Token name = consume(IDENTIFIER,
"Expect property name after '.'.");
expr = new Expr.Get(expr, name);
Code block 29
} else {
break;
}
}
Code block 30
@Override
public Void visitGetExpr(Expr.Get expr) {
resolve(expr.object);
return null;
}
Code block 31
@Override
public Object visitGetExpr(Expr.Get expr) {
Object object = evaluate(expr.object);
if (object instanceof LoxInstance) {
return ((LoxInstance) object).get(expr.name);
}
throw new RuntimeError(expr.name,
"Only instances have properties.");
}
Code block 32
private LoxClass klass;
Code block 33
private final Map<String, Object> fields = new HashMap<>();
Code block 34
LoxInstance(LoxClass klass) {
Code block 35
Object get(Token name) {
if (fields.containsKey(name.lexeme)) {
return fields.get(name.lexeme);
}
throw new RuntimeError(name,
"Undefined property '" + name.lexeme + "'.");
}
Code block 36
someObject.someProperty = value;
Code block 37
assignment → ( call "." )? IDENTIFIER "=" assignment
| logic_or ;
Code block 38
"Logical : Expr left, Token operator, Expr right",
Code block 39
"Set : Expr object, Token name, Expr value",
Code block 40
"Unary : Token operator, Expr right",
Code block 41
return new Expr.Assign(name, value);
Code block 42
} else if (expr instanceof Expr.Get) {
Expr.Get get = (Expr.Get)expr;
return new Expr.Set(get.object, get.name, value);
Code block 43
}
Code block 44
@Override
public Void visitSetExpr(Expr.Set expr) {
resolve(expr.value);
resolve(expr.object);
return null;
}
Code block 45
@Override
public Object visitSetExpr(Expr.Set expr) {
Object object = evaluate(expr.object);
if (!(object instanceof LoxInstance)) {
throw new RuntimeError(expr.name,
"Only instances have fields.");
}
Object value = evaluate(expr.value);
((LoxInstance)object).set(expr.name, value);
return value;
}
Code block 46
void set(Token name, Object value) {
fields.put(name.lexeme, value);
}
Code block 47
var m = object.method;
m(argument);
Code block 48
class Box {}
fun notMethod(argument) {
print "called function with " + argument;
}
var box = Box();
box.function = notMethod;
box.function("argument");
Code block 49
breakfast(omelette.filledWith(cheese), sausage);
Code block 50
var eggs = omelette.filledWith(cheese);
breakfast(eggs, sausage);
Code block 51
fun callback(a, b, c) {
object.method(a, b, c);
}
takeCallback(callback);
Code block 52
takeCallback(object.method);
Code block 53
class Person {
sayName() {
print this.name;
}
}
var jane = Person();
jane.name = "Jane";
var method = jane.sayName;
method(); // ?
Code block 54
class Person {
sayName() {
print this.name;
}
}
var jane = Person();
jane.name = "Jane";
var bill = Person();
bill.name = "Bill";
bill.sayName = jane.sayName;
bill.sayName(); // ?
Code block 55
define(stmt.name);
Code block 56
for (Stmt.Function method : stmt.methods) {
FunctionType declaration = FunctionType.METHOD;
resolveFunction(method, declaration);
}
Code block 57
return null;
Code block 58
NONE,
Code block 59
FUNCTION,
Code block 60
METHOD
Code block 61
}
Code block 62
environment.define(stmt.name.lexeme, null);
Code block 63
Map<String, LoxFunction> methods = new HashMap<>();
for (Stmt.Function method : stmt.methods) {
LoxFunction function = new LoxFunction(method, environment);
methods.put(method.name.lexeme, function);
}
LoxClass klass = new LoxClass(stmt.name.lexeme, methods);
Code block 64
environment.assign(stmt.name, klass);
Code block 65
final String name;
Code block 66
private final Map<String, LoxFunction> methods;
LoxClass(String name, Map<String, LoxFunction> methods) {
this.name = name;
this.methods = methods;
}
Code block 67
@Override
public String toString() {
Code block 68
Object get(Token name) {
if (fields.containsKey(name.lexeme)) {
return fields.get(name.lexeme);
}
Code block 69
LoxFunction method = klass.findMethod(name.lexeme);
if (method != null) return method;
Code block 70
throw new RuntimeError(name,
"Undefined property '" + name.lexeme + "'.");
Code block 71
LoxFunction findMethod(String name) {
if (methods.containsKey(name)) {
return methods.get(name);
}
return null;
}
Code block 72
class Bacon {
eat() {
print "Crunch crunch crunch!";
}
}
Bacon().eat(); // Prints "Crunch crunch crunch!".
Code block 73
class Egotist {
speak() {
print this;
}
}
var method = Egotist().speak;
method();
Code block 74
class Cake {
taste() {
var adjective = "delicious";
print "The " + this.flavor + " cake is " + adjective + "!";
}
}
var cake = Cake();
cake.flavor = "German chocolate";
cake.taste(); // Prints "The German chocolate cake is delicious!".
Code block 75
class Thing {
getCallback() {
fun localFunction() {
print this;
}
return localFunction;
}
}
var callback = Thing().getCallback();
callback();
Code block 76
"Set : Expr object, Token name, Expr value",
Code block 77
"This : Token keyword",
Code block 78
"Unary : Token operator, Expr right",
Code block 79
return new Expr.Literal(previous().literal);
}
Code block 80
if (match(THIS)) return new Expr.This(previous());
Code block 81
if (match(IDENTIFIER)) {
Code block 82
@Override
public Void visitThisExpr(Expr.This expr) {
resolveLocal(expr, expr.keyword);
return null;
}
Code block 83
define(stmt.name);
Code block 84
beginScope();
scopes.peek().put("this", true);
Code block 85
for (Stmt.Function method : stmt.methods) {
Code block 86
}
Code block 87
endScope();
Code block 88
return null;
Code block 89
LoxFunction method = klass.findMethod(name.lexeme);
Code block 90
if (method != null) return method.bind(this);
Code block 91
throw new RuntimeError(name,
"Undefined property '" + name.lexeme + "'.");
Code block 92
LoxFunction bind(LoxInstance instance) {
Environment environment = new Environment(closure);
environment.define("this", instance);
return new LoxFunction(declaration, environment);
}
Code block 93
@Override
public Object visitThisExpr(Expr.This expr) {
return lookUpVariable(expr.keyword, expr);
}
Code block 94
print this;
Code block 95
fun notAMethod() {
print this;
}
Code block 96
}
Code block 97
private enum ClassType {
NONE,
CLASS
}
private ClassType currentClass = ClassType.NONE;
Code block 98
void resolve(List<Stmt> statements) {
Code block 99
public Void visitClassStmt(Stmt.Class stmt) {
Code block 100
ClassType enclosingClass = currentClass;
currentClass = ClassType.CLASS;
Code block 101
declare(stmt.name);
Code block 102
endScope();
Code block 103
currentClass = enclosingClass;
Code block 104
return null;
Code block 105
public Void visitThisExpr(Expr.This expr) {
Code block 106
if (currentClass == ClassType.NONE) {
Lox.error(expr.keyword,
"Can't use 'this' outside of a class.");
return null;
}
Code block 107
resolveLocal(expr, expr.keyword);
Code block 108
List<Object> arguments) {
LoxInstance instance = new LoxInstance(this);
Code block 109
LoxFunction initializer = findMethod("init");
if (initializer != null) {
initializer.bind(instance).call(interpreter, arguments);
}
Code block 110
return instance;
Code block 111
public int arity() {
Code block 112
LoxFunction initializer = findMethod("init");
if (initializer == null) return 0;
return initializer.arity();
Code block 113
}
Code block 114
class Foo {
init() {
print this;
}
}
var foo = Foo();
print foo.init();
Code block 115
return returnValue.value;
}
Code block 116
if (isInitializer) return closure.getAt(0, "this");
Code block 117
return null;
Code block 118
private final Environment closure;
Code block 119
private final boolean isInitializer;
LoxFunction(Stmt.Function declaration, Environment closure,
boolean isInitializer) {
this.isInitializer = isInitializer;
Code block 120
this.closure = closure;
this.declaration = declaration;
Code block 121
public Void visitFunctionStmt(Stmt.Function stmt) {
Code block 122
LoxFunction function = new LoxFunction(stmt, environment,
false);
Code block 123
environment.define(stmt.name.lexeme, function);
Code block 124
for (Stmt.Function method : stmt.methods) {
Code block 125
LoxFunction function = new LoxFunction(method, environment,
method.name.lexeme.equals("init"));
Code block 126
methods.put(method.name.lexeme, function);
Code block 127
environment.define("this", instance);
Code block 128
return new LoxFunction(declaration, environment,
isInitializer);
Code block 129
}
Code block 130
class Foo {
init() {
return "something else";
}
}
Code block 131
FUNCTION,
Code block 132
INITIALIZER,
Code block 133
METHOD
Code block 134
FunctionType declaration = FunctionType.METHOD;
Code block 135
if (method.name.lexeme.equals("init")) {
declaration = FunctionType.INITIALIZER;
}
Code block 136
resolveFunction(method, declaration);
Code block 137
if (stmt.value != null) {
Code block 138
if (currentFunction == FunctionType.INITIALIZER) {
Lox.error(stmt.keyword,
"Can't return a value from an initializer.");
}
Code block 139
resolve(stmt.value);
Code block 140
class Foo {
init() {
return;
}
}
Code block 141
} catch (Return returnValue) {
Code block 142
if (isInitializer) return closure.getAt(0, "this");
Code block 143
return returnValue.value;
Code block 144
class Math {
class square(n) {
return n * n;
}
}
print Math.square(3); // Prints "9".
Code block 145
class Circle {
init(radius) {
this.radius = radius;
}
area {
return 3.141592653 * this.radius * this.radius;
}
}
var circle = Circle(4);
print circle.area; // Prints roughly "50.2655".
Code block 146
power = breadth × ease ÷ complexity
参考资料
- 原文:Classes
- 系列索引
- Robert Nystrom, Crafting Interpreters,© 2015–2021
评论 (0)