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

View file

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