Skip to main content

nomiscript/runtime/symbol/
local_aliases.rs

1//! The aliases that name a LABELS function for good: a lambda or DEFUN made
2//! inside the form calls its alias, which no call site can rebind and which
3//! ends with the form.
4
5use std::collections::BTreeSet;
6
7use super::entry::{Function, Symbol};
8use super::table::SymbolTable;
9
10const ALIAS_MARK: &str = " (LABELS ";
11
12impl SymbolTable {
13    /// The unspellable name of the LABELS function `name` of binding `id`.
14    pub(super) fn local_alias(name: &str, id: u32) -> String {
15        format!("{name}{ALIAS_MARK}{id})")
16    }
17
18    /// The LABELS function an alias was made for.
19    #[must_use]
20    pub fn local_alias_origin(alias: &str) -> Option<&str> {
21        alias.split_once(ALIAS_MARK).map(|(name, _)| name)
22    }
23
24    /// The name of the function `name` to a reader: an alias shows the
25    /// function it names.
26    #[must_use]
27    pub(super) fn shown(name: &str) -> &str {
28        Self::local_alias_origin(name).unwrap_or(name)
29    }
30
31    /// Binds the alias of the LABELS function `name`, its twin.
32    pub(crate) fn define_local_alias(&mut self, name: &str) {
33        let Some(function) = self.lookup(name).and_then(|symbol| symbol.function.clone()) else {
34            return;
35        };
36        let alias = Self::local_alias(name, function.definition);
37        self.define_scoped(Symbol::from_function(
38            alias,
39            Function {
40                local: false,
41                definition: 0,
42                ..function
43            },
44        ));
45    }
46
47    /// The LABELS functions in scope with the alias of each.
48    #[must_use]
49    pub(crate) fn local_function_aliases(&self) -> Vec<(String, String)> {
50        let origins: BTreeSet<&str> = self
51            .symbols
52            .keys()
53            .filter_map(|name| Self::local_alias_origin(name))
54            .collect();
55        origins
56            .into_iter()
57            .filter_map(|name| {
58                let id = self.visible_local_function(name)?.function_definition();
59                Some((name.to_string(), Self::local_alias(name, id)))
60            })
61            .collect()
62    }
63
64    /// The LABELS function `name` calls.
65    fn visible_local_function(&self, name: &str) -> Option<&Symbol> {
66        self.symbols
67            .get(name)
68            .filter(|symbol| symbol.is_local_function())
69    }
70}