Skip to main content

nomiscript/runtime/symbol/
entry.rs

1use std::collections::HashMap;
2
3use crate::ast::Expr;
4
5use super::homes::HomeKey;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub 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
23impl SymbolKind {
24    /// A native, operator or special form: a name no program may bind.
25    pub(super) fn is_builtin(self) -> bool {
26        matches!(self, Self::Native | Self::Operator | Self::SpecialForm)
27    }
28}
29
30/// The variable cell of a name.
31#[derive(Debug, Clone, Default, PartialEq)]
32pub(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)]
52pub(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
72impl Function {
73    pub(super) fn new(kind: SymbolKind) -> Self {
74        Self {
75            kind,
76            lambda: None,
77            block_depth: 0,
78            lexical_env: Vec::new(),
79            lexical_values: Vec::new(),
80            local: false,
81            definition: 0,
82        }
83    }
84}
85
86/// A name with its two cells: the variable it names and the function it names.
87#[derive(Debug, Clone, PartialEq)]
88pub 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
96impl Symbol {
97    /// A variable gets a value cell, any other kind a function cell.
98    pub fn new(name: impl Into<String>, kind: SymbolKind) -> Self {
99        let mut symbol = Self::bare(name);
100        match kind {
101            SymbolKind::Variable => symbol.value = Some(Variable::default()),
102            kind => symbol.function = Some(Function::new(kind)),
103        }
104        symbol
105    }
106
107    pub(super) fn bare(name: impl Into<String>) -> Self {
108        Self {
109            name: name.into(),
110            doc: None,
111            properties: HashMap::new(),
112            value: None,
113            function: None,
114        }
115    }
116
117    pub(super) fn from_value(name: impl Into<String>, cell: Variable) -> Self {
118        Self {
119            value: Some(cell),
120            ..Self::bare(name)
121        }
122    }
123
124    pub(super) fn from_function(name: impl Into<String>, cell: Function) -> Self {
125        Self {
126            function: Some(cell),
127            ..Self::bare(name)
128        }
129    }
130
131    pub(super) fn is_bare(&self) -> bool {
132        self.value.is_none() && self.function.is_none()
133    }
134
135    /// Writes the cells, doc and properties `new` carries over this symbol's.
136    pub(super) fn absorb(&mut self, new: Symbol) {
137        self.value = new.value.or(self.value.take());
138        self.function = new.function.or(self.function.take());
139        self.doc = new.doc.or(self.doc.take());
140        self.properties.extend(new.properties);
141    }
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    pub fn is_variable(&self) -> bool {
147        self.value.is_some() && !self.kind().is_builtin()
148    }
149
150    /// Whether the name is a LABELS function.
151    #[must_use]
152    pub fn is_local_function(&self) -> bool {
153        self.function
154            .as_ref()
155            .is_some_and(|function| function.local)
156    }
157
158    /// Marks this binding as a statically unrolled loop's variable.
159    #[must_use]
160    pub fn loop_constant(mut self) -> Self {
161        self.value.get_or_insert_default().loop_constant = true;
162        self
163    }
164
165    /// Whether this binding is a statically unrolled loop's variable.
166    #[must_use]
167    pub fn is_loop_constant(&self) -> bool {
168        self.value.as_ref().is_some_and(|cell| cell.loop_constant)
169    }
170
171    /// Marks this binding as copied into a closure's environment.
172    pub fn mark_captured(&mut self) {
173        self.value.get_or_insert_default().captured = true;
174    }
175
176    /// Whether a closure holds a copy of this binding.
177    #[must_use]
178    pub fn is_captured(&self) -> bool {
179        self.value.as_ref().is_some_and(|cell| cell.captured)
180    }
181
182    /// Records how many BLOCK labels were visible at the definition.
183    pub fn set_block_depth(&mut self, depth: usize) {
184        if let Some(function) = self.function.as_mut() {
185            function.block_depth = depth;
186        }
187    }
188
189    /// The BLOCK labels visible at the definition.
190    #[must_use]
191    pub fn block_depth(&self) -> usize {
192        self.function
193            .as_ref()
194            .map_or(0, |function| function.block_depth)
195    }
196
197    /// Records the lexical variables visible at the definition.
198    pub fn set_lexical_env(&mut self, env: Vec<(String, u32)>) {
199        if let Some(function) = self.function.as_mut() {
200            function.lexical_env = env;
201        }
202    }
203
204    /// The lexical variables visible at the definition.
205    #[must_use]
206    pub fn lexical_env(&self) -> &[(String, u32)] {
207        self.function
208            .as_ref()
209            .map_or(&[], |function| function.lexical_env.as_slice())
210    }
211
212    /// Records the lexical bindings the body of this function keeps.
213    pub fn set_lexical_values(&mut self, values: Vec<Symbol>) {
214        if let Some(function) = self.function.as_mut() {
215            function.lexical_values = values;
216        }
217    }
218
219    /// Drops the runtime values from the lexical bindings this function kept.
220    pub(crate) fn forget_runtime_lexicals(&mut self) {
221        let Some(function) = self.function.as_mut() else {
222            return;
223        };
224        for binding in &mut function.lexical_values {
225            if binding.value().is_some_and(Expr::is_wasm_runtime) {
226                binding.clear_value();
227            }
228        }
229    }
230
231    #[must_use]
232    pub fn with_value(mut self, value: Expr) -> Self {
233        self.value.get_or_insert_default().value = Some(value);
234        self
235    }
236
237    #[must_use]
238    pub fn name(&self) -> &str {
239        &self.name
240    }
241
242    /// The kind of the function cell, `Variable` for a name without one.
243    #[must_use]
244    pub fn kind(&self) -> SymbolKind {
245        self.function
246            .as_ref()
247            .map_or(SymbolKind::Variable, |function| function.kind)
248    }
249
250    #[must_use]
251    pub fn value(&self) -> Option<&Expr> {
252        self.value.as_ref()?.value.as_ref()
253    }
254
255    pub fn set_value(&mut self, value: Expr) {
256        let cell = self.value.get_or_insert_default();
257        cell.value = Some(value);
258        cell.expansion_value = None;
259    }
260
261    pub(crate) fn clear_value(&mut self) {
262        if let Some(cell) = self.value.as_mut() {
263            cell.value = None;
264            cell.expansion_value = None;
265        }
266    }
267
268    #[must_use]
269    pub fn expansion_value(&self) -> Option<&Expr> {
270        self.value.as_ref()?.expansion_value.as_ref()
271    }
272
273    pub fn set_expansion_value(&mut self, value: Expr) {
274        self.value.get_or_insert_default().expansion_value = Some(value);
275    }
276
277    pub(crate) fn clear_expansion_value(&mut self) {
278        if let Some(cell) = self.value.as_mut() {
279            cell.expansion_value = None;
280        }
281    }
282
283    /// Gives the name a function cell holding `func`, of kind `Function`
284    /// unless it already has one.
285    #[must_use]
286    pub fn with_function(mut self, func: Expr) -> Self {
287        self.function
288            .get_or_insert_with(|| Function::new(SymbolKind::Function))
289            .lambda = Some(func);
290        self
291    }
292
293    #[must_use]
294    pub fn function(&self) -> Option<&Expr> {
295        self.function.as_ref()?.lambda.as_ref()
296    }
297
298    /// Marks this function as bound by a LABELS form.
299    #[must_use]
300    pub fn local_function(mut self) -> Self {
301        if let Some(function) = self.function.as_mut() {
302            function.local = true;
303        }
304        self
305    }
306
307    /// Keeps the binding identity of the variable this one re-materialises.
308    #[must_use]
309    pub fn with_definition(mut self, id: u32) -> Self {
310        self.value.get_or_insert_default().definition = id;
311        self
312    }
313
314    /// Gives the variable the home its stores record into.
315    #[must_use]
316    pub(crate) fn with_home(mut self, home: Option<HomeKey>) -> Self {
317        self.value.get_or_insert_default().home = home;
318        self
319    }
320
321    /// The home of the binder this variable is, when it has one.
322    #[must_use]
323    pub(crate) fn home(&self) -> Option<&HomeKey> {
324        self.value.as_ref()?.home.as_ref()
325    }
326
327    /// The id of the variable binding, 0 without one.
328    #[must_use]
329    pub fn value_definition(&self) -> u32 {
330        self.value.as_ref().map_or(0, |cell| cell.definition)
331    }
332
333    /// The id of the function binding, 0 without one.
334    #[must_use]
335    pub fn function_definition(&self) -> u32 {
336        self.function.as_ref().map_or(0, |cell| cell.definition)
337    }
338
339    /// Whether either cell carries the binding id `id`.
340    pub(super) fn has_definition(&self, id: u32) -> bool {
341        self.value_definition() == id || self.function_definition() == id
342    }
343
344    #[must_use]
345    pub fn with_doc(mut self, doc: impl Into<String>) -> Self {
346        self.doc = Some(doc.into());
347        self
348    }
349
350    #[must_use]
351    pub fn doc(&self) -> Option<&str> {
352        self.doc.as_deref()
353    }
354
355    pub fn set_doc(&mut self, doc: impl Into<String>) {
356        self.doc = Some(doc.into());
357    }
358
359    #[must_use]
360    pub fn get_property(&self, key: &str) -> Option<&Expr> {
361        self.properties.get(key)
362    }
363
364    pub fn set_property(&mut self, key: impl Into<String>, value: Expr) {
365        self.properties.insert(key.into(), value);
366    }
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}