-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLoxClass.cpp
53 lines (45 loc) · 1.34 KB
/
LoxClass.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Copyright 2020.2.23 <Copyright hulin>
#include <string>
#include <memory>
#include <vector>
#include "./LoxClass.hpp"
#include "./LoxInstance.hpp"
#include "./Interpreter.hpp"
#include "./LoxFunction.hpp"
#include "./Token.hpp"
using std::string;
using std::shared_ptr;
using std::vector;
LoxClass::LoxClass(
string name_,
shared_ptr<LoxClass> superclass_,
map<string, shared_ptr<LoxFunction>> methods_
): name(name_), superclass(superclass_), methods(methods_) {}
Object LoxClass::call(
shared_ptr<Interpreter> interpreter,
vector<Object> arguments) {
auto instance = shared_ptr<LoxInstance>(new LoxInstance(*this));
shared_ptr<LoxFunction> initializer = findMethod("init");
if (initializer != nullptr) {
initializer->bind(instance)->call(interpreter, arguments);
}
return Object::make_instance_obj(instance);
}
int LoxClass::arity() {
shared_ptr<LoxFunction> initializer = findMethod("init");
if (initializer == nullptr) return 0;
return initializer->arity();
}
string LoxClass::toString() {
return name;
}
shared_ptr<LoxFunction> LoxClass::findMethod(string name) {
auto searched = methods.find(name);
if (searched != methods.end()) {
return searched->second;
}
if (superclass != nullptr) {
return superclass->findMethod(name);
}
return nullptr;
}