-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLoxEnvironment.cs
88 lines (75 loc) · 2.63 KB
/
LoxEnvironment.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
79
80
81
82
83
84
85
86
87
88
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lox
{
internal class LoxEnvironment
{
internal LoxEnvironment _enclosing { get; }
private readonly Dictionary<string, object> _values = new Dictionary<string, object>();
internal LoxEnvironment()
{
this._enclosing = null;
}
internal LoxEnvironment(LoxEnvironment enclosing)
{
this._enclosing= enclosing;
}
internal void define(string name, object value)
{
_values.Add(name, value);
}
//ancestorで得た環境のマップにあるその変数の値を返す。
internal object getAt(int distance,string name)
{
var tmp = ancestor(distance);
return tmp._values[name];
//return ancestor(distance)._values[name];
}
//このメソッドはチェーンの親に向かって固定数のホップを行い、そこにある環境を返します。
//ここでは変数が存在することさえチェックしません。そこにあることは、すでにリゾルバによって確認済み
internal LoxEnvironment ancestor(int distance)
{
LoxEnvironment environment = this;
for (int i = 0; i < distance; i++)
{
environment = environment._enclosing;
}
return environment;
}
//固定数の環境を辿り、そのマップに新しい値を記入します。
internal void AssignAt(int distance, Token name, object value)
{
//ancestor(distance)._values.Add(name.lexeme, value);
ancestor(distance)._values[name.lexeme]=value;
}
internal object get(Token name)
{
if (_values.ContainsKey(name.lexeme))
{
return _values[name.lexeme];
}
if (this._enclosing != null)
{
return this._enclosing.get(name);
}
throw new RuntimeError(name, "Undefined variable '" + name.lexeme + "'.");
}
internal void assign(Token name, object value)
{
if (_values.ContainsKey(name.lexeme))
{
_values[name.lexeme] = value;
return;
}
if (this._enclosing != null)
{
this._enclosing.assign(name, value);
return;
}
throw new RuntimeError(name, "Undefined variable '" + name.lexeme + "'.");
}
}
}