summaryrefslogtreecommitdiff
path: root/src/semantic/environment.rs
blob: 7876ad4e5110c6c0850cae06c3cc568857908b24 (plain)
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
use std::collections::HashMap;
use std::hash::Hash;

pub struct Environment<'a, T: 'a, U: 'a> {
    pub parent: Option<&'a Environment<'a, T, U>>,
    pub bindings: HashMap<T, U>,
}

impl<'a, T: 'a, U: 'a> Environment<'a, T, U>
    where T: Eq + Hash {
    pub fn new(parent: Option<&'a Environment<'a, T, U>>) -> Environment<'a, T, U> {
        Environment {
            parent: parent,
            bindings: HashMap::new(),
        }
    }

    pub fn set_parent(&mut self, parent: &'a Environment<'a, T, U>) {
        self.parent = Some(parent);
    }

    pub fn add_binding(&mut self, key: T, value: U) {
        self.bindings.insert(key, value);
    }

    pub fn lookup(&self, key: &T) -> Option<&U> {
        if let Some(v) = self.bindings.get(key) {
            Some(v)
        }
        else if let Some(p) = self.parent {
            p.lookup(key)
        }
        else {
            None
        }
    }
}