-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnvironment.java
More file actions
58 lines (48 loc) · 1.38 KB
/
Copy pathEnvironment.java
File metadata and controls
58 lines (48 loc) · 1.38 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
import java.util.*;
public class Environment <E>{
Environment<E> anc;
Map<String, E> bindings;
private int depth;
Environment(){
anc = null;
bindings = new HashMap<String,E>();
depth = 0;
}
Environment(Environment<E> ancestor){
anc = ancestor;
bindings = new HashMap<String,E>();
this.depth = ancestor.depth + 1;
}
public int getDepth() {
return this.depth;
}
Environment<E> beginScope(){
return new Environment<E>(this);
}
Environment<E> endScope(){
return anc;
}
void assoc(String id, E bind) throws InterpreterError {
if (bindings.containsKey(id))
throw new InterpreterError("variable already defined: " + id);
bindings.put(id, bind);
}
E find(String id) throws InterpreterError {
if (bindings.containsKey(id)) {
return bindings.get(id);
}
if (anc != null) {
return anc.find(id);
}
throw new InterpreterError("unbound variable: " + id);
}
public int getScopeDepth(String id) throws InterpreterError {
if (bindings.containsKey(id)) {
return this.depth;
}
if (anc != null) {
return anc.getScopeDepth(id);
}
throw new InterpreterError("unbound variable when checking depth: " + id);
}
}