-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobject.hpp
87 lines (76 loc) · 2.67 KB
/
object.hpp
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// object.hpp
#ifndef OBJECT_HPP
#define OBJECT_HPP
#include "chunk.hpp"
#include "value.hpp"
#include <vector>
// The ObjType enum defines the types of objects in the language.
// currently supports two types: LIST and FUNCTION.
enum class ObjType { LIST, FUNCTION };
// Obj is the base class for all objects in the language.
class Obj {
public:
ObjType type;
Obj(ObjType type) : type(type) {}
virtual ~Obj() = default;
// This method allows objects to be printed, although the implementation
// depends on the specific object type.
void printObject(const std::shared_ptr<Obj> &obj);
};
// ObjList is a class that represents a dynamic list object.
// It inherits from Obj and contains a vector to hold the elements
class ObjList : public Obj {
public:
std::vector<Value> elements;
ObjList() : Obj(ObjType::LIST) {}
// Appends to the end of a list (doesn't work)
void append(Value value) { elements.push_back(value); }
// Retrieves the element at a specific index. (doesnt work)
Value get(int index) const {
if (index < 0 || index >= elements.size()) {
throw std::out_of_range("Index out of bounds.");
}
return elements[index];
}
// Updates the value at a specific index in the list. (doesn't work)
void set(int index, Value value) {
if (index < 0 || index >= elements.size()) {
throw std::out_of_range("Index out of bounds.");
}
elements[index] = value;
}
// Removes the element at a specific index from the list. (doesn't work)
void remove(int index) {
if (index < 0 || index >= elements.size()) {
throw std::out_of_range("Index out of bounds.");
}
elements.erase(elements.begin() + index);
}
size_t size() const { return elements.size(); }
};
// ObjFunction represents a function object in the system.
// It contains the function's arity (number of arguments), its name,
// and a Chunk that stores the bytecode for the function. (also currently not
// working)
class ObjFunction : public Obj {
public:
int arity;
Chunk chunk;
std::string name;
ObjFunction() : Obj(ObjType::FUNCTION), arity(0), name(""), chunk() {}
};
// Utility function that checks if a Value is a function.
inline bool isFunction(const Value &value) {
return std::holds_alternative<std::shared_ptr<Obj>>(value) &&
std::dynamic_pointer_cast<ObjFunction>(
std::get<std::shared_ptr<Obj>>(value)) != nullptr;
}
// Utility function to cast a Value to an ObjFunction.
inline std::shared_ptr<ObjFunction> asFunction(const Value &value) {
if (std::holds_alternative<std::shared_ptr<Obj>>(value)) {
return std::dynamic_pointer_cast<ObjFunction>(
std::get<std::shared_ptr<Obj>>(value));
}
return nullptr;
}
#endif