crafting-interpreters/src/com/craftinginterpreters/lox/Environment.java

64 lines
1.5 KiB
Java
Raw Normal View History

2020-11-18 23:30:46 -08:00
package com.craftinginterpreters.lox;
import java.util.HashMap;
import java.util.Map;
class Environment {
2020-11-25 23:10:58 -08:00
private final Environment enclosing;
2020-11-18 23:30:46 -08:00
private final Map<String, Object> values = new HashMap<>();
2020-11-25 23:10:58 -08:00
Environment() {
enclosing = null;
}
Environment(Environment enclosing) {
this.enclosing = enclosing;
}
2020-11-18 23:30:46 -08:00
Object get(Token name) {
if (values.containsKey(name.lexeme)) {
return values.get(name.lexeme);
}
2020-11-25 23:10:58 -08:00
if (enclosing != null)
return enclosing.get(name);
2020-11-18 23:30:46 -08:00
throw new RuntimeError(name, "Undefined variable '" + name.lexeme + "'.");
}
2020-11-25 22:06:42 -08:00
void assign(Token name, Object value) {
if (values.containsKey(name.lexeme)) {
values.put(name.lexeme, value);
return;
}
2020-11-25 23:10:58 -08:00
if (enclosing != null) {
enclosing.assign(name, value);
return;
}
2020-11-25 22:06:42 -08:00
throw new RuntimeError(name, "Undefined variable '" + name.lexeme + "'.");
}
2020-11-18 23:30:46 -08:00
void define(String name, Object value) {
values.put(name, value);
}
2021-03-03 22:44:52 -08:00
Environment ancestor(int distance) {
Environment environment = this;
for (int i = 0; i < distance; i++) {
environment = environment.enclosing;
}
return environment;
}
Object getAt(int distance, String name) {
return ancestor(distance).values.get(name);
}
void assignAt(int distance, Token name, Object value) {
ancestor(distance).values.put(name.lexeme, value);
}
2020-11-18 23:30:46 -08:00
}