From 8d6191c7eebc47ba3fb11073b31c9355f3395232 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emmanuel=20Beno=C3=AEt?= Date: Sat, 31 Dec 2022 16:32:59 +0100 Subject: [PATCH] Environment - Support for assignment --- src/interpreter/environment.rs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/interpreter/environment.rs b/src/interpreter/environment.rs index 6b35d98..01e1734 100644 --- a/src/interpreter/environment.rs +++ b/src/interpreter/environment.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use crate::{errors::InterpreterError, tokens::Token}; -use super::Value; +use super::{InterpreterResult, Value}; /// The execution environment. #[derive(Debug, Default)] @@ -17,7 +17,7 @@ impl Environment { } /// Get the value of a variable. - pub fn get(&self, name: &Token) -> Result { + pub fn get(&self, name: &Token) -> InterpreterResult { match self.values.get(&name.lexeme as &str) { None => Err(InterpreterError::new( name, @@ -26,4 +26,17 @@ impl Environment { 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), + )) + } + } }