From 68a2ebd34fc94488e89ffb82b359ec6e7e152ae9 Mon Sep 17 00:00:00 2001 From: Tom Willemse Date: Thu, 8 Jul 2021 00:14:31 -0700 Subject: Restructure project to make room for clox --- .../src/com/craftinginterpreters/lox/LoxClass.java | 51 ++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 jlox/src/com/craftinginterpreters/lox/LoxClass.java (limited to 'jlox/src/com/craftinginterpreters/lox/LoxClass.java') diff --git a/jlox/src/com/craftinginterpreters/lox/LoxClass.java b/jlox/src/com/craftinginterpreters/lox/LoxClass.java new file mode 100644 index 0000000..5d1c136 --- /dev/null +++ b/jlox/src/com/craftinginterpreters/lox/LoxClass.java @@ -0,0 +1,51 @@ +package com.craftinginterpreters.lox; + +import java.util.List; +import java.util.Map; + +class LoxClass implements LoxCallable { + final String name; + final LoxClass superclass; + private final Map methods; + + LoxClass(String name, LoxClass superclass, Map methods) { + this.superclass = superclass; + this.name = name; + this.methods = methods; + } + + LoxFunction findMethod(String name) { + if (methods.containsKey(name)) { + return methods.get(name); + } + + if (superclass != null) { + return superclass.findMethod(name); + } + + return null; + } + + @Override + public String toString() { + return name; + } + + @Override + public Object call(Interpreter interpreter, List 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(); + } +} -- cgit v1.2.3-54-g00ecf