-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEnvironment.cpp
58 lines (47 loc) · 1.41 KB
/
Environment.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
#include <stdexcept>
#include <map>
#include <string>
#include "./Environment.hpp"
#include "./RuntimeError.hpp"
using std::map;
using std::string;
Environment::Environment(shared_ptr<Environment> enclosing_):
enclosing(enclosing_) {}
void Environment::define(string name, Object value) {
values[name] = value;
}
Object Environment::get(Token name) {
auto search = values.find(name.lexeme);
if (search != values.end()) {
return search->second;
}
if (enclosing != nullptr) {
return enclosing->get(name);
}
throw RuntimeError(name, "Undefined variable '" + name.lexeme + "'.");
}
Object Environment::getAt(int distance, string name) {
return ancestor(distance)->values[name];
}
void Environment::assign(Token name, Object value) {
auto search = values.find(name.lexeme);
if (search != values.end()) {
search->second = value;
return;
}
if (enclosing != nullptr) {
enclosing->assign(name, value);
return;
}
throw RuntimeError(name, "Undefined variable '" + name.lexeme + "'.");
}
void Environment::assignAt(int distance, Token name, Object value) {
ancestor(distance)->values[name.lexeme] = value;
}
shared_ptr<Environment> Environment::ancestor(int distance) {
shared_ptr<Environment> environment = shared_from_this();
for (int i = 0; i < distance; i++) {
environment = environment->enclosing;
}
return environment;
}