-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEnvironment.cpp
71 lines (58 loc) · 1.32 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
64
65
66
67
68
69
70
71
#include "Environment.h"
#include "RuntimeError.h"
Environment::Environment() : _values(std::map<std::string, std::any>())
{
_enclosing = nullptr;
}
Environment::Environment(Ref<Environment> enclosing)
: _values(std::map<std::string, std::any>())
{
_enclosing = enclosing;
}
Environment::~Environment()
{
}
void Environment::Assign(Token name, std::any value)
{
if (_values.find(name.GetLexeme()) != _values.end())
{
_values[name.GetLexeme()] = value;
return;
}
if (_enclosing != nullptr)
{
_enclosing->Assign(name, value);
return;
}
throw RuntimeError(name, "Undefined variable '" + name.GetLexeme() + "'.");
}
void Environment::Define(const std::string& name, std::any value)
{
_values[name] = value;
}
std::any Environment::Get(Token token)
{
std::string lexeme = token.GetLexeme();
if (_values.find(lexeme) != _values.end())
{
return _values[lexeme];
}
if (_enclosing != nullptr)
{
return _enclosing->Get(token);
}
throw RuntimeError(token, "Undefined variable '" + lexeme + "'.");
}
std::any Environment::GetAt(int distance, std::string name)
{
return Ancestor(distance)->GetValues()[name];
}
Ref<Environment> Environment::Ancestor(int distance)
{
std::shared_ptr<Environment> env = std::shared_ptr<Environment>(this);
for (int i = 0; i < distance; i++)
{
env = env->_enclosing;
}
return env;
}