39 lines
1.0 KiB
Java
39 lines
1.0 KiB
Java
package serene.simple;
|
|
|
|
import java.util.HashMap;
|
|
|
|
public class Scope {
|
|
private final HashMap<String, Object> symbolsMapping = new HashMap<String, Object>();
|
|
private final Scope parent;
|
|
private static final Scope root = new Scope(null);
|
|
|
|
public Scope() {
|
|
this(null);
|
|
}
|
|
|
|
public Scope(Scope parent) {
|
|
this.parent = parent;
|
|
}
|
|
|
|
public Object lookupSymbol(String symbolName) {
|
|
if (this.symbolsMapping.containsKey(symbolName)) {
|
|
return this.symbolsMapping.get(symbolName);
|
|
}
|
|
else if (this.parent != null) {
|
|
return this.parent.lookupSymbol(symbolName);
|
|
}
|
|
else {
|
|
throw new RuntimeException(String.format("Variable '%s' is not defined in this scope.",
|
|
symbolName));
|
|
}
|
|
}
|
|
|
|
public void insertSymbol(String symbolName, Object symbolValue) {
|
|
this.symbolsMapping.put(symbolName, symbolValue);
|
|
}
|
|
|
|
public static Scope getRootScope() {
|
|
return Scope.root;
|
|
}
|
|
}
|