-
Notifications
You must be signed in to change notification settings - Fork 0
/
Env.cs
65 lines (54 loc) · 1.45 KB
/
Env.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
namespace SharpLox;
public class Env
{
public readonly Env? Enclosing;
private readonly Dictionary<string, object?> Values = new();
public Env(Env? enclosing = null)
{
Enclosing = enclosing;
}
public Env Ancestor(int distance)
{
var environment = this;
for (int i = 0; i < distance; i++)
{
environment = environment.Enclosing!; // we just gotta trust
}
return environment;
}
public void Assign(Token name, object? value)
{
// This was wrong in previous commit. TryAdd is definitely not equivalent to this!
if (Values.ContainsKey(name.Lexeme))
{
Values[name.Lexeme] = value;
return;
}
if (Enclosing is not null)
{
Enclosing.Assign(name, value);
return;
}
throw new RuntimeError(name, $"Undefined variable '{name.Lexeme}'.");
}
public void Define(string name, object? value)
{
Values.Add(name, value);
}
public object? Get(Token name)
{
if (Values.TryGetValue(name.Lexeme, out var value))
{
return value;
}
if (Enclosing is not null)
{
return Enclosing.Get(name);
}
throw new RuntimeError(name, $"Undefined variable '{name.Lexeme}'.");
}
public object? GetAt(int distance, String name)
{
return Ancestor(distance).Values[name];
}
}