use std::collections::HashMap;
use crate::runtime::values::Value;
#[derive(Debug, Clone)]
pub struct Scope {
pub variables: HashMap<String, Value>,
pub parent: Option<Box<Scope>>,
}
impl Scope {
pub fn new() -> Self {
Self {
variables: HashMap::with_capacity(16), parent: None,
}
}
pub fn new_child(parent: Scope) -> Self {
Self {
variables: HashMap::with_capacity(8), parent: Some(Box::new(parent)),
}
}
pub fn set(&mut self, name: String, value: Value) {
self.variables.insert(name, value);
}
pub fn get(&self, name: &str) -> Option<Value> {
if let Some(value) = self.variables.get(name) {
return Some(value.clone());
}
if let Some(parent) = &self.parent {
return parent.get(name);
}
None
}
}
impl Default for Scope {
fn default() -> Self {
Self::new()
}
}