summaryrefslogtreecommitdiff
path: root/src/semantic/environment.rs
blob: 1f9ade09795a91da6cee2d823437540b3b94b3d6 (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
38
39
40
41
42
// Copyright ⓒ 2017 David Li.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

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
        }
    }
}