1
//! Writing a name's cells: `define`.
2

            
3
use super::entry::Symbol;
4
use super::table::SymbolTable;
5

            
6
impl SymbolTable {
7
    /// Defines a symbol: it writes only the cells it carries, so a variable
8
    /// leaves the function of its name alone and the other way round.
9
386003563
    pub fn define(&mut self, mut symbol: Symbol) {
10
386003563
        if self.in_macro_expansion {
11
2076392
            self.macro_locals.insert(symbol.name.clone());
12
383927171
        }
13
386003563
        let fresh_global = symbol
14
386003563
            .function
15
386003563
            .as_ref()
16
354113590
            .is_some_and(|function| function.definition == 0 && !function.local);
17
386003563
        self.stamp_definitions(&mut symbol);
18
386003563
        let under_local = self
19
386003563
            .symbols
20
386003563
            .get(&symbol.name)
21
386003563
            .is_some_and(Symbol::is_local_function);
22
386003563
        if let Some(cell) = symbol.function.take() {
23
354113590
            symbol.function = match fresh_global && under_local {
24
5828
                true => self.defer_function(&symbol.name, cell),
25
354107762
                false => Some(cell),
26
            };
27
31889973
        }
28
386003563
        match self.symbols.get_mut(&symbol.name) {
29
86752648
            Some(entry) => entry.absorb(symbol),
30
            None => {
31
299250915
                self.symbols.insert(symbol.name.clone(), symbol);
32
            }
33
        }
34
386003563
    }
35

            
36
    /// Gives a fresh cell its binding id; a cell a closing scope puts back
37
    /// keeps its own.
38
386003563
    fn stamp_definitions(&mut self, symbol: &mut Symbol) {
39
386003563
        if let Some(variable) = symbol.value.as_mut() {
40
56734597
            if variable.definition == 0 {
41
53253890
                self.shadow_special(&symbol.name);
42
53253890
                variable.definition = self.next_definition_id();
43
3480707
            } else if self
44
3480707
                .shadowed_globals
45
3480707
                .get(&symbol.name)
46
2384
                .is_some_and(|global| global.definition == variable.definition)
47
            {
48
2378
                self.shadowed_globals.remove(&symbol.name);
49
3478329
            }
50
329268966
        }
51
386003563
        if symbol.function.as_ref().is_some_and(|f| f.definition == 0) {
52
354070585
            self.shadow_function(symbol);
53
354070585
            if let Some(function) = symbol.function.as_mut() {
54
354070585
                function.definition = self.next_definition_id();
55
            }
56
31932978
        }
57
386003563
    }
58
}