1
use std::collections::HashMap;
2

            
3
use crate::ast::Expr;
4

            
5
use super::homes::HomeKey;
6

            
7
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8
pub enum SymbolKind {
9
    /// Built-in operators like +, -, *, /
10
    Operator,
11
    /// Native functions implemented in the runtime
12
    Native,
13
    /// User-defined functions
14
    Function,
15
    /// Variables and constants
16
    Variable,
17
    /// Special forms like if, let, define, lambda
18
    SpecialForm,
19
    /// User-defined macros
20
    Macro,
21
}
22

            
23
impl SymbolKind {
24
    /// A native, operator or special form: a name no program may bind.
25
488038525
    pub(super) fn is_builtin(self) -> bool {
26
488038525
        matches!(self, Self::Native | Self::Operator | Self::SpecialForm)
27
488038525
    }
28
}
29

            
30
/// The variable cell of a name.
31
#[derive(Debug, Clone, Default, PartialEq)]
32
pub(super) struct Variable {
33
    pub(super) value: Option<Expr>,
34
    /// The constant init of a global that lives in a wasm global: the only
35
    /// value a macro body reads while expanding (ISS-131).
36
    pub(super) expansion_value: Option<Expr>,
37
    /// A loop variable bound as constant data by a statically unrolled loop
38
    /// (0014 P11): a store to it is a structured error, never a rebinding.
39
    pub(super) loop_constant: bool,
40
    /// Copied into a closure's environment: a later store would not reach
41
    /// the closure's copy (ISS-001), so it is a structured error.
42
    pub(super) captured: bool,
43
    /// Table-assigned id of this binding (0 = unassigned): a lexical's tells a
44
    /// call site's rebinding from the binding a function was defined under.
45
    pub(super) definition: u32,
46
    /// The home of an assigned binder's local, which its stores write into.
47
    pub(super) home: Option<HomeKey>,
48
}
49

            
50
/// The function cell of a name: a function, macro, native or special form.
51
#[derive(Debug, Clone, PartialEq)]
52
pub(super) struct Function {
53
    /// Never `Variable`.
54
    pub(super) kind: SymbolKind,
55
    pub(super) lambda: Option<Expr>,
56
    /// The BLOCK labels visible where this function was defined: an inlined
57
    /// call sees only those and the body's own (ISS-179).
58
    pub(super) block_depth: usize,
59
    /// The lexical variables visible where this function was defined, which
60
    /// its body sees; empty for a top-level function.
61
    pub(super) lexical_env: Vec<(String, u32)>,
62
    /// The bindings of that environment its body reads and never assigns,
63
    /// which it keeps after their binder ended.
64
    pub(super) lexical_values: Vec<Symbol>,
65
    /// A LABELS function: it exists only inside its form.
66
    pub(super) local: bool,
67
    /// Table-assigned id (0 = unassigned): a cache keyed on it never serves a
68
    /// superseded body.
69
    pub(super) definition: u32,
70
}
71

            
72
impl Function {
73
354045879
    pub(super) fn new(kind: SymbolKind) -> Self {
74
354045879
        Self {
75
354045879
            kind,
76
354045879
            lambda: None,
77
354045879
            block_depth: 0,
78
354045879
            lexical_env: Vec::new(),
79
354045879
            lexical_values: Vec::new(),
80
354045879
            local: false,
81
354045879
            definition: 0,
82
354045879
        }
83
354045879
    }
84
}
85

            
86
/// A name with its two cells: the variable it names and the function it names.
87
#[derive(Debug, Clone, PartialEq)]
88
pub struct Symbol {
89
    pub(super) name: String,
90
    pub(super) doc: Option<String>,
91
    pub(super) properties: HashMap<String, Expr>,
92
    pub(super) value: Option<Variable>,
93
    pub(super) function: Option<Function>,
94
}
95

            
96
impl Symbol {
97
    /// A variable gets a value cell, any other kind a function cell.
98
382326360
    pub fn new(name: impl Into<String>, kind: SymbolKind) -> Self {
99
382326360
        let mut symbol = Self::bare(name);
100
382326360
        match kind {
101
28280482
            SymbolKind::Variable => symbol.value = Some(Variable::default()),
102
354045878
            kind => symbol.function = Some(Function::new(kind)),
103
        }
104
382326360
        symbol
105
382326360
    }
106

            
107
385886858
    pub(super) fn bare(name: impl Into<String>) -> Self {
108
385886858
        Self {
109
385886858
            name: name.into(),
110
385886858
            doc: None,
111
385886858
            properties: HashMap::new(),
112
385886858
            value: None,
113
385886858
            function: None,
114
385886858
        }
115
385886858
    }
116

            
117
3471567
    pub(super) fn from_value(name: impl Into<String>, cell: Variable) -> Self {
118
3471567
        Self {
119
3471567
            value: Some(cell),
120
3471567
            ..Self::bare(name)
121
3471567
        }
122
3471567
    }
123

            
124
86642
    pub(super) fn from_function(name: impl Into<String>, cell: Function) -> Self {
125
86642
        Self {
126
86642
            function: Some(cell),
127
86642
            ..Self::bare(name)
128
86642
        }
129
86642
    }
130

            
131
511049417
    pub(super) fn is_bare(&self) -> bool {
132
511049417
        self.value.is_none() && self.function.is_none()
133
511049417
    }
134

            
135
    /// Writes the cells, doc and properties `new` carries over this symbol's.
136
86752648
    pub(super) fn absorb(&mut self, new: Symbol) {
137
86752648
        self.value = new.value.or(self.value.take());
138
86752648
        self.function = new.function.or(self.function.take());
139
86752648
        self.doc = new.doc.or(self.doc.take());
140
86752648
        self.properties.extend(new.properties);
141
86752648
    }
142

            
143
    /// Whether the name is a variable: a value cell that is not the stand-in
144
    /// a host fn keeps in its own.
145
    #[must_use]
146
3131781996
    pub fn is_variable(&self) -> bool {
147
3131781996
        self.value.is_some() && !self.kind().is_builtin()
148
3131781996
    }
149

            
150
    /// Whether the name is a LABELS function.
151
    #[must_use]
152
2035839704
    pub fn is_local_function(&self) -> bool {
153
2035839704
        self.function
154
2035839704
            .as_ref()
155
1933606276
            .is_some_and(|function| function.local)
156
2035839704
    }
157

            
158
    /// Marks this binding as a statically unrolled loop's variable.
159
    #[must_use]
160
475849
    pub fn loop_constant(mut self) -> Self {
161
475849
        self.value.get_or_insert_default().loop_constant = true;
162
475849
        self
163
475849
    }
164

            
165
    /// Whether this binding is a statically unrolled loop's variable.
166
    #[must_use]
167
594065
    pub fn is_loop_constant(&self) -> bool {
168
594065
        self.value.as_ref().is_some_and(|cell| cell.loop_constant)
169
594065
    }
170

            
171
    /// Marks this binding as copied into a closure's environment.
172
17332
    pub fn mark_captured(&mut self) {
173
17332
        self.value.get_or_insert_default().captured = true;
174
17332
    }
175

            
176
    /// Whether a closure holds a copy of this binding.
177
    #[must_use]
178
1357935
    pub fn is_captured(&self) -> bool {
179
1357935
        self.value.as_ref().is_some_and(|cell| cell.captured)
180
1357935
    }
181

            
182
    /// Records how many BLOCK labels were visible at the definition.
183
567964
    pub fn set_block_depth(&mut self, depth: usize) {
184
567964
        if let Some(function) = self.function.as_mut() {
185
567964
            function.block_depth = depth;
186
        }
187
567964
    }
188

            
189
    /// The BLOCK labels visible at the definition.
190
    #[must_use]
191
413373
    pub fn block_depth(&self) -> usize {
192
413373
        self.function
193
413373
            .as_ref()
194
413373
            .map_or(0, |function| function.block_depth)
195
413373
    }
196

            
197
    /// Records the lexical variables visible at the definition.
198
5312854
    pub fn set_lexical_env(&mut self, env: Vec<(String, u32)>) {
199
5312854
        if let Some(function) = self.function.as_mut() {
200
5312854
            function.lexical_env = env;
201
        }
202
5312854
    }
203

            
204
    /// The lexical variables visible at the definition.
205
    #[must_use]
206
2332300
    pub fn lexical_env(&self) -> &[(String, u32)] {
207
2332300
        self.function
208
2332300
            .as_ref()
209
2332300
            .map_or(&[], |function| function.lexical_env.as_slice())
210
2332300
    }
211

            
212
    /// Records the lexical bindings the body of this function keeps.
213
5269217
    pub fn set_lexical_values(&mut self, values: Vec<Symbol>) {
214
5269217
        if let Some(function) = self.function.as_mut() {
215
5269217
            function.lexical_values = values;
216
        }
217
5269217
    }
218

            
219
    /// Drops the runtime values from the lexical bindings this function kept.
220
649274302
    pub(crate) fn forget_runtime_lexicals(&mut self) {
221
649274302
        let Some(function) = self.function.as_mut() else {
222
25297199
            return;
223
        };
224
623977103
        for binding in &mut function.lexical_values {
225
7915
            if binding.value().is_some_and(Expr::is_wasm_runtime) {
226
3749
                binding.clear_value();
227
4166
            }
228
        }
229
649274302
    }
230

            
231
    #[must_use]
232
53124055
    pub fn with_value(mut self, value: Expr) -> Self {
233
53124055
        self.value.get_or_insert_default().value = Some(value);
234
53124055
        self
235
53124055
    }
236

            
237
    #[must_use]
238
26963
    pub fn name(&self) -> &str {
239
26963
        &self.name
240
26963
    }
241

            
242
    /// The kind of the function cell, `Variable` for a name without one.
243
    #[must_use]
244
545197432
    pub fn kind(&self) -> SymbolKind {
245
545197432
        self.function
246
545197432
            .as_ref()
247
545197432
            .map_or(SymbolKind::Variable, |function| function.kind)
248
545197432
    }
249

            
250
    #[must_use]
251
1710387343
    pub fn value(&self) -> Option<&Expr> {
252
1710387343
        self.value.as_ref()?.value.as_ref()
253
1710387343
    }
254

            
255
22553505
    pub fn set_value(&mut self, value: Expr) {
256
22553505
        let cell = self.value.get_or_insert_default();
257
22553505
        cell.value = Some(value);
258
22553505
        cell.expansion_value = None;
259
22553505
    }
260

            
261
12082
    pub(crate) fn clear_value(&mut self) {
262
12082
        if let Some(cell) = self.value.as_mut() {
263
12082
            cell.value = None;
264
12082
            cell.expansion_value = None;
265
        }
266
12082
    }
267

            
268
    #[must_use]
269
56219240
    pub fn expansion_value(&self) -> Option<&Expr> {
270
56219240
        self.value.as_ref()?.expansion_value.as_ref()
271
56219240
    }
272

            
273
647359
    pub fn set_expansion_value(&mut self, value: Expr) {
274
647359
        self.value.get_or_insert_default().expansion_value = Some(value);
275
647359
    }
276

            
277
112549
    pub(crate) fn clear_expansion_value(&mut self) {
278
112549
        if let Some(cell) = self.value.as_mut() {
279
112549
            cell.expansion_value = None;
280
        }
281
112549
    }
282

            
283
    /// Gives the name a function cell holding `func`, of kind `Function`
284
    /// unless it already has one.
285
    #[must_use]
286
18072530
    pub fn with_function(mut self, func: Expr) -> Self {
287
18072530
        self.function
288
1
            .get_or_insert_with(|| Function::new(SymbolKind::Function))
289
18072530
            .lambda = Some(func);
290
18072530
        self
291
18072530
    }
292

            
293
    #[must_use]
294
239800059
    pub fn function(&self) -> Option<&Expr> {
295
239800059
        self.function.as_ref()?.lambda.as_ref()
296
239800059
    }
297

            
298
    /// Marks this function as bound by a LABELS form.
299
    #[must_use]
300
72425
    pub fn local_function(mut self) -> Self {
301
72425
        if let Some(function) = self.function.as_mut() {
302
72425
            function.local = true;
303
        }
304
72425
        self
305
72425
    }
306

            
307
    /// Keeps the binding identity of the variable this one re-materialises.
308
    #[must_use]
309
22320
    pub fn with_definition(mut self, id: u32) -> Self {
310
22320
        self.value.get_or_insert_default().definition = id;
311
22320
        self
312
22320
    }
313

            
314
    /// Gives the variable the home its stores record into.
315
    #[must_use]
316
1059845
    pub(crate) fn with_home(mut self, home: Option<HomeKey>) -> Self {
317
1059845
        self.value.get_or_insert_default().home = home;
318
1059845
        self
319
1059845
    }
320

            
321
    /// The home of the binder this variable is, when it has one.
322
    #[must_use]
323
786398
    pub(crate) fn home(&self) -> Option<&HomeKey> {
324
786398
        self.value.as_ref()?.home.as_ref()
325
786398
    }
326

            
327
    /// The id of the variable binding, 0 without one.
328
    #[must_use]
329
156736
    pub fn value_definition(&self) -> u32 {
330
156736
        self.value.as_ref().map_or(0, |cell| cell.definition)
331
156736
    }
332

            
333
    /// The id of the function binding, 0 without one.
334
    #[must_use]
335
273718
    pub fn function_definition(&self) -> u32 {
336
273718
        self.function.as_ref().map_or(0, |cell| cell.definition)
337
273718
    }
338

            
339
    /// Whether either cell carries the binding id `id`.
340
104570
    pub(super) fn has_definition(&self, id: u32) -> bool {
341
104570
        self.value_definition() == id || self.function_definition() == id
342
104570
    }
343

            
344
    #[must_use]
345
1873
    pub fn with_doc(mut self, doc: impl Into<String>) -> Self {
346
1873
        self.doc = Some(doc.into());
347
1873
        self
348
1873
    }
349

            
350
    #[must_use]
351
2718
    pub fn doc(&self) -> Option<&str> {
352
2718
        self.doc.as_deref()
353
2718
    }
354

            
355
    pub fn set_doc(&mut self, doc: impl Into<String>) {
356
        self.doc = Some(doc.into());
357
    }
358

            
359
    #[must_use]
360
3
    pub fn get_property(&self, key: &str) -> Option<&Expr> {
361
3
        self.properties.get(key)
362
3
    }
363

            
364
2
    pub fn set_property(&mut self, key: impl Into<String>, value: Expr) {
365
2
        self.properties.insert(key.into(), value);
366
2
    }
367

            
368
    pub fn remove_property(&mut self, key: &str) -> Option<Expr> {
369
        self.properties.remove(key)
370
    }
371

            
372
    #[must_use]
373
    pub fn properties(&self) -> &HashMap<String, Expr> {
374
        &self.properties
375
    }
376
}