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

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) {

View file

@ -48,6 +48,13 @@ impl<'a> InterpreterState<'a> {
variables: parent.variables,
}
}
fn lookup_var(&self, name: &Token, expr : &ast::ExprNode) -> SloxResult<Value> {
match self.variables.get(&(expr as *const ast::ExprNode)) {
Some(distance) => Ok(self.environment.borrow().get_at(*distance, name)),
None => self.environment.borrow().get(name),
}
}
}
/// Interpreter flow control, which may be either a value, a loop break or a