Skip to main content

nomiscript/runtime/symbol/
define.rs

1//! Writing a name's cells: `define`.
2
3use super::entry::Symbol;
4use super::table::SymbolTable;
5
6impl 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    pub fn define(&mut self, mut symbol: Symbol) {
10        if self.in_macro_expansion {
11            self.macro_locals.insert(symbol.name.clone());
12        }
13        let fresh_global = symbol
14            .function
15            .as_ref()
16            .is_some_and(|function| function.definition == 0 && !function.local);
17        self.stamp_definitions(&mut symbol);
18        let under_local = self
19            .symbols
20            .get(&symbol.name)
21            .is_some_and(Symbol::is_local_function);
22        if let Some(cell) = symbol.function.take() {
23            symbol.function = match fresh_global && under_local {
24                true => self.defer_function(&symbol.name, cell),
25                false => Some(cell),
26            };
27        }
28        match self.symbols.get_mut(&symbol.name) {
29            Some(entry) => entry.absorb(symbol),
30            None => {
31                self.symbols.insert(symbol.name.clone(), symbol);
32            }
33        }
34    }
35
36    /// Gives a fresh cell its binding id; a cell a closing scope puts back
37    /// keeps its own.
38    fn stamp_definitions(&mut self, symbol: &mut Symbol) {
39        if let Some(variable) = symbol.value.as_mut() {
40            if variable.definition == 0 {
41                self.shadow_special(&symbol.name);
42                variable.definition = self.next_definition_id();
43            } else if self
44                .shadowed_globals
45                .get(&symbol.name)
46                .is_some_and(|global| global.definition == variable.definition)
47            {
48                self.shadowed_globals.remove(&symbol.name);
49            }
50        }
51        if symbol.function.as_ref().is_some_and(|f| f.definition == 0) {
52            self.shadow_function(symbol);
53            if let Some(function) = symbol.function.as_mut() {
54                function.definition = self.next_definition_id();
55            }
56        }
57    }
58}