-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEnvironment.cpp
63 lines (49 loc) · 1.4 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
59
60
61
62
63
#include "./headers/Environment.hpp"
#include <iostream>
std::any Environment::get(Token name)
{
if (values.find(name.lexeme) != values.end())
{
if(values[name.lexeme].type() == typeid(std::nullptr_t))
{
throw RuntimeError(name, "Unassigned variable '" + name.lexeme + "'.");
}
return values[name.lexeme];
}
if(enclosing != nullptr) return enclosing->get(name);
throw RuntimeError(name, "Undefined variable '" + name.lexeme + "'.");
}
void Environment::define(std::string name, std::any value)
{
values[name] = value;
}
void Environment::assign(Token name, std::any value)
{
if (values.find(name.lexeme) != values.end())
{
values[name.lexeme] = value;
return;
}
if(enclosing != nullptr)
{
enclosing->assign(name, value);
return;
}
throw RuntimeError(name, "Undefined variable '" + name.lexeme + "'.");
}
std::any Environment::getAt(int distance, std::string name)
{
return ancestor(distance)->values[name];
}
std::shared_ptr<Environment> Environment::ancestor(int distance)
{
std::shared_ptr<Environment> environment = shared_from_this();
for(int i = 0; i < distance; i++) {
environment = environment->enclosing;
}
return environment;
}
void Environment::assignAt(int distance, Token& name, std::any value)
{
ancestor(distance)->values[name.lexeme] = value;
}