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

            
5
use std::collections::BTreeSet;
6

            
7
use super::entry::{Function, Symbol};
8
use super::table::SymbolTable;
9

            
10
const ALIAS_MARK: &str = " (LABELS ";
11

            
12
impl SymbolTable {
13
    /// The unspellable name of the LABELS function `name` of binding `id`.
14
61442
    pub(super) fn local_alias(name: &str, id: u32) -> String {
15
61442
        format!("{name}{ALIAS_MARK}{id})")
16
61442
    }
17

            
18
    /// The LABELS function an alias was made for.
19
    #[must_use]
20
2047981642
    pub fn local_alias_origin(alias: &str) -> Option<&str> {
21
2047981642
        alias.split_once(ALIAS_MARK).map(|(name, _)| name)
22
2047981642
    }
23

            
24
    /// The name of the function `name` to a reader: an alias shows the
25
    /// function it names.
26
    #[must_use]
27
4002
    pub(super) fn shown(name: &str) -> &str {
28
4002
        Self::local_alias_origin(name).unwrap_or(name)
29
4002
    }
30

            
31
    /// Binds the alias of the LABELS function `name`, its twin.
32
43638
    pub(crate) fn define_local_alias(&mut self, name: &str) {
33
43638
        let Some(function) = self.lookup(name).and_then(|symbol| symbol.function.clone()) else {
34
            return;
35
        };
36
43638
        let alias = Self::local_alias(name, function.definition);
37
43638
        self.define_scoped(Symbol::from_function(
38
43638
            alias,
39
43638
            Function {
40
43638
                local: false,
41
43638
                definition: 0,
42
43638
                ..function
43
43638
            },
44
43638
        ));
45
43638
    }
46

            
47
    /// The LABELS functions in scope with the alias of each.
48
    #[must_use]
49
9634532
    pub(crate) fn local_function_aliases(&self) -> Vec<(String, String)> {
50
9634532
        let origins: BTreeSet<&str> = self
51
9634532
            .symbols
52
9634532
            .keys()
53
2047632283
            .filter_map(|name| Self::local_alias_origin(name))
54
            .collect();
55
9634532
        origins
56
9634532
            .into_iter()
57
17803
            .filter_map(|name| {
58
17803
                let id = self.visible_local_function(name)?.function_definition();
59
17803
                Some((name.to_string(), Self::local_alias(name, id)))
60
17803
            })
61
            .collect()
62
9634532
    }
63

            
64
    /// The LABELS function `name` calls.
65
17803
    fn visible_local_function(&self, name: &str) -> Option<&Symbol> {
66
17803
        self.symbols
67
17803
            .get(name)
68
17803
            .filter(|symbol| symbol.is_local_function())
69
17803
    }
70
}