1
//! The symbol table's scoped state (0014 Stage 2): the globals the unit
2
//! stores to, skippable regions, scope frames and a macro's private names.
3

            
4
use std::collections::HashSet;
5

            
6
use crate::ast::Expr;
7
use crate::error::{Error, Result};
8

            
9
use crate::compiler::special::binding::shared::{reads_free, stores_free};
10

            
11
use super::entry::{Function, Symbol, Variable};
12
use super::table::SymbolTable;
13

            
14
/// The cell of a name a scope frame saved before a binder replaced it.
15
#[derive(Debug, Clone)]
16
pub(super) enum Shadowed {
17
    Value(Option<Variable>),
18
    Function(Option<Function>),
19
}
20

            
21
impl Shadowed {
22
691236
    fn same_cell(&self, other: &Self) -> bool {
23
691236
        std::mem::discriminant(self) == std::mem::discriminant(other)
24
691236
    }
25
}
26

            
27
3125324976
fn is_lexical_binding(specials: &HashSet<String>, name: &str, symbol: &Symbol) -> bool {
28
3125324976
    symbol.is_variable()
29
164488485
        && symbol
30
164488485
            .value()
31
164487444
            .is_some_and(|value| !matches!(value, Expr::WasmGlobal(..)))
32
163090097
        && !specials.contains(name)
33
3125324976
}
34

            
35
impl SymbolTable {
36
    /// Records the globals the unit about to compile stores to; replaces the
37
    /// previous unit's set.
38
2341832
    pub(crate) fn set_stored_globals(&mut self, stores: HashSet<String>) {
39
2341832
        self.stored_globals = stores;
40
2341832
    }
41

            
42
    /// Records the unit's defined specials and, among them, the ones a
43
    /// LET / LET* binds; replaces the previous unit's sets.
44
2341856
    pub(crate) fn set_unit_specials(&mut self, defined: HashSet<String>, dynamic: HashSet<String>) {
45
2341856
        self.unit_specials = defined;
46
2341856
        self.dynamic_specials = dynamic;
47
2341856
    }
48

            
49
    /// Whether a binder of the special `name` saves and restores its global.
50
    #[must_use]
51
5080909
    pub(crate) fn is_dynamic_special(&self, name: &str) -> bool {
52
5080909
        self.dynamic_specials.contains(name)
53
5080909
    }
54

            
55
    /// How many globals the current unit may give a home: the specials it
56
    /// defines or adopts and its stored globals.
57
    #[must_use]
58
90050
    pub(crate) fn unit_home_count(&self) -> usize {
59
90050
        self.unit_specials
60
90050
            .union(&self.dynamic_specials)
61
90050
            .chain(self.stored_globals.difference(&self.unit_specials))
62
90050
            .collect::<HashSet<_>>()
63
90050
            .len()
64
90050
    }
65

            
66
    /// Whether `name` is a global a `SETF` created, not a declared special.
67
    #[must_use]
68
157549
    pub(crate) fn is_created_global(&self, name: &str) -> bool {
69
157549
        self.created_globals.contains(name)
70
157549
    }
71

            
72
    /// Records the global `name` a `SETF` created.
73
22384
    pub(crate) fn mark_created_global(&mut self, name: &str) {
74
22384
        self.created_globals.insert(name.to_string());
75
22384
    }
76

            
77
    /// The constant an earlier unit left for the global variable `name`, which
78
    /// a store or a binder of the unit seeds its runtime cell from.
79
    #[must_use]
80
193408873
    pub(crate) fn constant_global(&self, name: &str) -> Option<Expr> {
81
193408873
        if self.in_macro_expansion {
82
1
            return None;
83
193408872
        }
84
193408872
        let symbol = self.symbols.get(name)?;
85
186232414
        if symbol.kind().is_builtin() {
86
8370589
            return None;
87
177861825
        }
88
177861825
        symbol
89
177861825
            .value()
90
1687650
            .filter(|value| !value.is_wasm_runtime())
91
            .cloned()
92
193408873
    }
93

            
94
    /// The session struct instance an earlier unit left for the global `name`.
95
    #[must_use]
96
150907
    pub(crate) fn instance_global(&self, name: &str) -> Option<Expr> {
97
150907
        self.symbols
98
150907
            .get(name)?
99
            .value()
100
625
            .filter(|value| matches!(value, Expr::Instance(..)))
101
            .cloned()
102
150907
    }
103

            
104
    /// Whether the current unit defines the special `name`.
105
    #[must_use]
106
14883708
    pub(crate) fn is_unit_special(&self, name: &str) -> bool {
107
14883708
        self.unit_specials.contains(name)
108
14883708
    }
109

            
110
    /// Whether `name` was declared special by a DEFVAR / DEFPARAMETER.
111
    #[must_use]
112
6804709
    pub(crate) fn is_special(&self, name: &str) -> bool {
113
6804709
        self.special_names.contains(name)
114
6804709
    }
115

            
116
    /// Whether the unit stores to the global `name`, making it a runtime cell.
117
    #[must_use]
118
7335783
    pub(crate) fn is_stored_global(&self, name: &str) -> bool {
119
7335783
        self.stored_globals.contains(name)
120
7335783
    }
121

            
122
    /// Defines a global variable: one a callee sees even when a LET rebinds it.
123
14178677
    pub fn define_special(&mut self, symbol: Symbol) {
124
14178677
        let name = symbol.name.clone();
125
14178677
        self.special_names.insert(name.clone());
126
14178677
        self.define(symbol);
127
14178677
        self.shadowed_globals.remove(&name);
128
14178677
    }
129

            
130
    /// Remembers the global `name` before a fresh binding replaces it.
131
53253890
    pub(super) fn shadow_special(&mut self, name: &str) {
132
53253890
        if !self.special_names.contains(name) || self.shadowed_globals.contains_key(name) {
133
38917335
            return;
134
14336555
        }
135
14336555
        if let Some(global) = self
136
14336555
            .symbols
137
14336555
            .get(name)
138
3489
            .and_then(|symbol| symbol.value.clone())
139
        {
140
3489
            self.shadowed_globals.insert(name.to_string(), global);
141
14333066
        }
142
53253890
    }
143

            
144
    /// The name of the unshadowable alias of the global function `name`; no
145
    /// reader token contains the space.
146
31088
    pub(super) fn function_alias(name: &str) -> String {
147
31088
        format!("{name} (global)")
148
31088
    }
149

            
150
    /// Keeps the global function a LABELS function `binding` is about to
151
    /// hide under an alias, so a quoted designator still names it through the
152
    /// ordinary named call. An open scope frame records the alias, so it
153
    /// closes with the frame.
154
354070585
    pub(super) fn shadow_function(&mut self, binding: &Symbol) {
155
354070585
        if !binding.is_local_function() {
156
353998160
            return;
157
72425
        }
158
72425
        let global = match self
159
72425
            .symbols
160
72425
            .get(&binding.name)
161
32741
            .and_then(|s| s.function.as_ref())
162
        {
163
31255
            Some(global) if Self::hideable(global) => global.clone(),
164
58956
            _ => return,
165
        };
166
13469
        self.define_scoped(Symbol::from_function(
167
13469
            Self::function_alias(&binding.name),
168
13469
            global,
169
13469
        ));
170
354070585
    }
171

            
172
    /// The name a quoted designator `name` calls: a LABELS function is
173
    /// invisible to it, so `Some` is the alias of the global function it
174
    /// hides, or an undefined-function error when there is none; `None` when
175
    /// `name` is not a LABELS function here.
176
91890
    pub(crate) fn designated_function(&self, name: &str) -> Result<Option<String>> {
177
91890
        if !self
178
91890
            .symbols
179
91890
            .get(name)
180
91890
            .is_some_and(Symbol::is_local_function)
181
        {
182
80099
            return Ok(None);
183
11791
        }
184
11791
        let alias = Self::function_alias(name);
185
11791
        if self.symbols.contains_key(&alias) {
186
11364
            return Ok(Some(alias));
187
427
        }
188
427
        Err(Error::UndefinedSymbol(name.to_string()))
189
91890
    }
190

            
191
    /// Marks an already defined global as special.
192
409042
    pub(crate) fn mark_special(&mut self, name: &str) {
193
409042
        self.created_globals.remove(name);
194
409042
        self.special_names.insert(name.to_string());
195
409042
    }
196

            
197
    /// The names a binder introduced: variables with a value that are
198
    /// neither specials nor host fns, and LABELS functions.
199
5315658
    pub(crate) fn lexical_names(&self) -> Vec<(String, u32)> {
200
5315658
        let mut names = Vec::new();
201
5315658
        for (name, symbol) in &self.symbols {
202
1134618432
            if symbol.is_local_function() {
203
50952
                names.push((name.clone(), symbol.function_definition()));
204
1134567480
            }
205
1134618432
            if self.is_lexical(name, symbol) || self.shadowed_globals.contains_key(name) {
206
29836
                names.push((name.clone(), symbol.value_definition()));
207
1134588596
            }
208
        }
209
5315658
        names.sort();
210
5315658
        names
211
5315658
    }
212

            
213
    /// The lexical variables currently bound, with their values.
214
    #[must_use]
215
5269214
    pub(crate) fn lexical_bindings(&self) -> Vec<Symbol> {
216
5269214
        let mut bindings: Vec<Symbol> = self
217
5269214
            .symbols
218
5269214
            .iter()
219
1126147249
            .filter(|(name, symbol)| self.is_lexical(name, symbol))
220
12972
            .filter_map(|(name, symbol)| Some(Symbol::from_value(name, symbol.value.clone()?)))
221
            .collect();
222
5269214
        bindings.sort_by(|a, b| a.name.cmp(&b.name));
223
5269214
        bindings
224
5269214
    }
225

            
226
    /// Rebinds the lexical variables `callee` kept from its definition whose
227
    /// binder ended; a runtime one cannot outlive its unit.
228
2331004
    fn restore_kept_lexicals(&mut self, callee: &str) -> Result<()> {
229
2331004
        let kept = self
230
2331004
            .lookup(callee)
231
2331004
            .and_then(|symbol| symbol.function.as_ref())
232
2331004
            .map_or_else(Vec::new, |function| function.lexical_values.clone());
233
2331004
        for binding in kept {
234
6681
            if self
235
6681
                .symbols
236
6681
                .get(binding.name())
237
1686
                .is_some_and(|s| s.value.is_some())
238
            {
239
1686
                continue;
240
4995
            }
241
4995
            if binding.value().is_none() {
242
2706
                return Err(Error::Compile(format!(
243
2706
                    "{}: reads {}, a runtime variable of a binder that ended, which does not outlive its unit; not supported yet",
244
2706
                    Self::shown(callee),
245
2706
                    binding.name()
246
2706
                )));
247
2289
            }
248
2289
            if let Some(cell) = binding.value {
249
2289
                self.put_value(&binding.name, cell);
250
            }
251
        }
252
2328298
        Ok(())
253
2331004
    }
254

            
255
    /// Drops the runtime values from the lexical bindings every function
256
    /// kept: a wasm local does not outlive its unit.
257
2439145
    pub(crate) fn forget_runtime_lexicals(&mut self) {
258
2439145
        self.symbols
259
2439145
            .values_mut()
260
2439145
            .for_each(Symbol::forget_runtime_lexicals);
261
2439145
    }
262

            
263
    /// The lexical variables a binder holds a compile-time value for, by name.
264
    #[must_use]
265
2269541
    pub(crate) fn lexical_constants(&self) -> Vec<(String, Expr)> {
266
2269541
        let mut constants: Vec<(String, Expr)> = self
267
2269541
            .symbols
268
2269541
            .iter()
269
410718827
            .filter(|(name, symbol)| self.is_lexical(name, symbol))
270
1341964
            .filter_map(|(name, symbol)| Some((name.clone(), symbol.value()?.clone())))
271
1341964
            .filter(|(_, value)| !value.is_wasm_runtime())
272
            .collect();
273
2269541
        constants.sort_by(|a, b| a.0.cmp(&b.0));
274
2269541
        constants
275
2269541
    }
276

            
277
    /// Unbinds every lexical variable but those in `keep`: a function body
278
    /// sees its own definition's lexical environment, never its caller's.
279
2331005
    pub(crate) fn hide_lexicals_except(&mut self, keep: &[(String, u32)]) {
280
2331005
        let specials = &self.special_names;
281
453582299
        self.symbols.retain(|name, symbol| {
282
453582299
            let kept = keep.iter().any(|(kept, _)| kept == name);
283
453582299
            if !kept && is_lexical_binding(specials, name, symbol) {
284
22056384
                symbol.value = None;
285
431525915
            }
286
453582299
            !symbol.is_bare()
287
453582299
        });
288
2331005
        for (name, global) in std::mem::take(&mut self.shadowed_globals) {
289
1988
            if keep.iter().any(|(kept, _)| *kept == name) {
290
19
                self.shadowed_globals.insert(name, global);
291
            } else {
292
1969
                self.put_value(&name, global);
293
            }
294
        }
295
2331005
    }
296

            
297
4258
    fn put_value(&mut self, name: &str, cell: Variable) {
298
4258
        self.symbols
299
4258
            .entry(name.to_string())
300
2289
            .or_insert_with(|| Symbol::bare(name))
301
4258
            .value = Some(cell);
302
4258
    }
303

            
304
    /// Narrows a table cloned from a call site to what the body of `callee`
305
    /// sees of lexical variables.
306
    ///
307
    /// A name of that environment the call site rebinds is an error: the
308
    /// inliner has no environments, so the body would read the call site's.
309
2332300
    pub(crate) fn hide_caller_lexicals(&mut self, callee: &str) -> Result<()> {
310
2332300
        let (env, function) = self.lookup(callee).map_or_else(
311
            || (Vec::new(), None),
312
2332300
            |symbol| (symbol.lexical_env().to_vec(), symbol.function().cloned()),
313
        );
314
29981
        let reads = |name: &str| {
315
29981
            function
316
29981
                .as_ref()
317
29981
                .map_or(Ok(true), |func| reads_free(self, func, name))
318
29981
        };
319
2332300
        for (name, id) in &env {
320
120481
            let rebound = self
321
120481
                .symbols
322
120481
                .get(name)
323
104570
                .is_some_and(|sym| !sym.has_definition(*id));
324
120481
            if rebound && reads(name)? {
325
656
                let verb = match function.as_ref() {
326
656
                    Some(func) if stores_free(self, func, name)? => "stores",
327
447
                    _ => "reads",
328
                };
329
656
                let callee = Self::shown(callee);
330
656
                return Err(crate::error::Error::Compile(format!(
331
656
                    "{callee}: {verb} {name}, which the call site rebinds; a function sees the binding of its definition; not supported yet"
332
656
                )));
333
119825
            }
334
        }
335
2331644
        if function.is_some() {
336
2331644
            self.reject_foreign_local_function(callee, &env, &reads)?;
337
        }
338
2331004
        self.hide_lexicals_except(&env);
339
2331004
        self.restore_kept_lexicals(callee)
340
2332300
    }
341

            
342
    /// Unbinds every runtime local: a separate wasm function has none of its
343
    /// caller's, so it gets only the params and captures installed after. The
344
    /// runtime values kept by functions go too, their indices are the caller's.
345
298021
    pub(crate) fn drop_runtime_locals(&mut self) {
346
298021
        self.forget_local_closure_bodies();
347
298021
        self.forget_runtime_lexicals();
348
55450512
        self.symbols.retain(|_, symbol| {
349
55450512
            if matches!(symbol.value(), Some(Expr::WasmLocal(..))) {
350
79913
                symbol.value = None;
351
55370599
            }
352
55450512
            !symbol.is_bare()
353
55450512
        });
354
298021
    }
355

            
356
    /// A LABELS function the call site sees but the callee's definition did
357
    /// not, which the callee reads, would replace the one it was defined with.
358
2331644
    fn reject_foreign_local_function(
359
2331644
        &self,
360
2331644
        callee: &str,
361
2331644
        env: &[(String, u32)],
362
2331644
        reads: &dyn Fn(&str) -> Result<bool>,
363
2331644
    ) -> Result<()> {
364
2331644
        for (name, symbol) in &self.symbols {
365
453634503
            let foreign = symbol.is_local_function()
366
77313
                && !env
367
77313
                    .iter()
368
86322
                    .any(|(kept, id)| kept == name && *id == symbol.function_definition());
369
453634503
            if foreign && reads(name)? {
370
640
                let callee = Self::shown(callee);
371
640
                return Err(crate::error::Error::Compile(format!(
372
640
                    "{callee}: calls {name}, a local function the call site binds; a function sees the functions of its definition; not supported yet"
373
640
                )));
374
453633863
            }
375
        }
376
2331004
        Ok(())
377
2331644
    }
378

            
379
    /// Whether `name` is currently bound by a binder as a lexical variable.
380
    #[must_use]
381
514000
    pub(crate) fn is_lexical_variable(&self, name: &str) -> bool {
382
514000
        self.symbols
383
514000
            .get(name)
384
355394
            .is_some_and(|symbol| self.is_lexical(name, symbol))
385
514000
    }
386

            
387
2671839902
    fn is_lexical(&self, name: &str, symbol: &Symbol) -> bool {
388
2671839902
        is_lexical_binding(&self.special_names, name, symbol)
389
2671839902
    }
390

            
391
    /// Whether `name` was bound inside the macro expansion this table
392
    /// evaluates (see [`Self::macro_locals`]).
393
    #[must_use]
394
397853
    pub(crate) fn is_macro_local(&self, name: &str) -> bool {
395
397853
        self.macro_locals.contains(name)
396
397853
    }
397

            
398
    /// Opens a scope frame; paired with [`Self::pop_scope`].
399
4464306
    pub(crate) fn push_scope(&mut self) {
400
4464306
        self.scopes.push(Vec::new());
401
4464306
    }
402

            
403
    /// Defines `symbol` for the innermost open frame, remembering the cells
404
    /// it shadows. Without an open frame this is [`Self::define`].
405
5392881
    pub(crate) fn define_scoped(&mut self, symbol: Symbol) {
406
5392881
        let prior = self.symbols.get(&symbol.name);
407
5392881
        let mut shadowed = Vec::new();
408
5392881
        if symbol.value.is_some() {
409
5292139
            shadowed.push(Shadowed::Value(prior.and_then(|p| p.value.clone())));
410
100742
        }
411
5392881
        if symbol.function.is_some() {
412
100742
            shadowed.push(Shadowed::Function(prior.and_then(|p| p.function.clone())));
413
5292139
        }
414
5392881
        if let Some(frame) = self.scopes.last_mut() {
415
5390169
            for cell in shadowed {
416
5390169
                let recorded = frame
417
5390169
                    .iter()
418
2781909
                    .any(|(name, saved)| *name == symbol.name && saved.same_cell(&cell));
419
5390169
                if !recorded {
420
4698934
                    frame.push((symbol.name.clone(), cell));
421
691235
                }
422
            }
423
2712
        }
424
5392881
        self.define(symbol);
425
5392881
    }
426

            
427
    /// Runs `body` in a frame of its own, closed whatever its result.
428
86417
    pub(crate) fn with_scope<T>(&mut self, body: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
429
86417
        self.push_scope();
430
86417
        let result = body(self);
431
86417
        self.pop_scope()?;
432
86417
        result
433
86417
    }
434

            
435
    /// Closes the innermost frame, putting back every cell it shadowed.
436
4464307
    pub(crate) fn pop_scope(&mut self) -> Result<()> {
437
4464307
        let frame = self.scopes.pop().ok_or_else(|| {
438
1
            crate::error::Error::Compile("internal: pop_scope() with no open scope".to_string())
439
1
        })?;
440
4464306
        for (name, shadowed) in frame.into_iter().rev() {
441
4700598
            match shadowed {
442
3458595
                Shadowed::Value(Some(cell)) => self.define(Symbol::from_value(name, cell)),
443
24539
                Shadowed::Function(Some(cell)) => self.define(Symbol::from_function(name, cell)),
444
1142309
                Shadowed::Value(None) => self.clear_cell(&name, |symbol| symbol.value = None),
445
75155
                Shadowed::Function(None) => self.clear_cell(&name, |symbol| symbol.function = None),
446
            }
447
        }
448
4464306
        Ok(())
449
4464307
    }
450

            
451
    /// Empties one cell of `name`, dropping the entry once both are empty.
452
1217880
    pub(super) fn clear_cell(&mut self, name: &str, clear: impl FnOnce(&mut Symbol)) {
453
1217880
        let Some(symbol) = self.symbols.get_mut(name) else {
454
416
            return;
455
        };
456
1217464
        clear(symbol);
457
1217464
        if symbol.is_bare() {
458
1200884
            self.symbols.remove(name);
459
16580
        }
460
1217880
    }
461
}