-
Notifications
You must be signed in to change notification settings - Fork 0
/
Environment.cs
67 lines (56 loc) · 1.6 KB
/
Environment.cs
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
namespace cslox;
public class Environment
{
public readonly Environment? Enclosing;
private readonly Dictionary<string, object?> _values = new();
public Environment(Environment? enclosing = null)
{
Enclosing = enclosing;
}
public void Define(string name, object? value)
{
_values.TryAdd(name, value);
}
public object? Get(Token token)
{
if (_values.TryGetValue(token.Lexeme, out var value))
return value;
if (Enclosing != null) return Enclosing.Get(token);
throw new RuntimeException(token, $"Undefined variable {token.Lexeme}.");
}
public void Assign(Token token, object? value)
{
if (_values.ContainsKey(token.Lexeme))
{
_values[token.Lexeme] = value;
return;
}
if (Enclosing != null)
{
Enclosing.Assign(token, value);
return;
}
throw new RuntimeException(token, $"Undefined variables {token.Lexeme}.");
}
public object? GetAt(int dist, string name)
{
var ancestor = Ancestor(dist);
if (ancestor != null && ancestor._values.TryGetValue(name, out var value)) return value;
return null;
}
private Environment? Ancestor(int dist)
{
var env = this;
for (var i = 0; i < dist; i++)
{
env = env?.Enclosing;
}
return env;
}
public void AssignAt(int dist, Token token, object? obj)
{
var values = Ancestor(dist)?._values;
if (values == null) return;
values[token.Lexeme] = obj;
}
}