schala/schala-lang/language/src/util.rs

54 lines
1.5 KiB
Rust
Raw Normal View History

use std::collections::HashMap;
use std::hash::Hash;
use std::cmp::Eq;
#[derive(Default, Debug)]
2018-08-19 21:31:28 -07:00
pub struct ScopeStack<'a, T: 'a, V: 'a> where T: Hash + Eq {
parent: Option<&'a ScopeStack<'a, T, V>>,
2018-05-10 22:32:36 -07:00
values: HashMap<T, V>,
scope_name: Option<String>
}
2018-08-19 21:31:28 -07:00
impl<'a, T, V> ScopeStack<'a, T, V> where T: Hash + Eq {
pub fn new(name: Option<String>) -> ScopeStack<'a, T, V> where T: Hash + Eq {
ScopeStack {
2018-05-11 01:56:12 -07:00
parent: None,
values: HashMap::new(),
scope_name: name
}
}
pub fn insert(&mut self, key: T, value: V) where T: Hash + Eq {
self.values.insert(key, value);
}
pub fn lookup(&self, key: &T) -> Option<&V> where T: Hash + Eq {
match (self.values.get(key), self.parent) {
(None, None) => None,
(None, Some(parent)) => parent.lookup(key),
(Some(value), _) => Some(value),
}
}
2018-09-22 00:26:38 -07:00
2018-08-19 21:31:28 -07:00
pub fn new_scope(&'a self, name: Option<String>) -> ScopeStack<'a, T, V> where T: Hash + Eq {
ScopeStack {
2018-05-10 22:28:25 -07:00
parent: Some(self),
2018-05-10 22:32:36 -07:00
values: HashMap::default(),
scope_name: name,
2018-05-10 22:28:25 -07:00
}
}
2018-10-20 00:55:37 -07:00
#[allow(dead_code)]
2018-05-10 22:32:36 -07:00
pub fn get_name(&self) -> Option<&String> {
self.scope_name.as_ref()
}
}
2019-03-07 23:51:31 -08:00
/// this is intended for use in tests, and does no error-handling whatsoever
pub fn quick_ast(input: &str) -> crate::ast::AST {
let tokens = crate::tokenizing::tokenize(input);
let mut parser = crate::parsing::Parser::new(tokens);
parser.parse().unwrap()
}
macro_rules! rc {
($string:tt) => { Rc::new(stringify!($string).to_string()) }
}