2022-07-18 02:00:19 +00:00
|
|
|
use std::collections::HashMap;
|
|
|
|
use std::hash::Hash;
|
2022-04-28 16:33:26 +00:00
|
|
|
|
2022-07-19 06:30:25 +00:00
|
|
|
/// Layered environment that lets us push and pop frames and lookup across
|
|
|
|
/// layers.
|
2022-07-18 03:06:37 +00:00
|
|
|
#[derive(Debug)]
|
2022-07-18 02:00:19 +00:00
|
|
|
pub struct LayeredEnv<K, V> {
|
2022-07-18 03:06:37 +00:00
|
|
|
inner: Option<InnerEnv<K, V>>,
|
|
|
|
}
|
|
|
|
|
2022-07-19 06:30:25 +00:00
|
|
|
impl<K: Hash + Eq, V> Default for LayeredEnv<K, V> {
|
|
|
|
fn default() -> Self {
|
|
|
|
LayeredEnv {
|
|
|
|
inner: Some(InnerEnv::new()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<K: Hash + Eq, V> LayeredEnv<K, V> {
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-18 03:06:37 +00:00
|
|
|
#[derive(Debug)]
|
|
|
|
struct InnerEnv<K, V> {
|
|
|
|
parent: Option<Box<InnerEnv<K, V>>>,
|
|
|
|
map: HashMap<K, V>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<K: Hash + Eq, V> InnerEnv<K, V> {
|
|
|
|
fn new() -> Self {
|
|
|
|
InnerEnv {
|
|
|
|
parent: None,
|
|
|
|
map: HashMap::new(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn with_parent(parent: InnerEnv<K, V>) -> 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,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
2022-07-18 02:00:19 +00:00
|
|
|
}
|