-
Notifications
You must be signed in to change notification settings - Fork 0
/
Environment.cs
78 lines (66 loc) · 1.95 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
68
69
70
71
72
73
74
75
76
77
78
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpLox
{
public class Environment
{
public readonly Environment Enclosing;
readonly Dictionary<string, object> Values = new Dictionary<string, object>();
public Environment()
{
Enclosing = null;
}
public Environment(Environment enclosing)
{
Enclosing = enclosing;
}
public void Define(string name, object value) => Values[name] = value;
public object Get(Token name)
{
if (Values.TryGetValue(name.Lexeme, out object value))
{
return value;
}
if (Enclosing != null)
{
return Enclosing.Get(name);
}
throw new RuntimeError(name, $"Undefined varable '{name.Lexeme}'!");
}
public void Assign(Token name, object value)
{
if (Values.ContainsKey(name.Lexeme))
{
Values[name.Lexeme] = value;
return;
}
else if (Enclosing != null)
{
Enclosing.Assign(name, value);
return;
}
throw new RuntimeError(name, $"Undefined varable '{name.Lexeme}'!");
}
public void AssignAt(int distance, Token name, object value)
{
Ancestor(distance).Values[name.Lexeme] = value;
}
public object GetAt(int distance, string name)
{
Ancestor(distance).Values.TryGetValue(name, out var value);
return value;
}
private Environment Ancestor(int distance)
{
var environment = this;
for (int i = 0; i < distance; i++)
{
environment = environment.Enclosing;
}
return environment;
}
}
}