Environment - Support for assignment

This commit is contained in:
Emmanuel BENOîT 2022-12-31 16:32:59 +01:00
parent 3a2e8eeda1
commit 8d6191c7ee

View file

@ -2,7 +2,7 @@ use std::collections::HashMap;
use crate::{errors::InterpreterError, tokens::Token}; use crate::{errors::InterpreterError, tokens::Token};
use super::Value; use super::{InterpreterResult, Value};
/// The execution environment. /// The execution environment.
#[derive(Debug, Default)] #[derive(Debug, Default)]
@ -17,7 +17,7 @@ impl Environment {
} }
/// Get the value of a variable. /// Get the value of a variable.
pub fn get(&self, name: &Token) -> Result<Value, InterpreterError> { pub fn get(&self, name: &Token) -> InterpreterResult {
match self.values.get(&name.lexeme as &str) { match self.values.get(&name.lexeme as &str) {
None => Err(InterpreterError::new( None => Err(InterpreterError::new(
name, name,
@ -26,4 +26,17 @@ impl Environment {
Some(value) => Ok(value.clone()), Some(value) => Ok(value.clone()),
} }
} }
/// Assign a value to an existing variable.
pub fn assign(&mut self, name: &Token, value: &Value) -> Result<(), InterpreterError> {
if self.values.contains_key(&name.lexeme as &str) {
self.values.insert(name.lexeme.clone(), value.clone());
Ok(())
} else {
Err(InterpreterError::new(
name,
&format!("undefined variable '{}'", name.lexeme),
))
}
}
} }