From 4ddcbc89adff8e23f57056d38de31d8d37eb81f5 Mon Sep 17 00:00:00 2001 From: Greg Shuflin Date: Thu, 21 Oct 2021 19:22:11 -0700 Subject: [PATCH] Parameterize type of ScopeStack scope names --- schala-lang/language/src/util.rs | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/schala-lang/language/src/util.rs b/schala-lang/language/src/util.rs index 0543759..6842041 100644 --- a/schala-lang/language/src/util.rs +++ b/schala-lang/language/src/util.rs @@ -8,18 +8,18 @@ pub fn deref_optional_box(x: &Option>) -> Option<&T> { } #[derive(Default, Debug)] -pub struct ScopeStack<'a, T: 'a, V: 'a> where T: Hash + Eq { - parent: Option<&'a ScopeStack<'a, T, V>>, +pub struct ScopeStack<'a, T: 'a, V: 'a, N=String> where T: Hash + Eq { + parent: Option<&'a ScopeStack<'a, T, V, N>>, values: HashMap, - scope_name: Option + scope_name: Option } -impl<'a, T, V> ScopeStack<'a, T, V> where T: Hash + Eq { - pub fn new(name: Option) -> ScopeStack<'a, T, V> where T: Hash + Eq { +impl<'a, T, V, N> ScopeStack<'a, T, V, N> where T: Hash + Eq { + pub fn new(scope_name: Option) -> Self where T: Hash + Eq { ScopeStack { parent: None, values: HashMap::new(), - scope_name: name + scope_name, } } pub fn insert(&mut self, key: T, value: V) where T: Hash + Eq { @@ -33,15 +33,24 @@ impl<'a, T, V> ScopeStack<'a, T, V> where T: Hash + Eq { } } - pub fn new_scope(&'a self, name: Option) -> ScopeStack<'a, T, V> where T: Hash + Eq { + pub fn new_scope(&'a self, scope_name: Option) -> Self where T: Hash + Eq { ScopeStack { parent: Some(self), values: HashMap::default(), - scope_name: name, + scope_name, } } + + pub fn lookup_with_scope(&self, key: &T) -> Option<(&V, Option<&N>)> where T: Hash + Eq { + match (self.values.get(key), self.parent) { + (None, None) => None, + (None, Some(parent)) => parent.lookup_with_scope(key), + (Some(value), _) => Some((value, self.scope_name.as_ref())) + } + } + #[allow(dead_code)] - pub fn get_name(&self) -> Option<&String> { + pub fn get_name(&self) -> Option<&N> { self.scope_name.as_ref() } }