-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnvironment.java
More file actions
113 lines (97 loc) · 2.54 KB
/
Environment.java
File metadata and controls
113 lines (97 loc) · 2.54 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import java.util.HashMap;
import java.util.Map;
/**
* class for environment data structure to store variable values association
*/
public class Environment {
final Environment enclosing;
private final Map<String, Object> values = new HashMap<>();
Environment(){
enclosing = null;
}
Environment(Environment enclosing){
this.enclosing = enclosing;
}
/**
* Method to get the values
*
* @param name Token
* @return Object
*/
Object get(Token name){
if(values.containsKey(name.lexeme)){
return values.get(name.lexeme);
}
if(enclosing != null) return enclosing.get(name);
throw new RuntimeError(name, "Undefined variable'"+ name.lexeme + "'.");
}
/**
* Method to assign variables
*
* @param name Token
* @param value Object
*/
void assign(Token name, Object value){
if(values.containsKey(name.lexeme)){
values.put(name.lexeme, value);
return;
}
if(enclosing != null){
enclosing.assign(name, value);
return;
}
throw new RuntimeError(name, "Undefined variable '" + name.lexeme + "'.");
}
/**
* Method to process and store variable definition
*
* @param name String
* @param value Object
*/
void define(String name, Object value){
values.put(name, value);
}
/**
* Method to traverse the distance and find the enclosing environment
*
* @param distance int
*
* @return Environment
*/
Environment ancestor(int distance) {
Environment environment = this;
for(int i = 0; i < distance; i++) {
environment = environment.enclosing;
}
return environment;
}
/**
* Method to get ancestor values using distance
*
* @param distance int
* @param name String
*
* @return Object
*/
Object getAt(int distance, String name) {
return ancestor(distance).values.get(name);
}
/**
* Method to assign value based on distance of environment scope
*
* @param distance int
* @param name Token
* @param value Object
*/
void assignAt(int distance, Token name, Object value) {
ancestor(distance).values.put(name.lexeme, value);
}
@Override
public String toString() {
String result = values.toString();
if (enclosing != null) {
result += " -> " + enclosing.toString();
}
return result;
}
}