[jlox] Interpret superclasses
This commit is contained in:
@@ -80,6 +80,14 @@ public class Interpreter implements Expr.Visitor<Object>, Stmt.Visitor<Void> {
|
||||
|
||||
@Override
|
||||
public Void visitClassStmt(Stmt.Class stmt) {
|
||||
Object superclass = null;
|
||||
if (stmt.superclass() != null) {
|
||||
superclass = evaluate(stmt.superclass());
|
||||
if (!(superclass instanceof LoxClass)) {
|
||||
throw new RuntimeError(stmt.superclass().name(), "Superclass must be a class.");
|
||||
}
|
||||
}
|
||||
|
||||
environment.define(stmt.name().lexeme(), null);
|
||||
|
||||
Map<String, LoxFunction> methods = new HashMap<>();
|
||||
@@ -88,7 +96,7 @@ public class Interpreter implements Expr.Visitor<Object>, Stmt.Visitor<Void> {
|
||||
methods.put(method.name().lexeme(), function);
|
||||
}
|
||||
|
||||
LoxClass clazz = new LoxClass(stmt.name().lexeme(), methods);
|
||||
LoxClass clazz = new LoxClass(stmt.name().lexeme(), (LoxClass) superclass, methods);
|
||||
environment.assign(stmt.name(), clazz);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -5,10 +5,12 @@ import java.util.Map;
|
||||
|
||||
public class LoxClass implements LoxCallable {
|
||||
final String name;
|
||||
private final LoxClass superclass;
|
||||
private final Map<String, LoxFunction> methods;
|
||||
|
||||
LoxClass(String name, Map<String, LoxFunction> methods) {
|
||||
LoxClass(String name, LoxClass superclass, Map<String, LoxFunction> methods) {
|
||||
this.name = name;
|
||||
this.superclass = superclass;
|
||||
this.methods = methods;
|
||||
}
|
||||
|
||||
@@ -39,6 +41,10 @@ public class LoxClass implements LoxCallable {
|
||||
return methods.get(name);
|
||||
}
|
||||
|
||||
if (superclass != null) {
|
||||
return superclass.findMethod(name);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user