use crate::syntax::names::{name_problem, word_runs};
use smol_str::SmolStr;
use std::collections::{HashMap, HashSet};
use temple_dsl::Names;
#[derive(Debug, Clone, Copy)]
enum Binding {
Variable,
Function { arity: usize },
}
#[derive(Default)]
pub(super) struct Scope {
globals: HashMap<SmolStr, Binding>,
locals: HashSet<SmolStr>,
}
impl Scope {
pub(super) fn add_variable(&mut self, name: &SmolStr) {
self.add_global(name, Binding::Variable);
}
pub(super) fn add_function(&mut self, name: &SmolStr, arity: usize) {
self.add_global(name, Binding::Function { arity });
}
fn add_global(&mut self, name: &SmolStr, binding: Binding) {
if self.admits(name) {
self.globals.insert(name.clone(), binding);
}
}
pub(super) fn add_local(&mut self, name: &SmolStr) {
if self.admits(name) {
self.locals.insert(name.clone());
}
}
fn admits(&self, name: &str) -> bool {
name_problem(name).is_none() && !self.globals.contains_key(name)
}
pub(super) fn clear_locals(&mut self) {
self.locals = HashSet::new();
}
pub(super) fn names_in(&self, text: &str) -> Names {
let mut names = Names::new();
for word in word_runs(text) {
if self.locals.contains(word) {
names.add_var(word);
} else if let Some(binding) = self.globals.get(word) {
add(&mut names, word, *binding);
}
}
names
}
pub(super) fn names(&self) -> impl Iterator<Item = &str> + Clone {
self.globals.keys().chain(&self.locals).map(SmolStr::as_str)
}
pub(super) fn all_names(&self) -> Names {
let mut names = Names::new();
for (name, binding) in &self.globals {
add(&mut names, name, *binding);
}
for name in &self.locals {
names.add_var(name.clone());
}
names
}
}
fn add(names: &mut Names, name: &str, binding: Binding) {
match binding {
Binding::Variable => names.add_var(name),
Binding::Function { arity } => names.add_function(name, arity),
}
}