2022-12-31 15:57:54 +01:00
|
|
|
use std::collections::HashMap;
|
|
|
|
|
|
|
|
use crate::{errors::InterpreterError, tokens::Token};
|
|
|
|
|
2022-12-31 16:32:59 +01:00
|
|
|
use super::{InterpreterResult, Value};
|
2022-12-31 15:57:54 +01:00
|
|
|
|
|
|
|
/// The execution environment.
|
|
|
|
#[derive(Debug, Default)]
|
|
|
|
pub struct Environment {
|
|
|
|
values: HashMap<String, Value>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Environment {
|
|
|
|
/// Define a new variable.
|
|
|
|
pub fn define(&mut self, name: String, value: Value) {
|
|
|
|
self.values.insert(name, value);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Get the value of a variable.
|
2022-12-31 16:32:59 +01:00
|
|
|
pub fn get(&self, name: &Token) -> InterpreterResult {
|
2022-12-31 15:57:54 +01:00
|
|
|
match self.values.get(&name.lexeme as &str) {
|
|
|
|
None => Err(InterpreterError::new(
|
|
|
|
name,
|
|
|
|
&format!("undefined variable '{}'", name.lexeme),
|
|
|
|
)),
|
|
|
|
Some(value) => Ok(value.clone()),
|
|
|
|
}
|
|
|
|
}
|
2022-12-31 16:32:59 +01:00
|
|
|
|
|
|
|
/// 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),
|
|
|
|
))
|
|
|
|
}
|
|
|
|
}
|
2022-12-31 15:57:54 +01:00
|
|
|
}
|