-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalue.cpp
86 lines (74 loc) · 2.67 KB
/
value.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
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
#include "value.hpp"
#include "object.hpp"
#include <iostream>
bool isBool(const Value &value) { return std::holds_alternative<bool>(value); }
bool isNil(const Value &value) {
return std::holds_alternative<std::monostate>(value);
}
bool isNumber(const Value &value) {
return std::holds_alternative<double>(value);
}
bool isObj(const Value &value) {
return std::holds_alternative<std::shared_ptr<Obj>>(value);
}
bool isString(const Value &value) {
return std::holds_alternative<std::string>(value);
}
// Compares two Values for equality. It checks if both values hold the same type
// and then compares them using std::visit.
bool valuesEqual(const Value &a, const Value &b) {
if (a.index() != b.index())
return false;
return std::visit(
[](const auto &lhs, const auto &rhs) -> bool {
using LhsT = std::decay_t<decltype(lhs)>;
using RhsT = std::decay_t<decltype(rhs)>;
if constexpr (std::is_same_v<LhsT, RhsT>) {
return lhs == rhs; // Compare if types are the same.
} else {
return false;
}
},
a, b);
}
// Prints a Value based on its type.
// Uses std::visit to apply different print logic for each type in the variant.
void printValue(const Value &value) {
std::visit(
[](const auto &v) {
using T = std::decay_t<decltype(v)>;
// Print boolean values as "true" or "false".
if constexpr (std::is_same_v<T, bool>) {
std::cout << (v ? "true" : "false");
// Print numeric values.
} else if constexpr (std::is_same_v<T, double>) {
std::cout << v;
// Print string values.
} else if constexpr (std::is_same_v<T, std::string>) {
std::cout << v;
// Print a list (ObjList) by recursively printing each element.
} else if constexpr (std::is_same_v<T, std::shared_ptr<ObjList>>) {
std::cout << "[";
for (size_t i = 0; i < v->elements.size(); ++i) {
printValue(v->elements[i]);
if (i < v->elements.size() - 1)
std::cout << ", ";
}
std::cout << "]";
// Print function objects (ObjFunction). If the function has a name,
// print it; otherwise, print "<script>"
} else if constexpr (std::is_same_v<T, ObjFunction *>) {
if (v->name.empty()) {
std::cout << "<script>";
} else {
std::cout << "<fn " << v->name << ">";
}
// Print "nil" for nil (monostate) values.
} else if constexpr (std::is_same_v<T, std::monostate>) {
std::cout << "nil";
} else {
std::cout << "Unknown value type.";
}
},
value);
}