-
Notifications
You must be signed in to change notification settings - Fork 0
/
Environment.h
104 lines (87 loc) · 2.2 KB
/
Environment.h
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#pragma once
#include <unordered_map>
#include <string>
#include "Lox.h"
class Environment
{
private:
std::unordered_map<std::string, Object> values;
Environment *enclosing;
public:
Environment()
{
enclosing = nullptr;
}
Environment(Environment *enclosing)
{
this->enclosing = enclosing;
}
void define(Token *name, Object value)
{
define(name->lexeme, value);
}
void define(std::string name, Object value)
{
// TODO: check redefinition?
values[name] = value;
}
void assign(Token *name, Object value)
{
auto it = values.find(name->lexeme);
if (it != values.end())
{
it->second = value;
}
else if (enclosing)
{
enclosing->assign(name, value);
}
else
{
Lox::runtimeError(*name, "Undefined variable '" + name->lexeme + "'");
}
}
Object get(Token *name)
{
auto it = values.find(name->lexeme);
if (it != values.end())
{
if (it->second.type == TYPE_UNINITIALIZED)
{
Lox::runtimeError(*name, "Uninitialized variable '" + name->lexeme + "'");
}
return it->second;
}
else if (enclosing)
{
return enclosing->get(name);
}
Lox::runtimeError(*name, "Undefined variable '" + name->lexeme + "'");
Object nil;
return nil;
}
Environment *ancestor(int distance)
{
Environment *environment = this;
for (int i = 0; i < distance; i++)
{
environment = environment->enclosing;
}
return environment;
}
Object getAt(int distance, Token *name)
{
Environment *environment = ancestor(distance);
return environment->values[name->lexeme];
}
Object getAt(int distance, std::string name)
{
Environment *environment = ancestor(distance);
return environment->values[name];
}
void defineAt(int distance, Token *name, Object value)
{
Environment *environment = ancestor(distance);
environment->values[name->lexeme] = value;
}
};