1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use std::collections::HashMap;
use std::hash::Hash;
pub struct Scope<K: Hash + Eq, V>(Vec<HashMap<K, V>>);
impl<K: Hash + Eq, V> Scope<K, V> {
#[inline]
pub fn new() -> Self {
Self(vec![HashMap::new()])
}
#[inline]
pub fn enter_scope(&mut self) {
self.0.push(HashMap::<K, V>::new());
}
#[inline]
pub fn leave_scope(&mut self) {
self.0.pop();
}
#[inline]
pub fn get(&self, item: &K) -> Option<&V> {
for stack_item in self.0.iter().rev() {
let cur_item = stack_item.get(item);
if cur_item.is_some() {
return cur_item;
}
}
None
}
#[inline]
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
self.0.last_mut().unwrap().insert(key, value)
}
pub fn depth(&self) -> usize {
self.0.len()
}
}