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