jlox/src/lox/Environment.java

64 lines
1.3 KiB
Java
Raw Normal View History

2021-09-19 18:13:47 +00:00
package lox;
import java.util.HashMap;
import java.util.Map;
class Environment {
2021-09-19 18:46:00 +00:00
final Environment enclosing;
2021-09-19 18:13:47 +00:00
private final Map<String, Object> values = new HashMap<>();
2021-09-19 18:46:00 +00:00
Environment() {
enclosing = null;
}
Environment(Environment enclosing) {
this.enclosing = enclosing;
}
2021-09-19 18:13:47 +00:00
void define(String name, Object value) {
values.put(name, value);
}
2021-10-24 19:09:51 +00:00
Environment ancestor(int distance) {
Environment environment = this;
for (int i = 0; i < distance; i++) {
environment = environment.enclosing;
}
return environment;
}
2021-09-19 18:46:00 +00:00
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 + "'.");
}
2021-10-24 19:09:51 +00:00
void assignAt(int distance, Token name, Object value) {
ancestor(distance).values.put(name.lexeme, value);
}
2021-09-19 18:13:47 +00:00
Object get(Token name) {
if (values.containsKey(name.lexeme)) {
return values.get(name.lexeme);
}
2021-09-19 18:46:00 +00:00
if (enclosing != null) {
return enclosing.get(name);
}
2021-09-19 18:13:47 +00:00
throw new RuntimeError(name, "Undefined variable '" + name.lexeme + "'.");
}
2021-10-24 19:09:51 +00:00
Object getAt(int distance, String name) {
return ancestor(distance).values.get(name);
}
2021-09-19 18:13:47 +00:00
}