e0/src/utils.rs

75 lines
1.7 KiB
Rust

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<K, V> {
inner: Option<InnerEnv<K, V>>,
}
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)
}
}
#[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,
},
}
}
}