Skip to content

Commit

Permalink
Add error and assign in environment
Browse files Browse the repository at this point in the history
  • Loading branch information
coletonodonnell committed Feb 15, 2022
1 parent 8e6f14f commit 970de0f
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/environment.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
use crate::token::{Literal, Token};
use crate::expression::Expr;
use std::collections::HashMap;

pub struct Environment {
instance: crate::Lox,
values: HashMap<String, Literal>
}

impl Environment {
pub fn build_envrionment() -> Environment {
pub fn build_envrionment(instance: crate::Lox) -> Environment {
Environment {
instance: instance,
values: HashMap::new()
}
}

// If there is an error send it here to report to the Lox instance
fn error(&mut self, token: Token, message: String) {
self.instance.interpreter_error(token, &*message);
}

pub fn get(&mut self, name: Token) -> Result<Literal, String> {
if self.values.contains_key(&name.lexeme) {
return Ok(self.values.get(&name.lexeme).unwrap().clone())
Expand All @@ -23,4 +31,13 @@ impl Environment {
pub fn define(&mut self, name: String, value: Literal) {
self.values.insert(name, value);
}

pub fn assign(&mut self, name: Token, value: Literal) {
if self.values.contains_key(&name.lexeme) {
self.values.insert(name.lexeme, value);
return
}

self.error(name.clone(), format!("Undefined variable {}.", name.lexeme));
}
}

0 comments on commit 970de0f

Please sign in to comment.