Environment - Support for assignment
This commit is contained in:
parent
3a2e8eeda1
commit
8d6191c7ee
1 changed files with 15 additions and 2 deletions
|
@ -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),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue