Trying to implement variable lookup and failing hard

* I'll probably have to rewrite environments as a Vec<HashMap> to make
    things simpler
This commit is contained in:
Emmanuel BENOîT 2023-01-06 08:05:33 +01:00
parent c97ad0ad7e
commit bd156e619f
2 changed files with 26 additions and 0 deletions
src/interpreter

View file

@ -81,6 +81,25 @@ impl Environment {
}
}
/// Access a variable at a specified distance in a parent environment.
pub fn get_at(&self, distance: usize, name: &Token) -> Value {
self.ancestor(distance)
.values
.get(&name.lexeme as &str)
.unwrap()
.unwrap()
.clone()
}
/// Access the ancestor environment at a specified distance from the current one.
fn ancestor(&self, distance: usize) -> &Self {
if distance == 0 {
&self
} else {
self.enclosing.unwrap().borrow().ancestor(distance - 1)
}
}
/// Assign a value to an existing variable.
pub fn assign(&mut self, name: &Token, value: Value) -> SloxResult<()> {
if self.values.contains_key(&name.lexeme as &str) {