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);
|
|
|
|
}
|
|
|
|
}
|