2018-05-10 22:23:42 -07:00
|
|
|
use std::collections::HashMap;
|
|
|
|
use std::hash::Hash;
|
|
|
|
use std::cmp::Eq;
|
|
|
|
|
2018-05-29 00:09:12 -07:00
|
|
|
//TODO rename this ScopeStack
|
2018-05-10 22:23:42 -07:00
|
|
|
#[derive(Default, Debug)]
|
|
|
|
pub struct StateStack<'a, T: 'a, V: 'a> where T: Hash + Eq {
|
|
|
|
parent: Option<&'a StateStack<'a, T, V>>,
|
2018-05-10 22:32:36 -07:00
|
|
|
values: HashMap<T, V>,
|
|
|
|
scope_name: Option<String>
|
2018-05-10 22:23:42 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, T, V> StateStack<'a, T, V> where T: Hash + Eq {
|
2018-05-11 01:56:12 -07:00
|
|
|
pub fn new(name: Option<String>) -> StateStack<'a, T, V> where T: Hash + Eq {
|
|
|
|
StateStack {
|
|
|
|
parent: None,
|
|
|
|
values: HashMap::new(),
|
|
|
|
scope_name: name
|
|
|
|
}
|
|
|
|
}
|
2018-05-10 22:23:42 -07:00
|
|
|
pub fn insert(&mut self, key: T, value: V) where T: Hash + Eq {
|
|
|
|
self.values.insert(key, value);
|
|
|
|
}
|
|
|
|
pub fn lookup(&self, key: &T) -> Option<&V> where T: Hash + Eq {
|
|
|
|
match (self.values.get(key), self.parent) {
|
|
|
|
(None, None) => None,
|
|
|
|
(None, Some(parent)) => parent.lookup(key),
|
|
|
|
(Some(value), _) => Some(value),
|
|
|
|
}
|
|
|
|
}
|
2018-05-29 00:09:12 -07:00
|
|
|
//TODO rename new_scope
|
2018-08-14 21:45:45 -07:00
|
|
|
pub fn new_scope(&'a self, name: Option<String>) -> StateStack<'a, T, V> where T: Hash + Eq {
|
2018-05-10 22:28:25 -07:00
|
|
|
StateStack {
|
|
|
|
parent: Some(self),
|
2018-05-10 22:32:36 -07:00
|
|
|
values: HashMap::default(),
|
|
|
|
scope_name: name,
|
2018-05-10 22:28:25 -07:00
|
|
|
}
|
|
|
|
}
|
2018-05-10 22:32:36 -07:00
|
|
|
pub fn get_name(&self) -> Option<&String> {
|
|
|
|
self.scope_name.as_ref()
|
|
|
|
}
|
2018-05-10 22:23:42 -07:00
|
|
|
}
|
|
|
|
|