Files
rlox/src/backend/environment.rs
T

45 lines
1.2 KiB
Rust
Raw Normal View History

use std::collections::HashMap;
use crate::{
frontend::{source_registry::SourceSlice, tokens::LiteralValue},
result::{LoxError, LoxResult},
};
pub struct Environment<'a> {
values: HashMap<String, LiteralValue>,
parent: Option<&'a Environment<'a>>,
}
impl<'a> Environment<'a> {
pub fn new() -> Self {
Environment {
values: HashMap::new(),
parent: None,
}
}
pub fn new_with_parent(parent: &'a Environment<'a>) -> Self {
Environment {
values: HashMap::new(),
parent: Some(parent),
}
}
pub fn get(&self, name: &str) -> LoxResult<LiteralValue> {
match self.values.get(name) {
Some(value) => Ok(value.clone()),
None => match self.parent {
Some(parent) => parent.get(name),
None => Err(LoxError::RuntimeError {
source_slice: SourceSlice::default(), // todo change this to the actual source slice
message: format!("Undefined variable '{}'", name),
}),
},
}
}
pub fn set(&mut self, name: String, value: LiteralValue) {
self.values.insert(name, value);
}
}