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, Namespace, 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    /// Create an empty global environment for the given execution mode.
211    ///
212    /// This is the *raw* constructor: no builtins, no bootstrap, no source
213    /// paths.  Use [`crate::Runtime::builder`] unless you are the builder.
214    pub fn new(execution_mode: ExecutionMode) -> Arc<Self> {
215        let id = NEXT_GLOBAL_ENV_ID.fetch_add(1, Ordering::Relaxed);
216        Arc::new(Self {
217            id,
218            namespaces: RwLock::new(HashMap::new()),
219            source_paths: RwLock::new(Vec::new()),
220            loaded: Mutex::new(std::collections::HashSet::new()),
221            loading: Mutex::new(HashMap::new()),
222            loading_done: Condvar::new(),
223            builtin_sources: RwLock::new(HashMap::new()),
224            gc_config: RwLock::new(None),
225            execution_mode,
226            tier_state: AtomicU8::new(TierState::TreeWalk as u8),
227            tiers: crate::tiered::tiers::Tiers::new(id),
228            async_rt: RwLock::new(None),
229            version_cache: Mutex::new(HashMap::new()),
230            deps_config: RwLock::new(None),
231            verify_commit_signatures: AtomicBool::new(false),
232            vcs: RwLock::new(crate::env::vcs::default_provider()),
233            sig_verify_cache: Mutex::new(HashSet::new()),
234            versioned_sources: RwLock::new(HashMap::new()),
235            versioned_offline: AtomicBool::new(false),
236            native_provenance: RwLock::new(HashMap::new()),
237            enforce_native_versions: AtomicBool::new(false),
238            provenance_warned: Mutex::new(HashSet::new()),
239            pinned_native_loader: RwLock::new(None),
240            native_require_loader: RwLock::new(None),
241            compiled_ns_loaders: RwLock::new(HashMap::new()),
242        })
243    }
244
245    /// Replace the source path list.
246    pub fn set_source_paths(&self, paths: Vec<std::path::PathBuf>) {
247        *self.source_paths.write().unwrap() = paths;
248    }
249
250    /// Register an embedded namespace source (called by cljrs-stdlib at startup).
251    pub fn register_builtin_source(&self, ns: &str, src: &'static str) {
252        self.builtin_sources
253            .write()
254            .unwrap()
255            .insert(Arc::from(ns), src);
256    }
257
258    /// Look up an embedded source for a namespace, if one has been registered.
259    pub fn builtin_source(&self, ns: &str) -> Option<&'static str> {
260        self.builtin_sources.read().unwrap().get(ns).copied()
261    }
262
263    /// Register a loader for an AOT-compiled namespace (called by the harness
264    /// `main` of a binary produced by `cljrs compile`).
265    pub fn register_compiled_ns_loader(&self, ns: &str, loader: CompiledNsLoader) {
266        self.compiled_ns_loaders
267            .write()
268            .unwrap()
269            .insert(Arc::from(ns), loader);
270    }
271
272    /// Look up the loader for an AOT-compiled namespace, if one is registered.
273    pub fn compiled_ns_loader(&self, ns: &str) -> Option<CompiledNsLoader> {
274        self.compiled_ns_loaders.read().unwrap().get(ns).cloned()
275    }
276
277    /// Mark a namespace as fully loaded from a file.
278    pub fn mark_loaded(&self, ns: &str) {
279        self.loaded.lock().unwrap().insert(Arc::from(ns));
280    }
281
282    /// True if the namespace has already been loaded from a file.
283    pub fn is_loaded(&self, ns: &str) -> bool {
284        self.loaded.lock().unwrap().contains(ns)
285    }
286
287    /// Set the GC configuration for automatic memory pressure management.
288    pub fn set_gc_config(&self, config: Arc<GcConfig>) {
289        *self.gc_config.write().unwrap() = Some(config);
290    }
291
292    /// Get the GC configuration, if one has been set.
293    pub fn gc_config(&self) -> Option<Arc<GcConfig>> {
294        self.gc_config.read().unwrap().clone()
295    }
296
297    /// Resolve a short alias to a full namespace name in `current_ns`.
298    pub fn resolve_alias(&self, current_ns: &str, alias: &str) -> Option<Arc<str>> {
299        let map = self.namespaces.read().unwrap();
300        let ns = map.get(current_ns)?;
301        let aliases = ns.get().aliases.lock().unwrap();
302        aliases.get(alias).cloned()
303    }
304
305    /// Resolve an auto-resolved keyword name (the text after `::`) to its
306    /// fully-qualified `ns/name` form.
307    ///
308    /// `::kw` qualifies with `current_ns` directly; `::alias/kw` looks
309    /// `alias` up in `current_ns`'s alias table (populated by `(require
310    /// '[... :as alias])`) and qualifies with the resolved namespace.
311    pub fn resolve_auto_keyword(&self, current_ns: &str, name: &str) -> Result<String, String> {
312        match name.split_once('/') {
313            Some((alias, kw_name)) => match self.resolve_alias(current_ns, alias) {
314                Some(ns) => Ok(format!("{ns}/{kw_name}")),
315                None => Err(format!(
316                    "invalid token: ::{name} (no such namespace alias: {alias})"
317                )),
318            },
319            None => Ok(format!("{current_ns}/{name}")),
320        }
321    }
322
323    /// Return the namespace with this name, creating it if it doesn't exist.
324    pub fn get_or_create_ns(&self, name: &str) -> GcPtr<Namespace> {
325        // Fast path: already exists.
326        {
327            let map = self.namespaces.read().unwrap();
328            if let Some(ns) = map.get(name) {
329                return ns.clone();
330            }
331        }
332        // Slow path: insert.
333        let mut map = self.namespaces.write().unwrap();
334        // Re-check after acquiring write lock.
335        if let Some(ns) = map.get(name) {
336            return ns.clone();
337        }
338        let ns = GcPtr::new(Namespace::new(name));
339        map.insert(Arc::from(name), ns.clone());
340        ns
341    }
342
343    /// Intern `name` with `val` in the given namespace, returning the Var.
344    pub fn intern(&self, ns_name: &str, name: Arc<str>, val: Value) -> GcPtr<Var> {
345        let ns = self.get_or_create_ns(ns_name);
346        let mut interns = ns.get().interns.lock().unwrap();
347        if let Some(var) = interns.get(&name) {
348            // Update existing var.
349            var.get().bind(val);
350            return var.clone();
351        }
352        let var = GcPtr::new(Var::new(ns_name, name.as_ref()));
353        var.get().bind(val);
354        interns.insert(name, var.clone());
355        var
356    }
357
358    /// Look up a Var in the named namespace (interns only).
359    pub fn lookup_var(&self, ns_name: &str, sym_name: &str) -> Option<GcPtr<Var>> {
360        let map = self.namespaces.read().unwrap();
361        let ns = map.get(ns_name)?;
362        let interns = ns.get().interns.lock().unwrap();
363        interns.get(sym_name).cloned()
364    }
365
366    /// Look up a value in `ns_name`: checks interns then refers.
367    /// Routes through the dynamic binding stack so `binding` overrides work.
368    pub fn lookup_in_ns(&self, ns_name: &str, sym_name: &str) -> Option<Value> {
369        let map = self.namespaces.read().unwrap();
370        let ns = map.get(ns_name)?;
371        let ns_ref = ns.get();
372        // Check interns first.
373        {
374            let interns = ns_ref.interns.lock().unwrap();
375            if let Some(var) = interns.get(sym_name) {
376                return crate::env::dynamics::deref_var(var);
377            }
378        }
379        // Then refers.
380        {
381            let refers = ns_ref.refers.lock().unwrap();
382            if let Some(var) = refers.get(sym_name) {
383                return crate::env::dynamics::deref_var(var);
384            }
385        }
386        None
387    }
388
389    /// Look up the raw Var (not its value) in `ns_name`: interns then refers.
390    pub fn lookup_var_in_ns(&self, ns_name: &str, sym_name: &str) -> Option<GcPtr<Var>> {
391        let map = self.namespaces.read().unwrap();
392        let ns = map.get(ns_name)?;
393        let ns_ref = ns.get();
394        {
395            let interns = ns_ref.interns.lock().unwrap();
396            if let Some(var) = interns.get(sym_name) {
397                return Some(var.clone());
398            }
399        }
400        {
401            let refers = ns_ref.refers.lock().unwrap();
402            if let Some(var) = refers.get(sym_name) {
403                return Some(var.clone());
404            }
405        }
406        None
407    }
408
409    /// Copy all interns from `src_ns` into `dst_ns` as refers.
410    pub fn refer_all(&self, dst_ns: &str, src_ns: &str) {
411        let map = self.namespaces.read().unwrap();
412        let src = match map.get(src_ns) {
413            Some(ns) => ns.clone(),
414            None => return,
415        };
416        let dst = match map.get(dst_ns) {
417            Some(ns) => ns.clone(),
418            None => return,
419        };
420        let src_interns = src.get().interns.lock().unwrap();
421        let mut dst_refers = dst.get().refers.lock().unwrap();
422        for (name, var) in src_interns.iter() {
423            dst_refers.insert(name.clone(), var.clone());
424        }
425    }
426
427    /// Copy selected interns from `src_ns` into `dst_ns` as refers.
428    pub fn refer_named(&self, dst_ns: &str, src_ns: &str, names: &[Arc<str>]) {
429        let map = self.namespaces.read().unwrap();
430        let src = match map.get(src_ns) {
431            Some(ns) => ns.clone(),
432            None => return,
433        };
434        let dst = match map.get(dst_ns) {
435            Some(ns) => ns.clone(),
436            None => return,
437        };
438        let src_interns = src.get().interns.lock().unwrap();
439        let mut dst_refers = dst.get().refers.lock().unwrap();
440        for name in names {
441            if let Some(var) = src_interns.get(name) {
442                // Use insert (not or_insert_with) so that an explicit
443                // `require :refer [name]` always overrides a previous refer
444                // (e.g. one inherited from clojure.core via refer-all).
445                // clojure.core.async's `into` intentionally shadows clojure.core/into;
446                // or_insert_with would silently drop the override.
447                dst_refers.insert(name.clone(), var.clone());
448            }
449        }
450    }
451
452    /// Register `alias` → `full_ns` in `current_ns`'s alias table.
453    pub fn add_alias(&self, current_ns: &str, alias: &str, full_ns: &str) {
454        let ns_ptr = self.get_or_create_ns(current_ns);
455        let mut aliases = ns_ptr.get().aliases.lock().unwrap();
456        aliases.insert(Arc::from(alias), Arc::from(full_ns));
457    }
458
459    /// Process-unique identity of this runtime instance.
460    #[inline(always)]
461    pub fn id(&self) -> u64 {
462        self.id
463    }
464
465    /// This runtime's Tier-1/Tier-2 state.
466    #[inline(always)]
467    pub fn tiers(&self) -> &Arc<crate::tiered::tiers::Tiers> {
468        &self.tiers
469    }
470
471    /// This runtime's cache of lowered IR.
472    #[inline(always)]
473    pub fn ir_cache(&self) -> &crate::tiered::ir_cache::IrCache {
474        self.tiers.ir_cache()
475    }
476
477    /// This runtime's JIT counters, profiles, and native-code tables.
478    #[inline(always)]
479    pub fn jit(&self) -> &crate::tiered::jit_state::JitState {
480        self.tiers.jit()
481    }
482
483    /// The JIT compiler attached to this runtime, if any.
484    ///
485    /// `None` when no JIT is linked or installed; callers then keep to the
486    /// interpreter tiers.  Installed by `cljrs_compiler::jit::install`.
487    #[inline(always)]
488    pub fn jit_backend(&self) -> Option<Arc<dyn crate::tiered::backend::JitBackend>> {
489        self.tiers.jit().backend().cloned()
490    }
491
492    // ── Execution mode and tier state ────────────────────────────────────
493
494    /// How this runtime executes function calls.
495    #[inline(always)]
496    pub fn execution_mode(&self) -> ExecutionMode {
497        self.execution_mode
498    }
499
500    /// Which tiers are live right now.
501    #[inline(always)]
502    pub fn tier_state(&self) -> TierState {
503        TierState::from_u8(self.tier_state.load(Ordering::Acquire))
504    }
505
506    /// Raise the live tier state.  Called once by the runtime builder after
507    /// the bootstrap completes; lowering the tier is not supported, so a
508    /// request below the current state is ignored.
509    pub fn set_tier_state(&self, tier: TierState) {
510        let _ = self.tier_state.fetch_max(tier as u8, Ordering::AcqRel);
511    }
512
513    /// True when IR may be lowered, cached, and interpreted.  This is the
514    /// gate the old `compiler_ready` flag served.
515    #[inline(always)]
516    pub fn ir_enabled(&self) -> bool {
517        self.tier_state().ir_enabled()
518    }
519
520    // ── Evaluation entry points ──────────────────────────────────────────
521
522    /// Evaluate `form` in `env`.
523    #[inline(always)]
524    pub fn eval(&self, form: &Form, env: &mut Env) -> EvalResult {
525        crate::interp::eval::eval(form, env)
526    }
527
528    /// Call a Clojure function, taking the path this runtime's
529    /// [`ExecutionMode`] selects.
530    ///
531    /// This is the single function-call dispatch point: tree walk, tier-1 IR,
532    /// and JIT-native execution are all reached from here.
533    #[inline(always)]
534    pub fn call_cljrs_fn(&self, func: &CljxFn, args: &[Value], env: &mut Env) -> EvalResult {
535        match self.execution_mode {
536            ExecutionMode::TreeWalk => crate::interp::apply::call_cljrs_fn(func, args, env),
537            ExecutionMode::Tiered | ExecutionMode::TieredNoJit => {
538                crate::tiered::apply::call_cljrs_fn(func, args, env)
539            }
540            ExecutionMode::NoGcTransaction => crate::env::depth::call_cljrs_fn(func, args, env),
541        }
542    }
543
544    /// Notify the active tier that a new `fn*` was defined.
545    ///
546    /// In a tiered runtime with IR enabled this eagerly lowers the function
547    /// (when eager lowering is on); in every other mode it does nothing.
548    #[inline(always)]
549    pub fn on_fn_defined(&self, f: &CljxFn, env: &mut Env) {
550        if self.execution_mode.is_tiered() && self.ir_enabled() {
551            crate::tiered::ir_interp::eager_lower_fn(f, env);
552        }
553    }
554
555    /// Install an async runtime. Called once by `cljrs_async::init`.
556    /// Subsequent calls are silently ignored (first writer wins).
557    pub fn set_async_runtime(&self, rt: Arc<dyn AsyncRuntime>) {
558        let mut guard = self.async_rt.write().unwrap();
559        if guard.is_none() {
560            *guard = Some(rt);
561        }
562    }
563
564    /// Return the async runtime, if one has been registered.
565    pub fn async_runtime(&self) -> Option<Arc<dyn AsyncRuntime>> {
566        self.async_rt.read().unwrap().clone()
567    }
568
569    /// Return `(source_file, git_repo_root)` for the named namespace, if
570    /// both have been populated by the loader.
571    pub fn get_ns_git_context(&self, ns_name: &str) -> Option<(Arc<str>, Arc<str>)> {
572        let map = self.namespaces.read().unwrap();
573        let ns = map.get(ns_name)?;
574        let ns_ref = ns.get();
575        let file = ns_ref.source_file.lock().unwrap().clone()?;
576        let repo = ns_ref.git_repo_root.lock().unwrap().clone()?;
577        Some((file, repo))
578    }
579
580    /// Store a resolved versioned value in the cache.
581    /// Key: `"<ns>/<name>@<commit>"`.
582    pub fn cache_versioned(&self, ns: &str, name: &str, commit: &str, val: Value) {
583        let key: Arc<str> = Arc::from(format!("{ns}/{name}@{commit}"));
584        self.version_cache.lock().unwrap().insert(key, val);
585    }
586
587    /// Retrieve a previously resolved versioned value, if cached.
588    pub fn get_cached_versioned(&self, ns: &str, name: &str, commit: &str) -> Option<Value> {
589        let key = format!("{ns}/{name}@{commit}");
590        self.version_cache
591            .lock()
592            .unwrap()
593            .get(key.as_str())
594            .cloned()
595    }
596
597    /// Mark namespace `name@commit` as loaded in the standard loaded set.
598    pub fn cache_versioned_ns(&self, ns: &str, commit: &str) {
599        let key: Arc<str> = Arc::from(format!("{ns}@{commit}"));
600        self.version_cache.lock().unwrap().insert(key, Value::Nil);
601    }
602
603    /// Record the source text of a versioned namespace fetched from git.
604    /// Key: `"<ns>@<commit>"`.  Consumed by the AOT compiler for embedding.
605    pub fn record_versioned_source(&self, versioned_ns: &str, src: &str) {
606        self.versioned_sources
607            .write()
608            .unwrap()
609            .insert(Arc::from(versioned_ns), Arc::from(src));
610    }
611
612    /// Snapshot of all versioned sources fetched this session, sorted by key.
613    pub fn versioned_sources_snapshot(&self) -> Vec<(Arc<str>, Arc<str>)> {
614        let map = self.versioned_sources.read().unwrap();
615        let mut entries: Vec<_> = map.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
616        entries.sort_by(|a, b| a.0.cmp(&b.0));
617        entries
618    }
619
620    /// Restrict versioned-namespace resolution to embedded builtin sources
621    /// (no git).  Called by AOT harness binaries, which embed every pinned
622    /// source discovered at compile time.
623    pub fn set_versioned_offline(&self, offline: bool) {
624        self.versioned_offline.store(offline, Ordering::Relaxed);
625    }
626
627    /// True when versioned namespaces may only come from embedded sources.
628    pub fn versioned_offline(&self) -> bool {
629        self.versioned_offline.load(Ordering::Relaxed)
630    }
631
632    /// Record the git commit a native (Rust-backed) package was built from.
633    /// Called at registration time (`Registry::set_provenance` or the
634    /// `register_provenance!` inventory entry in cljrs-interop).
635    pub fn set_native_provenance(&self, ns: &str, commit: &str) {
636        self.native_provenance
637            .write()
638            .unwrap()
639            .insert(Arc::from(ns), Arc::from(commit));
640    }
641
642    /// The recorded provenance commit for a native package's namespace.
643    pub fn native_provenance_for(&self, ns: &str) -> Option<Arc<str>> {
644        self.native_provenance.read().unwrap().get(ns).cloned()
645    }
646
647    /// Make pinned-native provenance mismatches hard errors.
648    pub fn set_enforce_native_versions(&self, enforce: bool) {
649        self.enforce_native_versions
650            .store(enforce, Ordering::Relaxed);
651    }
652
653    /// True when pinned-native provenance mismatches are errors.
654    pub fn enforce_native_versions(&self) -> bool {
655        self.enforce_native_versions.load(Ordering::Relaxed)
656    }
657
658    /// Install the pinned-native package loader (called once by
659    /// `cljrs::native::pinned::install`; first writer wins).
660    pub fn set_pinned_native_loader(&self, loader: PinnedNativeLoader) {
661        let mut guard = self.pinned_native_loader.write().unwrap();
662        if guard.is_none() {
663            *guard = Some(loader);
664        }
665    }
666
667    /// Install the native-dependency `require` loader (called once by
668    /// `cljrs::native::pinned::install`; first writer wins).
669    pub fn set_native_require_loader(&self, loader: NativeRequireLoader) {
670        let mut guard = self.native_require_loader.write().unwrap();
671        if guard.is_none() {
672            *guard = Some(loader);
673        }
674    }
675
676    /// The installed VCS backend, or `None` when this build has none (see
677    /// [`crate::env::vcs`]).  Callers must degrade gracefully: "no provider"
678    /// means "this source file is not in a git repository".
679    pub fn vcs(&self) -> Option<Arc<dyn crate::env::vcs::VcsProvider>> {
680        self.vcs.read().unwrap().clone()
681    }
682
683    /// Replace the VCS backend.  Lets an embedder that built without the
684    /// `deps` feature supply its own git implementation, or a sandboxed host
685    /// remove the default one (`None`) so no versioned resolution can reach
686    /// the filesystem's git history.
687    ///
688    /// Drops every cached signature verdict: those were reached by the
689    /// outgoing provider, against its trust set and its view of the
690    /// repository, and say nothing about what the incoming one would decide
691    /// for the same `(repo, commit)`.  Keeping them would let a permissive
692    /// provider launder an approval for source a later provider serves.
693    pub fn set_vcs_provider(&self, provider: Option<Arc<dyn crate::env::vcs::VcsProvider>>) {
694        // Neither this nor `check_commit_signature` ever holds the `vcs` and
695        // `sig_verify_cache` locks at the same time, and the two reach for
696        // them in opposite orders — keep it that way, or the pair becomes a
697        // lock-order inversion.
698        *self.vcs.write().unwrap() = provider;
699        self.invalidate_signature_cache();
700    }
701
702    /// Forget every cached signature verdict, so the next
703    /// [`check_commit_signature`](Self::check_commit_signature) re-asks the
704    /// current provider.  Called whenever the thing that produced those
705    /// verdicts changes: the provider itself, or its trusted-key set.
706    pub fn invalidate_signature_cache(&self) {
707        self.sig_verify_cache.lock().unwrap().clear();
708    }
709
710    /// If `:verify-commit-signatures` is enabled, verify that `commit` inside
711    /// `repo_root` carries a valid GPG or SSH signature.
712    ///
713    /// Returns `Ok(())` immediately when the feature is off.  On the happy
714    /// path the result is cached per `(repo_root, commit)` so each commit is
715    /// only verified once per session.  On failure returns
716    /// `EvalError::CommitSignatureVerificationFailed`.
717    ///
718    /// If verification is demanded but this build has no VCS provider, the
719    /// check fails: silently accepting an unverifiable commit would defeat the
720    /// flag the user explicitly turned on.
721    pub fn check_commit_signature(&self, repo_root: &str, commit: &str) -> EvalResult<()> {
722        if !self.verify_commit_signatures.load(Ordering::Relaxed) {
723            return Ok(());
724        }
725        let key = (Arc::<str>::from(repo_root), Arc::<str>::from(commit));
726        if self.sig_verify_cache.lock().unwrap().contains(&key) {
727            return Ok(());
728        }
729        let Some(vcs) = self.vcs() else {
730            return Err(crate::env::error::EvalError::Runtime(format!(
731                "commit-signature verification is enabled, but this build has no VCS \
732                 provider to verify commit {commit} with (cljrs-runtime built without \
733                 the `deps` feature)"
734            )));
735        };
736        vcs.verify_commit_signature(std::path::Path::new(repo_root), commit)
737            .map_err(|e| match e {
738                crate::env::vcs::SignatureFailure::Untrusted { commit, reason } => {
739                    crate::env::error::EvalError::CommitSignatureVerificationFailed {
740                        commit,
741                        reason,
742                    }
743                }
744                crate::env::vcs::SignatureFailure::Error(msg) => {
745                    crate::env::error::EvalError::Runtime(msg)
746                }
747            })?;
748        self.sig_verify_cache.lock().unwrap().insert(key);
749        Ok(())
750    }
751
752    /// Build the trusted-signer key set from a parsed `cljrs.edn` config and
753    /// install it, so subsequent `check_commit_signature` calls verify against
754    /// it.  Inline keys are parsed directly; `File` entries are read from disk.
755    /// Returns the number of keys loaded; warns (to stderr) on any key that
756    /// fails to load rather than aborting.  Returns 0 when this build has no
757    /// VCS provider, since there is nothing that could consume the keys.
758    ///
759    /// Replacing the trust set invalidates the signature cache for the same
760    /// reason replacing the provider does: a verdict reached under the old
761    /// keys is not a verdict under the new ones.  (In the normal flow this
762    /// runs at session start, before anything has been verified.)
763    pub fn load_trusted_signers(&self, config: &cljrs_project::config::DepsConfig) -> usize {
764        let Some(vcs) = self.vcs() else {
765            return 0;
766        };
767        let loaded = vcs.load_trusted_signers(&config.trusted_signers);
768        self.invalidate_signature_cache();
769        loaded
770    }
771}
772
773// ── Env ───────────────────────────────────────────────────────────────────────
774
775/// The full execution environment: a stack of local frames plus the global env.
776pub struct Env {
777    pub frames: Vec<Frame>,
778    pub current_ns: Arc<str>,
779    pub globals: Arc<GlobalEnv>,
780    /// When set, unversioned same-namespace symbol lookups implicitly resolve
781    /// at this commit hash instead of HEAD.  Set by the versioned resolver when
782    /// evaluating a function body fetched from git history.
783    pub versioned_eval_commit: Option<Arc<str>>,
784    /// True when evaluating the body of an `^:async` function.
785    /// Set by `cljrs-async`; allows the `await` special form to know whether
786    /// to yield (async context) or block the OS thread (sync context).
787    pub is_async: bool,
788}
789
790impl Env {
791    pub fn new(globals: Arc<GlobalEnv>, ns: &str) -> Self {
792        Self {
793            frames: Vec::new(),
794            current_ns: Arc::from(ns),
795            globals,
796            versioned_eval_commit: None,
797            is_async: false,
798        }
799    }
800
801    /// Create an Env for evaluating source at a specific commit.
802    pub fn new_versioned(globals: Arc<GlobalEnv>, ns: &str, commit: &str) -> Self {
803        Self {
804            versioned_eval_commit: Some(Arc::from(commit)),
805            ..Self::new(globals, ns)
806        }
807    }
808
809    /// Create an Env pre-loaded with a function's closed-over bindings.
810    pub fn with_closure(globals: Arc<GlobalEnv>, ns: &str, f: &CljxFn) -> Self {
811        let mut env = Self::new(globals, ns);
812        if !f.closed_over_names.is_empty() {
813            env.push_frame();
814            for (name, val) in f.closed_over_names.iter().zip(f.closed_over_vals.iter()) {
815                env.bind(name.clone(), val.clone());
816            }
817        }
818        env
819    }
820
821    pub fn push_frame(&mut self) {
822        self.frames.push(Frame::new());
823    }
824
825    pub fn pop_frame(&mut self) {
826        self.frames.pop();
827    }
828
829    /// Bind `name` to `val` in the top frame.
830    pub fn bind(&mut self, name: Arc<str>, val: Value) {
831        if let Some(frame) = self.frames.last_mut() {
832            frame.bind(name, val);
833        }
834        // If there are no frames, the binding is silently dropped.
835        // Callers must push a frame first.
836    }
837
838    /// Look up `name`: local frames (innermost first), then the current namespace.
839    pub fn lookup(&self, name: &str) -> Option<Value> {
840        tracing::trace!(target: "env", "lookup {} in {} frames", name, self.frames.len());
841        for frame in self.frames.iter().rev() {
842            if let Some(v) = frame.lookup(name) {
843                return Some(v.clone());
844            }
845        }
846        self.globals.lookup_in_ns(&self.current_ns, name)
847    }
848
849    /// Look up `name` in local frames only — does **not** fall back to the
850    /// global namespace.  Used by the versioned resolver to check for local
851    /// bindings before applying commit inheritance.
852    pub fn lookup_local_frames(&self, name: &str) -> Option<Value> {
853        for frame in self.frames.iter().rev() {
854            if let Some(v) = frame.lookup(name) {
855                return Some(v.clone());
856            }
857        }
858        None
859    }
860
861    /// Look up the Var object for `name` in the current namespace.
862    pub fn lookup_var(&self, name: &str) -> Option<GcPtr<Var>> {
863        self.globals.lookup_var_in_ns(&self.current_ns, name)
864    }
865
866    /// Collect all current local bindings (all frames, innermost last).
867    /// Used for closure capture.
868    pub fn all_local_bindings(&self) -> (Vec<Arc<str>>, Vec<Value>) {
869        let mut names = Vec::new();
870        let mut vals = Vec::new();
871        // Outermost first so inner frames override on lookup.
872        for frame in &self.frames {
873            for (n, v) in &frame.bindings {
874                names.push(n.clone());
875                vals.push(v.clone());
876            }
877        }
878        (names, vals)
879    }
880
881    /// Create a child Env for closure capture (same globals, same ns, captures locals).
882    pub fn child(&self) -> Self {
883        let (names, vals) = self.all_local_bindings();
884        let mut child = Self::new(self.globals.clone(), &self.current_ns);
885        child.is_async = self.is_async;
886        if !names.is_empty() {
887            child.push_frame();
888            for (n, v) in names.into_iter().zip(vals) {
889                child.bind(n, v);
890            }
891        }
892        child
893    }
894
895    #[inline(always)]
896    pub fn eval(&mut self, form: &Form) -> EvalResult {
897        let globals = self.globals.clone();
898        globals.eval(form, self)
899    }
900
901    #[inline(always)]
902    pub fn call_cljrs_fn(&mut self, func: &CljxFn, args: &[Value]) -> EvalResult {
903        let globals = self.globals.clone();
904        globals.call_cljrs_fn(func, args, self)
905    }
906
907    #[inline(always)]
908    pub fn on_fn_defined(&mut self, func: &CljxFn) {
909        let globals = self.globals.clone();
910        globals.on_fn_defined(func, self);
911    }
912}