Interpreter - Additional errors for variables

* Uninitialized variable usage
  * Redefining variables
This commit is contained in:
Emmanuel BENOîT 2023-01-01 10:52:29 +01:00
parent e92628a4eb
commit 81aef09c5b
2 changed files with 25 additions and 10 deletions

View file

@ -7,16 +7,19 @@ use super::{InterpreterResult, Value};
/// A mutable reference to an environment.
pub type EnvironmentRef = Rc<RefCell<Environment>>;
/// A variable.
pub type Variable = Option<Value>;
/// The execution environment.
#[derive(Debug, Default)]
pub struct Environment {
enclosing: Option<EnvironmentRef>,
values: HashMap<String, Value>,
values: HashMap<String, Variable>,
}
impl Environment {
/// Create an environment enclosed in another.
pub fn create_child(parent: &Rc<RefCell<Self>>) -> Rc<RefCell<Self>> {
pub fn create_child(parent: &EnvironmentRef) -> EnvironmentRef {
Rc::new(RefCell::new(Self {
enclosing: Some(parent.clone()),
values: HashMap::default(),
@ -24,8 +27,16 @@ impl Environment {
}
/// Define a new variable.
pub fn define(&mut self, name: String, value: Value) {
self.values.insert(name, value);
pub fn define(&mut self, name: &Token, value: Variable) -> Result<(), InterpreterError> {
if self.values.contains_key(&name.lexeme as &str) {
Err(InterpreterError::new(
name,
&format!("variables '{}' already defined in scope", name.lexeme),
))
} else {
self.values.insert(name.lexeme.clone(), value);
Ok(())
}
}
/// Get the value of a variable.
@ -38,14 +49,18 @@ impl Environment {
)),
Some(parent) => parent.borrow().get(name),
},
Some(value) => Ok(value.clone()),
Some(None) => Err(InterpreterError::new(
name,
&format!("variable '{}' has not been initialized", name.lexeme),
)),
Some(Some(value)) => Ok(value.clone()),
}
}
/// Assign a value to an existing variable.
pub fn assign(&mut self, name: &Token, value: Value) -> InterpreterResult {
if self.values.contains_key(&name.lexeme as &str) {
self.values.insert(name.lexeme.clone(), value);
self.values.insert(name.lexeme.clone(), Some(value));
Ok(Value::Nil)
} else {
match &mut self.enclosing {

View file

@ -77,11 +77,11 @@ impl ast::StmtNode {
name: &Token,
initializer: &Option<ast::ExprNode>,
) -> InterpreterResult {
let value = match initializer {
Some(expr) => expr.interprete(environment)?,
None => Value::Nil,
let variable = match initializer {
Some(expr) => Some(expr.interprete(environment)?),
None => None,
};
environment.borrow_mut().define(name.lexeme.clone(), value);
environment.borrow_mut().define(name, variable)?;
Ok(Value::Nil)
}