Skip to main content

cljrs_runtime/env/
env.rs

1//! Lexical environment: local frames, global namespace table, and current Env.
2
3use std::collections::{HashMap, HashSet};
4use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
5use std::sync::{Arc, Condvar, Mutex, RwLock};
6
7use crate::env::async_hook::AsyncRuntime;
8
9use crate::env::error::EvalResult;
10use crate::mode::{ExecutionMode, TierState};
11use cljrs_gc::{GcConfig, GcPtr};
12use cljrs_reader::Form;
13use cljrs_value::{CljxFn, Keyword, Namespace, ReferClojureFilter, Value, Var};
14// ── RequireSpec / RequireRefer ─────────────────────────────────────────────────
15
16/// How symbols should be referred into the requiring namespace.
17#[derive(Debug, Clone)]
18pub enum RequireRefer {
19    None,
20    All,
21    Named(Vec<Arc<str>>),
22}
23
24/// A parsed `require` specification.
25#[derive(Debug, Clone)]
26pub struct RequireSpec {
27    pub ns: Arc<str>,
28    /// Present when the namespace symbol carried a `@<hash>` version suffix.
29    pub version: Option<Arc<str>>,
30    pub alias: Option<Arc<str>>,
31    pub refer: RequireRefer,
32}
33
34// ── Frame ─────────────────────────────────────────────────────────────────────
35
36/// One stack frame of local bindings (a single `let*`, `fn`, or `loop*` scope).
37pub struct Frame {
38    pub bindings: Vec<(Arc<str>, Value)>,
39}
40
41impl Default for Frame {
42    fn default() -> Self {
43        Self::new()
44    }
45}
46
47impl Frame {
48    pub fn new() -> Self {
49        Self {
50            bindings: Vec::new(),
51        }
52    }
53
54    pub fn bind(&mut self, name: Arc<str>, val: Value) {
55        // Shadow: push new binding; lookup searches from the end.
56        self.bindings.push((name, val));
57    }
58
59    pub fn lookup(&self, name: &str) -> Option<&Value> {
60        // Search in reverse order so later bindings shadow earlier ones.
61        tracing::trace!(target: "env", "lookup {}", name);
62        for (n, v) in self.bindings.iter().rev() {
63            if n.as_ref() == name {
64                return Some(v);
65            }
66        }
67        None
68    }
69}
70
71// ── GlobalEnv ─────────────────────────────────────────────────────────────────
72
73/// The global mutable store of all namespaces.
74pub struct GlobalEnv {
75    /// Process-unique identity of this runtime instance.
76    ///
77    /// Allocated from a counter, not derived from the `Arc`'s address: an
78    /// address is only unique while the allocation is live, so a dropped
79    /// runtime could hand its key to the next one and let it inherit stale
80    /// cross-defn IR.  Used to scope per-instance registries.
81    id: u64,
82    pub namespaces: RwLock<HashMap<Arc<str>, GcPtr<Namespace>>>,
83    /// Directories to search when resolving namespace names to files.
84    pub source_paths: RwLock<Vec<std::path::PathBuf>>,
85    /// Namespaces that have been fully loaded from a file (idempotent guard).
86    pub loaded: Mutex<std::collections::HashSet<Arc<str>>>,
87    /// Namespaces currently being loaded, mapped to the thread loading them.
88    /// Used to detect true circular requires (same thread) vs concurrent loads
89    /// (different thread — those wait on `loading_done` instead of erroring).
90    pub loading: Mutex<HashMap<Arc<str>, std::thread::ThreadId>>,
91    /// Signalled whenever a namespace finishes loading (or fails).
92    pub loading_done: Condvar,
93    /// Built-in namespace sources embedded in the binary.
94    /// Checked by `load_ns` before falling back to source-path search.
95    pub builtin_sources: RwLock<HashMap<Arc<str>, &'static str>>,
96    /// GC configuration for automatic collection based on memory pressure.
97    pub gc_config: RwLock<Option<Arc<GcConfig>>>,
98    /// How this runtime executes function calls.  Fixed when the runtime is
99    /// built; see [`crate::RuntimeBuilder::execution_mode`].
100    execution_mode: ExecutionMode,
101    /// Which tiers are live right now (see [`TierState`]).  Starts at
102    /// [`TierState::TreeWalk`] — nothing can be lowered until `clojure.core`
103    /// exists — and is raised once to `execution_mode.target_tier()` when the
104    /// builder finishes bootstrapping.
105    tier_state: AtomicU8,
106    /// This runtime's Tier-1 and Tier-2 state: the lowered-IR cache, the JIT
107    /// counters and native-code tables, and the JIT backend attached to this
108    /// runtime.  Instance state: two runtimes in one process never read,
109    /// evict, or invalidate each other's entries, and everything dies with
110    /// the runtime.
111    tiers: Arc<crate::tiered::tiers::Tiers>,
112    /// Optional async runtime registered by `cljrs-async`.
113    /// `None` when the library is not linked; `Some` after `cljrs_async::init`.
114    pub async_rt: RwLock<Option<Arc<dyn AsyncRuntime>>>,
115    /// Cache of values resolved at a specific commit.
116    /// Key format: `"<ns>/<name>@<commit>"` for individual vars,
117    /// or `"<ns>@<commit>"` for whole versioned namespaces.
118    pub version_cache: Mutex<HashMap<Arc<str>, Value>>,
119    /// Parsed `cljrs.edn` config, loaded once at startup.
120    pub deps_config: RwLock<Option<Arc<cljrs_project::config::DepsConfig>>>,
121    /// When true, every versioned-symbol or versioned-namespace resolution must
122    /// carry a valid commit signature (verified natively against `trusted_keys`)
123    /// before the historical code is executed.  Off by default; enabled via
124    /// `--verify-commit-signatures` CLI flag or `:verify-commit-signatures true`
125    /// in `cljrs.edn`.
126    pub verify_commit_signatures: AtomicBool,
127    /// The git backend used by versioned resolution and signature checking, or
128    /// `None` in builds that carry no VCS implementation (wasm, or
129    /// `cljrs-runtime` without its default `deps` feature).  With no provider,
130    /// source files are treated as living outside any repository and versioned
131    /// resolution can only use embedded (AOT) sources.  See [`crate::env::vcs`].
132    vcs: RwLock<Option<Arc<dyn crate::env::vcs::VcsProvider>>>,
133    /// Session-scoped cache of commits that have already passed signature
134    /// verification this run, keyed by `(repo_root, commit_hash)`.
135    pub sig_verify_cache: Mutex<HashSet<(Arc<str>, Arc<str>)>>,
136    /// Pinned source texts fetched from git this session, keyed by
137    /// `"<ns>@<commit>"`.  The AOT compiler embeds these in the produced
138    /// binary so versioned namespaces resolve without git at runtime.
139    pub versioned_sources: RwLock<HashMap<Arc<str>, Arc<str>>>,
140    /// When true (set by AOT harness main), versioned namespaces resolve
141    /// only from embedded builtin sources — never from git.  A versioned
142    /// namespace that was not embedded at compile time fails with a clear
143    /// error instead of attempting a fetch.
144    pub versioned_offline: AtomicBool,
145    /// Provenance of native (Rust-backed) packages recorded at registration:
146    /// namespace → the git commit the package was built from.  Consulted by
147    /// the versioned resolver's native HEAD fallback to detect pinned-commit
148    /// mismatches.
149    pub native_provenance: RwLock<HashMap<Arc<str>, Arc<str>>>,
150    /// When true, a pinned lookup of a native function whose recorded
151    /// provenance does not match the requested commit is an error instead of
152    /// a once-per-pin warning.  CLI: `--enforce-native-versions`; cljrs.edn:
153    /// `:enforce-native-versions true`.
154    pub enforce_native_versions: AtomicBool,
155    /// Pinned-native mismatches already warned about this session
156    /// (key: `"<ns>@<commit>"`), so each pin warns at most once.
157    pub provenance_warned: Mutex<HashSet<Arc<str>>>,
158    /// Optional loader for **pinned native packages** (`:rust/load :dylib`),
159    /// installed by the CLI.  Called by the versioned resolver with
160    /// `(globals, base_ns, commit)` before falling back to the HEAD native
161    /// binding; returns `Ok(true)` when it registered the package's pinned
162    /// implementations into the `"<base_ns>@<commit>"` namespace.
163    #[allow(clippy::type_complexity)]
164    pub pinned_native_loader: RwLock<Option<PinnedNativeLoader>>,
165    /// Optional loader for **native dependencies on the plain `require` path**
166    /// (`:rust/load :dylib`), installed by the CLI.  Called by the
167    /// unversioned namespace loader with `(globals, ns)` when a `require`d
168    /// namespace has no Clojure source on the source path; returns `Ok(true)`
169    /// when it built the dep's crate at the pinned `:git/sha` and registered
170    /// the package's exports into the **unversioned** namespace, so a plain
171    /// `(require '[my.native.lib :as lib])` brings the native code in.
172    #[allow(clippy::type_complexity)]
173    pub native_require_loader: RwLock<Option<NativeRequireLoader>>,
174    /// Loaders for **AOT-compiled namespaces**, installed by the binary
175    /// produced by `cljrs compile`.  Keyed by namespace name.  When a plain
176    /// `require` resolves a namespace that has a registered loader, `load_ns`
177    /// invokes the loader instead of interpreting Clojure source: the loader
178    /// evaluates the namespace's small interpreted preamble (its `ns`/`require`
179    /// and macro definitions) and then calls the namespace's natively compiled
180    /// initializer, so the bulk of the namespace runs as machine code rather
181    /// than being tree-walked at startup.
182    #[allow(clippy::type_complexity)]
183    pub compiled_ns_loaders: RwLock<HashMap<Arc<str>, CompiledNsLoader>>,
184}
185
186/// Loader callback for an AOT-compiled namespace (see
187/// `GlobalEnv::compiled_ns_loaders`).  Given the global env, it loads the
188/// namespace by running its interpreted preamble and its compiled initializer.
189pub type CompiledNsLoader = Arc<dyn Fn(&Arc<GlobalEnv>) -> EvalResult<()> + Send + Sync>;
190
191/// Loader callback for pinned native packages (see
192/// `GlobalEnv::pinned_native_loader`).
193pub type PinnedNativeLoader =
194    Arc<dyn Fn(&Arc<GlobalEnv>, &str, &str) -> EvalResult<bool> + Send + Sync>;
195
196/// Loader callback for native dependencies reached through a plain `require`
197/// (see `GlobalEnv::native_require_loader`).
198pub type NativeRequireLoader = Arc<dyn Fn(&Arc<GlobalEnv>, &str) -> EvalResult<bool> + Send + Sync>;
199
200/// Source of [`GlobalEnv::id`] values.
201static NEXT_GLOBAL_ENV_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
202
203impl std::fmt::Debug for GlobalEnv {
204    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
205        write!(f, "GlobalEnv {{ ... }}")
206    }
207}
208
209impl GlobalEnv {
210    pub(crate) fn var_is_private(var: &Var) -> bool {
211        matches!(
212            var.get_meta(),
213            Some(Value::Map(meta))
214                if matches!(
215                    meta.get(&Value::keyword(Keyword::simple("private"))),
216                    Some(Value::Bool(true))
217                )
218        )
219    }
220
221    /// Create an empty global environment for the given execution mode.
222    ///
223    /// This is the *raw* constructor: no builtins, no bootstrap, no source
224    /// paths.  Use [`crate::Runtime::builder`] unless you are the builder.
225    pub fn new(execution_mode: ExecutionMode) -> Arc<Self> {
226        let id = NEXT_GLOBAL_ENV_ID.fetch_add(1, Ordering::Relaxed);
227        Arc::new(Self {
228            id,
229            namespaces: RwLock::new(HashMap::new()),
230            source_paths: RwLock::new(Vec::new()),
231            loaded: Mutex::new(std::collections::HashSet::new()),
232            loading: Mutex::new(HashMap::new()),
233            loading_done: Condvar::new(),
234            builtin_sources: RwLock::new(HashMap::new()),
235            gc_config: RwLock::new(None),
236            execution_mode,
237            tier_state: AtomicU8::new(TierState::TreeWalk as u8),
238            tiers: crate::tiered::tiers::Tiers::new(id),
239            async_rt: RwLock::new(None),
240            version_cache: Mutex::new(HashMap::new()),
241            deps_config: RwLock::new(None),
242            verify_commit_signatures: AtomicBool::new(false),
243            vcs: RwLock::new(crate::env::vcs::default_provider()),
244            sig_verify_cache: Mutex::new(HashSet::new()),
245            versioned_sources: RwLock::new(HashMap::new()),
246            versioned_offline: AtomicBool::new(false),
247            native_provenance: RwLock::new(HashMap::new()),
248            enforce_native_versions: AtomicBool::new(false),
249            provenance_warned: Mutex::new(HashSet::new()),
250            pinned_native_loader: RwLock::new(None),
251            native_require_loader: RwLock::new(None),
252            compiled_ns_loaders: RwLock::new(HashMap::new()),
253        })
254    }
255
256    /// Replace the source path list.
257    pub fn set_source_paths(&self, paths: Vec<std::path::PathBuf>) {
258        *self.source_paths.write().unwrap() = paths;
259    }
260
261    /// Register an embedded namespace source (called by cljrs-stdlib at startup).
262    pub fn register_builtin_source(&self, ns: &str, src: &'static str) {
263        self.builtin_sources
264            .write()
265            .unwrap()
266            .insert(Arc::from(ns), src);
267    }
268
269    /// Look up an embedded source for a namespace, if one has been registered.
270    pub fn builtin_source(&self, ns: &str) -> Option<&'static str> {
271        self.builtin_sources.read().unwrap().get(ns).copied()
272    }
273
274    /// Register a loader for an AOT-compiled namespace (called by the harness
275    /// `main` of a binary produced by `cljrs compile`).
276    pub fn register_compiled_ns_loader(&self, ns: &str, loader: CompiledNsLoader) {
277        self.compiled_ns_loaders
278            .write()
279            .unwrap()
280            .insert(Arc::from(ns), loader);
281    }
282
283    /// Look up the loader for an AOT-compiled namespace, if one is registered.
284    pub fn compiled_ns_loader(&self, ns: &str) -> Option<CompiledNsLoader> {
285        self.compiled_ns_loaders.read().unwrap().get(ns).cloned()
286    }
287
288    /// Mark a namespace as fully loaded from a file.
289    pub fn mark_loaded(&self, ns: &str) {
290        self.loaded.lock().unwrap().insert(Arc::from(ns));
291    }
292
293    /// True if the namespace has already been loaded from a file.
294    pub fn is_loaded(&self, ns: &str) -> bool {
295        self.loaded.lock().unwrap().contains(ns)
296    }
297
298    /// Set the GC configuration for automatic memory pressure management.
299    pub fn set_gc_config(&self, config: Arc<GcConfig>) {
300        *self.gc_config.write().unwrap() = Some(config);
301    }
302
303    /// Get the GC configuration, if one has been set.
304    pub fn gc_config(&self) -> Option<Arc<GcConfig>> {
305        self.gc_config.read().unwrap().clone()
306    }
307
308    /// Resolve a short alias to a full namespace name in `current_ns`.
309    pub fn resolve_alias(&self, current_ns: &str, alias: &str) -> Option<Arc<str>> {
310        let map = self.namespaces.read().unwrap();
311        let ns = map.get(current_ns)?;
312        let aliases = ns.get().aliases.lock().unwrap();
313        aliases.get(alias).cloned()
314    }
315
316    /// The namespace a qualified symbol's `ns` part names, read from
317    /// `current_ns`'s alias table.
318    ///
319    /// A `:require … :as` alias wins; anything else is taken literally. This
320    /// is the whole rule, and the only place it is written: callers that
321    /// resolve relative to something other than an `Env`'s `current_ns` —
322    /// `resolve`, which is relative to the `*ns*` dynamic var, and versioned
323    /// resolution, which is relative to a defining namespace — name that
324    /// namespace here rather than open-coding the lookup.
325    pub fn resolve_ns_part_in(&self, current_ns: &str, ns_part: &str) -> Arc<str> {
326        self.resolve_alias(current_ns, ns_part)
327            .unwrap_or_else(|| Arc::from(ns_part))
328    }
329
330    /// Resolve an auto-resolved keyword name (the text after `::`) to its
331    /// fully-qualified `ns/name` form.
332    ///
333    /// `::kw` qualifies with `current_ns` directly; `::alias/kw` looks
334    /// `alias` up in `current_ns`'s alias table (populated by `(require
335    /// '[... :as alias])`) and qualifies with the resolved namespace.
336    pub fn resolve_auto_keyword(&self, current_ns: &str, name: &str) -> Result<String, String> {
337        match name.split_once('/') {
338            Some((alias, kw_name)) => match self.resolve_alias(current_ns, alias) {
339                Some(ns) => Ok(format!("{ns}/{kw_name}")),
340                None => Err(format!(
341                    "invalid token: ::{name} (no such namespace alias: {alias})"
342                )),
343            },
344            None => Ok(format!("{current_ns}/{name}")),
345        }
346    }
347
348    /// Return the namespace with this name, creating it if it doesn't exist.
349    pub fn get_or_create_ns(&self, name: &str) -> GcPtr<Namespace> {
350        // Fast path: already exists.
351        {
352            let map = self.namespaces.read().unwrap();
353            if let Some(ns) = map.get(name) {
354                return ns.clone();
355            }
356        }
357        // Slow path: insert.
358        let mut map = self.namespaces.write().unwrap();
359        // Re-check after acquiring write lock.
360        if let Some(ns) = map.get(name) {
361            return ns.clone();
362        }
363        let ns = GcPtr::new(Namespace::new(name));
364        map.insert(Arc::from(name), ns.clone());
365        ns
366    }
367
368    /// Intern `name` with `val` in the given namespace, returning the Var.
369    pub fn intern(&self, ns_name: &str, name: Arc<str>, val: Value) -> GcPtr<Var> {
370        let ns = self.get_or_create_ns(ns_name);
371        let mut interns = ns.get().interns.lock().unwrap();
372        if let Some(var) = interns.get(&name) {
373            // Update existing var.
374            var.get().bind(val);
375            return var.clone();
376        }
377        let var = GcPtr::new(Var::new(ns_name, name.as_ref()));
378        var.get().bind(val);
379        interns.insert(name, var.clone());
380        var
381    }
382
383    /// Look up a Var in the named namespace (interns only).
384    pub fn lookup_var(&self, ns_name: &str, sym_name: &str) -> Option<GcPtr<Var>> {
385        let map = self.namespaces.read().unwrap();
386        let ns = map.get(ns_name)?;
387        let interns = ns.get().interns.lock().unwrap();
388        interns.get(sym_name).cloned()
389    }
390
391    /// Look up a value in `ns_name`: checks interns then refers.
392    /// Routes through the dynamic binding stack so `binding` overrides work.
393    pub fn lookup_in_ns(&self, ns_name: &str, sym_name: &str) -> Option<Value> {
394        let map = self.namespaces.read().unwrap();
395        let ns = map.get(ns_name)?;
396        let ns_ref = ns.get();
397        // Check interns first.
398        {
399            let interns = ns_ref.interns.lock().unwrap();
400            if let Some(var) = interns.get(sym_name) {
401                return crate::env::dynamics::deref_var(var);
402            }
403        }
404        // Then refers.
405        {
406            let refers = ns_ref.refers.lock().unwrap();
407            if let Some(var) = refers.get(sym_name) {
408                return crate::env::dynamics::deref_var(var);
409            }
410        }
411        None
412    }
413
414    /// Look up the raw Var (not its value) in `ns_name`: interns then refers.
415    pub fn lookup_var_in_ns(&self, ns_name: &str, sym_name: &str) -> Option<GcPtr<Var>> {
416        let map = self.namespaces.read().unwrap();
417        let ns = map.get(ns_name)?;
418        let ns_ref = ns.get();
419        {
420            let interns = ns_ref.interns.lock().unwrap();
421            if let Some(var) = interns.get(sym_name) {
422                return Some(var.clone());
423            }
424        }
425        {
426            let refers = ns_ref.refers.lock().unwrap();
427            if let Some(var) = refers.get(sym_name) {
428                return Some(var.clone());
429            }
430        }
431        None
432    }
433
434    /// Copy all interns from `src_ns` into `dst_ns` as refers.
435    ///
436    /// This is the *explicit* refer — `(:require [x :refer :all])` — so it is
437    /// never narrowed by `dst_ns`'s `(:refer-clojure ...)` filter, matching
438    /// `clojure.core/refer`: naming a namespace explicitly re-maps even names
439    /// an earlier `refer-clojure` left out.  The automatic core refer every
440    /// namespace starts with goes through [`GlobalEnv::refer_core`] instead.
441    pub fn refer_all(&self, dst_ns: &str, src_ns: &str) {
442        let map = self.namespaces.read().unwrap();
443        let src = match map.get(src_ns) {
444            Some(ns) => ns.clone(),
445            None => return,
446        };
447        let dst = match map.get(dst_ns) {
448            Some(ns) => ns.clone(),
449            None => return,
450        };
451        let src_interns = src.get().interns.lock().unwrap();
452        let mut dst_refers = dst.get().refers.lock().unwrap();
453        for (name, var) in src_interns.iter() {
454            if Self::var_is_private(var.get()) {
455                continue;
456            }
457            dst_refers.insert(name.clone(), var.clone());
458        }
459    }
460
461    /// Apply the automatic `clojure.core` refer that every namespace starts
462    /// with, narrowed by `dst_ns`'s `(:refer-clojure ...)` filter.
463    pub fn refer_core(&self, dst_ns: &str) {
464        self.refer_core_impl(dst_ns, false);
465    }
466
467    /// `replace`: drop the refers `dst_ns` already inherited from
468    /// `clojure.core` before re-referring, under the same lock — so installing
469    /// a filter after the namespace was pre-referred neither leaves stale
470    /// names behind nor exposes a window where core is only half-referred.
471    fn refer_core_impl(&self, dst_ns: &str, replace: bool) {
472        let map = self.namespaces.read().unwrap();
473        let src = match map.get("clojure.core") {
474            Some(ns) => ns.clone(),
475            None => return,
476        };
477        let dst = match map.get(dst_ns) {
478            Some(ns) => ns.clone(),
479            None => return,
480        };
481        // Lock order is filter → src interns → dst refers throughout.
482        let filter = dst.get().refer_clojure_filter.lock().unwrap();
483        let src_interns = src.get().interns.lock().unwrap();
484        let mut dst_refers = dst.get().refers.lock().unwrap();
485        if replace {
486            dst_refers.retain(|_, var| var.get().namespace.as_ref() != "clojure.core");
487        }
488        match filter.as_ref() {
489            Some(f) => {
490                for (name, var) in src_interns.iter() {
491                    if Self::var_is_private(var.get()) {
492                        continue;
493                    }
494                    if let Some(local) = f.local_name(name) {
495                        dst_refers.insert(local, var.clone());
496                    }
497                }
498            }
499            None => {
500                for (name, var) in src_interns.iter() {
501                    if Self::var_is_private(var.get()) {
502                        continue;
503                    }
504                    dst_refers.insert(name.clone(), var.clone());
505                }
506            }
507        }
508    }
509
510    /// Install `dst_ns`'s `(:refer-clojure ...)` filter (`None` removes any
511    /// previous one) and re-apply the automatic `clojure.core` refer under it.
512    ///
513    /// Refers already inherited from `clojure.core` are dropped first, so a
514    /// filter set after the namespace was pre-referred — the loader refers core
515    /// before it reads the file, and `ns` itself refers core before it reaches
516    /// the clause — still takes effect.
517    pub fn set_refer_clojure_filter(
518        &self,
519        dst_ns: &str,
520        filter: Option<ReferClojureFilter>,
521    ) -> Result<(), String> {
522        if let Some(f) = &filter {
523            self.validate_refer_clojure_filter(f)?;
524        }
525        let dst = self.get_or_create_ns(dst_ns);
526        {
527            let mut slot = dst.get().refer_clojure_filter.lock().unwrap();
528            // Nothing to install and nothing to undo: leave the refers alone.
529            if slot.is_none() && filter.is_none() {
530                return Ok(());
531            }
532            *slot = filter;
533        }
534        self.refer_core_impl(dst_ns, true);
535        Ok(())
536    }
537
538    /// Check a `(:refer-clojure ...)` filter against the names `clojure.core`
539    /// actually publishes, so a typo fails at the `ns` form rather than as an
540    /// unbound symbol somewhere further down the file.
541    ///
542    /// `:only` and `:rename` name specific vars and must resolve; `:exclude` is
543    /// subtractive and stays permissive (excluding a name core does not have is
544    /// harmless, and lets a file stay portable across core versions).  Clojure
545    /// validates `:only` the same way but ignores an unresolvable `:rename`
546    /// key, since it only consults the rename map for names already in its
547    /// to-do list.
548    ///
549    /// Two names landing on the same local name is an error rather than a coin
550    /// flip: with `:rename {inc str}` both `inc` and core's own `str` want the
551    /// name `str`.  Clojure warns and lets whichever one its intern table
552    /// yields last win; picking a winner by hash order here would make the
553    /// choice unstable from run to run.
554    fn validate_refer_clojure_filter(&self, filter: &ReferClojureFilter) -> Result<(), String> {
555        let map = self.namespaces.read().unwrap();
556        let Some(core) = map.get("clojure.core").cloned() else {
557            return Ok(());
558        };
559        drop(map);
560        let interns = core.get().interns.lock().unwrap();
561        // A runtime built without the core bootstrap has nothing to check
562        // against; do not fail every name.
563        if interns.is_empty() {
564            return Ok(());
565        }
566
567        for (opt, names) in [
568            ("only", filter.only.iter().flatten().collect::<Vec<_>>()),
569            ("rename", filter.rename.keys().collect::<Vec<_>>()),
570        ] {
571            let mut unknown: Vec<&str> = names
572                .into_iter()
573                .filter(|n| !interns.contains_key(*n))
574                .map(|n| n.as_ref())
575                .collect();
576            if !unknown.is_empty() {
577                unknown.sort_unstable();
578                return Err(format!(
579                    ":refer-clojure :{opt} names {}, which clojure.core does not define",
580                    unknown.join(", ")
581                ));
582            }
583        }
584
585        // local name → the core name referred under it.
586        let mut taken: HashMap<Arc<str>, Arc<str>> = HashMap::new();
587        let mut conflicts: Vec<(Arc<str>, Arc<str>, Arc<str>)> = Vec::new();
588        for name in interns.keys() {
589            let Some(local) = filter.local_name(name) else {
590                continue;
591            };
592            if let Some(prev) = taken.insert(local.clone(), name.clone()) {
593                let (a, b) = if prev.as_ref() <= name.as_ref() {
594                    (prev, name.clone())
595                } else {
596                    (name.clone(), prev)
597                };
598                conflicts.push((local, a, b));
599            }
600        }
601        if !conflicts.is_empty() {
602            conflicts.sort_unstable();
603            let (local, a, b) = &conflicts[0];
604            return Err(format!(
605                ":refer-clojure would refer both {a} and {b} as {local}; \
606                 rename or exclude one of them"
607            ));
608        }
609        Ok(())
610    }
611
612    /// Names `ns_name` resolves to something other than `clojure.core`'s var
613    /// of the same name — what the IR lowerer must not inline as a builtin.
614    ///
615    /// Three things put a name in here: a `def` in `ns_name` itself, a refer
616    /// of that name from another namespace (or of a *different* core name
617    /// under it, via `:rename`), and a `(:refer-clojure ...)` filter that
618    /// leaves the name out of the automatic core refer.  In each case an
619    /// unqualified call resolves to something that is not `clojure.core/name`
620    /// — or to nothing at all — and the tree-walking interpreter calls that,
621    /// so the lowered call site has to as well (issue #337).
622    ///
623    /// A name absent from the namespace's tables is *not* reported: with no
624    /// evidence to the contrary the lowerer keeps assuming core, which is what
625    /// the automatic core refer makes true for the overwhelming majority of
626    /// call sites (and keeps the lowerer's synthetic names, e.g. `case=`,
627    /// working in namespaces whose refers are not populated yet).
628    pub fn core_shadowed_names(&self, ns_name: &str) -> HashSet<Arc<str>> {
629        let mut out: HashSet<Arc<str>> = HashSet::new();
630        let (ns, core) = {
631            let map = self.namespaces.read().unwrap();
632            match map.get(ns_name) {
633                Some(ns) => (ns.clone(), map.get("clojure.core").cloned()),
634                None => return out,
635            }
636        };
637        let ns_ref = ns.get();
638
639        // A var bound here is core's only if it *is* core's var under its own
640        // name; core's own namespace passes this trivially for its interns.
641        let shadows = |name: &Arc<str>, var: &GcPtr<Var>| {
642            let v = var.get();
643            v.namespace.as_ref() != "clojure.core" || v.name != *name
644        };
645        for table in [&ns_ref.interns, &ns_ref.refers] {
646            let entries = table.lock().unwrap();
647            for (name, var) in entries.iter() {
648                if shadows(name, var) {
649                    out.insert(name.clone());
650                }
651            }
652        }
653
654        // Names the `(:refer-clojure ...)` filter kept out of the automatic
655        // refer: nothing binds them here, so they are not core's either.
656        // Lock order is filter → core interns, as in `refer_core_impl`.
657        let filter = ns_ref.refer_clojure_filter.lock().unwrap();
658        if let (Some(filter), Some(core)) = (filter.as_ref(), core) {
659            let interns = core.get().interns.lock().unwrap();
660            for name in interns.keys() {
661                if filter.local_name(name).as_ref() != Some(name) {
662                    out.insert(name.clone());
663                }
664            }
665        }
666        out
667    }
668
669    /// Copy selected interns from `src_ns` into `dst_ns` as refers.
670    pub fn refer_named(&self, dst_ns: &str, src_ns: &str, names: &[Arc<str>]) {
671        let map = self.namespaces.read().unwrap();
672        let src = match map.get(src_ns) {
673            Some(ns) => ns.clone(),
674            None => return,
675        };
676        let dst = match map.get(dst_ns) {
677            Some(ns) => ns.clone(),
678            None => return,
679        };
680        let src_interns = src.get().interns.lock().unwrap();
681        let mut dst_refers = dst.get().refers.lock().unwrap();
682        for name in names {
683            if let Some(var) = src_interns.get(name) {
684                // Private vars are never referable, whether selected by
685                // `:refer :all` or named explicitly with `:refer [name]`.
686                if Self::var_is_private(var.get()) {
687                    continue;
688                }
689                // Use insert (not or_insert_with) so that an explicit
690                // `require :refer [name]` always overrides a previous refer
691                // (e.g. one inherited from clojure.core via refer-all).
692                // clojure.core.async's `into` intentionally shadows clojure.core/into;
693                // or_insert_with would silently drop the override.
694                dst_refers.insert(name.clone(), var.clone());
695            }
696        }
697    }
698
699    /// Register `alias` → `full_ns` in `current_ns`'s alias table.
700    pub fn add_alias(&self, current_ns: &str, alias: &str, full_ns: &str) {
701        let ns_ptr = self.get_or_create_ns(current_ns);
702        let mut aliases = ns_ptr.get().aliases.lock().unwrap();
703        aliases.insert(Arc::from(alias), Arc::from(full_ns));
704    }
705
706    /// Process-unique identity of this runtime instance.
707    #[inline(always)]
708    pub fn id(&self) -> u64 {
709        self.id
710    }
711
712    /// This runtime's Tier-1/Tier-2 state.
713    #[inline(always)]
714    pub fn tiers(&self) -> &Arc<crate::tiered::tiers::Tiers> {
715        &self.tiers
716    }
717
718    /// This runtime's cache of lowered IR.
719    #[inline(always)]
720    pub fn ir_cache(&self) -> &crate::tiered::ir_cache::IrCache {
721        self.tiers.ir_cache()
722    }
723
724    /// This runtime's JIT counters, profiles, and native-code tables.
725    #[inline(always)]
726    pub fn jit(&self) -> &crate::tiered::jit_state::JitState {
727        self.tiers.jit()
728    }
729
730    /// The JIT compiler attached to this runtime, if any.
731    ///
732    /// `None` when no JIT is linked or installed; callers then keep to the
733    /// interpreter tiers.  Installed by `cljrs_compiler::jit::install`.
734    #[inline(always)]
735    pub fn jit_backend(&self) -> Option<Arc<dyn crate::tiered::backend::JitBackend>> {
736        self.tiers.jit().backend().cloned()
737    }
738
739    // ── Execution mode and tier state ────────────────────────────────────
740
741    /// How this runtime executes function calls.
742    #[inline(always)]
743    pub fn execution_mode(&self) -> ExecutionMode {
744        self.execution_mode
745    }
746
747    /// Which tiers are live right now.
748    #[inline(always)]
749    pub fn tier_state(&self) -> TierState {
750        TierState::from_u8(self.tier_state.load(Ordering::Acquire))
751    }
752
753    /// Raise the live tier state.  Called once by the runtime builder after
754    /// the bootstrap completes; lowering the tier is not supported, so a
755    /// request below the current state is ignored.
756    pub fn set_tier_state(&self, tier: TierState) {
757        let _ = self.tier_state.fetch_max(tier as u8, Ordering::AcqRel);
758    }
759
760    /// True when IR may be lowered, cached, and interpreted.  This is the
761    /// gate the old `compiler_ready` flag served.
762    #[inline(always)]
763    pub fn ir_enabled(&self) -> bool {
764        self.tier_state().ir_enabled()
765    }
766
767    // ── Evaluation entry points ──────────────────────────────────────────
768
769    /// Evaluate `form` in `env`.
770    #[inline(always)]
771    pub fn eval(&self, form: &Form, env: &mut Env) -> EvalResult {
772        crate::interp::eval::eval(form, env)
773    }
774
775    /// Call a Clojure function, taking the path this runtime's
776    /// [`ExecutionMode`] selects.
777    ///
778    /// This is the single function-call dispatch point: tree walk, tier-1 IR,
779    /// and JIT-native execution are all reached from here.
780    #[inline(always)]
781    pub fn call_cljrs_fn(&self, func: &CljxFn, args: &[Value], env: &mut Env) -> EvalResult {
782        match self.execution_mode {
783            ExecutionMode::TreeWalk => crate::interp::apply::call_cljrs_fn(func, args, env),
784            ExecutionMode::Tiered | ExecutionMode::TieredNoJit => {
785                crate::tiered::apply::call_cljrs_fn(func, args, env)
786            }
787            ExecutionMode::NoGcTransaction => crate::env::depth::call_cljrs_fn(func, args, env),
788        }
789    }
790
791    /// Notify the active tier that a new `fn*` was defined.
792    ///
793    /// In a tiered runtime with IR enabled this eagerly lowers the function
794    /// (when eager lowering is on); in every other mode it does nothing.
795    #[inline(always)]
796    pub fn on_fn_defined(&self, f: &CljxFn, env: &mut Env) {
797        if self.execution_mode.is_tiered() && self.ir_enabled() {
798            crate::tiered::ir_interp::eager_lower_fn(f, env);
799        }
800    }
801
802    /// Install an async runtime. Called once by `cljrs_async::init`.
803    /// Subsequent calls are silently ignored (first writer wins).
804    pub fn set_async_runtime(&self, rt: Arc<dyn AsyncRuntime>) {
805        let mut guard = self.async_rt.write().unwrap();
806        if guard.is_none() {
807            *guard = Some(rt);
808        }
809    }
810
811    /// Return the async runtime, if one has been registered.
812    pub fn async_runtime(&self) -> Option<Arc<dyn AsyncRuntime>> {
813        self.async_rt.read().unwrap().clone()
814    }
815
816    /// Return `(source_file, git_repo_root)` for the named namespace, if
817    /// both have been populated by the loader.
818    pub fn get_ns_git_context(&self, ns_name: &str) -> Option<(Arc<str>, Arc<str>)> {
819        let map = self.namespaces.read().unwrap();
820        let ns = map.get(ns_name)?;
821        let ns_ref = ns.get();
822        let file = ns_ref.source_file.lock().unwrap().clone()?;
823        let repo = ns_ref.git_repo_root.lock().unwrap().clone()?;
824        Some((file, repo))
825    }
826
827    /// Store a resolved versioned value in the cache.
828    /// Key: `"<ns>/<name>@<commit>"`.
829    pub fn cache_versioned(&self, ns: &str, name: &str, commit: &str, val: Value) {
830        let key: Arc<str> = Arc::from(format!("{ns}/{name}@{commit}"));
831        self.version_cache.lock().unwrap().insert(key, val);
832    }
833
834    /// Retrieve a previously resolved versioned value, if cached.
835    pub fn get_cached_versioned(&self, ns: &str, name: &str, commit: &str) -> Option<Value> {
836        let key = format!("{ns}/{name}@{commit}");
837        self.version_cache
838            .lock()
839            .unwrap()
840            .get(key.as_str())
841            .cloned()
842    }
843
844    /// Mark namespace `name@commit` as loaded in the standard loaded set.
845    pub fn cache_versioned_ns(&self, ns: &str, commit: &str) {
846        let key: Arc<str> = Arc::from(format!("{ns}@{commit}"));
847        self.version_cache.lock().unwrap().insert(key, Value::Nil);
848    }
849
850    /// Record the source text of a versioned namespace fetched from git.
851    /// Key: `"<ns>@<commit>"`.  Consumed by the AOT compiler for embedding.
852    pub fn record_versioned_source(&self, versioned_ns: &str, src: &str) {
853        self.versioned_sources
854            .write()
855            .unwrap()
856            .insert(Arc::from(versioned_ns), Arc::from(src));
857    }
858
859    /// Snapshot of all versioned sources fetched this session, sorted by key.
860    pub fn versioned_sources_snapshot(&self) -> Vec<(Arc<str>, Arc<str>)> {
861        let map = self.versioned_sources.read().unwrap();
862        let mut entries: Vec<_> = map.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
863        entries.sort_by(|a, b| a.0.cmp(&b.0));
864        entries
865    }
866
867    /// Restrict versioned-namespace resolution to embedded builtin sources
868    /// (no git).  Called by AOT harness binaries, which embed every pinned
869    /// source discovered at compile time.
870    pub fn set_versioned_offline(&self, offline: bool) {
871        self.versioned_offline.store(offline, Ordering::Relaxed);
872    }
873
874    /// True when versioned namespaces may only come from embedded sources.
875    pub fn versioned_offline(&self) -> bool {
876        self.versioned_offline.load(Ordering::Relaxed)
877    }
878
879    /// Record the git commit a native (Rust-backed) package was built from.
880    /// Called at registration time (`Registry::set_provenance` or the
881    /// `register_provenance!` inventory entry in cljrs-interop).
882    pub fn set_native_provenance(&self, ns: &str, commit: &str) {
883        self.native_provenance
884            .write()
885            .unwrap()
886            .insert(Arc::from(ns), Arc::from(commit));
887    }
888
889    /// The recorded provenance commit for a native package's namespace.
890    pub fn native_provenance_for(&self, ns: &str) -> Option<Arc<str>> {
891        self.native_provenance.read().unwrap().get(ns).cloned()
892    }
893
894    /// Make pinned-native provenance mismatches hard errors.
895    pub fn set_enforce_native_versions(&self, enforce: bool) {
896        self.enforce_native_versions
897            .store(enforce, Ordering::Relaxed);
898    }
899
900    /// True when pinned-native provenance mismatches are errors.
901    pub fn enforce_native_versions(&self) -> bool {
902        self.enforce_native_versions.load(Ordering::Relaxed)
903    }
904
905    /// Install the pinned-native package loader (called once by
906    /// `cljrs::native::pinned::install`; first writer wins).
907    pub fn set_pinned_native_loader(&self, loader: PinnedNativeLoader) {
908        let mut guard = self.pinned_native_loader.write().unwrap();
909        if guard.is_none() {
910            *guard = Some(loader);
911        }
912    }
913
914    /// Install the native-dependency `require` loader (called once by
915    /// `cljrs::native::pinned::install`; first writer wins).
916    pub fn set_native_require_loader(&self, loader: NativeRequireLoader) {
917        let mut guard = self.native_require_loader.write().unwrap();
918        if guard.is_none() {
919            *guard = Some(loader);
920        }
921    }
922
923    /// The installed VCS backend, or `None` when this build has none (see
924    /// [`crate::env::vcs`]).  Callers must degrade gracefully: "no provider"
925    /// means "this source file is not in a git repository".
926    pub fn vcs(&self) -> Option<Arc<dyn crate::env::vcs::VcsProvider>> {
927        self.vcs.read().unwrap().clone()
928    }
929
930    /// Replace the VCS backend.  Lets an embedder that built without the
931    /// `deps` feature supply its own git implementation, or a sandboxed host
932    /// remove the default one (`None`) so no versioned resolution can reach
933    /// the filesystem's git history.
934    ///
935    /// Drops every cached signature verdict: those were reached by the
936    /// outgoing provider, against its trust set and its view of the
937    /// repository, and say nothing about what the incoming one would decide
938    /// for the same `(repo, commit)`.  Keeping them would let a permissive
939    /// provider launder an approval for source a later provider serves.
940    pub fn set_vcs_provider(&self, provider: Option<Arc<dyn crate::env::vcs::VcsProvider>>) {
941        // Neither this nor `check_commit_signature` ever holds the `vcs` and
942        // `sig_verify_cache` locks at the same time, and the two reach for
943        // them in opposite orders — keep it that way, or the pair becomes a
944        // lock-order inversion.
945        *self.vcs.write().unwrap() = provider;
946        self.invalidate_signature_cache();
947    }
948
949    /// Forget every cached signature verdict, so the next
950    /// [`check_commit_signature`](Self::check_commit_signature) re-asks the
951    /// current provider.  Called whenever the thing that produced those
952    /// verdicts changes: the provider itself, or its trusted-key set.
953    pub fn invalidate_signature_cache(&self) {
954        self.sig_verify_cache.lock().unwrap().clear();
955    }
956
957    /// If `:verify-commit-signatures` is enabled, verify that `commit` inside
958    /// `repo_root` carries a valid GPG or SSH signature.
959    ///
960    /// Returns `Ok(())` immediately when the feature is off.  On the happy
961    /// path the result is cached per `(repo_root, commit)` so each commit is
962    /// only verified once per session.  On failure returns
963    /// `EvalError::CommitSignatureVerificationFailed`.
964    ///
965    /// If verification is demanded but this build has no VCS provider, the
966    /// check fails: silently accepting an unverifiable commit would defeat the
967    /// flag the user explicitly turned on.
968    pub fn check_commit_signature(&self, repo_root: &str, commit: &str) -> EvalResult<()> {
969        if !self.verify_commit_signatures.load(Ordering::Relaxed) {
970            return Ok(());
971        }
972        let key = (Arc::<str>::from(repo_root), Arc::<str>::from(commit));
973        if self.sig_verify_cache.lock().unwrap().contains(&key) {
974            return Ok(());
975        }
976        let Some(vcs) = self.vcs() else {
977            return Err(crate::env::error::EvalError::Runtime(format!(
978                "commit-signature verification is enabled, but this build has no VCS \
979                 provider to verify commit {commit} with (cljrs-runtime built without \
980                 the `deps` feature)"
981            )));
982        };
983        vcs.verify_commit_signature(std::path::Path::new(repo_root), commit)
984            .map_err(|e| match e {
985                crate::env::vcs::SignatureFailure::Untrusted { commit, reason } => {
986                    crate::env::error::EvalError::CommitSignatureVerificationFailed {
987                        commit,
988                        reason,
989                    }
990                }
991                crate::env::vcs::SignatureFailure::Error(msg) => {
992                    crate::env::error::EvalError::Runtime(msg)
993                }
994            })?;
995        self.sig_verify_cache.lock().unwrap().insert(key);
996        Ok(())
997    }
998
999    /// Build the trusted-signer key set from a parsed `cljrs.edn` config and
1000    /// install it, so subsequent `check_commit_signature` calls verify against
1001    /// it.  Inline keys are parsed directly; `File` entries are read from disk.
1002    /// Returns the number of keys loaded; warns (to stderr) on any key that
1003    /// fails to load rather than aborting.  Returns 0 when this build has no
1004    /// VCS provider, since there is nothing that could consume the keys.
1005    ///
1006    /// Replacing the trust set invalidates the signature cache for the same
1007    /// reason replacing the provider does: a verdict reached under the old
1008    /// keys is not a verdict under the new ones.  (In the normal flow this
1009    /// runs at session start, before anything has been verified.)
1010    pub fn load_trusted_signers(&self, config: &cljrs_project::config::DepsConfig) -> usize {
1011        let Some(vcs) = self.vcs() else {
1012            return 0;
1013        };
1014        let loaded = vcs.load_trusted_signers(&config.trusted_signers);
1015        self.invalidate_signature_cache();
1016        loaded
1017    }
1018}
1019
1020// ── Env ───────────────────────────────────────────────────────────────────────
1021
1022/// The full execution environment: a stack of local frames plus the global env.
1023pub struct Env {
1024    pub frames: Vec<Frame>,
1025    pub current_ns: Arc<str>,
1026    pub globals: Arc<GlobalEnv>,
1027    /// When set, unversioned same-namespace symbol lookups implicitly resolve
1028    /// at this commit hash instead of HEAD.  Set by the versioned resolver when
1029    /// evaluating a function body fetched from git history.
1030    pub versioned_eval_commit: Option<Arc<str>>,
1031    /// True when evaluating the body of an `^:async` function.
1032    /// Set by `cljrs-async`; allows the `await` special form to know whether
1033    /// to yield (async context) or block the OS thread (sync context).
1034    pub is_async: bool,
1035}
1036
1037impl Env {
1038    pub fn new(globals: Arc<GlobalEnv>, ns: &str) -> Self {
1039        Self {
1040            frames: Vec::new(),
1041            current_ns: Arc::from(ns),
1042            globals,
1043            versioned_eval_commit: None,
1044            is_async: false,
1045        }
1046    }
1047
1048    /// The namespace a qualified symbol's `ns` part names, here.
1049    ///
1050    /// `ns_part` may be a `:require … :as` alias or a namespace name; an alias
1051    /// wins, and anything else is taken literally. This is what makes
1052    /// `(m/f x)` and `(my.lib/f x)` mean the same thing after
1053    /// `(:require [my.lib :as m])`.
1054    ///
1055    /// Relative to THIS env's `current_ns`. A caller resolving relative to
1056    /// some other namespace wants [`GlobalEnv::resolve_ns_part_in`], which
1057    /// this delegates to.
1058    pub fn resolve_ns_part(&self, ns_part: &str) -> Arc<str> {
1059        self.globals.resolve_ns_part_in(&self.current_ns, ns_part)
1060    }
1061
1062    /// The namespace a symbol belongs to: [`Self::resolve_ns_part`] when it
1063    /// carries one, and the current namespace when it does not.
1064    pub fn resolve_ns_or_current(&self, ns_part: Option<&str>) -> Arc<str> {
1065        match ns_part {
1066            Some(ns_part) => self.resolve_ns_part(ns_part),
1067            None => self.current_ns.clone(),
1068        }
1069    }
1070
1071    /// Create an Env for evaluating source at a specific commit.
1072    pub fn new_versioned(globals: Arc<GlobalEnv>, ns: &str, commit: &str) -> Self {
1073        Self {
1074            versioned_eval_commit: Some(Arc::from(commit)),
1075            ..Self::new(globals, ns)
1076        }
1077    }
1078
1079    /// Create an Env pre-loaded with a function's closed-over bindings.
1080    pub fn with_closure(globals: Arc<GlobalEnv>, ns: &str, f: &CljxFn) -> Self {
1081        let mut env = Self::new(globals, ns);
1082        if !f.closed_over_names.is_empty() {
1083            env.push_frame();
1084            for (name, val) in f.closed_over_names.iter().zip(f.closed_over_vals.iter()) {
1085                env.bind(name.clone(), val.clone());
1086            }
1087        }
1088        env
1089    }
1090
1091    pub fn push_frame(&mut self) {
1092        self.frames.push(Frame::new());
1093    }
1094
1095    pub fn pop_frame(&mut self) {
1096        self.frames.pop();
1097    }
1098
1099    /// Bind `name` to `val` in the top frame.
1100    pub fn bind(&mut self, name: Arc<str>, val: Value) {
1101        if let Some(frame) = self.frames.last_mut() {
1102            frame.bind(name, val);
1103        }
1104        // If there are no frames, the binding is silently dropped.
1105        // Callers must push a frame first.
1106    }
1107
1108    /// Look up `name`: local frames (innermost first), then the current namespace.
1109    pub fn lookup(&self, name: &str) -> Option<Value> {
1110        tracing::trace!(target: "env", "lookup {} in {} frames", name, self.frames.len());
1111        for frame in self.frames.iter().rev() {
1112            if let Some(v) = frame.lookup(name) {
1113                return Some(v.clone());
1114            }
1115        }
1116        self.globals.lookup_in_ns(&self.current_ns, name)
1117    }
1118
1119    /// Look up `name` in local frames only — does **not** fall back to the
1120    /// global namespace.  Used by the versioned resolver to check for local
1121    /// bindings before applying commit inheritance.
1122    pub fn lookup_local_frames(&self, name: &str) -> Option<Value> {
1123        for frame in self.frames.iter().rev() {
1124            if let Some(v) = frame.lookup(name) {
1125                return Some(v.clone());
1126            }
1127        }
1128        None
1129    }
1130
1131    /// Look up the Var object for `name` in the current namespace.
1132    pub fn lookup_var(&self, name: &str) -> Option<GcPtr<Var>> {
1133        self.globals.lookup_var_in_ns(&self.current_ns, name)
1134    }
1135
1136    /// Collect all current local bindings (all frames, innermost last).
1137    /// Used for closure capture.
1138    pub fn all_local_bindings(&self) -> (Vec<Arc<str>>, Vec<Value>) {
1139        let mut names = Vec::new();
1140        let mut vals = Vec::new();
1141        // Outermost first so inner frames override on lookup.
1142        for frame in &self.frames {
1143            for (n, v) in &frame.bindings {
1144                names.push(n.clone());
1145                vals.push(v.clone());
1146            }
1147        }
1148        (names, vals)
1149    }
1150
1151    /// Create a child Env for closure capture (same globals, same ns, captures locals).
1152    pub fn child(&self) -> Self {
1153        let (names, vals) = self.all_local_bindings();
1154        let mut child = Self::new(self.globals.clone(), &self.current_ns);
1155        child.is_async = self.is_async;
1156        if !names.is_empty() {
1157            child.push_frame();
1158            for (n, v) in names.into_iter().zip(vals) {
1159                child.bind(n, v);
1160            }
1161        }
1162        child
1163    }
1164
1165    #[inline(always)]
1166    pub fn eval(&mut self, form: &Form) -> EvalResult {
1167        let globals = self.globals.clone();
1168        globals.eval(form, self)
1169    }
1170
1171    #[inline(always)]
1172    pub fn call_cljrs_fn(&mut self, func: &CljxFn, args: &[Value]) -> EvalResult {
1173        let globals = self.globals.clone();
1174        globals.call_cljrs_fn(func, args, self)
1175    }
1176
1177    #[inline(always)]
1178    pub fn on_fn_defined(&mut self, func: &CljxFn) {
1179        let globals = self.globals.clone();
1180        globals.on_fn_defined(func, self);
1181    }
1182}