-
Notifications
You must be signed in to change notification settings - Fork 992
/
Environment.java
90 lines (71 loc) · 1.94 KB
/
Environment.java
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
//>= Statements and State
package com.craftinginterpreters.lox;
import java.util.HashMap;
import java.util.Map;
class Environment {
final Environment enclosing;
private final Map<String, Object> values = new HashMap<>();
Environment() {
enclosing = null;
}
Environment(Environment enclosing) {
this.enclosing = enclosing;
}
void declare(Token name) {
// Note: Can't just use define(name, null). That will overwrite a
// previously defined global value.
if (!values.containsKey(name.text)) {
values.put(name.text, null);
}
}
Object get(Token name) {
if (values.containsKey(name.text)) {
return values.get(name.text);
}
if (enclosing != null) return enclosing.get(name);
throw new RuntimeError(name,
"Undefined variable '" + name.text + "'.");
}
void assign(Token name, Object value) {
if (values.containsKey(name.text)) {
values.put(name.text, value);
return;
}
if (enclosing != null) {
enclosing.assign(name, value);
return;
}
throw new RuntimeError(name,
"Undefined variable '" + name.text + "'.");
}
void define(String name, Object value) {
values.put(name, value);
}
//>= Resolving and Binding
Object getAt(int distance, String name) {
Environment environment = this;
for (int i = 0; i < distance; i++) {
environment = environment.enclosing;
}
return environment.values.get(name);
}
void assignAt(int distance, Token name, Object value) {
Environment environment = this;
for (int i = 0; i < distance; i++) {
environment = environment.enclosing;
}
environment.values.put(name.text, value);
}
//>= Statements and State
Environment enterScope() {
return new Environment(this);
}
@Override
public String toString() {
String result = values.toString();
if (enclosing != null) {
result += " -> " + enclosing.toString();
}
return result;
}
}