use std::collections::HashMap; use std::hash::Hash; /// Layered environment that lets us push and pop frames and lookup across /// layers. #[derive(Debug)] pub struct LayeredEnv { inner: Option>, } impl Default for LayeredEnv { fn default() -> Self { LayeredEnv { inner: Some(InnerEnv::new()), } } } impl LayeredEnv { pub fn insert(&mut self, key: K, value: V) { self.inner.as_mut().unwrap().map.insert(key, value); } pub fn push(&mut self) { let inner = self.inner.take().unwrap(); self.inner = Some(InnerEnv::with_parent(inner)); } pub fn pop(&mut self) { let inner = self.inner.take().unwrap(); self.inner = Some(*inner.parent.unwrap()); } /// Look up the key within the environment. /// /// If a key exists in multiple layers at once, the top-most one (of the /// stack) will shadow all the others. /// /// TODO: Make a "lookup" function that traverses all environments. pub fn lookup(&self, key: &K) -> Option<&V> { self.inner.as_ref().unwrap().lookup(key) } } #[derive(Debug)] struct InnerEnv { parent: Option>>, map: HashMap, } impl InnerEnv { fn new() -> Self { InnerEnv { parent: None, map: HashMap::new(), } } fn with_parent(parent: InnerEnv) -> Self { InnerEnv { parent: Some(Box::new(parent)), map: HashMap::new(), } } fn lookup(&self, key: &K) -> Option<&V> { match self.map.get(key) { Some(v) => Some(v), None => match self.parent.as_ref() { Some(p) => p.lookup(key), None => None, }, } } }