45 lines
1.1 KiB
Rust
45 lines
1.1 KiB
Rust
use super::Value;
|
|
use std::collections::HashMap;
|
|
use std::rc::Rc;
|
|
use std::cell::RefCell;
|
|
|
|
#[derive(Debug)]
|
|
pub struct Env {
|
|
pub values: HashMap<String, Value>,
|
|
pub parent: Option<Rc<RefCell<Env>>>,
|
|
}
|
|
|
|
impl Env {
|
|
pub fn new(parent: Option<Rc<RefCell<Env>>>) -> Self {
|
|
Self {
|
|
values: HashMap::new(),
|
|
parent,
|
|
}
|
|
}
|
|
|
|
pub fn define(&mut self, name: String, val: Value) {
|
|
self.values.insert(name, val);
|
|
}
|
|
|
|
pub fn assign(&mut self, name: &str, val: Value) -> bool {
|
|
if self.values.contains_key(name) {
|
|
self.values.insert(name.to_string(), val);
|
|
true
|
|
} else if let Some(parent) = &self.parent {
|
|
parent.borrow_mut().assign(name, val)
|
|
} else {
|
|
false
|
|
}
|
|
}
|
|
|
|
pub fn get(&self, name: &str) -> Option<Value> {
|
|
if let Some(val) = self.values.get(name) {
|
|
Some(val.clone())
|
|
} else if let Some(parent) = &self.parent {
|
|
parent.borrow().get(name)
|
|
} else {
|
|
None
|
|
}
|
|
}
|
|
}
|