-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEnvironment.hpp
77 lines (67 loc) · 2.17 KB
/
Environment.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
#ifndef Environment_h
#define Environment_h
#include "FwdTypes.hpp"
#include <unordered_map>
#include <string>
class Environment : public std::enable_shared_from_this<Environment> {
std::shared_ptr<Environment> enclosing;
std::unordered_map<std::string,Value> values;
// note: constuctor is private as always accessed through std::shared_ptr<Environment>
Environment() = default;
public:
static std::shared_ptr<Environment> makeShared(
std::shared_ptr<Environment> parent = nullptr, std::shared_ptr<Environment> clone = nullptr) {
std::shared_ptr<Environment> e{ new Environment() };
e->enclosing = parent;
if (clone) {
e->values = clone->values;
}
return e;
}
void define(const std::string& name, Value value) {
if (auto iter = values.find(name); iter != values.end()) {
iter->second = value;
}
else {
values.insert({name, value});
}
}
Value get(const std::string& name) {
if (auto iter = values.find(name); iter != values.end()) {
return iter->second;
}
if (enclosing) {
return enclosing->get(name);
}
throw Error("Undefined variable \'" + name + "\'.");
}
void assign(const std::string& name, const Value& value) {
if (auto iter = values.find(name); iter != values.end()) {
iter->second = value;
return;
}
if (enclosing) {
enclosing->assign(name, value);
return;
}
throw Error("Undefined variable \'" + name + "\'.");
}
std::shared_ptr<Environment> ancestor(unsigned distance) {
if (distance == 0) {
return shared_from_this();
}
else if (enclosing) {
return enclosing->ancestor(distance - 1);
}
else {
return nullptr;
}
}
Value getAt(unsigned distance, const std::string& name) {
return ancestor(distance)->get(name);
}
void assignAt(unsigned distance, const std::string& name, const Value& value) {
ancestor(distance)->assign(name, value);
}
};
#endif // Environment_h