[Chapter12&Classes] - Adding support for classes

This commit is contained in:
Adnan Ioricce 2024-10-06 03:11:41 +00:00
parent 9559cab2ce
commit 05a8ac6127
7 changed files with 418 additions and 203 deletions

@ -38,6 +38,23 @@ class Interpreter implements Expr.Visitor<Object>,Stmt.Visitor<Void> {
}
return evaluate(expr.right);
}
@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;
}
@Override
public Object visitThisExpr(Expr.This expr) {
return lookUpVariable(expr.keyword, expr);
}
@Override
public Object visitUnaryExpr(Expr.Unary expr) {
Object right = evaluate(expr.right);
@ -141,13 +158,24 @@ class Interpreter implements Expr.Visitor<Object>,Stmt.Visitor<Void> {
return function.call(this, arguments);
}
@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.");
}
@Override
public Void visitExpressionStmt(Stmt.Expression stmt) {
evaluate(stmt.expression);
return null;
}
@Override
public Void visitFunctionStmt(Stmt.Function stmt) {
LoxFunction function = new LoxFunction(stmt,environment);
LoxFunction function = new LoxFunction(stmt, environment,
false);
environment.define(stmt.name.lexeme, function);
return null;
}
@ -251,7 +279,20 @@ class Interpreter implements Expr.Visitor<Object>,Stmt.Visitor<Void> {
executeBlock(stmt.statements, new Environment(environment));
return null;
}
@Override
public void visitClassStmt(Stmt.Class stmt){
environment.define(stmt.name.lexeme, null);
Map<String, LoxFunction> methods = new HashMap<>();
for (Stmt.Function method : stmt.methods) {
LoxFunction function = new LoxFunction(method, environment,
method.name.lexeme.equals("init"));
methods.put(method.name.lexeme, function);
}
LoxClass klass = new LoxClass(stmt.name.lexeme, methods);
environment.assign(stmt.name, klass);
return null;
}
private String stringify(Object object) {
if (object == null) return "nil";

43
src/com/lox/LoxClass.java Normal file

@ -0,0 +1,43 @@
package com.lox;
import java.util.List;
import java.util.Map;
class LoxClass implements LoxCallable {
final String name;
private final Map<String, LoxFunction> methods;
LoxClass(String name, Map<String, LoxFunction> methods) {
this.name = name;
this.methods = methods;
}
LoxFunction findMethod(String name) {
if (methods.containsKey(name)) {
return methods.get(name);
}
return null;
}
@Override
public String toString(){
return name;
}
@Override
public Object call(
Intepreter interpreter
, List<Object> arguments){
LoxInstance instance = new LoxInstance(this);
LoxFunction initializer = findMethod("init");
if (initializer != null) {
initializer.bind(instance).call(interpreter, arguments);
}
return instance;
}
@Override
public int arity(){
LoxFunction initializer = findMethod("init");
if (initializer == null) return 0;
return initializer.arity();
}
}

@ -5,10 +5,21 @@ import java.util.List;
class LoxFunction implements LoxCallable {
private final Stmt.Function declaration;
private final Environment closure;
LoxFunction(Stmt.Function declaration, Environment closure) {
private final boolean isInitializer;
LoxFunction(Stmt.Function declaration, Environment closure,
boolean isInitializer) {
this.isInitializer = isInitializer;
this.closure = closure;
this.declaration = declaration;
}
LoxFunction bind(LoxInstance instance) {
Environment environment = new Environment(closure);
environment.define("this", instance);
return new LoxFunction(declaration, environment,
isInitializer);
}
@Override
public String toString() {
return "<fn " + declaration.name.lexeme + ">";
@ -28,8 +39,12 @@ class LoxFunction implements LoxCallable {
try {
interpreter.executeBlock(declaration.body, environment);
} catch (Return returnValue) {
if (isInitializer) return closure.getAt(0, "this");
return returnValue.value;
}
if (isInitializer) return closure.getAt(0, "this");
return null;
}
}

@ -0,0 +1,33 @@
package com.lox;
import java.util.HashMap;
import java.util.Map;
class LoxInstance {
private LoxClass klass;
private final Map<String, Object> fields = new HashMap<>();
LoxInstance(LoxClass klass){
this.klass = klass;
}
Object get(Token name) {
if (fields.containsKey(name.lexeme)) {
return fields.get(name.lexeme);
}
LoxFunction method = klass.findMethod(name.lexeme);
if (method != null) return method.bind(this);
throw new RuntimeError(name,
"Undefined property '" + name.lexeme + "'.");
}
void set(Token name, Object value) {
fields.put(name.lexeme, value);
}
@Override
public String toString(){
return klass.name + " Instance";
}
}

@ -31,6 +31,19 @@ class Parser {
return null;
}
}
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,)
}
private Expr expression(){
return assignment();
}
@ -174,8 +187,13 @@ class Parser {
if (expr instanceof Expr.Variable) {
Token name = ((Expr.Variable)expr).name;
return new Expr.Assign(name, value);
} else if (expr instanceof Expr.Get) {
Expr.Get get = (Expr.Get)expr;
return new Expr.Set(get.object, get.name, value);
}
error(equals, "Invalid assignment target.");
}
@ -275,6 +293,10 @@ class Parser {
while(true){
if(match(LEFT_PAREN)){
expr = finishCall(expr);
} else if(match(DOT)){
Token name = consume(IDENTIFIER
, "Expect property name after '.'.");
expr = new Expr.Get(expr, name);
}
else {
break;
@ -301,6 +323,8 @@ class Parser {
return new Expr.Variable(previous());
}
if (match(THIS)) return new Expr.This(previous());
throw error(peek(), "Expect expression.");
}

@ -14,8 +14,18 @@ class Resolver implements Expr.Visitor<Void>, Stmt.Visitor<Void> {
}
private enum FunctionType {
NONE,
FUNCTION,
INITIALIZER,
METHOD,
FUNCTION
}
private enum ClassType {
NONE,
CLASS
}
private ClassType currentClass = ClassType.NONE;
private void resolve(Expr expr) {
expr.accept(this);
}
@ -41,6 +51,27 @@ class Resolver implements Expr.Visitor<Void>, Stmt.Visitor<Void> {
return null;
}
@Override
public void visitClassStmt(Stmt.Class stmt){
ClassType enclosingClass = currentClass;
currentClass = ClassType.CLASS;
declare(stmt.name);
define(stmt.name);
beginScope();
scopes.peek().put("this", true);
for (Stmt.Function method : stmt.methods) {
FunctionType declaration = FunctionType.METHOD;
if (method.name.lexeme.equals("init")) {
declaration = FunctionType.INITIALIZER;
}
resolveFunction(method, declaration);
}
endScope();
currentClass = enclosingClass;
return null;
}
@Override
public Void visitExpressionStmt(Stmt.Expression stmt) {
resolve(stmt.expression);
return null;
@ -72,6 +103,10 @@ class Resolver implements Expr.Visitor<Void>, Stmt.Visitor<Void> {
Lox.error(stmt.keyword, "Can't return from top-level code.");
}
if (stmt.value != null) {
if (currentFunction == FunctionType.INITIALIZER) {
Lox.error(stmt.keyword,
"Can't return a value from an initializer.");
}
resolve(stmt.value);
}
@ -133,7 +168,11 @@ class Resolver implements Expr.Visitor<Void>, Stmt.Visitor<Void> {
return null;
}
@Override
public Void visitGetExpr(Expr.Get expr){
resolve(expr.object);
return null;
}
@Override
public Void visitGroupingExpr(Expr.Grouping expr) {
resolve(expr.expression);
@ -150,6 +189,22 @@ class Resolver implements Expr.Visitor<Void>, Stmt.Visitor<Void> {
resolve(expr.right);
return null;
}
@Override
public Void visitSetExpr(Expr.Set expr) {
resolve(expr.value);
resolve(expr.object);
return null;
}
@Override
public Void visitThisExpr(Expr.This expr) {
if (currentClass == ClassType.NONE) {
Lox.error(expr.keyword,
"Can't use 'this' outside of a class.");
return null;
}
resolveLocal(expr, expr.keyword);
return null;
}
@Override
public Void visitUnaryExpr(Expr.Unary expr) {

@ -16,14 +16,18 @@ public class GenerateAst {
"Assign : Token name, Expr value",
"Binary : Expr left, Token operator, Expr right",
"Call : Expr callee, Token paren, List<Expr> arguments",
"Get : Expr object, Token name",
"Grouping : Expr expression",
"Literal : Object value",
"Logical : Expr left, Token operator, Expr right",
"Set : Expr object, Token name, Expr value",
"This : Token keyword",
"Unary : Token operator, Expr right",
"Variable : Token name"
));
defineAst(outputDir, "Stmt", Arrays.asList(
"Block : List<Stmt> statements",
"Class : Token name, List<Stmt.Function> methods",
"If : Expr condition, Stmt thenBranch," +
" Stmt elseBranch",
"Expression : Expr expression",