nomiscript/runtime/symbol/table.rs
1use std::collections::{HashMap, HashSet};
2use std::sync::Arc;
3use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
4
5use crate::ast::{Expr, StructId};
6use crate::compiler::budget::SharedBudget;
7use crate::error::Result;
8
9use super::entry::{Symbol, Variable};
10use super::regions::ExitRegion;
11use super::structs::StructLayout;
12
13#[derive(Debug, Clone, Default)]
14pub struct SymbolTable {
15 pub(super) symbols: HashMap<String, Symbol>,
16 pub(super) structs: super::structs::StructRegistry,
17 /// The struct instances earlier units left (see [`super::instances`]).
18 pub(super) instances: super::instances::InstanceHeap,
19 /// Registered nomiscript tests, in declaration order. Populated
20 /// by `DEFTEST`, drained by `RUN-TESTS`. Each entry is
21 /// `(name, body)` where `body` is the test's wrapped (PROGN ...)
22 /// form. Lives on the table so each compiler/evaluator instance
23 /// gets its own isolated registry — no global state.
24 pub(super) tests: Vec<(String, Expr)>,
25 /// Per-native-fn compile-time reference counter. Bumped each time
26 /// the compiler emits a `call $<host-fn-idx>` for a registered
27 /// `HostFnSpec`. Read by `(coverage-dump)` to certify the test
28 /// surface reaches every native. Compile-time count (not runtime
29 /// hits) — sufficient for the parity contract "every native has
30 /// at least one test that compiles against it"; runtime hit
31 /// counts via a wasm-global counter array land in a follow-up.
32 pub(super) native_coverage: HashMap<String, u32>,
33 /// Upper-cased names of the registered host fns, which no program may
34 /// redefine or rebind.
35 pub(super) host_names: HashSet<String>,
36 /// Globals declared by DEFVAR / DEFPARAMETER (and built-in constants): a
37 /// binding of one of these names is dynamic, so a callee sees it.
38 pub(super) special_names: HashSet<String>,
39 /// Globals a `SETF` of an undefined name created and no DEFVAR has
40 /// declared special since: a binder of one is lexical.
41 pub(super) created_globals: HashSet<String>,
42 /// The manifest of the unit that last compiled, until a host takes it
43 /// (see [`super::definitions`]).
44 pub(super) unit_slots: Vec<super::definitions::UnitSlot>,
45 /// The source of each closure that unit created, by site.
46 pub(super) unit_closures: Vec<super::closures::ClosureSource>,
47 /// The symbols that unit wrote, as they stood before it.
48 pub(super) unit_pre: std::collections::BTreeMap<String, super::definitions::Written>,
49 /// Every definition form of that unit, by slot, in text order.
50 pub(super) unit_versions: std::collections::BTreeMap<
51 (String, super::definitions::Slot),
52 Vec<super::definitions::Version>,
53 >,
54 /// Names of defuns currently being inlined on the eval path, in entry
55 /// order. The eval-side `call_lambda` walks a defun body inline for
56 /// constant folding; a recursive defun whose recursion doesn't fold to a
57 /// base case (e.g. a runtime-arg call) would otherwise recurse the
58 /// compiler's native stack forever. A name already on this stack signals
59 /// re-entry, so the call site short-circuits to a runtime placeholder
60 /// (handing the real lowering to the codegen monomorph path) rather than
61 /// inlining again. Threaded on the table because the eval path only ever
62 /// carries `&mut SymbolTable`.
63 pub(super) inline_stack: Vec<String>,
64 /// Result `WasmType` of each emitted closure, keyed by `ClosureSigId`'s raw
65 /// id. A closure value carries only `WasmType::Closure(sig)` — the sig's
66 /// param/result types live on the codegen `CompileContext`, invisible to the
67 /// eval surface. The closure-emit sites (which have the context) record the
68 /// result here so the ctx-less eval paths — FOLD's accumulator-type probe,
69 /// MAP/FILTER element typing, binding-local sizing — predict a HOF result
70 /// type that AGREES with what `compile_*_to_stack` emits (which reads the
71 /// real sig). Without it, eval guesses from the seed and drifts from
72 /// codegen, mis-sizing a local (invalid wasm). Carried on the table because
73 /// the eval recursion only ever threads `&mut SymbolTable`.
74 pub(super) closure_results: HashMap<u32, crate::ast::WasmType>,
75 /// Parameter `WasmType`s of each emitted closure, recorded alongside
76 /// [`Self::closure_results`] so FILTER's eval mirror coerces a constant
77 /// list's members to the predicate's parameter exactly as codegen does, and
78 /// a LET-bound lambda's call can tell an argument that does not fit.
79 pub(super) closure_params: HashMap<u32, Vec<crate::ast::WasmType>>,
80 /// Value-position lambda sources keyed by the place their closure value was
81 /// bound to. A closure is emitted with FIXED parameter types, so applying it
82 /// to an argument of another type is a mismatch; a higher-order native or a
83 /// call recovers the source here and compiles it with the actual types
84 /// instead. Carried on the table so the ctx-less eval surface sees the same
85 /// source as codegen; a local place lives and dies with its function body.
86 pub(super) closure_bodies: HashMap<crate::ast::Place, (crate::ast::LambdaParams, Expr)>,
87 /// True while evaluating a macro's PRIVATE expansion body (set on the
88 /// DISPOSABLE clone `expand_macro` evaluates it against, alongside
89 /// [`Self::suspend_runtime_guards`]). A macro body is never itself
90 /// codegen'd — only its OUTPUT (the expansion) is, once spliced back
91 /// in — so the LET/LET* eval-side "promote a setf-mutated constant
92 /// binding to runtime, matching what CODEGEN does for the same form"
93 /// step must skip that promotion here: there is no codegen pass on
94 /// THIS body to agree with, and promoting would block legitimate pure
95 /// compile-time arithmetic a macro uses to build its expansion.
96 pub(super) in_macro_expansion: bool,
97 /// Set when an evaluation on a macro-expansion table produced a runtime
98 /// placeholder; `expand_macro` rejects the expansion then, so no form
99 /// can drop a runtime sub-result unseen. Shared by every clone of the
100 /// expansion table (a fresh cell per [`Self::mark_macro_expansion`]);
101 /// atomic because `SymbolTable` must stay `Send` + `Sync`.
102 pub(super) runtime_value_seen: Arc<AtomicBool>,
103 /// The last function-definition id handed out. Shared by every clone and
104 /// never replaced, so ids stay unique across the clones that share one
105 /// monomorph cache.
106 pub(super) last_definition_id: Arc<AtomicU32>,
107 /// Bumped when DEFUN or DEFMACRO redefines an existing name, so a
108 /// monomorph emitted against the old environment misses. Shared by every
109 /// clone for the same reason as [`Self::last_definition_id`].
110 pub(super) redefinition_epoch: Arc<AtomicU32>,
111 /// Runtime-branch nesting depth: raised while compiling code that runs
112 /// only when a runtime test selects it (an IF/COND/HANDLER-CASE arm, an
113 /// AND/OR continuation). Non-zero means a compile-time-only definition or
114 /// SETF must be refused. Not a recursion ceiling: arms enter it via
115 /// [`Self::enter_runtime_branch`] without charging
116 /// [`Self::shared_recursion_depth`]; only the natively recursive
117 /// hand-offs (AND/OR, effect-position COND) also charge that budget.
118 pub(super) runtime_guard_depth: usize,
119 /// Current SHARED compile-time recursion depth — THE recursion
120 /// ceiling for every mechanism that recurses the compiler's own native
121 /// stack (macro expansion, eval-time inlining, codegen-path inlining,
122 /// and the AND/OR/COND runtime-guard hand-off). Calibrated under a
123 /// 2 MiB stack against a MIXED nesting of all of them together (the
124 /// combination no single mechanism's own frame cost alone would
125 /// predict), so a lower PER-MECHANISM ceiling would only ever be
126 /// dominated by this one — each `enter_*` below bumps only this
127 /// counter, not a separate one of its own.
128 pub(super) shared_recursion_depth: usize,
129 /// Output nesting of each open macro expansion, outermost first: the
130 /// spliced expansions compose into one tree as deep as their sum.
131 pub(super) expansion_depths: Vec<usize>,
132 /// One monotonic compile-time work budget (ADR-0034 / plan 0011 Phase
133 /// 0), shared across every clone this table makes for a classification
134 /// probe or a macro's private expansion environment. A discarded probe's
135 /// or recompile pass's charges stay, and so do those of a unit's earlier
136 /// attempts. Reset once per unit by [`Self::reset_budget`].
137 pub(super) budget: SharedBudget,
138 /// The globals the current compilation unit stores to (0014 Stage 2,
139 /// §Stores to globals): each is a runtime cell from its definition on,
140 /// never a constant a fold may read.
141 pub(super) stored_globals: HashSet<String>,
142 /// Set on the copy [`Self::probe_at_init`] makes, so its trial runs no trial.
143 pub(super) in_init_trial: bool,
144 /// The homes the current attempt at the unit allocated and what its
145 /// stores write into them (see [`super::homes`]); shared by every clone.
146 pub(super) homes: Arc<std::sync::Mutex<super::homes::HomeBook>>,
147 /// The globals a host read back as values no constant holds, with the
148 /// type of each (see [`super::carry`]).
149 pub(super) lost_homes: std::collections::BTreeMap<String, String>,
150 /// The DEFVAR / DEFPARAMETER names of the current compilation unit.
151 pub(super) unit_specials: HashSet<String>,
152 /// The unit's specials some LET / LET* binds: each lives in a mutable
153 /// wasm global its binders save and restore.
154 pub(super) dynamic_specials: HashSet<String>,
155 /// Depth of bodies that run zero or more times (a runtime loop, a segment
156 /// a GO skips): a definition there is refused (ADR-0034 decision 1).
157 pub(super) skippable_depth: usize,
158 /// The BLOCK, TAGBODY or HANDLER-CASE forms whose caught exit may skip
159 /// the forms being compiled, outermost first.
160 pub(super) exit_regions: Vec<ExitRegion>,
161 /// The identity of the function (DEFUN, LAMBDA, LABELS) whose body this
162 /// table is compiled or evaluated against; every clone of it inherits it.
163 pub(super) function_owner: Option<u64>,
164 /// Open scope frames (0014 Stage 2, ISS-039): each records the cell a
165 /// scoped definition shadowed, restored when the frame closes. A binder
166 /// shadows without copying the table, so a definition its body makes
167 /// outlives the frame.
168 pub(super) scopes: Vec<Vec<(String, super::scope::Shadowed)>>,
169 /// The names bound inside a macro's private expansion environment (its
170 /// parameters, its own LET variables): the only places a macro body may
171 /// store to (ADR-0034:233, an expansion makes no commits).
172 pub(super) macro_locals: std::collections::HashSet<String>,
173 /// The global of a special that a lexical binding currently shadows, so a
174 /// callee defined outside that binding gets the global back.
175 pub(super) shadowed_globals: HashMap<String, Variable>,
176 /// The eval surface's open BLOCK frames, innermost last (see
177 /// [`super::eval_blocks`]); every path leaves them balanced.
178 pub(super) eval_blocks: Vec<super::eval_blocks::EvalBlock>,
179 /// The loops whose implicit NIL block is open, innermost last: the loop
180 /// form a NIL block wraps is not wrapped again.
181 pub(super) loop_blocks: Vec<crate::ast::Expr>,
182 /// The work units one iteration of the enclosing forced unroll may spend
183 /// on loops nested in it; `None` outside any.
184 pub(super) unroll_share: Option<u64>,
185 /// Set while the eval walk is in dead code (see
186 /// [`Self::is_dead_code`]).
187 pub(super) dead_code: bool,
188}
189
190/// Hard ceiling on the SHARED compile-time recursion budget (see
191/// [`SymbolTable::shared_recursion_depth`]). THE recursion ceiling for
192/// macro expansion, eval-time and codegen-path inlining, and the AND/OR/
193/// COND runtime-guard hand-off — compilation is not guaranteed a large
194/// native stack, and each of these mechanisms' own native-stack cost per
195/// level is high enough that `24` levels, mixed in any combination, stays
196/// comfortably within a default ~2 MiB thread while far exceeding any
197/// legitimate script's nesting.
198pub const MAX_SHARED_RECURSION_DEPTH: usize = 24;
199
200const HIDDEN_MARK: &str = " CAPTURE ";
201
202impl SymbolTable {
203 #[must_use]
204 pub fn new() -> Self {
205 Self::default()
206 }
207
208 /// Charges `units` against this table's shared compile-time work
209 /// budget (see [`Self::budget`]), erroring once
210 /// [`crate::compiler::budget::MAX_ELAB_WORK`] is crossed.
211 pub(crate) fn charge_work(&self, units: u64) -> Result<()> {
212 self.budget.charge(units)
213 }
214
215 /// The measurement counters of the current compilation (plan 0014
216 /// Stage 0): folds performed and macro bodies that read a global. Shared
217 /// by every clone, like the work budget.
218 pub(crate) fn measurements(&self) -> &SharedBudget {
219 &self.budget
220 }
221
222 /// A clone for the store scan, which expands the macros the compilation
223 /// expands again: its work counts against its own ceiling.
224 #[must_use]
225 pub(crate) fn scan_scratch(&self) -> Self {
226 Self {
227 budget: self.budget.for_scan(),
228 ..self.clone()
229 }
230 }
231
232 /// Starts a fresh work budget for a new compilation unit. Every clone
233 /// this table makes afterwards shares the fresh counter; clones made
234 /// before this call keep charging the old one, so this must run before
235 /// any compilation work begins.
236 pub(crate) fn reset_budget(&mut self) {
237 self.budget = SharedBudget::new();
238 }
239
240 /// Starts the measurement counters of a new attempt at the unit, whose
241 /// work stays on the unit's budget.
242 pub(crate) fn reset_measurements(&mut self) {
243 self.budget = self.budget.with_fresh_measurements();
244 }
245
246 /// Marks this table as evaluating a macro's PRIVATE expansion body
247 /// (see [`Self::in_macro_expansion`]) — called alongside
248 /// [`Self::suspend_runtime_guards`] on the SAME disposable clone.
249 pub(crate) fn mark_macro_expansion(&mut self) {
250 self.in_macro_expansion = true;
251 self.runtime_value_seen = Arc::new(AtomicBool::new(false));
252 }
253
254 /// A clone for PREDICTION probes (type, pair element): it has its own
255 /// throwaway runtime-effect cell, so a probe's note never reaches this
256 /// table. A real evaluation keeps `clone()`, which shares the cell.
257 #[must_use]
258 pub(crate) fn speculative_clone(&self) -> Self {
259 Self {
260 runtime_value_seen: Arc::new(AtomicBool::new(false)),
261 ..self.clone()
262 }
263 }
264
265 /// Records a runtime placeholder produced while evaluating a macro body.
266 pub(crate) fn note_runtime_value(&mut self) {
267 if self.in_macro_expansion {
268 self.runtime_value_seen.store(true, Ordering::Relaxed);
269 }
270 }
271
272 /// Whether a runtime placeholder was produced during this macro body.
273 #[must_use]
274 pub(crate) fn saw_runtime_value(&self) -> bool {
275 self.runtime_value_seen.load(Ordering::Relaxed)
276 }
277
278 /// Whether this table is currently evaluating a macro's private
279 /// expansion body (see [`Self::in_macro_expansion`]).
280 #[must_use]
281 pub(crate) fn is_macro_expansion(&self) -> bool {
282 self.in_macro_expansion
283 }
284
285 /// Records the result `WasmType` for a closure signature id (see
286 /// `Self::closure_results`). Called by the closure-emit sites, which hold
287 /// the `CompileContext` and so know the sig's true result type.
288 pub fn record_closure_result(
289 &mut self,
290 sig: crate::ast::ClosureSigId,
291 result: crate::ast::WasmType,
292 ) {
293 self.closure_results.insert(sig.0, result);
294 }
295
296 /// The recorded result `WasmType` for a closure signature id, or `None` if
297 /// the closure wasn't emitted through a recording site (e.g. a closure
298 /// reaching the eval surface from a path that doesn't record).
299 pub fn closure_result(&self, sig: crate::ast::ClosureSigId) -> Option<crate::ast::WasmType> {
300 self.closure_results.get(&sig.0).copied()
301 }
302
303 #[must_use]
304 pub fn with_builtins() -> Self {
305 let mut table = Self::without_prelude();
306 // Prelude loads last so its DEFUNs resolve the builtins + accessors.
307 if let Err(e) = table.load_prelude() {
308 tracing::error!("universal prelude failed to load: {e}");
309 }
310 table
311 }
312
313 #[must_use]
314 pub fn with_builtins_for_wasm() -> Self {
315 Self::with_builtins()
316 }
317
318 /// A variable name no program can spell or collide with, unique across
319 /// every clone of this table, for the parameter `param` of `factory`.
320 #[must_use]
321 pub fn hidden_name(&self, factory: &str, param: &str) -> String {
322 format!(
323 "{param}{HIDDEN_MARK}{} {factory}",
324 self.next_definition_id()
325 )
326 }
327
328 /// The `(factory, parameter)` a [`Self::hidden_name`] was made for.
329 #[must_use]
330 pub fn hidden_origin(name: &str) -> Option<(&str, &str)> {
331 let (param, rest) = name.split_once(HIDDEN_MARK)?;
332 let (_, factory) = rest.split_once(' ')?;
333 Some((factory, param))
334 }
335
336 #[must_use]
337 pub fn is_hidden_name(name: &str) -> bool {
338 Self::hidden_origin(name).is_some()
339 }
340
341 pub(super) fn next_definition_id(&self) -> u32 {
342 bump(&self.last_definition_id).saturating_add(1)
343 }
344
345 /// Records that DEFMACRO is about to replace an existing macro or function.
346 pub(crate) fn note_redefinition(&self) {
347 bump(&self.redefinition_epoch);
348 }
349
350 #[must_use]
351 pub(crate) fn redefinition_epoch(&self) -> u32 {
352 self.redefinition_epoch.load(Ordering::Relaxed)
353 }
354
355 #[must_use]
356 pub fn lookup(&self, name: &str) -> Option<&Symbol> {
357 self.symbols.get(name)
358 }
359
360 /// Looks up a (possibly namespaced) name via its canonical key (ADR-0029).
361 /// Resolution is strict and lexical: a qualified `(Some(ns), name)` looks
362 /// up only `NS:NAME`, an unqualified `(None, name)` looks up only `NAME` —
363 /// there is no cross-namespace fallback and no ambient "current namespace".
364 /// Most call sites pass the already-canonical `Expr::Symbol` string straight
365 /// to [`Self::lookup`]; this helper is for callers that hold the split parts.
366 #[must_use]
367 pub fn lookup_qualified(&self, namespace: Option<&str>, name: &str) -> Option<&Symbol> {
368 self.lookup(&crate::ast::canonical_symbol(namespace, name))
369 }
370
371 pub fn lookup_mut(&mut self, name: &str) -> Option<&mut Symbol> {
372 self.symbols.get_mut(name)
373 }
374
375 pub fn remove(&mut self, name: &str) -> Option<Symbol> {
376 self.symbols.remove(name)
377 }
378
379 #[must_use]
380 pub fn contains(&self, name: &str) -> bool {
381 self.symbols.contains_key(name)
382 }
383
384 pub fn iter(&self) -> impl Iterator<Item = (&String, &Symbol)> {
385 self.symbols.iter()
386 }
387
388 pub fn define_struct(
389 &mut self,
390 name: impl Into<String>,
391 fields: Vec<String>,
392 ) -> Result<StructId> {
393 self.structs.define(name.into(), fields)
394 }
395
396 #[must_use]
397 pub(crate) fn struct_layout(&self, id: StructId) -> Option<&StructLayout> {
398 self.structs.layout(id)
399 }
400}
401
402/// Saturating increment; returns the value before it.
403fn bump(counter: &AtomicU32) -> u32 {
404 match counter.try_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
405 Some(value.saturating_add(1))
406 }) {
407 Ok(previous) | Err(previous) => previous,
408 }
409}