use std::collections::HashMap; use std::rc::Rc; use itertools::Itertools; use lasso::Spur; use thiserror::Error; use crate::utils::Stackframe; use crate::ast::{Expr, Clause}; type ImportMap = HashMap>>; #[derive(Debug, Clone, Error)] pub enum ResolutionError { #[error("Reference cycle at {0:?}")] Cycle(Vec>>), #[error("No module provides {0:?}")] NoModule(Rc>), #[error(transparent)] Delegate(#[from] Err) } type ResolutionResult = Result>, ResolutionError>; /// Recursively resolves symbols to their original names in expressions /// while caching every resolution. This makes the resolution process /// lightning fast and invalidation completely impossible since /// the intermediate steps of a resolution aren't stored. pub struct NameResolver { cache: HashMap>, ResolutionResult>, split: FSplit, get_imports: FImps } impl NameResolver where FSplit: FnMut(Rc>) -> Option<(Rc>, Rc>)>, FImps: FnMut(Rc>) -> Result, E: Clone { pub fn new(split: FSplit, get_imports: FImps) -> Self { Self { cache: HashMap::new(), split, get_imports } } fn split(&self, symbol: Rc>) -> Result<(Rc>, Rc>), ResolutionError> { let (path, name) = (self.split)(symbol.clone()) .ok_or_else(|| ResolutionError::NoModule(symbol.clone()))?; if name.is_empty() { panic!("get_modname matched all to module and nothing to name") } Ok((path, name)) } /// Obtains a symbol's originnal name /// Uses a substack to detect loops fn find_origin_rec( &mut self, symbol: Rc>, import_path: Stackframe>> ) -> Result>, ResolutionError> { if let Some(cached) = self.cache.get(&symbol) { return cached.clone() } // The imports and path of the referenced file and the local name let (path, name) = self.split(symbol)?; let imports = (self.get_imports)(path.clone())?; let result = if let Some(source) = imports.get(&name[0]) { let new_sym = source.iter().chain(name.iter()).cloned().collect_vec(); if import_path.iter().any(|el| el.as_ref() == new_sym.as_slice()) { Err(ResolutionError::Cycle(import_path.iter().cloned().collect())) } else { self.find_origin_rec(Rc::new(new_sym), import_path.push(symbol.clone())) } } else { Ok(symbol.clone()) // If not imported, it must be locally defined }; self.cache.insert(symbol, result.clone()); result } fn process_exprv_rec(&mut self, exv: &[Expr]) -> Result, ResolutionError> { exv.iter().map(|ex| self.process_expression_rec(ex)).collect() } fn process_exprmrcopt_rec(&mut self, exbo: &Option> ) -> Result>, ResolutionError> { exbo.iter().map(|exb| Ok(Rc::new(self.process_expression_rec(exb)?))) .next().transpose() } fn process_clause_rec(&mut self, tok: &Clause) -> Result> { Ok(match tok { Clause::S(c, exv) => Clause::S(*c, Rc::new( exv.iter().map(|e| self.process_expression_rec(e)) .collect::>()? )), Clause::Lambda(name, typ, body) => Clause::Lambda(name.clone(), Rc::new(self.process_exprv_rec(&typ)?), Rc::new(self.process_exprv_rec(&body)?) ), Clause::Auto(name, typ, body) => Clause::Auto(name.clone(), Rc::new(self.process_exprv_rec(&typ)?), Rc::new(self.process_exprv_rec(&body)?) ), Clause::Name(name) => Clause::Name(self.find_origin(name.clone())?), x => x.clone() }) } fn process_expression_rec(&mut self, Expr(token, typ): &Expr) -> Result> { Ok(Expr( self.process_clause_rec(token)?, Rc::new(typ.iter().map(|t| { self.process_clause_rec(t) }).collect::>()?) )) } pub fn find_origin(&mut self, symbol: Rc>) -> Result>, ResolutionError> { self.find_origin_rec(symbol.clone(), Stackframe::new(symbol)) } #[allow(dead_code)] pub fn process_clause(&mut self, clause: &Clause) -> Result> { self.process_clause_rec(clause) } pub fn process_expression(&mut self, ex: &Expr) -> Result> { self.process_expression_rec(ex) } }