Lines
96.61 %
Functions
95.16 %
Branches
100 %
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use crate::ast::{Expr, StructId};
use crate::compiler::budget::SharedBudget;
use crate::error::Result;
use super::entry::{Symbol, Variable};
use super::regions::ExitRegion;
use super::structs::StructLayout;
#[derive(Debug, Clone, Default)]
pub struct SymbolTable {
pub(super) symbols: HashMap<String, Symbol>,
pub(super) structs: super::structs::StructRegistry,
/// The struct instances earlier units left (see [`super::instances`]).
pub(super) instances: super::instances::InstanceHeap,
/// Registered nomiscript tests, in declaration order. Populated
/// by `DEFTEST`, drained by `RUN-TESTS`. Each entry is
/// `(name, body)` where `body` is the test's wrapped (PROGN ...)
/// form. Lives on the table so each compiler/evaluator instance
/// gets its own isolated registry — no global state.
pub(super) tests: Vec<(String, Expr)>,
/// Per-native-fn compile-time reference counter. Bumped each time
/// the compiler emits a `call $<host-fn-idx>` for a registered
/// `HostFnSpec`. Read by `(coverage-dump)` to certify the test
/// surface reaches every native. Compile-time count (not runtime
/// hits) — sufficient for the parity contract "every native has
/// at least one test that compiles against it"; runtime hit
/// counts via a wasm-global counter array land in a follow-up.
pub(super) native_coverage: HashMap<String, u32>,
/// Upper-cased names of the registered host fns, which no program may
/// redefine or rebind.
pub(super) host_names: HashSet<String>,
/// Globals declared by DEFVAR / DEFPARAMETER (and built-in constants): a
/// binding of one of these names is dynamic, so a callee sees it.
pub(super) special_names: HashSet<String>,
/// Globals a `SETF` of an undefined name created and no DEFVAR has
/// declared special since: a binder of one is lexical.
pub(super) created_globals: HashSet<String>,
/// The manifest of the unit that last compiled, until a host takes it
/// (see [`super::definitions`]).
pub(super) unit_slots: Vec<super::definitions::UnitSlot>,
/// The source of each closure that unit created, by site.
pub(super) unit_closures: Vec<super::closures::ClosureSource>,
/// The symbols that unit wrote, as they stood before it.
pub(super) unit_pre: std::collections::BTreeMap<String, super::definitions::Written>,
/// Every definition form of that unit, by slot, in text order.
pub(super) unit_versions: std::collections::BTreeMap<
(String, super::definitions::Slot),
Vec<super::definitions::Version>,
>,
/// Names of defuns currently being inlined on the eval path, in entry
/// order. The eval-side `call_lambda` walks a defun body inline for
/// constant folding; a recursive defun whose recursion doesn't fold to a
/// base case (e.g. a runtime-arg call) would otherwise recurse the
/// compiler's native stack forever. A name already on this stack signals
/// re-entry, so the call site short-circuits to a runtime placeholder
/// (handing the real lowering to the codegen monomorph path) rather than
/// inlining again. Threaded on the table because the eval path only ever
/// carries `&mut SymbolTable`.
pub(super) inline_stack: Vec<String>,
/// Result `WasmType` of each emitted closure, keyed by `ClosureSigId`'s raw
/// id. A closure value carries only `WasmType::Closure(sig)` — the sig's
/// param/result types live on the codegen `CompileContext`, invisible to the
/// eval surface. The closure-emit sites (which have the context) record the
/// result here so the ctx-less eval paths — FOLD's accumulator-type probe,
/// MAP/FILTER element typing, binding-local sizing — predict a HOF result
/// type that AGREES with what `compile_*_to_stack` emits (which reads the
/// real sig). Without it, eval guesses from the seed and drifts from
/// codegen, mis-sizing a local (invalid wasm). Carried on the table because
/// the eval recursion only ever threads `&mut SymbolTable`.
pub(super) closure_results: HashMap<u32, crate::ast::WasmType>,
/// Parameter `WasmType`s of each emitted closure, recorded alongside
/// [`Self::closure_results`] so FILTER's eval mirror coerces a constant
/// list's members to the predicate's parameter exactly as codegen does, and
/// a LET-bound lambda's call can tell an argument that does not fit.
pub(super) closure_params: HashMap<u32, Vec<crate::ast::WasmType>>,
/// Value-position lambda sources keyed by the place their closure value was
/// bound to. A closure is emitted with FIXED parameter types, so applying it
/// to an argument of another type is a mismatch; a higher-order native or a
/// call recovers the source here and compiles it with the actual types
/// instead. Carried on the table so the ctx-less eval surface sees the same
/// source as codegen; a local place lives and dies with its function body.
pub(super) closure_bodies: HashMap<crate::ast::Place, (crate::ast::LambdaParams, Expr)>,
/// True while evaluating a macro's PRIVATE expansion body (set on the
/// DISPOSABLE clone `expand_macro` evaluates it against, alongside
/// [`Self::suspend_runtime_guards`]). A macro body is never itself
/// codegen'd — only its OUTPUT (the expansion) is, once spliced back
/// in — so the LET/LET* eval-side "promote a setf-mutated constant
/// binding to runtime, matching what CODEGEN does for the same form"
/// step must skip that promotion here: there is no codegen pass on
/// THIS body to agree with, and promoting would block legitimate pure
/// compile-time arithmetic a macro uses to build its expansion.
pub(super) in_macro_expansion: bool,
/// Set when an evaluation on a macro-expansion table produced a runtime
/// placeholder; `expand_macro` rejects the expansion then, so no form
/// can drop a runtime sub-result unseen. Shared by every clone of the
/// expansion table (a fresh cell per [`Self::mark_macro_expansion`]);
/// atomic because `SymbolTable` must stay `Send` + `Sync`.
pub(super) runtime_value_seen: Arc<AtomicBool>,
/// The last function-definition id handed out. Shared by every clone and
/// never replaced, so ids stay unique across the clones that share one
/// monomorph cache.
pub(super) last_definition_id: Arc<AtomicU32>,
/// Bumped when DEFUN or DEFMACRO redefines an existing name, so a
/// monomorph emitted against the old environment misses. Shared by every
/// clone for the same reason as [`Self::last_definition_id`].
pub(super) redefinition_epoch: Arc<AtomicU32>,
/// Runtime-branch nesting depth: raised while compiling code that runs
/// only when a runtime test selects it (an IF/COND/HANDLER-CASE arm, an
/// AND/OR continuation). Non-zero means a compile-time-only definition or
/// SETF must be refused. Not a recursion ceiling: arms enter it via
/// [`Self::enter_runtime_branch`] without charging
/// [`Self::shared_recursion_depth`]; only the natively recursive
/// hand-offs (AND/OR, effect-position COND) also charge that budget.
pub(super) runtime_guard_depth: usize,
/// Current SHARED compile-time recursion depth — THE recursion
/// ceiling for every mechanism that recurses the compiler's own native
/// stack (macro expansion, eval-time inlining, codegen-path inlining,
/// and the AND/OR/COND runtime-guard hand-off). Calibrated under a
/// 2 MiB stack against a MIXED nesting of all of them together (the
/// combination no single mechanism's own frame cost alone would
/// predict), so a lower PER-MECHANISM ceiling would only ever be
/// dominated by this one — each `enter_*` below bumps only this
/// counter, not a separate one of its own.
pub(super) shared_recursion_depth: usize,
/// Output nesting of each open macro expansion, outermost first: the
/// spliced expansions compose into one tree as deep as their sum.
pub(super) expansion_depths: Vec<usize>,
/// One monotonic compile-time work budget (ADR-0034 / plan 0011 Phase
/// 0), shared across every clone this table makes for a classification
/// probe or a macro's private expansion environment. A discarded probe's
/// or recompile pass's charges stay, and so do those of a unit's earlier
/// attempts. Reset once per unit by [`Self::reset_budget`].
pub(super) budget: SharedBudget,
/// The globals the current compilation unit stores to (0014 Stage 2,
/// §Stores to globals): each is a runtime cell from its definition on,
/// never a constant a fold may read.
pub(super) stored_globals: HashSet<String>,
/// Set on the copy [`Self::probe_at_init`] makes, so its trial runs no trial.
pub(super) in_init_trial: bool,
/// The homes the current attempt at the unit allocated and what its
/// stores write into them (see [`super::homes`]); shared by every clone.
pub(super) homes: Arc<std::sync::Mutex<super::homes::HomeBook>>,
/// The globals a host read back as values no constant holds, with the
/// type of each (see [`super::carry`]).
pub(super) lost_homes: std::collections::BTreeMap<String, String>,
/// The DEFVAR / DEFPARAMETER names of the current compilation unit.
pub(super) unit_specials: HashSet<String>,
/// The unit's specials some LET / LET* binds: each lives in a mutable
/// wasm global its binders save and restore.
pub(super) dynamic_specials: HashSet<String>,
/// Depth of bodies that run zero or more times (a runtime loop, a segment
/// a GO skips): a definition there is refused (ADR-0034 decision 1).
pub(super) skippable_depth: usize,
/// The BLOCK, TAGBODY or HANDLER-CASE forms whose caught exit may skip
/// the forms being compiled, outermost first.
pub(super) exit_regions: Vec<ExitRegion>,
/// The identity of the function (DEFUN, LAMBDA, LABELS) whose body this
/// table is compiled or evaluated against; every clone of it inherits it.
pub(super) function_owner: Option<u64>,
/// Open scope frames (0014 Stage 2, ISS-039): each records the cell a
/// scoped definition shadowed, restored when the frame closes. A binder
/// shadows without copying the table, so a definition its body makes
/// outlives the frame.
pub(super) scopes: Vec<Vec<(String, super::scope::Shadowed)>>,
/// The names bound inside a macro's private expansion environment (its
/// parameters, its own LET variables): the only places a macro body may
/// store to (ADR-0034:233, an expansion makes no commits).
pub(super) macro_locals: std::collections::HashSet<String>,
/// The global of a special that a lexical binding currently shadows, so a
/// callee defined outside that binding gets the global back.
pub(super) shadowed_globals: HashMap<String, Variable>,
/// The eval surface's open BLOCK frames, innermost last (see
/// [`super::eval_blocks`]); every path leaves them balanced.
pub(super) eval_blocks: Vec<super::eval_blocks::EvalBlock>,
/// The loops whose implicit NIL block is open, innermost last: the loop
/// form a NIL block wraps is not wrapped again.
pub(super) loop_blocks: Vec<crate::ast::Expr>,
/// The work units one iteration of the enclosing forced unroll may spend
/// on loops nested in it; `None` outside any.
pub(super) unroll_share: Option<u64>,
/// Set while the eval walk is in dead code (see
/// [`Self::is_dead_code`]).
pub(super) dead_code: bool,
}
/// Hard ceiling on the SHARED compile-time recursion budget (see
/// [`SymbolTable::shared_recursion_depth`]). THE recursion ceiling for
/// macro expansion, eval-time and codegen-path inlining, and the AND/OR/
/// COND runtime-guard hand-off — compilation is not guaranteed a large
/// native stack, and each of these mechanisms' own native-stack cost per
/// level is high enough that `24` levels, mixed in any combination, stays
/// comfortably within a default ~2 MiB thread while far exceeding any
/// legitimate script's nesting.
pub const MAX_SHARED_RECURSION_DEPTH: usize = 24;
const HIDDEN_MARK: &str = " CAPTURE ";
impl SymbolTable {
#[must_use]
pub fn new() -> Self {
Self::default()
/// Charges `units` against this table's shared compile-time work
/// budget (see [`Self::budget`]), erroring once
/// [`crate::compiler::budget::MAX_ELAB_WORK`] is crossed.
pub(crate) fn charge_work(&self, units: u64) -> Result<()> {
self.budget.charge(units)
/// The measurement counters of the current compilation (plan 0014
/// Stage 0): folds performed and macro bodies that read a global. Shared
/// by every clone, like the work budget.
pub(crate) fn measurements(&self) -> &SharedBudget {
&self.budget
/// A clone for the store scan, which expands the macros the compilation
/// expands again: its work counts against its own ceiling.
pub(crate) fn scan_scratch(&self) -> Self {
Self {
budget: self.budget.for_scan(),
..self.clone()
/// Starts a fresh work budget for a new compilation unit. Every clone
/// this table makes afterwards shares the fresh counter; clones made
/// before this call keep charging the old one, so this must run before
/// any compilation work begins.
pub(crate) fn reset_budget(&mut self) {
self.budget = SharedBudget::new();
/// Starts the measurement counters of a new attempt at the unit, whose
/// work stays on the unit's budget.
pub(crate) fn reset_measurements(&mut self) {
self.budget = self.budget.with_fresh_measurements();
/// Marks this table as evaluating a macro's PRIVATE expansion body
/// (see [`Self::in_macro_expansion`]) — called alongside
/// [`Self::suspend_runtime_guards`] on the SAME disposable clone.
pub(crate) fn mark_macro_expansion(&mut self) {
self.in_macro_expansion = true;
self.runtime_value_seen = Arc::new(AtomicBool::new(false));
/// A clone for PREDICTION probes (type, pair element): it has its own
/// throwaway runtime-effect cell, so a probe's note never reaches this
/// table. A real evaluation keeps `clone()`, which shares the cell.
pub(crate) fn speculative_clone(&self) -> Self {
runtime_value_seen: Arc::new(AtomicBool::new(false)),
/// Records a runtime placeholder produced while evaluating a macro body.
pub(crate) fn note_runtime_value(&mut self) {
if self.in_macro_expansion {
self.runtime_value_seen.store(true, Ordering::Relaxed);
/// Whether a runtime placeholder was produced during this macro body.
pub(crate) fn saw_runtime_value(&self) -> bool {
self.runtime_value_seen.load(Ordering::Relaxed)
/// Whether this table is currently evaluating a macro's private
/// expansion body (see [`Self::in_macro_expansion`]).
pub(crate) fn is_macro_expansion(&self) -> bool {
self.in_macro_expansion
/// Records the result `WasmType` for a closure signature id (see
/// `Self::closure_results`). Called by the closure-emit sites, which hold
/// the `CompileContext` and so know the sig's true result type.
pub fn record_closure_result(
&mut self,
sig: crate::ast::ClosureSigId,
result: crate::ast::WasmType,
) {
self.closure_results.insert(sig.0, result);
/// The recorded result `WasmType` for a closure signature id, or `None` if
/// the closure wasn't emitted through a recording site (e.g. a closure
/// reaching the eval surface from a path that doesn't record).
pub fn closure_result(&self, sig: crate::ast::ClosureSigId) -> Option<crate::ast::WasmType> {
self.closure_results.get(&sig.0).copied()
pub fn with_builtins() -> Self {
let mut table = Self::without_prelude();
// Prelude loads last so its DEFUNs resolve the builtins + accessors.
if let Err(e) = table.load_prelude() {
tracing::error!("universal prelude failed to load: {e}");
table
pub fn with_builtins_for_wasm() -> Self {
Self::with_builtins()
/// A variable name no program can spell or collide with, unique across
/// every clone of this table, for the parameter `param` of `factory`.
pub fn hidden_name(&self, factory: &str, param: &str) -> String {
format!(
"{param}{HIDDEN_MARK}{} {factory}",
self.next_definition_id()
)
/// The `(factory, parameter)` a [`Self::hidden_name`] was made for.
pub fn hidden_origin(name: &str) -> Option<(&str, &str)> {
let (param, rest) = name.split_once(HIDDEN_MARK)?;
let (_, factory) = rest.split_once(' ')?;
Some((factory, param))
pub fn is_hidden_name(name: &str) -> bool {
Self::hidden_origin(name).is_some()
pub(super) fn next_definition_id(&self) -> u32 {
bump(&self.last_definition_id).saturating_add(1)
/// Records that DEFMACRO is about to replace an existing macro or function.
pub(crate) fn note_redefinition(&self) {
bump(&self.redefinition_epoch);
pub(crate) fn redefinition_epoch(&self) -> u32 {
self.redefinition_epoch.load(Ordering::Relaxed)
pub fn lookup(&self, name: &str) -> Option<&Symbol> {
self.symbols.get(name)
/// Looks up a (possibly namespaced) name via its canonical key (ADR-0029).
/// Resolution is strict and lexical: a qualified `(Some(ns), name)` looks
/// up only `NS:NAME`, an unqualified `(None, name)` looks up only `NAME` —
/// there is no cross-namespace fallback and no ambient "current namespace".
/// Most call sites pass the already-canonical `Expr::Symbol` string straight
/// to [`Self::lookup`]; this helper is for callers that hold the split parts.
pub fn lookup_qualified(&self, namespace: Option<&str>, name: &str) -> Option<&Symbol> {
self.lookup(&crate::ast::canonical_symbol(namespace, name))
pub fn lookup_mut(&mut self, name: &str) -> Option<&mut Symbol> {
self.symbols.get_mut(name)
pub fn remove(&mut self, name: &str) -> Option<Symbol> {
self.symbols.remove(name)
pub fn contains(&self, name: &str) -> bool {
self.symbols.contains_key(name)
pub fn iter(&self) -> impl Iterator<Item = (&String, &Symbol)> {
self.symbols.iter()
pub fn define_struct(
name: impl Into<String>,
fields: Vec<String>,
) -> Result<StructId> {
self.structs.define(name.into(), fields)
pub(crate) fn struct_layout(&self, id: StructId) -> Option<&StructLayout> {
self.structs.layout(id)
/// Saturating increment; returns the value before it.
fn bump(counter: &AtomicU32) -> u32 {
match counter.try_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
Some(value.saturating_add(1))
}) {
Ok(previous) | Err(previous) => previous,