Skip to main content

cljrs_runtime/interp/
apply.rs

1//! Function application and the recur trampoline.
2
3use crate::builtins::form::form_to_value;
4use cljrs_gc::GcPtr;
5use cljrs_reader::{Form, FormKind};
6use cljrs_value::{
7    Atom, CljxFn, CljxFnArity, Delay, LazySeq, MapValue, PersistentList, Symbol, Thunk, Value,
8    Volatile,
9};
10use std::collections::HashMap;
11use std::sync::Arc;
12
13use crate::env::env::Env;
14use crate::env::error::{EvalError, EvalResult, value_error_to_eval_error};
15use crate::interp::destructure::value_to_seq_vec;
16use crate::interp::eval::eval;
17
18/// Convert an EvalError to a Value for storage (e.g. agent errors).
19/// Preserves Thrown values (ex-info); other errors become strings.
20#[allow(dead_code)]
21fn eval_error_to_value(e: EvalError) -> Value {
22    match e {
23        EvalError::Thrown(v) => v,
24        other => Value::string(format!("{other}")),
25    }
26}
27
28// ── Watch notification ───────────────────────────────────────────────────────
29
30/// Fire all watches on a watchable (atom, var, agent).
31/// Each watch fn is called as `(f key ref old new)`.
32/// Errors thrown by watch fns are re-thrown (matching Clojure behavior).
33fn fire_watches(
34    watches: &std::sync::Mutex<Vec<(Value, Value)>>,
35    reference: &Value,
36    old: &Value,
37    new: &Value,
38    env: &mut Env,
39) {
40    let ws: Vec<(Value, Value)> = watches.lock().unwrap().clone();
41    for (key, f) in &ws {
42        let args = vec![key.clone(), reference.clone(), old.clone(), new.clone()];
43        if let Err(e) = crate::env::apply::apply_value(f, args, env) {
44            // Re-throw watch errors (Clojure behavior: exception propagates to caller)
45            // We can't return EvalResult from here, so we store and re-throw below.
46            // For now, propagate by re-invoking so it surfaces.
47            // Actually, in Clojure, watch exceptions propagate to the mutating call.
48            // We need to handle this differently — but for simplicity, just ignore for now
49            // and let the caller check. Actually let's just use a thread-local to propagate.
50            WATCH_ERROR.with(|cell| {
51                cell.borrow_mut().replace(e);
52            });
53            return;
54        }
55    }
56}
57
58thread_local! {
59    static WATCH_ERROR: std::cell::RefCell<Option<EvalError>> = const { std::cell::RefCell::new(None) };
60}
61
62/// Check if a watch error occurred and propagate it.
63fn check_watch_error() -> EvalResult<()> {
64    WATCH_ERROR.with(|cell| {
65        if let Some(e) = cell.borrow_mut().take() {
66            Err(e)
67        } else {
68            Ok(())
69        }
70    })
71}
72
73// ── ClosureThunk ──────────────────────────────────────────────────────────────
74
75/// A Thunk that calls a zero-arg Clojure closure when forced.
76#[derive(Debug)]
77pub struct ClosureThunk {
78    pub f: CljxFn,
79    pub globals: std::sync::Arc<crate::env::env::GlobalEnv>,
80    pub ns: std::sync::Arc<str>,
81}
82
83/// A Thunk that wraps any zero-arg callable `Value` (a `Value::Fn`, a
84/// `Value::NativeFunction`, etc.) and forces by routing through
85/// `apply_value`.  Used by [`make_lazy_seq_from_fn`] when the supplied
86/// value isn't a plain Clojure fn — for example the IR interpreter's
87/// `AllocClosure` produces a `NativeFunction` wrapping the IR closure.
88struct CallableValueThunk {
89    callee: Value,
90    globals: std::sync::Arc<crate::env::env::GlobalEnv>,
91    ns: std::sync::Arc<str>,
92}
93
94impl std::fmt::Debug for CallableValueThunk {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        f.debug_struct("CallableValueThunk")
97            .field("callee", &self.callee.type_name())
98            .field("ns", &self.ns)
99            .finish()
100    }
101}
102
103impl cljrs_gc::Trace for CallableValueThunk {
104    fn trace(&self, visitor: &mut cljrs_gc::MarkVisitor) {
105        self.callee.trace(visitor);
106    }
107}
108
109impl Thunk for CallableValueThunk {
110    fn force(&self) -> Result<Value, String> {
111        let mut env = Env::new(self.globals.clone(), &self.ns);
112        crate::env::apply::apply_value(&self.callee, Vec::new(), &mut env)
113            .map_err(|e| format!("{e}"))
114    }
115}
116
117/// Wrap a zero-arg callable value in a `Value::LazySeq` whose `force`
118/// calls it.
119///
120/// Accepts any `Value` whose type-name is "fn" — `Value::Fn`,
121/// `Value::NativeFunction`, `Value::BoundFn`, etc. — and unwraps any
122/// surrounding `WithMeta`.  The fast path stays in `Value::Fn` (a direct
123/// `ClosureThunk`); other callables route through a thunk that dispatches
124/// via `apply_value` on force.
125///
126/// This is the value-level analogue of [`handle_make_lazy_seq`], usable
127/// from contexts that already have a `Value` (e.g. the IR interpreter)
128/// rather than a `Form`.
129pub fn make_lazy_seq_from_fn(
130    f_val: &Value,
131    globals: std::sync::Arc<crate::env::env::GlobalEnv>,
132    ns: std::sync::Arc<str>,
133) -> EvalResult {
134    let unwrapped = f_val.unwrap_meta();
135    if let Value::Fn(g) = unwrapped {
136        let thunk = ClosureThunk {
137            f: g.get().clone(),
138            globals,
139            ns,
140        };
141        return Ok(Value::LazySeq(GcPtr::new(LazySeq::new(Box::new(thunk)))));
142    }
143    // Anything else with type-name "fn" is acceptable; route through
144    // apply_value at force-time.  Reject non-callable values up front.
145    if unwrapped.type_name() != "fn" {
146        return Err(EvalError::Runtime(format!(
147            "make-lazy-seq requires a fn, got {}",
148            unwrapped.type_name(),
149        )));
150    }
151    let thunk = CallableValueThunk {
152        callee: unwrapped.clone(),
153        globals,
154        ns,
155    };
156    Ok(Value::LazySeq(GcPtr::new(LazySeq::new(Box::new(thunk)))))
157}
158
159impl cljrs_gc::Trace for ClosureThunk {
160    fn trace(&self, visitor: &mut cljrs_gc::MarkVisitor) {
161        self.f.trace(visitor);
162    }
163}
164
165impl Thunk for ClosureThunk {
166    fn force(&self) -> Result<Value, String> {
167        // Root the closed-over values so they survive GC.  The thunk may live
168        // on the Rust stack outside any Env frame (e.g., after LazySeq::realize
169        // drops its Mutex guard), so GC wouldn't trace them otherwise.
170        let _closed_root = crate::env::gc_roots::root_values(&self.f.closed_over_vals);
171        let mut env = Env::with_closure(self.globals.clone(), &self.ns, &self.f);
172        call_cljrs_fn(&self.f, &[], &mut env).map_err(|e| format!("{e}"))
173    }
174}
175
176/// Native fns that [`eval_call`] intercepts at the form level, because they
177/// need unevaluated forms or the environment.
178///
179/// The `match` in [`eval_call`] must have an arm for every name here; other
180/// evaluators (the async tree-walker, the IR interpreter) consult this
181/// predicate to decide when to hand a call back to the synchronous path.
182pub fn is_form_intercepted(name: &str) -> bool {
183    matches!(
184        name,
185        "apply"
186            | "atom"
187            | "reset!"
188            | "swap!"
189            | "volatile!"
190            | "vreset!"
191            | "agent"
192            | "make-lazy-seq"
193            | "make-delay"
194            | "vswap!"
195            | "send"
196            | "send-off"
197            | "with-bindings*"
198            | "alter-var-root"
199            | "vary-meta"
200            | "eval"
201            | "find-ns"
202            | "the-ns"
203            | "ns-interns"
204            | "ns-publics"
205            | "ns-refers"
206            | "ns-map"
207            | "all-ns"
208            | "create-ns"
209            | "ns-aliases"
210            | "remove-ns"
211            | "alter-meta!"
212            | "ns-resolve"
213            | "resolve"
214            | "intern"
215            | "bound-fn*"
216    )
217}
218
219/// Evaluate a call expression `(func-form arg1 arg2 ...)`.
220///
221/// Handles:
222/// - Macro expansion (if callee is a macro).
223/// - The `apply` function (spread last arg).
224/// - The `swap!` function (needs env to call the function).
225/// - Regular function calls.
226pub fn eval_call(func_form: &Form, arg_forms: &[Form], env: &mut Env) -> EvalResult {
227    // Interop: (.methodName target args...) — method call syntax.
228    if let FormKind::Symbol(s) = &func_form.kind
229        && is_method_sugar(s)
230    {
231        return eval_method_call(&s[1..], arg_forms, env);
232    }
233
234    // Evaluate the callee first.
235    let callee = eval(func_form, env)?;
236
237    // Root the callee so it survives any GC triggered during argument evaluation.
238    let _callee_root = crate::env::gc_roots::root_value(&callee);
239
240    // Macro check: expand then re-eval.
241    if let Value::Macro(mfn) = &callee {
242        let expanded = macro_apply(mfn.get(), func_form, arg_forms, env)?;
243        return eval(&expanded, env);
244    }
245
246    // Special case: `apply` native fn — spread last arg.
247    if let Value::NativeFunction(nf) = &callee {
248        crate::env::policy::check_native(&nf.get().name)?;
249        match nf.get().name.as_ref() {
250            "apply" => return handle_apply_call(arg_forms, env),
251            "atom" => return handle_atom_call(arg_forms, env),
252            "reset!" => return handle_reset_bang(arg_forms, env),
253            "swap!" => return handle_swap_call(arg_forms, env),
254            "volatile!" => return handle_volatile(arg_forms, env),
255            "vreset!" => return handle_vreset(arg_forms, env),
256            "agent" => return handle_agent_call(arg_forms, env),
257            "make-lazy-seq" => return handle_make_lazy_seq(arg_forms, env),
258            "make-delay" => return handle_make_delay(arg_forms, env),
259            "vswap!" => return handle_vswap(arg_forms, env),
260            "send" | "send-off" => return handle_send(arg_forms, env),
261            "with-bindings*" => return handle_with_bindings(arg_forms, env),
262            "alter-var-root" => return handle_alter_var_root(arg_forms, env),
263            "vary-meta" => return handle_vary_meta(arg_forms, env),
264            "eval" => return handle_eval(arg_forms, env),
265            "find-ns" | "the-ns" => return handle_find_ns(arg_forms, env),
266            "ns-interns" | "ns-publics" => return handle_ns_interns(arg_forms, env),
267            "ns-refers" => return handle_ns_refers(arg_forms, env),
268            "ns-map" => return handle_ns_map(arg_forms, env),
269            "all-ns" => return handle_all_ns(arg_forms, env),
270            "create-ns" => return handle_create_ns(arg_forms, env),
271            "ns-aliases" => return handle_ns_aliases(arg_forms, env),
272            "remove-ns" => return handle_remove_ns(arg_forms, env),
273            "alter-meta!" => return handle_alter_meta(arg_forms, env),
274            "ns-resolve" => return handle_ns_resolve(arg_forms, env),
275            "resolve" => return handle_resolve(arg_forms, env),
276            "intern" => return handle_intern(arg_forms, env),
277            "bound-fn*" => return handle_bound_fn_star(arg_forms, env),
278            _ => {}
279        }
280    }
281
282    // Evaluate arguments one-at-a-time, rooting partial results so that
283    // previously-evaluated args survive any GC triggered during later evals.
284    let mut args: Vec<Value> = Vec::with_capacity(arg_forms.len());
285    for f in arg_forms {
286        // Root the already-evaluated args before each eval that could trigger GC.
287        let _args_root = crate::env::gc_roots::root_values(&args);
288        args.push(eval(f, env)?);
289    }
290
291    // For Clojure functions, dispatch through `GlobalEnv::call_cljrs_fn` so
292    // the runtime's execution mode picks the path: the IR-aware dispatcher in
293    // `crate::tiered::apply` for a tiered runtime, this module's plain tree
294    // walker otherwise.
295    if let Value::Fn(f) = &callee {
296        // `^:async` functions dispatch through the async runtime (when one is
297        // registered), spawning the body and returning a Future immediately.
298        if let Some(fut) = crate::env::apply::dispatch_if_async(&callee, &args, env) {
299            return Ok(fut);
300        }
301        let _args_root = crate::env::gc_roots::root_values(&args);
302        crate::env::gc_roots::gc_safepoint(env);
303        return env.call_cljrs_fn(f.get(), &args);
304    }
305
306    crate::env::apply::apply_value(&callee, args, env)
307}
308
309// ── Interop method calls ─────────────────────────────────────────────────────
310
311/// Evaluate `(.methodName target args...)` interop syntax.
312///
313/// Currently supports a small set of methods on built-in types:
314/// - `.indexOf` on strings and vectors
315/// - `.startsWith`, `.endsWith`, `.contains`, `.substring`, `.length`,
316///   `.charAt`, `.toUpperCase`, `.toLowerCase`, `.trim`, `.replace`,
317///   `.split` on strings
318fn eval_method_call(method: &str, arg_forms: &[Form], env: &mut Env) -> EvalResult {
319    if arg_forms.is_empty() {
320        return Err(EvalError::Runtime(format!(
321            ".{method} requires a target object"
322        )));
323    }
324    let target = eval(&arg_forms[0], env)?;
325    let args: Vec<Value> = arg_forms[1..]
326        .iter()
327        .map(|f| eval(f, env))
328        .collect::<EvalResult<_>>()?;
329
330    dispatch_method(method, &target, &args)
331}
332
333/// The `.method` / `.-field` head predicate.
334///
335/// Re-exported from `cljrs_ir::lower` so the evaluator, the async evaluator,
336/// the ANF lowerer and the AOT driver all read one definition.
337pub use cljrs_ir::lower::is_method_sugar;
338
339/// Dispatch `(.method target args…)` on an already-evaluated target.
340///
341/// Form-free, so the Tier-1 IR interpreter can route dot-marked
342/// `CallDirect` instructions here (see `dispatch_sentinel_by_name` in
343/// `crate::tiered`) and behave exactly like the tree-walker's interop path.
344pub fn dispatch_method(method: &str, target: &Value, args: &[Value]) -> EvalResult {
345    match target {
346        Value::Str(s) => dispatch_string_method(method, s.get(), args),
347        Value::Vector(v) => dispatch_vector_method(method, v, args),
348        Value::List(_) | Value::Cons(_) | Value::LazySeq(_) => {
349            dispatch_seq_method(method, target, args)
350        }
351        Value::TypeInstance(ti) => {
352            // `.-field` reads a deftype/defrecord field. There are no host
353            // methods to call on an interpreter instance, so a plain `.method`
354            // is unsupported (protocol methods are called as `(proto-fn inst)`).
355            if let Some(field) = method.strip_prefix('-') {
356                let key = Value::keyword(cljrs_value::Keyword::simple(field));
357                let inst = ti.get();
358                // A mutable field lives in the interior-mutable cell; an
359                // immutable one in the field map.
360                if let Some(atom) = &inst.mutable
361                    && let Value::Map(m) = atom.get().deref()
362                    && let Some(v) = m.get(&key)
363                {
364                    return Ok(v);
365                }
366                Ok(inst.fields.get(&key).unwrap_or(Value::Nil))
367            } else {
368                Err(EvalError::Runtime(format!(
369                    ".{method} not supported on {} (only .-field access is)",
370                    target.type_name()
371                )))
372            }
373        }
374        _ => Err(EvalError::Runtime(format!(
375            ".{method} not supported on type {}",
376            target.type_name()
377        ))),
378    }
379}
380
381fn dispatch_string_method(method: &str, s: &str, args: &[Value]) -> EvalResult {
382    match method {
383        "indexOf" => {
384            let needle = match args.first() {
385                Some(Value::Str(s)) => s.get().to_string(),
386                Some(Value::Char(c)) => c.to_string(),
387                Some(v) => {
388                    return Err(EvalError::Runtime(format!(
389                        ".indexOf expects string or char argument, got {}",
390                        v.type_name()
391                    )));
392                }
393                None => return Err(EvalError::Runtime(".indexOf requires an argument".into())),
394            };
395            match s.find(&needle) {
396                Some(pos) => Ok(Value::Long(pos as i64)),
397                None => Ok(Value::Long(-1)),
398            }
399        }
400        "lastIndexOf" => {
401            let needle = match args.first() {
402                Some(Value::Str(s)) => s.get().to_string(),
403                Some(Value::Char(c)) => c.to_string(),
404                _ => {
405                    return Err(EvalError::Runtime(
406                        ".lastIndexOf requires a string or char argument".into(),
407                    ));
408                }
409            };
410            match s.rfind(&needle) {
411                Some(pos) => Ok(Value::Long(pos as i64)),
412                None => Ok(Value::Long(-1)),
413            }
414        }
415        "startsWith" => {
416            let prefix = require_str_arg(args, ".startsWith")?;
417            Ok(Value::Bool(s.starts_with(&prefix)))
418        }
419        "endsWith" => {
420            let suffix = require_str_arg(args, ".endsWith")?;
421            Ok(Value::Bool(s.ends_with(&suffix)))
422        }
423        "contains" => {
424            let sub = require_str_arg(args, ".contains")?;
425            Ok(Value::Bool(s.contains(&sub)))
426        }
427        "length" => Ok(Value::Long(s.len() as i64)),
428        "isEmpty" => Ok(Value::Bool(s.is_empty())),
429        "charAt" => {
430            let idx = require_long_arg(args, ".charAt")? as usize;
431            s.chars()
432                .nth(idx)
433                .map(Value::Char)
434                .ok_or_else(|| EvalError::Runtime(format!(".charAt index {idx} out of bounds")))
435        }
436        "substring" => {
437            let start = require_long_arg(args, ".substring")? as usize;
438            let end = args
439                .get(1)
440                .map(|v| match v {
441                    Value::Long(n) => Ok(*n as usize),
442                    _ => Err(EvalError::Runtime(
443                        ".substring end must be an integer".into(),
444                    )),
445                })
446                .transpose()?;
447            let result = match end {
448                Some(e) => &s[start..e.min(s.len())],
449                None => &s[start..],
450            };
451            Ok(Value::Str(GcPtr::new(result.to_string())))
452        }
453        "toUpperCase" => Ok(Value::Str(GcPtr::new(s.to_uppercase()))),
454        "toLowerCase" => Ok(Value::Str(GcPtr::new(s.to_lowercase()))),
455        "trim" => Ok(Value::Str(GcPtr::new(s.trim().to_string()))),
456        "replace" => {
457            let from = require_str_arg(args, ".replace")?;
458            let to = match args.get(1) {
459                Some(Value::Str(s)) => s.get().to_string(),
460                Some(Value::Char(c)) => c.to_string(),
461                _ => {
462                    return Err(EvalError::Runtime(
463                        ".replace requires two string arguments".into(),
464                    ));
465                }
466            };
467            Ok(Value::Str(GcPtr::new(s.replace(&from, &to))))
468        }
469        "split" => {
470            let sep = require_str_arg(args, ".split")?;
471            let parts: Vec<Value> = s
472                .split(&sep)
473                .map(|p| Value::Str(GcPtr::new(p.to_string())))
474                .collect();
475            Ok(Value::Vector(GcPtr::new(
476                cljrs_value::PersistentVector::from_iter(parts),
477            )))
478        }
479        _ => Err(EvalError::Runtime(format!(
480            ".{method} not supported on String"
481        ))),
482    }
483}
484
485fn dispatch_vector_method(
486    method: &str,
487    v: &GcPtr<cljrs_value::PersistentVector>,
488    args: &[Value],
489) -> EvalResult {
490    match method {
491        "indexOf" => {
492            let needle = args
493                .first()
494                .ok_or_else(|| EvalError::Runtime(".indexOf requires an argument".into()))?;
495            for (i, item) in v.get().iter().enumerate() {
496                if item == needle {
497                    return Ok(Value::Long(i as i64));
498                }
499            }
500            Ok(Value::Long(-1))
501        }
502        "size" | "count" => Ok(Value::Long(v.get().count() as i64)),
503        _ => Err(EvalError::Runtime(format!(
504            ".{method} not supported on Vector"
505        ))),
506    }
507}
508
509fn dispatch_seq_method(method: &str, target: &Value, args: &[Value]) -> EvalResult {
510    match method {
511        "indexOf" => {
512            let needle = args
513                .first()
514                .ok_or_else(|| EvalError::Runtime(".indexOf requires an argument".into()))?;
515            let items = crate::interp::destructure::value_to_seq_vec(target);
516            for (i, item) in items.iter().enumerate() {
517                if item == needle {
518                    return Ok(Value::Long(i as i64));
519                }
520            }
521            Ok(Value::Long(-1))
522        }
523        _ => Err(EvalError::Runtime(format!(
524            ".{method} not supported on {}",
525            target.type_name()
526        ))),
527    }
528}
529
530fn require_str_arg(args: &[Value], method: &str) -> Result<String, EvalError> {
531    match args.first() {
532        Some(Value::Str(s)) => Ok(s.get().to_string()),
533        Some(Value::Char(c)) => Ok(c.to_string()),
534        _ => Err(EvalError::Runtime(format!(
535            "{method} requires a string argument"
536        ))),
537    }
538}
539
540fn require_long_arg(args: &[Value], method: &str) -> Result<i64, EvalError> {
541    match args.first() {
542        Some(Value::Long(n)) => Ok(*n),
543        _ => Err(EvalError::Runtime(format!(
544            "{method} requires an integer argument"
545        ))),
546    }
547}
548
549/// Resolve a type symbol from `extend-type` to a canonical tag.
550/// Canonical tags ARE the short names, so this just passes through.
551pub fn resolve_type_tag(sym: &str) -> Arc<str> {
552    Arc::from(sym)
553}
554
555/// Tree-walking execution path (original implementation).
556pub fn call_cljrs_fn(f: &CljxFn, args: &[Value], caller_env: &mut Env) -> EvalResult {
557    let arity = select_arity(f, args.len())?;
558
559    // Register the caller's env as a GC root so its local bindings survive
560    // any collection triggered while we're executing the callee's body.
561    let _caller_root = crate::env::gc_roots::push_env_root(caller_env);
562
563    // Create a fresh env with closure bindings, executing in the defining namespace.
564    // This ensures macros qualify symbols relative to their definition site.
565    let mut env = Env::with_closure(caller_env.globals.clone(), &f.defining_ns, f);
566
567    let mut current_args = Vec::from(args);
568    loop {
569        // Root current_args on the shadow stack so they survive GC.
570        // They haven't been bound into the env yet.
571        let _args_root = crate::env::gc_roots::root_values(&current_args);
572
573        // GC safepoint before entering function body
574        crate::env::gc_roots::gc_safepoint(&env);
575
576        env.push_frame();
577
578        // Under GC: scope this call's heap allocations in a fresh alloc frame.
579        // Everything the body (and parameter binding) allocates is rooted only
580        // until the frame drops at the end of this trampoline iteration, so a
581        // deep call's locals and a `recur`'s dead intermediates become
582        // collectable instead of being pinned for the lifetime of the enclosing
583        // top-level form.  `result` is moved out before the frame drops and is
584        // re-rooted at the top of the next iteration (`root_values`) or by the
585        // caller during return unwinding — no GC safepoint runs in the
586        // interval, exactly as the IR/JIT dispatch seam relies on (below).
587        #[cfg(not(feature = "no-gc"))]
588        let _call_frame = cljrs_gc::push_alloc_frame();
589
590        // Self-reference for named functions: use self_ptr when available so
591        // the binding is pointer-equal to the outer Value::Fn holding this fn.
592        //
593        // BEFORE the params, not after: both bind into this one frame, so
594        // binding the fn's own name last OVERWROTE a parameter that shared it.
595        // `(defn text [text] {:text text})` then returned the function as its
596        // own :text. In Clojure the name is visible in the body but a parameter
597        // shadows it, which is exactly what this order gives.
598        if let Some(ref name) = f.name {
599            let self_val = if let Some(ref p) = f.self_ptr {
600                Value::Fn(p.clone())
601            } else {
602                Value::Fn(GcPtr::new(f.clone()))
603            };
604            env.bind(name.clone(), self_val);
605        }
606
607        // Bind params.
608        bind_fn_params(arity, &current_args, &mut env)?;
609
610        // Eval body, catching Recur.
611        // Under no-gc: push a scratch region; evaluate all-but-last in it,
612        // then pop scratch before the tail expression so the return value
613        // lands in the caller's allocation context.
614        #[cfg(not(feature = "no-gc"))]
615        let result = eval_body_recur_fn(&arity.body, &mut env);
616        #[cfg(feature = "no-gc")]
617        let result = {
618            let mut scratch = cljrs_gc::alloc_ctx::ScratchGuard::new();
619            // scratch drops here: resets the region (frees intermediates)
620            eval_body_with_scratch(&arity.body, &mut scratch, &mut env)
621        };
622        env.pop_frame();
623        // _call_frame drops at the end of this iteration (after the match
624        // below), freeing this call's intermediates.
625
626        match result {
627            Ok(v) => return Ok(v),
628            Err(EvalError::Recur(new_args)) => {
629                // For variadic arities, recur provides n+1 values where the
630                // last value IS the rest collection (not spread args to be
631                // re-collected). Flatten it so bind_fn_params sees the right
632                // number of individual args.
633                if arity.rest_param.is_some() {
634                    let n = arity.params.len();
635                    if new_args.len() == n + 1 {
636                        let mut flat = new_args[..n].to_vec();
637                        // Spread the rest collection back into individual args.
638                        let rest_val = &new_args[n];
639                        match rest_val {
640                            Value::Nil => {} // no extra args
641                            _ => {
642                                let rest_items = value_to_seq_vec(rest_val);
643                                flat.extend(rest_items);
644                            }
645                        }
646                        current_args = flat;
647                    } else {
648                        current_args = new_args;
649                    }
650                } else {
651                    current_args = new_args;
652                }
653            }
654            Err(e) => return Err(e),
655        }
656    }
657}
658
659/// Bind function parameters in the current (top) frame, expanding any
660/// destructuring patterns the arity carries.
661pub fn bind_fn_params(arity: &CljxFnArity, args: &[Value], env: &mut Env) -> EvalResult<()> {
662    bind_fn_params_impl(arity, args, env, true)
663}
664
665/// Bind only the *named* parameters — the positional slots and the rest list —
666/// leaving the arity's destructuring patterns unexpanded.
667///
668/// For the IR tier: the lowered prologue expands those same patterns into
669/// explicit IR bindings (`lower_fn_body_destructured`), and the ANF lowerer
670/// never emits `LoadLocal`, so a destructured name is only ever read as an IR
671/// register — the env copy is unobservable.  Producing it anyway would not be
672/// free, though: an `:or` default is evaluated eagerly, exactly as
673/// `(get m :k default)` evaluates its third argument, so a side-effecting
674/// default would fire once here and once in the prologue — twice per call.
675pub fn bind_fn_params_positional(
676    arity: &CljxFnArity,
677    args: &[Value],
678    env: &mut Env,
679) -> EvalResult<()> {
680    bind_fn_params_impl(arity, args, env, false)
681}
682
683fn bind_fn_params_impl(
684    arity: &CljxFnArity,
685    args: &[Value],
686    env: &mut Env,
687    destructure: bool,
688) -> EvalResult<()> {
689    let n = arity.params.len();
690    // Bind positional params.
691    for (i, name) in arity.params.iter().enumerate() {
692        let val = args.get(i).cloned().unwrap_or(Value::Nil);
693        env.bind(name.clone(), val);
694    }
695    // Bind rest param.
696    if let Some(ref rest) = arity.rest_param {
697        let rest_items = args[n..].to_vec();
698        let rest_val = if rest_items.is_empty() {
699            Value::Nil
700        } else {
701            Value::List(GcPtr::new(PersistentList::from_iter(rest_items)))
702        };
703        env.bind(rest.clone(), rest_val.clone());
704        // Apply rest destructuring if present.
705        if destructure && let Some(ref pattern) = arity.destructure_rest {
706            // When the rest pattern is a map destructure (e.g. `& {:keys [bar]}`),
707            // convert the rest args list into a map of alternating key-value pairs,
708            // matching Clojure's keyword-arguments convention.
709            let destructure_val = if pattern.is_kwargs_rest_pattern() {
710                let items = value_to_seq_vec(&rest_val);
711                Value::from_kwargs_rest(items).map_err(value_error_to_eval_error)?
712            } else {
713                rest_val
714            };
715            crate::interp::destructure::bind_pattern(pattern, destructure_val, env)?;
716        }
717    }
718    // Apply positional destructuring patterns.
719    if destructure {
720        for (idx, pattern) in &arity.destructure_params {
721            let val = args.get(*idx).cloned().unwrap_or(Value::Nil);
722            crate::interp::destructure::bind_pattern(pattern, val, env)?;
723        }
724    }
725    Ok(())
726}
727
728/// Eval a function body, propagating Recur up (does not catch it).
729#[cfg(not(feature = "no-gc"))]
730fn eval_body_recur_fn(body: &[cljrs_reader::Form], env: &mut Env) -> EvalResult {
731    let mut result = Value::Nil;
732    for form in body {
733        result = eval(form, env)?;
734    }
735    Ok(result)
736}
737
738/// Under `no-gc`: evaluate body forms with the scratch region active for all
739/// non-tail forms, then pop the scratch before the tail expression so the
740/// return value (or `recur` args) are allocated in the caller's context.
741#[cfg(feature = "no-gc")]
742fn eval_body_with_scratch(
743    body: &[cljrs_reader::Form],
744    scratch: &mut cljrs_gc::alloc_ctx::ScratchGuard,
745    env: &mut Env,
746) -> EvalResult {
747    if body.is_empty() {
748        scratch.pop_for_return();
749        return Ok(Value::Nil);
750    }
751    // Eval all non-tail forms in the scratch region.
752    for form in &body[..body.len() - 1] {
753        eval(form, env)?;
754    }
755    // Pop scratch so the tail expression allocates in the caller's context.
756    scratch.pop_for_return();
757    eval(&body[body.len() - 1], env)
758}
759
760/// Select the matching arity for the given argument count.
761pub fn select_arity(f: &CljxFn, argc: usize) -> EvalResult<&CljxFnArity> {
762    let name = f.name.as_deref().unwrap_or("fn");
763    // Try fixed arities first.
764    for arity in &f.arities {
765        if arity.rest_param.is_none() && arity.params.len() == argc {
766            return Ok(arity);
767        }
768    }
769    // Try variadic arities.
770    for arity in &f.arities {
771        if arity.rest_param.is_some() && argc >= arity.params.len() {
772            return Ok(arity);
773        }
774    }
775    // Build expected string.
776    let expected: Vec<String> = f
777        .arities
778        .iter()
779        .map(|a| {
780            if a.rest_param.is_some() {
781                format!("{}+", a.params.len())
782            } else {
783                a.params.len().to_string()
784            }
785        })
786        .collect();
787    Err(EvalError::Arity {
788        name: name.to_string(),
789        expected: expected.join(" or "),
790        got: argc,
791    })
792}
793
794/// Expand a macro: convert unevaluated arg forms to values, call the macro fn,
795/// then convert the resulting Value back to a Form.
796///
797/// Clojure macros receive two implicit leading arguments:
798/// - `&form`: the entire call expression as a quoted value
799/// - `&env`: a map of local bindings at the call site (symbol → value)
800fn macro_apply(
801    mfn: &CljxFn,
802    func_form: &Form,
803    arg_forms: &[Form],
804    env: &mut Env,
805) -> EvalResult<Form> {
806    // Resolve ::kw forms using the caller's namespace before the macro sees them.
807    // In Clojure, ::kw is resolved at read time; we approximate that here so a
808    // macro splicing its arguments into a new form cannot re-resolve them against
809    // the macro's own namespace.
810    let resolved_args: Vec<Form> = arg_forms
811        .iter()
812        .map(|f| crate::builtins::form::resolve_auto_forms(f, env))
813        .collect::<EvalResult<Vec<Form>>>()?;
814
815    // &form: the whole call expression as a list value.
816    let form_val = {
817        let mut items = vec![form_to_value(func_form)?];
818        for f in &resolved_args {
819            items.push(form_to_value(f)?);
820        }
821        Value::List(GcPtr::new(PersistentList::from_iter(items)))
822    };
823
824    // &env: local variable bindings at call site as a map (symbol → value).
825    let env_val = {
826        let (names, vals) = env.all_local_bindings();
827        let mut m = MapValue::empty();
828        for (name, val) in names.iter().zip(vals.iter()) {
829            m = m.assoc(Value::symbol(Symbol::simple(name.as_ref())), val.clone());
830        }
831        Value::Map(m)
832    };
833
834    // Prepend &form and &env, then pass remaining arg forms as unevaluated values.
835    let mut args = vec![form_val, env_val];
836    for f in &resolved_args {
837        args.push(form_to_value(f)?);
838    }
839
840    let expanded_val = call_cljrs_fn(mfn, args.as_ref(), env)?;
841    let dummy_span = cljrs_types::span::Span::new(Arc::new("<macro>".to_string()), 0, 0, 1, 1);
842    crate::interp::macros::value_to_form(&expanded_val, dummy_span)
843}
844
845/// Handle `(apply f arg1 ... last-coll)` — spread the last arg.
846fn handle_apply_call(arg_forms: &[Form], env: &mut Env) -> EvalResult {
847    let mut evaled: Vec<Value> = Vec::with_capacity(arg_forms.len());
848    for f in arg_forms {
849        let _root = crate::env::gc_roots::root_values(&evaled);
850        evaled.push(eval(f, env)?);
851    }
852
853    if evaled.len() < 2 {
854        return Err(EvalError::Arity {
855            name: "apply".into(),
856            expected: "2+".into(),
857            got: evaled.len(),
858        });
859    }
860
861    let f = evaled.remove(0);
862    let last = evaled.pop().unwrap();
863    // Root f, last, and remaining evaled args during spread (which may realize lazy seqs).
864    let _f_root = crate::env::gc_roots::root_value(&f);
865    let _last_root = crate::env::gc_roots::root_value(&last);
866    let _evaled_root = crate::env::gc_roots::root_values(&evaled);
867    // Spread last arg.
868    let spread = value_to_seq_vec(&last);
869    evaled.extend(spread);
870    crate::env::apply::apply_value(&f, evaled, env)
871}
872
873/// Handle `(make-lazy-seq f)` — wraps a zero-arg fn in a lazy sequence.
874pub fn handle_make_lazy_seq(arg_forms: &[Form], env: &mut Env) -> EvalResult {
875    if arg_forms.len() != 1 {
876        return Err(EvalError::Arity {
877            name: "make-lazy-seq".into(),
878            expected: "1".into(),
879            got: arg_forms.len(),
880        });
881    }
882    let f_val = eval(&arg_forms[0], env)?;
883    let f = match f_val {
884        Value::Fn(f) => f.get().clone(),
885        other => {
886            return Err(EvalError::Runtime(format!(
887                "make-lazy-seq requires a fn, got {}",
888                other.type_name()
889            )));
890        }
891    };
892    let thunk = ClosureThunk {
893        f,
894        globals: env.globals.clone(),
895        ns: env.current_ns.clone(),
896    };
897    Ok(Value::LazySeq(GcPtr::new(LazySeq::new(Box::new(thunk)))))
898}
899
900/// Handle `(make-delay f)` — wraps a zero-arg fn in a Delay.
901fn handle_make_delay(arg_forms: &[Form], env: &mut Env) -> EvalResult {
902    if arg_forms.len() != 1 {
903        return Err(EvalError::Arity {
904            name: "make-delay".into(),
905            expected: "1".into(),
906            got: arg_forms.len(),
907        });
908    }
909    let f_val = eval(&arg_forms[0], env)?;
910    let f = match f_val {
911        Value::Fn(f) => f.get().clone(),
912        other => {
913            return Err(EvalError::Runtime(format!(
914                "make-delay requires a fn, got {}",
915                other.type_name()
916            )));
917        }
918    };
919    let thunk = ClosureThunk {
920        f,
921        globals: env.globals.clone(),
922        ns: env.current_ns.clone(),
923    };
924    Ok(Value::Delay(GcPtr::new(Delay::new(Box::new(thunk)))))
925}
926
927/// Handle `(vswap! vol f & args)` — apply f to current volatile value and store.
928fn handle_vswap(arg_forms: &[Form], env: &mut Env) -> EvalResult {
929    if arg_forms.len() < 2 {
930        return Err(EvalError::Arity {
931            name: "vswap!".into(),
932            expected: "2+".into(),
933            got: arg_forms.len(),
934        });
935    }
936    let vol_val = eval(&arg_forms[0], env)?;
937    let f = eval(&arg_forms[1], env)?;
938    let extra: Vec<Value> = arg_forms[2..]
939        .iter()
940        .map(|a| eval(a, env))
941        .collect::<EvalResult<_>>()?;
942
943    match vol_val {
944        Value::Volatile(v) => {
945            let cur = v.get().deref();
946            let mut call_args = vec![cur];
947            call_args.extend(extra);
948            // Under no-gc: the value written into the volatile must live in the
949            // StaticArena since the volatile outlives all scratch regions.
950            #[cfg(feature = "no-gc")]
951            let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
952            let new_val = crate::env::apply::apply_value(&f, call_args, env)?;
953            v.get().reset(new_val.clone());
954            Ok(new_val)
955        }
956        other => Err(EvalError::Runtime(format!(
957            "vswap!: expected volatile, got {}",
958            other.type_name()
959        ))),
960    }
961}
962
963// ── volatile! ────────────────────────────────────────────────────────────────
964
965/// Handle `(volatile! init-val)`.
966fn handle_volatile(arg_forms: &[Form], env: &mut Env) -> EvalResult {
967    if arg_forms.is_empty() {
968        return Err(EvalError::Arity {
969            name: "volatile!".into(),
970            expected: "1".into(),
971            got: 0,
972        });
973    }
974    // Under no-gc: volatile initial value must live in the StaticArena since
975    // the Volatile container outlives all scratch regions.
976    #[cfg(feature = "no-gc")]
977    let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
978    let initial = eval(&arg_forms[0], env)?;
979    Ok(Value::Volatile(GcPtr::new(Volatile::new(initial))))
980}
981
982// ── vreset! ──────────────────────────────────────────────────────────────────
983
984/// Handle `(vreset! vol new-val)`.
985fn handle_vreset(arg_forms: &[Form], env: &mut Env) -> EvalResult {
986    if arg_forms.len() < 2 {
987        return Err(EvalError::Arity {
988            name: "vreset!".into(),
989            expected: "2".into(),
990            got: arg_forms.len(),
991        });
992    }
993    let vol_val = eval(&arg_forms[0], env)?;
994    // Under no-gc: the new value written into the volatile must live in the
995    // StaticArena since the volatile outlives all scratch regions.
996    #[cfg(feature = "no-gc")]
997    let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
998    let new_val = eval(&arg_forms[1], env)?;
999    match &vol_val {
1000        Value::Volatile(v) => {
1001            v.get().reset(new_val.clone());
1002            Ok(new_val)
1003        }
1004        other => Err(EvalError::Runtime(format!(
1005            "vreset!: expected volatile, got {}",
1006            other.type_name()
1007        ))),
1008    }
1009}
1010
1011// ── agent ────────────────────────────────────────────────────────────────────
1012
1013/// Handle `(agent init-val & opts)`.
1014fn handle_agent_call(_arg_forms: &[Form], _env: &mut Env) -> EvalResult {
1015    Err(EvalError::Runtime("agent is not yet implemented".into()))
1016}
1017
1018/// Handle `(send agent f & extra)` / `(send-off agent f & extra)`.
1019fn handle_send(_arg_forms: &[Form], _env: &mut Env) -> EvalResult {
1020    Err(EvalError::Runtime(
1021        "send/send-off: agents are not yet implemented".into(),
1022    ))
1023}
1024
1025// ── atom ──────────────────────────────────────────────────────────────────────
1026
1027/// Handle `(swap! atom f & args)`.
1028fn handle_atom_call(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1029    if arg_forms.is_empty() {
1030        return Err(EvalError::Arity {
1031            name: "atom".into(),
1032            expected: "1+".into(),
1033            got: 0,
1034        });
1035    }
1036    // Under no-gc: atom initial value must live in the StaticArena since the
1037    // Atom container outlives all scratch regions.
1038    #[cfg(feature = "no-gc")]
1039    let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1040    let initial = eval(&arg_forms[0], env)?;
1041
1042    // Evaluate and parse keyword options; unknown keys / nil keys are ignored.
1043    let options: Vec<Value> = arg_forms[1..]
1044        .iter()
1045        .map(|f| eval(f, env))
1046        .collect::<EvalResult<_>>()?;
1047
1048    let mut meta_opt: Option<Value> = None;
1049    let mut validator_opt: Option<Value> = None;
1050    let mut i = 0;
1051    while i + 1 < options.len() {
1052        match &options[i] {
1053            Value::Keyword(k) if k.get().name.as_ref() == "meta" => {
1054                meta_opt = Some(options[i + 1].clone());
1055                i += 2;
1056            }
1057            Value::Keyword(k) if k.get().name.as_ref() == "validator" => {
1058                let vf = options[i + 1].clone();
1059                validator_opt = if vf == Value::Nil { None } else { Some(vf) };
1060                i += 2;
1061            }
1062            _ => {
1063                i += 2;
1064            }
1065        }
1066    }
1067
1068    // Validate :meta must be nil or a map.
1069    if let Some(ref m) = meta_opt
1070        && !matches!(m, Value::Nil | Value::Map(_))
1071    {
1072        return Err(EvalError::Thrown(Value::string(
1073            "Atom metadata must be a map or nil".to_string(),
1074        )));
1075    }
1076
1077    // Check validator on the initial value.
1078    if let Some(ref vf) = validator_opt {
1079        let result = crate::env::apply::apply_value(vf, vec![initial.clone()], env)?;
1080        if result == Value::Nil || result == Value::Bool(false) {
1081            return Err(EvalError::Thrown(Value::string(
1082                "Invalid initial value for atom".to_string(),
1083            )));
1084        }
1085    }
1086
1087    let atom = GcPtr::new(Atom::new(initial));
1088    if let Some(m) = meta_opt {
1089        atom.get()
1090            .set_meta(if m == Value::Nil { None } else { Some(m) });
1091    }
1092    if let Some(vf) = validator_opt {
1093        atom.get().set_validator(Some(vf));
1094    }
1095    Ok(Value::Atom(atom))
1096}
1097
1098// ── shared-atom (Phase B3, two-tier ADR) ──────────────────────────────────────
1099//
1100// `shared-atom` is the cross-isolate tier of the two-tier atom design: its
1101// contents live in `SharedValue` (Send + Sync, refcounted) behind a lock-free
1102// `ArcSwap`, so the same atom can be observed and mutated from any isolate.
1103// `deref`/`reset!`/`swap!`/`compare-and-set!` all route through these helpers
1104// when handed a `Value::SharedAtom`, so the surface mirrors a local `atom`
1105// except that values are promoted on write and demoted on read.
1106
1107/// `reset!` on a shared-atom: promote the new value and store it atomically.
1108/// Returns the (isolate-local) value that was written.
1109fn shared_atom_reset(sa: &Arc<cljrs_value::SharedAtom>, new_val: Value) -> EvalResult {
1110    let promoted = cljrs_value::promote(&new_val).map_err(|e| EvalError::Runtime(e.to_string()))?;
1111    sa.reset(promoted);
1112    Ok(new_val)
1113}
1114
1115/// `swap!` on a shared-atom: CAS-retry loop.  Loads the current value, demotes
1116/// it into an isolate-local `Value`, applies `f` (plus any extra args), promotes
1117/// the result, and commits with a single compare-and-set — retrying from the
1118/// fresh value if another isolate raced us in between.
1119fn shared_atom_swap(
1120    sa: &Arc<cljrs_value::SharedAtom>,
1121    f: &Value,
1122    extra: Vec<Value>,
1123    env: &mut Env,
1124) -> EvalResult {
1125    loop {
1126        let cur = sa.deref_val();
1127        let old_val = cljrs_value::demote(&cur);
1128        let mut call_args = Vec::with_capacity(1 + extra.len());
1129        call_args.push(old_val);
1130        call_args.extend(extra.iter().cloned());
1131        let new_val = crate::env::apply::apply_value(f, call_args, env)?;
1132        let promoted =
1133            cljrs_value::promote(&new_val).map_err(|e| EvalError::Runtime(e.to_string()))?;
1134        if sa.compare_and_set(&cur, promoted) {
1135            return Ok(new_val);
1136        }
1137        // Lost the race; another writer committed first. Re-read and retry.
1138    }
1139}
1140
1141// ── reset! ────────────────────────────────────────────────────────────────────
1142
1143fn handle_reset_bang(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1144    if arg_forms.len() < 2 {
1145        return Err(EvalError::Arity {
1146            name: "reset!".into(),
1147            expected: "2".into(),
1148            got: arg_forms.len(),
1149        });
1150    }
1151    let atom_val = eval(&arg_forms[0], env)?;
1152    // Under no-gc: the new value written into the atom must live in the
1153    // StaticArena since the atom outlives all scratch regions.
1154    #[cfg(feature = "no-gc")]
1155    let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1156    let new_val = eval(&arg_forms[1], env)?;
1157
1158    let atom = match &atom_val {
1159        Value::Atom(a) => a.clone(),
1160        Value::SharedAtom(sa) => return shared_atom_reset(sa, new_val),
1161        v => {
1162            return Err(EvalError::Runtime(format!(
1163                "reset! requires an atom, got {}",
1164                v.type_name()
1165            )));
1166        }
1167    };
1168
1169    validate_atom_value(&atom, &new_val, env)?;
1170    let old_val = atom.get().deref();
1171    atom.get().reset(new_val.clone());
1172    fire_watches(&atom.get().watches, &atom_val, &old_val, &new_val, env);
1173    check_watch_error()?;
1174    Ok(new_val)
1175}
1176
1177/// Call the atom's validator (if any) on `new_val`. Throws if invalid.
1178fn validate_atom_value(atom: &GcPtr<Atom>, new_val: &Value, env: &mut Env) -> EvalResult<()> {
1179    if let Some(vf) = atom.get().get_validator() {
1180        let result = crate::env::apply::apply_value(&vf, vec![new_val.clone()], env)?;
1181        if result == Value::Nil || result == Value::Bool(false) {
1182            return Err(EvalError::Thrown(Value::string(
1183                "Invalid value for atom".to_string(),
1184            )));
1185        }
1186    }
1187    Ok(())
1188}
1189
1190// ── swap! ─────────────────────────────────────────────────────────────────────
1191
1192fn handle_swap_call(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1193    let mut evaled: Vec<Value> = arg_forms
1194        .iter()
1195        .map(|f| eval(f, env))
1196        .collect::<EvalResult<_>>()?;
1197
1198    if evaled.len() < 2 {
1199        return Err(EvalError::Arity {
1200            name: "swap!".into(),
1201            expected: "2+".into(),
1202            got: evaled.len(),
1203        });
1204    }
1205
1206    let atom_val = evaled.remove(0);
1207    let f = evaled.remove(0);
1208
1209    let atom = match &atom_val {
1210        Value::Atom(a) => a.clone(),
1211        Value::SharedAtom(sa) => return shared_atom_swap(sa, &f, evaled, env),
1212        v => {
1213            return Err(EvalError::Runtime(format!(
1214                "swap! requires an atom, got {}",
1215                v.type_name()
1216            )));
1217        }
1218    };
1219
1220    let old_val = atom.get().deref();
1221    let mut args = vec![old_val.clone()];
1222    args.extend(evaled);
1223    // Under no-gc: the value written into the atom must live in the StaticArena
1224    // since the atom outlives all scratch regions.
1225    #[cfg(feature = "no-gc")]
1226    let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1227    let new_val = crate::env::apply::apply_value(&f, args, env)?;
1228    validate_atom_value(&atom, &new_val, env)?;
1229    atom.get().reset(new_val.clone());
1230    fire_watches(&atom.get().watches, &atom_val, &old_val, &new_val, env);
1231    check_watch_error()?;
1232    Ok(new_val)
1233}
1234
1235// ── with-bindings* ────────────────────────────────────────────────────────────
1236
1237/// `(with-bindings* {#'var val ...} fn)` — push a binding frame, call fn with
1238/// no args, pop the frame, return the result.
1239fn handle_with_bindings(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1240    if arg_forms.len() < 2 {
1241        return Err(EvalError::Arity {
1242            name: "with-bindings*".into(),
1243            expected: "2".into(),
1244            got: arg_forms.len(),
1245        });
1246    }
1247    let map_val = eval(&arg_forms[0], env)?;
1248    let func_val = eval(&arg_forms[1], env)?;
1249
1250    let mut frame: HashMap<usize, Value> = HashMap::new();
1251    if let Value::Map(m) = &map_val {
1252        m.for_each(|k, v| {
1253            if let Value::Var(vp) = k {
1254                frame.insert(crate::env::dynamics::var_key_of(vp), v.clone());
1255            }
1256            // non-Var keys silently ignored
1257        });
1258    } else {
1259        return Err(EvalError::Runtime(
1260            "with-bindings*: first arg must be a map".into(),
1261        ));
1262    }
1263
1264    let _guard = crate::env::dynamics::push_frame(frame);
1265    crate::env::apply::apply_value(&func_val, vec![], env)
1266}
1267
1268// ── alter-var-root ────────────────────────────────────────────────────────────
1269
1270/// `(alter-var-root #'v f & args)` — atomically apply `f` to the root value.
1271fn handle_alter_var_root(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1272    if arg_forms.len() < 2 {
1273        return Err(EvalError::Arity {
1274            name: "alter-var-root".into(),
1275            expected: "2+".into(),
1276            got: arg_forms.len(),
1277        });
1278    }
1279    let var_val = eval(&arg_forms[0], env)?;
1280    let f = eval(&arg_forms[1], env)?;
1281    let extra: Vec<Value> = arg_forms[2..]
1282        .iter()
1283        .map(|form| eval(form, env))
1284        .collect::<EvalResult<_>>()?;
1285
1286    let vp = match &var_val {
1287        Value::Var(vp) => vp.clone(),
1288        v => {
1289            return Err(EvalError::Runtime(format!(
1290                "alter-var-root: expected var, got {}",
1291                v.type_name()
1292            )));
1293        }
1294    };
1295    let old_val = vp.get().deref().unwrap_or(Value::Nil);
1296    let mut call_args = vec![old_val.clone()];
1297    call_args.extend(extra);
1298    // Under no-gc: the new Var root value must live in the StaticArena since
1299    // Vars outlive all scratch regions.
1300    #[cfg(feature = "no-gc")]
1301    let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1302    let new_val = crate::env::apply::apply_value(&f, call_args, env)?;
1303    vp.get().bind(new_val.clone());
1304    fire_watches(&vp.get().watches, &var_val, &old_val, &new_val, env);
1305    check_watch_error()?;
1306    Ok(new_val)
1307}
1308
1309// ── vary-meta ────────────────────────────────────────────────────────────────
1310
1311/// `(vary-meta obj f & args)` — apply `f` to obj's metadata, store result as new meta.
1312fn handle_vary_meta(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1313    if arg_forms.len() < 2 {
1314        return Err(EvalError::Arity {
1315            name: "vary-meta".into(),
1316            expected: "2+".into(),
1317            got: arg_forms.len(),
1318        });
1319    }
1320    let obj = eval(&arg_forms[0], env)?;
1321    let f = eval(&arg_forms[1], env)?;
1322    let extra: Vec<Value> = arg_forms[2..]
1323        .iter()
1324        .map(|form| eval(form, env))
1325        .collect::<EvalResult<_>>()?;
1326
1327    let current_meta = match &obj {
1328        Value::Var(vp) => vp.get().get_meta().unwrap_or(Value::Nil),
1329        _ => Value::Nil,
1330    };
1331    let mut call_args = vec![current_meta];
1332    call_args.extend(extra);
1333    let new_meta = crate::env::apply::apply_value(&f, call_args, env)?;
1334    if let Value::Var(vp) = &obj {
1335        vp.get().set_meta(new_meta);
1336    }
1337    Ok(obj)
1338}
1339
1340// ── eval ─────────────────────────────────────────────────────────────────────
1341
1342/// `(eval form)` — evaluate a form *value*.
1343fn handle_eval(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1344    let [arg] = arg_forms else {
1345        return Err(EvalError::Arity {
1346            name: "eval".into(),
1347            expected: "1".into(),
1348            got: arg_forms.len(),
1349        });
1350    };
1351    let value = eval(arg, env)?;
1352    eval_eval(vec![value], env)
1353}
1354
1355/// Execute `eval` with an already-evaluated arg: `[form-value]`.
1356///
1357/// The form is evaluated in a fresh top-level environment of the current
1358/// namespace, so it sees vars but not the caller's locals — as on the JVM.
1359pub fn eval_eval(args: Vec<Value>, env: &mut Env) -> EvalResult {
1360    let [value] = args.as_slice() else {
1361        return Err(EvalError::Arity {
1362            name: "eval".into(),
1363            expected: "1".into(),
1364            got: args.len(),
1365        });
1366    };
1367    let span = cljrs_types::span::Span::new(Arc::new("<eval>".to_string()), 0, 0, 1, 1);
1368    let form = crate::interp::macros::value_to_form(value, span)?;
1369    let mut top = Env::new(env.globals.clone(), &env.current_ns);
1370    eval(&form, &mut top)
1371}
1372
1373// ── Value-level special form dispatch (used by IR interpreter) ───────────────
1374//
1375// These mirror the `handle_*` functions above but accept already-evaluated
1376// `Vec<Value>` instead of `&[Form]`.  The IR interpreter calls these directly
1377// to bypass the sentinel stubs registered in clojure.core.
1378
1379/// Execute `reset!` with already-evaluated args: `[atom, new-val]`.
1380pub fn eval_reset_bang(args: Vec<Value>, env: &mut Env) -> EvalResult {
1381    if args.len() < 2 {
1382        return Err(EvalError::Arity {
1383            name: "reset!".into(),
1384            expected: "2".into(),
1385            got: args.len(),
1386        });
1387    }
1388    let atom_val = args[0].clone();
1389    let new_val = args[1].clone();
1390    let atom = match &atom_val {
1391        Value::Atom(a) => a.clone(),
1392        Value::SharedAtom(sa) => return shared_atom_reset(sa, new_val),
1393        v => {
1394            return Err(EvalError::Runtime(format!(
1395                "reset! requires an atom, got {}",
1396                v.type_name()
1397            )));
1398        }
1399    };
1400    #[cfg(feature = "no-gc")]
1401    let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1402    validate_atom_value(&atom, &new_val, env)?;
1403    let old_val = atom.get().deref();
1404    atom.get().reset(new_val.clone());
1405    fire_watches(&atom.get().watches, &atom_val, &old_val, &new_val, env);
1406    check_watch_error()?;
1407    Ok(new_val)
1408}
1409
1410/// Execute `swap!` with already-evaluated args: `[atom, f, extra...]`.
1411pub fn eval_swap_bang(mut args: Vec<Value>, env: &mut Env) -> EvalResult {
1412    if args.len() < 2 {
1413        return Err(EvalError::Arity {
1414            name: "swap!".into(),
1415            expected: "2+".into(),
1416            got: args.len(),
1417        });
1418    }
1419    let atom_val = args.remove(0);
1420    let f = args.remove(0);
1421    let atom = match &atom_val {
1422        Value::Atom(a) => a.clone(),
1423        Value::SharedAtom(sa) => return shared_atom_swap(sa, &f, args, env),
1424        v => {
1425            return Err(EvalError::Runtime(format!(
1426                "swap! requires an atom, got {}",
1427                v.type_name()
1428            )));
1429        }
1430    };
1431    let old_val = atom.get().deref();
1432    let mut call_args = vec![old_val.clone()];
1433    call_args.extend(args);
1434    #[cfg(feature = "no-gc")]
1435    let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1436    let new_val = crate::env::apply::apply_value(&f, call_args, env)?;
1437    validate_atom_value(&atom, &new_val, env)?;
1438    atom.get().reset(new_val.clone());
1439    fire_watches(&atom.get().watches, &atom_val, &old_val, &new_val, env);
1440    check_watch_error()?;
1441    Ok(new_val)
1442}
1443
1444/// Execute `volatile!` with already-evaluated args: `[init-val]`.
1445pub fn eval_volatile(args: Vec<Value>) -> EvalResult {
1446    if args.is_empty() {
1447        return Err(EvalError::Arity {
1448            name: "volatile!".into(),
1449            expected: "1".into(),
1450            got: 0,
1451        });
1452    }
1453    #[cfg(feature = "no-gc")]
1454    let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1455    Ok(Value::Volatile(GcPtr::new(Volatile::new(
1456        args.into_iter().next().unwrap(),
1457    ))))
1458}
1459
1460/// Execute `vreset!` with already-evaluated args: `[volatile, new-val]`.
1461pub fn eval_vreset_bang(args: Vec<Value>) -> EvalResult {
1462    if args.len() < 2 {
1463        return Err(EvalError::Arity {
1464            name: "vreset!".into(),
1465            expected: "2".into(),
1466            got: args.len(),
1467        });
1468    }
1469    #[cfg(feature = "no-gc")]
1470    let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1471    let new_val = args[1].clone();
1472    match &args[0] {
1473        Value::Volatile(v) => {
1474            v.get().reset(new_val.clone());
1475            Ok(new_val)
1476        }
1477        other => Err(EvalError::Runtime(format!(
1478            "vreset!: expected volatile, got {}",
1479            other.type_name()
1480        ))),
1481    }
1482}
1483
1484/// Execute `vswap!` with already-evaluated args: `[volatile, f, extra...]`.
1485pub fn eval_vswap_bang(mut args: Vec<Value>, env: &mut Env) -> EvalResult {
1486    if args.len() < 2 {
1487        return Err(EvalError::Arity {
1488            name: "vswap!".into(),
1489            expected: "2+".into(),
1490            got: args.len(),
1491        });
1492    }
1493    let vol_val = args.remove(0);
1494    let f = args.remove(0);
1495    match vol_val {
1496        Value::Volatile(v) => {
1497            let cur = v.get().deref();
1498            let mut call_args = vec![cur];
1499            call_args.extend(args);
1500            #[cfg(feature = "no-gc")]
1501            let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1502            let new_val = crate::env::apply::apply_value(&f, call_args, env)?;
1503            v.get().reset(new_val.clone());
1504            Ok(new_val)
1505        }
1506        other => Err(EvalError::Runtime(format!(
1507            "vswap!: expected volatile, got {}",
1508            other.type_name()
1509        ))),
1510    }
1511}
1512
1513/// Wrap a zero-arg callable in a `Value::Delay`.
1514///
1515/// Analogous to [`make_lazy_seq_from_fn`] but produces a `Delay` instead of
1516/// a `LazySeq`.
1517pub fn make_delay_from_fn(
1518    f_val: &Value,
1519    globals: std::sync::Arc<crate::env::env::GlobalEnv>,
1520    ns: std::sync::Arc<str>,
1521) -> EvalResult {
1522    let f = match f_val {
1523        Value::Fn(f) => f.get().clone(),
1524        other => {
1525            return Err(EvalError::Runtime(format!(
1526                "make-delay requires a fn, got {}",
1527                other.type_name()
1528            )));
1529        }
1530    };
1531    let thunk = ClosureThunk { f, globals, ns };
1532    Ok(Value::Delay(GcPtr::new(Delay::new(Box::new(thunk)))))
1533}
1534
1535/// Execute `alter-var-root` with already-evaluated args: `[var, f, extra...]`.
1536pub fn eval_alter_var_root(mut args: Vec<Value>, env: &mut Env) -> EvalResult {
1537    if args.len() < 2 {
1538        return Err(EvalError::Arity {
1539            name: "alter-var-root".into(),
1540            expected: "2+".into(),
1541            got: args.len(),
1542        });
1543    }
1544    let var_val = args.remove(0);
1545    let f = args.remove(0);
1546    let vp = match &var_val {
1547        Value::Var(vp) => vp.clone(),
1548        v => {
1549            return Err(EvalError::Runtime(format!(
1550                "alter-var-root: expected var, got {}",
1551                v.type_name()
1552            )));
1553        }
1554    };
1555    let old_val = vp.get().deref().unwrap_or(Value::Nil);
1556    let mut call_args = vec![old_val.clone()];
1557    call_args.extend(args);
1558    #[cfg(feature = "no-gc")]
1559    let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1560    let new_val = crate::env::apply::apply_value(&f, call_args, env)?;
1561    vp.get().bind(new_val.clone());
1562    fire_watches(&vp.get().watches, &var_val, &old_val, &new_val, env);
1563    check_watch_error()?;
1564    Ok(new_val)
1565}
1566
1567/// Execute `vary-meta` with already-evaluated args: `[obj, f, extra...]`.
1568pub fn eval_vary_meta(mut args: Vec<Value>, env: &mut Env) -> EvalResult {
1569    if args.len() < 2 {
1570        return Err(EvalError::Arity {
1571            name: "vary-meta".into(),
1572            expected: "2+".into(),
1573            got: args.len(),
1574        });
1575    }
1576    let obj = args.remove(0);
1577    let f = args.remove(0);
1578    let current_meta = match &obj {
1579        Value::Var(vp) => vp.get().get_meta().unwrap_or(Value::Nil),
1580        _ => Value::Nil,
1581    };
1582    let mut call_args = vec![current_meta];
1583    call_args.extend(args);
1584    let new_meta = crate::env::apply::apply_value(&f, call_args, env)?;
1585    if let Value::Var(vp) = &obj {
1586        vp.get().set_meta(new_meta);
1587    }
1588    Ok(obj)
1589}
1590
1591/// Execute `with-bindings*` with already-evaluated args: `[bindings-map, f]`.
1592pub fn eval_with_bindings_star(args: Vec<Value>, env: &mut Env) -> EvalResult {
1593    if args.len() < 2 {
1594        return Err(EvalError::Arity {
1595            name: "with-bindings*".into(),
1596            expected: "2".into(),
1597            got: args.len(),
1598        });
1599    }
1600    let mut frame: HashMap<usize, Value> = HashMap::new();
1601    if let Value::Map(m) = &args[0] {
1602        m.for_each(|k, v| {
1603            if let Value::Var(vp) = k {
1604                frame.insert(crate::env::dynamics::var_key_of(vp), v.clone());
1605            }
1606        });
1607    } else {
1608        return Err(EvalError::Runtime(
1609            "with-bindings*: first arg must be a map".into(),
1610        ));
1611    }
1612    let _guard = crate::env::dynamics::push_frame(frame);
1613    crate::env::apply::apply_value(&args[1], vec![], env)
1614}
1615
1616/// Execute `send` / `send-off` with already-evaluated args: `[agent, f, extra...]`.
1617pub fn eval_send_to_agent(_args: Vec<Value>, _env: &mut Env) -> EvalResult {
1618    Err(EvalError::Runtime(
1619        "send/send-off: agents are not yet implemented".into(),
1620    ))
1621}
1622
1623// ── Namespace reflection (env-needing) ────────────────────────────────────────
1624
1625fn ns_name_from_val(v: &Value) -> Result<String, EvalError> {
1626    match v {
1627        Value::Symbol(s) => Ok(s.get().name.as_ref().to_string()),
1628        Value::Str(s) => Ok(s.get().clone()),
1629        Value::Namespace(ns) => Ok(ns.get().name.as_ref().to_string()),
1630        Value::Keyword(k) => Ok(k.get().name.as_ref().to_string()),
1631        other => Err(EvalError::Runtime(format!(
1632            "expected symbol, string, or namespace, got {}",
1633            other.type_name()
1634        ))),
1635    }
1636}
1637
1638/// Resolve an already-evaluated arg to a `Namespace`, matching Clojure's
1639/// `the-ns`: pass a `Namespace` through unchanged, otherwise resolve a
1640/// symbol/string/keyword name against the global namespace table, throwing
1641/// if there's no such namespace (rather than a "wrong type" error).
1642fn the_ns(v: &Value, env: &Env) -> Result<GcPtr<cljrs_value::Namespace>, EvalError> {
1643    if let Value::Namespace(ns) = v {
1644        return Ok(ns.clone());
1645    }
1646    let name = ns_name_from_val(v)?;
1647    let map = env.globals.namespaces.read().unwrap();
1648    match map.get(name.as_str()) {
1649        Some(ns) => Ok(ns.clone()),
1650        None => Err(EvalError::Runtime(format!("No namespace: {name} found"))),
1651    }
1652}
1653
1654/// `(ns-interns ns)` / `(ns-publics ns)` — map of unqualified Symbol → Var
1655/// for all interned vars. Accepts a namespace, symbol, or string (via `the-ns`).
1656fn handle_ns_interns(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1657    if arg_forms.is_empty() {
1658        return Err(EvalError::Arity {
1659            name: "ns-interns".into(),
1660            expected: "1".into(),
1661            got: 0,
1662        });
1663    }
1664    let arg = eval(&arg_forms[0], env)?;
1665    let ns = the_ns(&arg, env)?;
1666    crate::builtins::builtins::builtin_ns_interns(&[Value::Namespace(ns)])
1667        .map_err(crate::env::error::value_error_to_eval_error)
1668}
1669
1670/// `(ns-refers ns)` — map of Symbol → Var for all referred vars.
1671fn handle_ns_refers(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1672    if arg_forms.is_empty() {
1673        return Err(EvalError::Arity {
1674            name: "ns-refers".into(),
1675            expected: "1".into(),
1676            got: 0,
1677        });
1678    }
1679    let arg = eval(&arg_forms[0], env)?;
1680    let ns = the_ns(&arg, env)?;
1681    crate::builtins::builtins::builtin_ns_refers(&[Value::Namespace(ns)])
1682        .map_err(crate::env::error::value_error_to_eval_error)
1683}
1684
1685/// `(ns-map ns)` — map of Symbol → Var for all visible names (interns + refers).
1686fn handle_ns_map(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1687    if arg_forms.is_empty() {
1688        return Err(EvalError::Arity {
1689            name: "ns-map".into(),
1690            expected: "1".into(),
1691            got: 0,
1692        });
1693    }
1694    let arg = eval(&arg_forms[0], env)?;
1695    let ns = the_ns(&arg, env)?;
1696    crate::builtins::builtins::builtin_ns_map(&[Value::Namespace(ns)])
1697        .map_err(crate::env::error::value_error_to_eval_error)
1698}
1699
1700/// `(find-ns sym)` / `(the-ns sym)` — look up a namespace by name; nil if not found.
1701fn handle_find_ns(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1702    if arg_forms.is_empty() {
1703        return Err(EvalError::Arity {
1704            name: "find-ns".into(),
1705            expected: "1".into(),
1706            got: 0,
1707        });
1708    }
1709    let arg = eval(&arg_forms[0], env)?;
1710    let name = ns_name_from_val(&arg)?;
1711    let map = env.globals.namespaces.read().unwrap();
1712    match map.get(name.as_str()) {
1713        Some(ns) => Ok(Value::Namespace(ns.clone())),
1714        None => Ok(Value::Nil),
1715    }
1716}
1717
1718/// `(all-ns)` — lazy sequence of all live namespaces.
1719fn handle_all_ns(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1720    if !arg_forms.is_empty() {
1721        let _ = eval(&arg_forms[0], env)?; // tolerate extra args
1722    }
1723    let map = env.globals.namespaces.read().unwrap();
1724    let items: Vec<Value> = map
1725        .values()
1726        .map(|ns| Value::Namespace(ns.clone()))
1727        .collect();
1728    drop(map);
1729    Ok(Value::List(cljrs_gc::GcPtr::new(
1730        cljrs_value::PersistentList::from_iter(items),
1731    )))
1732}
1733
1734/// `(create-ns sym)` — create (or return existing) namespace, return it.
1735fn handle_create_ns(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1736    if arg_forms.is_empty() {
1737        return Err(EvalError::Arity {
1738            name: "create-ns".into(),
1739            expected: "1".into(),
1740            got: 0,
1741        });
1742    }
1743    let arg = eval(&arg_forms[0], env)?;
1744    let name = ns_name_from_val(&arg)?;
1745    let ns = env.globals.get_or_create_ns(&name);
1746    Ok(Value::Namespace(ns))
1747}
1748
1749/// `(ns-aliases ns)` — map of Symbol → Namespace for all aliases in ns.
1750fn handle_ns_aliases(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1751    if arg_forms.is_empty() {
1752        return Err(EvalError::Arity {
1753            name: "ns-aliases".into(),
1754            expected: "1".into(),
1755            got: 0,
1756        });
1757    }
1758    let ns_val = eval(&arg_forms[0], env)?;
1759    let ns_name = ns_name_from_val(&ns_val)?;
1760    let map = env.globals.namespaces.read().unwrap();
1761    let ns = match map.get(ns_name.as_str()) {
1762        Some(ns) => ns.clone(),
1763        None => return Ok(Value::Map(cljrs_value::MapValue::empty())),
1764    };
1765    let aliases = ns.get().aliases.lock().unwrap().clone();
1766    drop(map);
1767    let mut m = cljrs_value::MapValue::empty();
1768    for (alias, full_ns_name) in &aliases {
1769        let sym = Value::symbol(cljrs_value::Symbol::simple(alias.clone()));
1770        let nsmap = env.globals.namespaces.read().unwrap();
1771        if let Some(target_ns) = nsmap.get(full_ns_name.as_ref()) {
1772            m = m.assoc(sym, Value::Namespace(target_ns.clone()));
1773        }
1774    }
1775    Ok(Value::Map(m))
1776}
1777
1778/// `(remove-ns sym)` — remove a namespace (returns nil; used sparingly in tests).
1779fn handle_remove_ns(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1780    if arg_forms.is_empty() {
1781        return Err(EvalError::Arity {
1782            name: "remove-ns".into(),
1783            expected: "1".into(),
1784            got: 0,
1785        });
1786    }
1787    let arg = eval(&arg_forms[0], env)?;
1788    let name = ns_name_from_val(&arg)?;
1789    env.globals
1790        .namespaces
1791        .write()
1792        .unwrap()
1793        .remove(name.as_str());
1794    Ok(Value::Nil)
1795}
1796
1797/// `(alter-meta! ref f & args)` — apply f to ref's current meta + args, store and return new meta.
1798fn handle_alter_meta(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1799    if arg_forms.len() < 2 {
1800        return Err(EvalError::Arity {
1801            name: "alter-meta!".into(),
1802            expected: "2+".into(),
1803            got: arg_forms.len(),
1804        });
1805    }
1806    let obj = eval(&arg_forms[0], env)?;
1807    let f = eval(&arg_forms[1], env)?;
1808    let extra: Vec<Value> = arg_forms[2..]
1809        .iter()
1810        .map(|form| eval(form, env))
1811        .collect::<EvalResult<_>>()?;
1812
1813    let current_meta = match &obj {
1814        Value::Var(vp) => vp
1815            .get()
1816            .get_meta()
1817            .unwrap_or(Value::Map(cljrs_value::MapValue::empty())),
1818        _ => Value::Map(cljrs_value::MapValue::empty()),
1819    };
1820    let mut call_args = vec![current_meta];
1821    call_args.extend(extra);
1822    let new_meta = crate::env::apply::apply_value(&f, call_args, env)?;
1823    if let Value::Var(vp) = &obj {
1824        vp.get().set_meta(new_meta.clone());
1825    }
1826    Ok(new_meta)
1827}
1828
1829/// `(ns-resolve ns sym)` — return the Var for sym in ns, or nil if not found.
1830fn handle_ns_resolve(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1831    if arg_forms.len() < 2 {
1832        return Err(EvalError::Arity {
1833            name: "ns-resolve".into(),
1834            expected: "2".into(),
1835            got: arg_forms.len(),
1836        });
1837    }
1838    let ns_arg = eval(&arg_forms[0], env)?;
1839    let sym_arg = eval(&arg_forms[1], env)?;
1840    let ns_name = ns_name_from_val(&ns_arg)?;
1841    let sym_name = match &sym_arg {
1842        Value::Symbol(s) => s.get().name.as_ref().to_string(),
1843        Value::Str(s) => s.get().clone(),
1844        other => {
1845            return Err(EvalError::Runtime(format!(
1846                "ns-resolve: second arg must be symbol or string, got {}",
1847                other.type_name()
1848            )));
1849        }
1850    };
1851    match env.globals.lookup_var(&ns_name, &sym_name) {
1852        Some(var_ptr) => Ok(Value::Var(var_ptr)),
1853        None => Ok(Value::Nil),
1854    }
1855}
1856
1857/// Get the namespace name from `*ns*` (dynamic var), falling back to `env.current_ns`.
1858/// This is important for `resolve` inside macros, where `env.current_ns` is the
1859/// macro's defining namespace but `*ns*` is the caller's namespace.
1860fn resolve_current_ns(env: &Env) -> Arc<str> {
1861    if let Some(var) = env.globals.lookup_var("clojure.core", "*ns*") {
1862        let val = crate::env::dynamics::deref_var(&var);
1863        if let Some(Value::Namespace(ns_ptr)) = val {
1864            return ns_ptr.get().name.clone();
1865        }
1866    }
1867    env.current_ns.clone()
1868}
1869
1870/// `(resolve sym)` — return the Var for sym in the current namespace, or nil.
1871fn handle_resolve(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1872    if arg_forms.len() != 1 {
1873        return Err(EvalError::Arity {
1874            name: "resolve".into(),
1875            expected: "1".into(),
1876            got: arg_forms.len(),
1877        });
1878    }
1879    let resolve_ns = resolve_current_ns(env);
1880    let sym_arg = eval(&arg_forms[0], env)?;
1881    let sym_name = match &sym_arg {
1882        Value::Symbol(s) => {
1883            let sym = s.get();
1884            // If qualified (ns/name), use the given ns; otherwise current ns.
1885            if let Some(ns) = &sym.namespace {
1886                // Relative to `*ns*`, not to `env.current_ns` — `resolve` is
1887                // defined in terms of the dynamic var.
1888                let full_ns = env.globals.resolve_ns_part_in(&resolve_ns, ns.as_ref());
1889                return Ok(
1890                    match env.globals.lookup_var_in_ns(&full_ns, sym.name.as_ref()) {
1891                        Some(var_ptr) => Value::Var(var_ptr),
1892                        None => Value::Nil,
1893                    },
1894                );
1895            }
1896            sym.name.as_ref().to_string()
1897        }
1898        Value::Str(s) => s.get().clone(),
1899        other => {
1900            return Err(EvalError::Runtime(format!(
1901                "resolve: arg must be symbol or string, got {}",
1902                other.type_name()
1903            )));
1904        }
1905    };
1906    Ok(match env.globals.lookup_var_in_ns(&resolve_ns, &sym_name) {
1907        Some(var_ptr) => Value::Var(var_ptr),
1908        None => Value::Nil,
1909    })
1910}
1911
1912fn handle_intern(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1913    if arg_forms.len() < 2 || arg_forms.len() > 3 {
1914        return Err(EvalError::Runtime("intern expects 2 or 3 arguments".into()));
1915    }
1916    let ns_val = eval(&arg_forms[0], env)?;
1917    let ns_name: Arc<str> = match &ns_val {
1918        Value::Symbol(s) => s.get().name.clone(),
1919        Value::Namespace(ns) => ns.get().name.clone(),
1920        other => {
1921            return Err(EvalError::Runtime(format!(
1922                "intern: first arg must be namespace or symbol, got {}",
1923                other.type_name()
1924            )));
1925        }
1926    };
1927    let var_name: Arc<str> = match eval(&arg_forms[1], env)? {
1928        Value::Symbol(s) => s.get().name.clone(),
1929        other => {
1930            return Err(EvalError::Runtime(format!(
1931                "intern: second arg must be symbol, got {}",
1932                other.type_name()
1933            )));
1934        }
1935    };
1936    // Namespace must already exist (Clojure throws if it doesn't)
1937    let ns = {
1938        let map = env.globals.namespaces.read().unwrap();
1939        map.get(ns_name.as_ref()).cloned()
1940    };
1941    let ns = ns.ok_or_else(|| EvalError::Runtime(format!("No namespace: {ns_name} found")))?;
1942    let var = if arg_forms.len() == 3 {
1943        // Under no-gc: interned Var values live in the StaticArena since they
1944        // are namespace-scoped and outlive all scratch regions.
1945        #[cfg(feature = "no-gc")]
1946        let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1947        let val = eval(&arg_forms[2], env)?;
1948        let mut interns = ns.get().interns.lock().unwrap();
1949        if let Some(var) = interns.get(&var_name) {
1950            var.get().bind(val);
1951            var.clone()
1952        } else {
1953            let var =
1954                cljrs_gc::GcPtr::new(cljrs_value::Var::new(ns_name.clone(), var_name.clone()));
1955            var.get().bind(val);
1956            interns.insert(var_name, var.clone());
1957            var
1958        }
1959    } else {
1960        let mut interns = ns.get().interns.lock().unwrap();
1961        if let Some(var) = interns.get(&var_name) {
1962            var.clone()
1963        } else {
1964            let var =
1965                cljrs_gc::GcPtr::new(cljrs_value::Var::new(ns_name.clone(), var_name.clone()));
1966            interns.insert(var_name, var.clone());
1967            var
1968        }
1969    };
1970    Ok(Value::Var(var))
1971}
1972
1973// ── bound-fn* ────────────────────────────────────────────────────────────────
1974
1975/// `(bound-fn* f)` — capture current dynamic bindings and wrap `f` so that
1976/// when the wrapper is called, those bindings are installed.
1977fn handle_bound_fn_star(arg_forms: &[Form], env: &mut Env) -> EvalResult {
1978    if arg_forms.len() != 1 {
1979        return Err(EvalError::Arity {
1980            name: "bound-fn*".into(),
1981            expected: "1".into(),
1982            got: arg_forms.len(),
1983        });
1984    }
1985    let f = eval(&arg_forms[0], env)?;
1986    // Merge all binding frames into a single flat frame (bottom-up so inner wins)
1987    let frames = crate::env::dynamics::capture_current();
1988    let mut merged = std::collections::HashMap::new();
1989    for frame in &frames {
1990        merged.extend(frame.iter().map(|(k, v)| (*k, v.clone())));
1991    }
1992    Ok(Value::BoundFn(cljrs_gc::GcPtr::new(cljrs_value::BoundFn {
1993        wrapped: f,
1994        captured_bindings: merged,
1995    })))
1996}