Skip to main content

cljrs_runtime/interp/
special.rs

1//! Special form evaluators.
2
3use std::collections::{HashMap, HashSet};
4use std::sync::Arc;
5
6use crate::builtins::form::{
7    expand_pairs, expand_reader_conds, expand_reader_conds_cow, form_to_value, resolve_auto_forms,
8    select_reader_cond,
9};
10use crate::env::env::{Env, RequireRefer, RequireSpec};
11use crate::env::error::{EvalError, EvalResult};
12use crate::env::loader::load_ns;
13use crate::interp::destructure::bind_pattern;
14use crate::interp::eval::{eval, eval_body, is_special_form};
15use cljrs_gc::GcPtr;
16use cljrs_reader::Form;
17use cljrs_reader::form::FormKind;
18use cljrs_value::error::ExceptionInfo;
19use cljrs_value::{
20    CljxFn, CljxFnArity, CljxFuture, FutureState, Keyword, MapValue, Protocol, ProtocolMethod,
21    ReferClojureFilter, TypeHint, Value, ValueError,
22};
23
24/// Dispatch to the right special-form handler.
25pub fn eval_special(head: &str, args: &[Form], env: &mut Env) -> EvalResult {
26    crate::env::policy::check_special(head)?;
27    match head {
28        "def" => eval_def(args, env),
29        "fn*" | "fn" => eval_fn(args, env),
30        "if" => eval_if(args, env),
31        "do" => eval_body(args, env),
32        "let*" | "let" => eval_let(args, env),
33        "loop*" | "loop" => eval_loop(args, env),
34        "recur" => eval_recur(args, env),
35        "quote" => eval_quote(args, env),
36        "var" => eval_var(args, env),
37        "set!" => eval_set_bang(args, env),
38        "throw" => eval_throw(args, env),
39        "try" => eval_try(args, env),
40        "defn" => eval_defn(args, env, false),
41        "defn-" => eval_defn(args, env, true),
42        "defmacro" => eval_defmacro(args, env),
43        "defonce" => eval_defonce(args, env),
44        "and" => eval_and(args, env),
45        "or" => eval_or(args, env),
46        "." => Err(EvalError::Runtime("interop not yet implemented".into())),
47        "ns" => eval_ns(args, env),
48        "require" => eval_require(args, env),
49        "letfn" => eval_letfn(args, env),
50        "in-ns" => eval_in_ns(args, env),
51        "alias" => eval_alias(args, env),
52        "protocol*" => eval_protocol_star(args, env),
53        "deftype*" => eval_deftype_star(args, env),
54        "load-file" => eval_load_file(args, env),
55        "binding" => eval_binding(args, env),
56        "with-out-str" => eval_with_out_str(args, env),
57        "await" => eval_await(args, env),
58        _ => unreachable!("unknown special form: {head}"),
59    }
60}
61
62// ── def ───────────────────────────────────────────────────────────────────────
63
64fn eval_def(args: &[Form], env: &mut Env) -> EvalResult {
65    let target = parse_def(args, env)?;
66    let val = match target.value_form {
67        Some(form) => {
68            // Under no-gc: def value expressions go to the StaticArena since the
69            // Var must outlive all scratch regions.
70            #[cfg(feature = "no-gc")]
71            let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
72            eval(form, env)?
73        }
74        None => Value::Nil,
75    };
76    intern_def(target, val, env)
77}
78
79/// A parsed `(def name "doc"? value?)`: everything but the value itself.
80///
81/// Public, together with [`parse_def`] and [`intern_def`], so the async
82/// evaluator (`cljrs-async`) can evaluate `value_form` with a yielding
83/// evaluator and still share the rest of `def`.
84pub struct DefTarget<'a> {
85    pub name: String,
86    /// Metadata from `^meta` on the name and the docstring, merged.
87    pub meta: Option<Value>,
88    /// The value expression; `None` for `(def name)`.
89    pub value_form: Option<&'a Form>,
90}
91
92/// Parse the name, metadata and docstring of a `def` without evaluating its
93/// value expression. `^{...}` metadata on the name *is* evaluated here.
94pub fn parse_def<'a>(args: &'a [Form], env: &mut Env) -> EvalResult<DefTarget<'a>> {
95    if args.is_empty() {
96        return Err(EvalError::Runtime("def requires a name".into()));
97    }
98    let (name, meta_opt) = extract_def_name(&args[0], env)?;
99    // Optional docstring: (def name "docstring" value)
100    let (docstring, val_idx) = if args.len() > 2
101        && let FormKind::Str(s) = &args[1].kind
102    {
103        (Some(s.clone()), 2)
104    } else {
105        (None, 1)
106    };
107    Ok(DefTarget {
108        name,
109        meta: merge_meta(meta_opt, docstring.as_deref().map(doc_meta)),
110        value_form: args.get(val_idx),
111    })
112}
113
114/// Intern `val` under a parsed `def` target in the current namespace.
115pub fn intern_def(target: DefTarget<'_>, val: Value, env: &mut Env) -> EvalResult {
116    let var = env
117        .globals
118        .intern(&env.current_ns, Arc::from(target.name.as_str()), val);
119    if let Some(meta_val) = target.meta {
120        var.get().set_meta(meta_val);
121    }
122    Ok(Value::Var(var))
123}
124
125/// The already-bound var a `defonce` named `name` would leave untouched, if
126/// any.
127pub fn defonce_existing(name: &str, env: &Env) -> Option<Value> {
128    env.globals
129        .lookup_var(&env.current_ns, name)
130        .filter(|var| var.get().is_bound())
131        .map(Value::Var)
132}
133
134/// Build a `{:doc "..."}` metadata map fragment for a docstring.
135fn doc_meta(doc: &str) -> Value {
136    Value::Map(MapValue::empty().assoc(
137        Value::keyword(Keyword::parse("doc")),
138        Value::string(doc.to_string()),
139    ))
140}
141
142fn private_meta() -> Value {
143    Value::Map(
144        MapValue::empty().assoc(Value::keyword(Keyword::parse("private")), Value::Bool(true)),
145    )
146}
147
148/// Build a `{:arglists ([x] [x y & more])}` metadata fragment from a
149/// `Value::Fn`/`Value::Macro`'s parsed arities. `skip` elides leading fixed
150/// params that aren't part of the public signature (defmacro's implicit
151/// `&form`/`&env`).
152fn arglists_meta(fn_val: &Value, skip: usize) -> Option<Value> {
153    let arities = match fn_val {
154        Value::Fn(f) => &f.get().arities,
155        Value::Macro(f) => &f.get().arities,
156        _ => return None,
157    };
158    let lists: Vec<Value> = arities
159        .iter()
160        .map(|a| {
161            let mut syms: Vec<Value> = a
162                .params
163                .iter()
164                .skip(skip)
165                .map(|p| Value::symbol(cljrs_value::Symbol::simple(p.as_ref())))
166                .collect();
167            if let Some(rest) = &a.rest_param {
168                syms.push(Value::symbol(cljrs_value::Symbol::simple("&")));
169                syms.push(Value::symbol(cljrs_value::Symbol::simple(rest.as_ref())));
170            }
171            Value::Vector(GcPtr::new(cljrs_value::PersistentVector::from_iter(syms)))
172        })
173        .collect();
174    Some(Value::Map(MapValue::empty().assoc(
175        Value::keyword(Keyword::parse("arglists")),
176        Value::Vector(GcPtr::new(cljrs_value::PersistentVector::from_iter(lists))),
177    )))
178}
179
180/// Extract the def name and optional metadata from the name form.
181fn extract_def_name(form: &Form, env: &mut Env) -> EvalResult<(String, Option<Value>)> {
182    match &form.kind {
183        FormKind::Symbol(s) => Ok((s.clone(), None)),
184        // `^:a ^:b x` nests `Meta` forms; unwrap all, outer mark winning.
185        FormKind::Meta(meta_form, inner) => {
186            let meta_val = compile_meta_form(meta_form, env)?;
187            let (name, inner_meta) = extract_def_name(inner, env)?;
188            Ok((name, merge_meta(inner_meta, Some(meta_val))))
189        }
190        _ => Err(EvalError::Runtime("def name must be a symbol".into())),
191    }
192}
193
194/// Expand a metadata shorthand form into a map value, evaluating the general
195/// case (`^{:x (+ 1 2)}` → `{:x 3}`).
196///
197/// The shorthand table itself lives in [`crate::builtins::form`] and is shared
198/// with the quoted position, which differs only in resolving that general case
199/// as data instead.
200pub fn compile_meta_form(meta: &Form, env: &mut Env) -> EvalResult<Value> {
201    crate::builtins::form::expand_meta_annotation(meta, &mut |f| eval(f, env))
202}
203
204// ── fn* ───────────────────────────────────────────────────────────────────────
205
206fn eval_fn(args: &[Form], env: &mut Env) -> EvalResult {
207    // `:async` may be requested on the first argument, `(fn ^:async [..] ..)`
208    // / `(fn ^:async name [..] ..)`, or on the params vector after a name,
209    // `(fn name ^:async [..] ..)` (also how `defn name ^:async [..]` arrives).
210    let is_async = Form::fn_args_request_async(args);
211    // Peel any leading `^meta` wrappers off the first argument.
212    let peeled: Vec<Form>;
213    let args: &[Form] = if matches!(args.first().map(|f| &f.kind), Some(FormKind::Meta(..))) {
214        let (_, head) = args[0].peel_meta();
215        peeled = std::iter::once(head.clone())
216            .chain(args[1..].iter().cloned())
217            .collect();
218        &peeled
219    } else {
220        args
221    };
222
223    let mut idx = 0;
224    let mut name: Option<Arc<str>> = None;
225
226    // Optional name.
227    if let Some(FormKind::Symbol(s)) = args.first().map(|f| &f.kind)
228        && !is_special_form(s)
229    {
230        name = Some(Arc::from(s.as_str()));
231        idx = 1;
232    }
233
234    let rest = &args[idx..];
235    if rest.is_empty() {
236        return Err(EvalError::Runtime("fn* requires params and body".into()));
237    }
238
239    // A `^hint` on the params vector or on an arity clause is advisory — the
240    // structural shape is the form underneath it.
241    let arities = match &rest[0].unmeta().kind {
242        FormKind::Vector(_) => {
243            // Single arity: (fn* [params] body...)
244            vec![parse_arity(&rest[0], &rest[1..])?]
245        }
246        FormKind::List(_) => {
247            // Multi-arity: (fn* ([params] body...) ...)
248            rest.iter()
249                .map(|arity_form| {
250                    if let Some(forms) = arity_form.as_list() {
251                        if forms.is_empty() {
252                            return Err(EvalError::Runtime("arity clause requires params".into()));
253                        }
254                        parse_arity(&forms[0], &forms[1..])
255                    } else {
256                        Err(EvalError::Runtime("expected arity clause (list)".into()))
257                    }
258                })
259                .collect::<EvalResult<Vec<_>>>()?
260        }
261        _ => {
262            return Err(EvalError::Runtime(
263                "fn* expects vector or arity clauses".into(),
264            ));
265        }
266    };
267
268    // Capture closed-over locals.
269    let (closed_over_names, closed_over_vals) = env.all_local_bindings();
270
271    let mut cljrs_fn = CljxFn::new(
272        name.clone(),
273        arities,
274        closed_over_names,
275        closed_over_vals,
276        false,
277        Arc::clone(&env.current_ns),
278    );
279    cljrs_fn.is_async = is_async;
280
281    env.on_fn_defined(&cljrs_fn);
282
283    // Eagerly lower each arity to IR if the compiler is ready.
284    //eager_lower_fn(&cljrs_fn, env);
285
286    let mut ptr = GcPtr::new(cljrs_fn);
287    // For named anonymous functions (fn g ...), store a back-pointer so that
288    // the self-reference returned from the body is pointer-equal to the outer
289    // binding — required for `(= f (f))` to be `true`.
290    if ptr.get().name.is_some() {
291        let self_clone = ptr.clone();
292        ptr.get_mut().self_ptr = Some(self_clone);
293    }
294    Ok(Value::Fn(ptr))
295}
296
297/// Parse one arity: params-form and body forms.
298pub fn parse_arity(params_form: &Form, body: &[Form]) -> EvalResult<CljxFnArity> {
299    let Some(param_forms) = params_form.as_vector() else {
300        return Err(EvalError::Runtime(
301            "fn arity params must be a vector".into(),
302        ));
303    };
304
305    let mut params: Vec<Arc<str>> = Vec::new();
306    let mut param_hints: Vec<Option<TypeHint>> = Vec::new();
307    let mut rest_param: Option<Arc<str>> = None;
308    let mut rest_hint: Option<TypeHint> = None;
309    let mut destructure_params: Vec<(usize, Form)> = Vec::new();
310    let mut destructure_rest: Option<Form> = None;
311    let mut saw_amp = false;
312
313    for p in param_forms {
314        // Peel a leading `^hint` (e.g. `^long x`, `^doubles a`) from the param,
315        // resolving the `:tag` to a primitive `TypeHint`.  Unknown / non-primitive
316        // tags resolve to `None` and are simply ignored (Clojure treats them as
317        // advisory).  The unwrapped form keeps the existing symbol/destructure
318        // handling unchanged.
319        let (hint, p) = peel_param_hint(p);
320        match &p.kind {
321            FormKind::Symbol(s) if s == "&" => {
322                saw_amp = true;
323            }
324            FormKind::Symbol(s) => {
325                if saw_amp {
326                    rest_param = Some(Arc::from(s.as_str()));
327                    rest_hint = hint;
328                    break;
329                } else {
330                    params.push(Arc::from(s.as_str()));
331                    param_hints.push(hint);
332                }
333            }
334            // Destructuring patterns: vectors and maps
335            FormKind::Vector(_) | FormKind::Map(_) => {
336                if saw_amp {
337                    let gensym = format!("__destructure_rest_{}", params.len());
338                    rest_param = Some(Arc::from(gensym.as_str()));
339                    destructure_rest = Some(p.clone());
340                    break;
341                } else {
342                    let idx = params.len();
343                    let gensym = format!("__destructure_{idx}");
344                    params.push(Arc::from(gensym.as_str()));
345                    // Destructured params can't be primitive-tagged.
346                    param_hints.push(None);
347                    destructure_params.push((idx, p.clone()));
348                }
349            }
350            _ => {
351                return Err(EvalError::Runtime(
352                    "fn params must be symbols, vectors, or maps".into(),
353                ));
354            }
355        }
356    }
357
358    let body = desugar_pre_post_conditions(body);
359
360    Ok(CljxFnArity {
361        params,
362        rest_param,
363        body,
364        destructure_params,
365        destructure_rest,
366        ir_arity_id: crate::interp::arity::fresh_arity_id(),
367        param_hints,
368        rest_hint,
369    })
370}
371
372/// Desugar a `:pre`/`:post` conditions map at the head of a function body.
373///
374/// Clojure binds `%` to the return value inside `:post` conditions. This
375/// transforms the raw body forms into equivalent assertion code so the
376/// interpreter does not need to handle conditions separately at call time.
377///
378/// Input body (simplified):
379/// ```text
380/// [{:pre [(pos? x)] :post [(pos? %)]} (inc x)]
381/// ```
382/// Output body:
383/// ```text
384/// [(assert (pos? x))
385///  (let* [% (inc x)]
386///    (assert (pos? %))
387///    %)]
388/// ```
389fn desugar_pre_post_conditions(body: &[Form]) -> Vec<Form> {
390    let first = match body.first() {
391        Some(f) => f,
392        None => return body.to_vec(),
393    };
394
395    let entries = match first.as_map() {
396        Some(entries) => entries,
397        None => return body.to_vec(),
398    };
399
400    let mut pre_conds: Vec<Form> = Vec::new();
401    let mut post_conds: Vec<Form> = Vec::new();
402    let mut has_conditions = false;
403
404    for chunk in entries.chunks(2) {
405        if chunk.len() < 2 {
406            break;
407        }
408        let (key, val) = (&chunk[0], &chunk[1]);
409        match &key.kind {
410            FormKind::Keyword(k) if k == "pre" => {
411                if let FormKind::Vector(conds) = &val.kind {
412                    pre_conds.extend_from_slice(conds);
413                    has_conditions = true;
414                }
415            }
416            FormKind::Keyword(k) if k == "post" => {
417                if let FormKind::Vector(conds) = &val.kind {
418                    post_conds.extend_from_slice(conds);
419                    has_conditions = true;
420                }
421            }
422            _ => {}
423        }
424    }
425
426    if !has_conditions {
427        return body.to_vec();
428    }
429
430    let real_body = &body[1..]; // strip the conditions map
431    let span = first.span.clone();
432    let mut new_body: Vec<Form> = Vec::new();
433
434    // Emit (assert cond) for each :pre condition.
435    for cond in &pre_conds {
436        new_body.push(make_assert_call(cond, &span));
437    }
438
439    if post_conds.is_empty() {
440        new_body.extend_from_slice(real_body);
441    } else {
442        // Wrap real body in (let* [% <body>] (assert post-cond)... %)
443        // so that % refers to the return value inside :post conditions.
444        let percent = Form::new(FormKind::Symbol("%".to_string()), span.clone());
445
446        let body_expr = if real_body.len() == 1 {
447            real_body[0].clone()
448        } else {
449            let mut do_forms = vec![Form::new(FormKind::Symbol("do".to_string()), span.clone())];
450            do_forms.extend_from_slice(real_body);
451            Form::new(FormKind::List(do_forms), span.clone())
452        };
453
454        let binding_vec = Form::new(
455            FormKind::Vector(vec![percent.clone(), body_expr]),
456            span.clone(),
457        );
458
459        let mut let_forms = vec![
460            Form::new(FormKind::Symbol("let*".to_string()), span.clone()),
461            binding_vec,
462        ];
463        for cond in &post_conds {
464            let_forms.push(make_assert_call(cond, &span));
465        }
466        let_forms.push(percent);
467
468        new_body.push(Form::new(FormKind::List(let_forms), span));
469    }
470
471    new_body
472}
473
474/// Build `(assert <cond>)` as a Form node.
475fn make_assert_call(cond: &Form, span: &cljrs_types::span::Span) -> Form {
476    Form::new(
477        FormKind::List(vec![
478            Form::new(FormKind::Symbol("assert".to_string()), span.clone()),
479            cond.clone(),
480        ]),
481        span.clone(),
482    )
483}
484
485/// Peel a `^hint` wrapper off a parameter form, returning the resolved
486/// primitive [`TypeHint`] (if the tag is a recognized primitive) together with
487/// the unwrapped inner form.  A param with no metadata returns `(None, form)`.
488fn peel_param_hint(p: &Form) -> (Option<TypeHint>, &Form) {
489    if let FormKind::Meta(meta, inner) = &p.kind {
490        let hint = tag_name_of_meta(meta).and_then(|n| TypeHint::from_tag(&n));
491        // Recurse in case of stacked metadata; the innermost form is the param.
492        let (inner_hint, inner_form) = peel_param_hint(inner);
493        (hint.or(inner_hint), inner_form)
494    } else {
495        (None, p)
496    }
497}
498
499/// Extract the bare tag name from a `^meta` form: `^long` (symbol shorthand) or
500/// `^{:tag long}` (explicit map).  Strips any namespace from the tag symbol.
501fn tag_name_of_meta(meta: &Form) -> Option<Arc<str>> {
502    match &meta.kind {
503        // `^long x` — the metadata is a bare symbol naming the tag.
504        FormKind::Symbol(s) => Some(strip_tag_ns(s)),
505        // `^{:tag long} x` — pull the `:tag` entry out of the map literal.
506        FormKind::Map(entries) => entries.chunks(2).find_map(|kv| {
507            let is_tag = matches!(&kv[0].kind, FormKind::Keyword(k) if k == "tag");
508            if !is_tag {
509                return None;
510            }
511            match kv.get(1).map(|f| &f.kind) {
512                Some(FormKind::Symbol(s)) => Some(strip_tag_ns(s)),
513                Some(FormKind::Str(s)) => Some(strip_tag_ns(s)),
514                _ => None,
515            }
516        }),
517        _ => None,
518    }
519}
520
521/// Strip a namespace prefix from a tag name (`clojure.core/long` → `long`).
522fn strip_tag_ns(s: &str) -> Arc<str> {
523    match s.rfind('/') {
524        Some(pos) if pos + 1 < s.len() => Arc::from(&s[pos + 1..]),
525        _ => Arc::from(s),
526    }
527}
528
529// ── if ────────────────────────────────────────────────────────────────────────
530
531fn eval_if(args: &[Form], env: &mut Env) -> EvalResult {
532    if args.is_empty() {
533        return Err(EvalError::Runtime("if requires a test".into()));
534    }
535    let test = eval(&args[0], env)?;
536    let truthy = !matches!(test, Value::Nil | Value::Bool(false));
537    if truthy {
538        if args.len() > 1 {
539            eval(&args[1], env)
540        } else {
541            Ok(Value::Nil)
542        }
543    } else if args.len() > 2 {
544        eval(&args[2], env)
545    } else {
546        Ok(Value::Nil)
547    }
548}
549
550// ── let* ──────────────────────────────────────────────────────────────────────
551
552fn eval_let(args: &[Form], env: &mut Env) -> EvalResult {
553    let bindings = match args.first().and_then(|f| f.as_vector()) {
554        Some(v) => expand_pairs(v)
555            .map_err(|_| EvalError::Runtime("let* binding vector must have even length".into()))?
556            .into_owned(),
557        None => return Err(EvalError::Runtime("let* requires a binding vector".into())),
558    };
559
560    let body = &args[1..];
561
562    // Detect assoc/conj chains that can be virtualized.
563    let chains = crate::interp::virtualize::detect_let_chains(&bindings);
564    let virtualizable_chains = find_virtualizable_chains(&chains, &bindings, body);
565
566    env.push_frame();
567
568    let pairs: Vec<_> = bindings.chunks(2).collect();
569    let mut i = 0;
570    while i < pairs.len() {
571        // Check if this binding starts a virtualizable chain.
572        if let Some(chain) = virtualizable_chains.iter().find(|c| c.start == i) {
573            match eval_virtualized_chain(chain, &pairs, env) {
574                Ok(()) => {
575                    i += chain.len;
576                    continue;
577                }
578                Err(e) => {
579                    env.pop_frame();
580                    return Err(e);
581                }
582            }
583        }
584
585        // Normal evaluation.
586        let pair = pairs[i];
587        let val = match eval(&pair[1], env) {
588            Ok(v) => v,
589            Err(e) => {
590                env.pop_frame();
591                return Err(e);
592            }
593        };
594        if let Err(e) = bind_pattern(&pair[0], val, env) {
595            env.pop_frame();
596            return Err(e);
597        }
598        i += 1;
599    }
600
601    let result = eval_body(body, env);
602    env.pop_frame();
603    result
604}
605
606/// Filter chains to only those that are safe to virtualize.
607///
608/// A chain is safe if no intermediate binding is used outside the chain
609/// (i.e., it's only used as the collection argument of the next step).
610fn find_virtualizable_chains<'a>(
611    chains: &'a [crate::interp::virtualize::LetChain],
612    bindings: &[Form],
613    body: &[Form],
614) -> Vec<&'a crate::interp::virtualize::LetChain> {
615    chains
616        .iter()
617        .filter(|chain| {
618            // Check that no intermediate (all except the last) is used in body
619            // or in other bindings outside the chain.
620            for j in chain.start..(chain.start + chain.len - 1) {
621                let name = match &bindings[j * 2].kind {
622                    FormKind::Symbol(s) => s.as_str(),
623                    _ => return false,
624                };
625                if crate::interp::virtualize::binding_used_in_body(name, body) {
626                    return false;
627                }
628                if crate::interp::virtualize::binding_used_in_other_bindings(
629                    name,
630                    bindings,
631                    chain.start,
632                    chain.len,
633                ) {
634                    return false;
635                }
636            }
637            true
638        })
639        .collect()
640}
641
642/// Evaluate an assoc/conj chain using transient operations.
643///
644/// Instead of creating N intermediate persistent collections, we:
645/// 1. Evaluate the root collection (first arg of the first assoc/conj)
646/// 2. Convert to transient
647/// 3. Apply each assoc!/conj! mutably
648/// 4. Convert back to persistent
649/// 5. Bind only the final name (and intermediate names point to intermediate
650///    transient values for correctness, though they shouldn't be used).
651fn eval_virtualized_chain(
652    chain: &crate::interp::virtualize::LetChain,
653    pairs: &[&[Form]],
654    env: &mut Env,
655) -> Result<(), EvalError> {
656    use crate::builtins::transients::{
657        builtin_assoc_bang, builtin_conj_bang, builtin_persistent_bang, builtin_transient,
658    };
659
660    // Step 1: Evaluate the root collection (first arg of the first call).
661    let first_pair = pairs[chain.start];
662    let first_expr_forms = match &first_pair[1].kind {
663        FormKind::List(forms) => forms,
664        _ => unreachable!("chain detection ensures this is a list"),
665    };
666    let root_collection = eval(&first_expr_forms[1], env)?;
667
668    // Step 2: Convert to transient.
669    let mut transient = match builtin_transient(std::slice::from_ref(&root_collection)) {
670        Ok(t) => t,
671        Err(_) => {
672            // Collection doesn't support transients (e.g., sorted map).
673            // Fall back to normal evaluation for the whole chain.
674            return eval_chain_normally(chain, pairs, env);
675        }
676    };
677
678    // Step 3: Apply each chain operation using transient mutation.
679    for j in 0..chain.len {
680        let pair_idx = chain.start + j;
681        let pair = pairs[pair_idx];
682        let expr_forms = match &pair[1].kind {
683            FormKind::List(forms) => forms,
684            _ => unreachable!(),
685        };
686
687        // Evaluate the non-collection arguments.
688        let mut args = vec![transient.clone()];
689        for arg_form in expr_forms.iter().skip(2) {
690            args.push(eval(arg_form, env)?);
691        }
692
693        // Apply the transient operation.
694        transient = match chain.ops[j] {
695            crate::interp::virtualize::ChainOpKind::Assoc => {
696                builtin_assoc_bang(&args).map_err(|e| EvalError::Runtime(e.to_string()))?
697            }
698            crate::interp::virtualize::ChainOpKind::Conj => {
699                builtin_conj_bang(&args).map_err(|e| EvalError::Runtime(e.to_string()))?
700            }
701        };
702
703        // Bind intermediate names to a placeholder (they shouldn't be used,
704        // but we need them in the env for structural correctness).
705        // Only the last binding gets the persistent result.
706        if j < chain.len - 1 {
707            let name = match &pair[0].kind {
708                FormKind::Symbol(s) => s.clone(),
709                _ => unreachable!(),
710            };
711            // Bind to nil as placeholder — intermediates are verified as unused.
712            env.bind(Arc::from(name.as_str()), Value::Nil);
713        }
714    }
715
716    // Step 4: Convert back to persistent.
717    let persistent =
718        builtin_persistent_bang(&[transient]).map_err(|e| EvalError::Runtime(e.to_string()))?;
719
720    // Step 5: Bind the final name.
721    let last_pair = pairs[chain.start + chain.len - 1];
722    bind_pattern(&last_pair[0], persistent, env)?;
723
724    Ok(())
725}
726
727/// Fallback: evaluate a chain using normal persistent operations.
728fn eval_chain_normally(
729    chain: &crate::interp::virtualize::LetChain,
730    pairs: &[&[Form]],
731    env: &mut Env,
732) -> Result<(), EvalError> {
733    for j in 0..chain.len {
734        let pair_idx = chain.start + j;
735        let pair = pairs[pair_idx];
736        let val = eval(&pair[1], env)?;
737        bind_pattern(&pair[0], val, env)?;
738    }
739    Ok(())
740}
741
742// ── loop* / recur ─────────────────────────────────────────────────────────────
743
744pub fn eval_loop(args: &[Form], env: &mut Env) -> EvalResult {
745    let bindings = match args.first().and_then(|f| f.as_vector()) {
746        Some(v) => expand_pairs(v)
747            .map_err(|_| EvalError::Runtime("loop* binding vector must have even length".into()))?
748            .into_owned(),
749        None => return Err(EvalError::Runtime("loop* requires a binding vector".into())),
750    };
751
752    let body = &args[1..];
753
754    // Separate pattern forms and initial values.
755    let patterns: Vec<Form> = bindings.iter().step_by(2).cloned().collect();
756    let mut current_vals: Vec<Value> = Vec::new();
757
758    // Evaluate initial values.
759    for i in (1..bindings.len()).step_by(2) {
760        current_vals.push(eval(&bindings[i], env)?);
761    }
762
763    loop {
764        // Root current_vals so they survive GC — they're not yet bound in env.
765        let _vals_root = crate::env::gc_roots::root_values(&current_vals);
766
767        // GC safepoint on every loop iteration so tight recur loops
768        // don't starve the collector.
769        crate::env::gc_roots::gc_safepoint(env);
770
771        // Under no-gc: push a fresh scratch region for this iteration.
772        // Intermediates allocated in the body land here and are freed
773        // after the iteration ends.
774        #[cfg(feature = "no-gc")]
775        let mut scratch = cljrs_gc::alloc_ctx::ScratchGuard::new();
776
777        // Under GC: scope this iteration's heap allocations in a fresh alloc
778        // frame.  Every value the body allocates is rooted (via ALLOC_ROOTS)
779        // only until this frame drops at the end of the iteration; the
780        // intermediates — and the previous iteration's now-dead recur values —
781        // then become collectable, instead of being pinned for the lifetime of
782        // the enclosing top-level form.  `result` (the return value or recur
783        // values) is moved out before the frame drops and is re-rooted at the
784        // top of the next iteration (`root_values`) or by the caller during
785        // return unwinding; no GC safepoint runs in the interval, exactly as
786        // the IR/JIT dispatch seam relies on (see `crate::tiered::apply`).
787        #[cfg(not(feature = "no-gc"))]
788        let _iter_frame = cljrs_gc::push_alloc_frame();
789
790        env.push_frame();
791        for (pat, val) in patterns.iter().zip(current_vals.iter()) {
792            if let Err(e) = bind_pattern(pat, val.clone(), env) {
793                env.pop_frame();
794                return Err(e);
795            }
796        }
797
798        // Under no-gc: pop scratch before tail expression so the return value
799        // or recur args are allocated in the enclosing scope's context.
800        #[cfg(not(feature = "no-gc"))]
801        let result = eval_body_recur(body, env);
802        #[cfg(feature = "no-gc")]
803        let result = eval_body_with_scratch_loop(body, &mut scratch, env);
804
805        env.pop_frame();
806        // scratch / _iter_frame drop at the end of the iteration (after the
807        // match below), freeing this iteration's intermediates.
808
809        match result {
810            Ok(v) => return Ok(v),
811            Err(EvalError::Recur(new_vals)) => {
812                if new_vals.len() != patterns.len() {
813                    return Err(EvalError::Arity {
814                        name: "recur".into(),
815                        expected: patterns.len().to_string(),
816                        got: new_vals.len(),
817                    });
818                }
819                // new_vals were evaluated in the caller's context (scratch was
820                // popped before the tail form), so they survive the reset.
821                current_vals = new_vals;
822            }
823            Err(e) => return Err(e),
824        }
825    }
826}
827
828fn eval_recur(args: &[Form], env: &mut Env) -> EvalResult {
829    let vals: Vec<Value> = args
830        .iter()
831        .map(|f| eval(f, env))
832        .collect::<EvalResult<_>>()?;
833    Err(EvalError::Recur(vals))
834}
835
836/// Eval body forms, propagating Recur without catching it.
837pub fn eval_body_recur(body: &[Form], env: &mut Env) -> EvalResult {
838    let mut result = Value::Nil;
839    for form in body {
840        result = eval(form, env)?;
841    }
842    Ok(result)
843}
844
845/// Under `no-gc`: eval loop body with scratch-region semantics.
846///
847/// Evaluates all non-tail forms inside the scratch region, then pops the
848/// scratch before the tail (return/recur) expression so it lands in the
849/// caller's context.
850#[cfg(feature = "no-gc")]
851fn eval_body_with_scratch_loop(
852    body: &[Form],
853    scratch: &mut cljrs_gc::alloc_ctx::ScratchGuard,
854    env: &mut Env,
855) -> EvalResult {
856    if body.is_empty() {
857        scratch.pop_for_return();
858        return Ok(Value::Nil);
859    }
860    for form in &body[..body.len() - 1] {
861        eval(form, env)?;
862    }
863    scratch.pop_for_return();
864    eval(&body[body.len() - 1], env)
865}
866
867// ── quote ─────────────────────────────────────────────────────────────────────
868
869fn eval_quote(args: &[Form], env: &Env) -> EvalResult {
870    match args.first() {
871        // `::kw` and an auto-resolved map's symbol keys resolve against the
872        // reading namespace even under quote - the JVM resolves them at read
873        // time, before quote can see them.
874        Some(f) => form_to_value(&resolve_auto_forms(f, env)?),
875        None => Err(EvalError::Runtime("quote requires an argument".into())),
876    }
877}
878
879// ── var ───────────────────────────────────────────────────────────────────────
880
881fn eval_var(args: &[Form], env: &mut Env) -> EvalResult {
882    let sym = match args.first().map(|f| &f.kind) {
883        Some(FormKind::Symbol(s)) => s.clone(),
884        _ => return Err(EvalError::Runtime("var requires a symbol".into())),
885    };
886    let parsed = cljrs_value::Symbol::parse(&sym);
887    let ns: Arc<str> = env.resolve_ns_or_current(parsed.namespace.as_deref());
888    let name = parsed.name.as_ref();
889    env.globals
890        .lookup_var_in_ns(&ns, name)
891        .map(Value::Var)
892        .ok_or_else(|| EvalError::UnboundSymbol(sym))
893}
894
895// ── set! ──────────────────────────────────────────────────────────────────────
896
897fn eval_set_bang(args: &[Form], env: &mut Env) -> EvalResult {
898    let target = args
899        .first()
900        .ok_or_else(|| EvalError::Runtime("set! requires a target".into()))?;
901    let val = if args.len() > 1 {
902        eval(&args[1], env)?
903    } else {
904        Value::Nil
905    };
906    match &target.kind {
907        FormKind::Symbol(sym) => set_bang_symbol(sym, val, env),
908        _ => match set_bang_field_target(target) {
909            Some((field, inst_form)) => {
910                let inst = eval(inst_form, env)?;
911                set_type_instance_field(&inst, field, val)
912            }
913            None => Err(set_bang_target_error()),
914        },
915    }
916}
917
918/// `(set! sym val)` for an already-evaluated `val`: a mutable deftype field in
919/// scope, else the thread-local binding of the var `sym` names, else its root.
920pub fn set_bang_symbol(sym: &str, val: Value, env: &mut Env) -> EvalResult {
921    // A bare unqualified name inside a deftype method may be one of its
922    // mutable fields; only if not does it fall through to var logic.
923    if !sym.contains('/')
924        && let Some(v) = try_set_mutable_field(env, sym, &val)?
925    {
926        return Ok(v);
927    }
928    let parsed = cljrs_value::Symbol::parse(sym);
929    let ns = parsed.namespace.as_deref().unwrap_or(&env.current_ns);
930    let var = env
931        .globals
932        .lookup_var_in_ns(ns, &parsed.name)
933        .ok_or_else(|| EvalError::UnboundSymbol(sym.to_string()))?;
934    // Prefer updating the thread-local binding if one exists.
935    if !crate::env::dynamics::set_thread_local(&var, val.clone()) {
936        var.get().bind(val.clone());
937    }
938    Ok(val)
939}
940
941/// For a `(set! (.-field inst) v)` target, the field name and the `inst`
942/// form; `None` for any other non-symbol target.
943pub fn set_bang_field_target(target: &Form) -> Option<(&str, &Form)> {
944    match &target.kind {
945        FormKind::List(parts) if parts.len() == 2 => match &parts[0].kind {
946            FormKind::Symbol(op) if op.starts_with(".-") => Some((&op[2..], &parts[1])),
947            _ => None,
948        },
949        _ => None,
950    }
951}
952
953/// The error for a `set!` target that is neither a symbol nor `(.-field inst)`.
954pub fn set_bang_target_error() -> EvalError {
955    EvalError::Runtime("set! requires a symbol or (.-field inst) target".into())
956}
957
958/// If `sym` names a mutable field of the `__deftype_self__` instance in scope,
959/// update its cell AND refresh the in-scope local snapshot, returning the new
960/// value. `None` when `sym` is not such a field, so `set!` falls through to var
961/// logic.
962fn try_set_mutable_field(env: &mut Env, sym: &str, val: &Value) -> EvalResult<Option<Value>> {
963    let Some(Value::TypeInstance(ti)) = env.lookup_local_frames(DEFTYPE_SELF) else {
964        return Ok(None);
965    };
966    let Some(atom) = ti.get().mutable.clone() else {
967        return Ok(None);
968    };
969    let key = Value::keyword(cljrs_value::Keyword::simple(sym));
970    let Value::Map(map) = atom.get().deref() else {
971        return Ok(None);
972    };
973    if map.get(&key).is_none() {
974        return Ok(None);
975    }
976    atom.get().reset(Value::Map(map.assoc(key, val.clone())));
977    // Keep the method's local snapshot consistent for later reads.
978    env.bind(Arc::from(sym), val.clone());
979    Ok(Some(val.clone()))
980}
981
982/// Set a mutable field on an explicit instance: `(set! (.-field inst) v)`.
983pub fn set_type_instance_field(inst: &Value, field: &str, val: Value) -> EvalResult {
984    let Value::TypeInstance(ti) = inst else {
985        return Err(EvalError::Runtime(format!(
986            "set! (.-{field} …): target is not a type instance"
987        )));
988    };
989    let atom = ti.get().mutable.clone().ok_or_else(|| {
990        EvalError::Runtime(format!("set! (.-{field} …): type has no mutable fields"))
991    })?;
992    let key = Value::keyword(cljrs_value::Keyword::simple(field));
993    let map = match atom.get().deref() {
994        Value::Map(m) => m,
995        _ => MapValue::empty(),
996    };
997    if map.get(&key).is_none() {
998        return Err(EvalError::Runtime(format!(
999            "set!: {field} is not a mutable field"
1000        )));
1001    }
1002    atom.get().reset(Value::Map(map.assoc(key, val.clone())));
1003    Ok(val)
1004}
1005
1006// ── throw ─────────────────────────────────────────────────────────────────────
1007
1008fn eval_throw(args: &[Form], env: &mut Env) -> EvalResult {
1009    let val = match args.first() {
1010        Some(f) => eval(f, env)?,
1011        None => Value::Nil,
1012    };
1013    Err(throw_value(val))
1014}
1015
1016/// The error `(throw val)` raises for an already-evaluated `val`.
1017///
1018/// Wraps non-error values in an ExceptionInfo so try/catch always sees a
1019/// Value::Error and ex-message / ex-data work uniformly inside the handler.
1020pub fn throw_value(val: Value) -> EvalError {
1021    let val = match val {
1022        Value::Error(_) => val,
1023        other => {
1024            let msg = format!("{}", other);
1025            Value::Error(GcPtr::new(ExceptionInfo::new(
1026                ValueError::Other(msg.clone()),
1027                msg,
1028                None,
1029                None,
1030            )))
1031        }
1032    };
1033    EvalError::Thrown(val)
1034}
1035
1036// ── try ───────────────────────────────────────────────────────────────────────
1037
1038/// A catch clause: `(catch Type binding body...)`.
1039///
1040/// Public so the async evaluator (`cljrs-async`) can reuse `parse_try_args` to
1041/// build a yielding `try`/`catch`.
1042pub struct CatchClause<'a> {
1043    pub type_sym: &'a str,
1044    pub binding: &'a str,
1045    pub body: &'a [Form],
1046}
1047
1048/// Convert a non-Thrown EvalError into a `Value::Error` so it can be bound
1049/// inside a catch clause and inspected with `ex-message` / `ex-data`.
1050///
1051/// Public so the async evaluator can convert errors the same way `try` does.
1052pub fn eval_error_to_value(err: &EvalError) -> Value {
1053    let msg = err.to_string();
1054    Value::Error(GcPtr::new(ExceptionInfo::new(
1055        ValueError::Other(msg.clone()),
1056        msg,
1057        None,
1058        None,
1059    )))
1060}
1061
1062/// Test whether the type symbol on a `(catch <Type> e ...)` clause matches a
1063/// thrown value. Type names are matched by their last `.`-separated segment so
1064/// fully-qualified names like `java.lang.Exception` work as well as bare ones.
1065pub fn catch_type_matches(type_name: &str, val: &Value) -> bool {
1066    let short = type_name.rsplit('.').next().unwrap_or(type_name);
1067    match short {
1068        // Catch-all (matches any value, error or not — back-compat).
1069        // `:default` is the ClojureScript universal catch keyword; it arrives
1070        // here as the keyword's name ("default") via `parse_try_args`.
1071        "Object" | "Exception" | "Throwable" | "Error" | "default" => true,
1072        // ExceptionInfo only matches actual ex-info / Exception values.
1073        "ExceptionInfo" => matches!(val, Value::Error(_)),
1074        _ => false,
1075    }
1076}
1077
1078fn eval_try(args: &[Form], env: &mut Env) -> EvalResult {
1079    let (body, catches, fin_body) = parse_try_args(args);
1080
1081    let mut result = eval_body(body, env);
1082
1083    // Handle catch: never intercept Recur (loop trampoline signal).
1084    let err_opt = match std::mem::replace(&mut result, Ok(Value::Nil)) {
1085        Ok(v) => {
1086            result = Ok(v);
1087            None
1088        }
1089        Err(EvalError::Recur(args)) => {
1090            result = Err(EvalError::Recur(args));
1091            None
1092        }
1093        Err(EvalError::GasExhausted) => {
1094            result = Err(EvalError::GasExhausted);
1095            None
1096        }
1097        Err(other) => Some(other),
1098    };
1099
1100    if let Some(err) = err_opt {
1101        let thrown_val = match err {
1102            EvalError::Thrown(v) => v,
1103            ref other => eval_error_to_value(other),
1104        };
1105        let mut handled = false;
1106        for c in &catches {
1107            if catch_type_matches(c.type_sym, &thrown_val) {
1108                env.push_frame();
1109                env.bind(Arc::from(c.binding), thrown_val.clone());
1110                result = eval_body(c.body, env);
1111                env.pop_frame();
1112                handled = true;
1113                break;
1114            }
1115        }
1116        if !handled {
1117            // No matching catch — re-throw.
1118            result = Err(EvalError::Thrown(thrown_val));
1119        }
1120    }
1121
1122    // Always run finally.  Its normal (Ok) value is discarded — `try` returns
1123    // the body/catch result — but an exception thrown from `finally` supersedes
1124    // the pending result or exception (matching JVM/Clojure semantics).
1125    if !fin_body.is_empty() {
1126        eval_body(fin_body, env)?;
1127    }
1128
1129    result
1130}
1131
1132/// The class name or `:default` keyword naming what a `catch` clause catches.
1133fn catch_target(f: &Form) -> Option<&str> {
1134    f.as_symbol().or_else(|| f.as_keyword())
1135}
1136
1137/// Split try args into (body, catch clauses, finally body).
1138///
1139/// Public so the async evaluator can parse `try` forms identically.
1140pub fn parse_try_args(args: &[Form]) -> (&[Form], Vec<CatchClause<'_>>, &[Form]) {
1141    let mut body_end = args.len();
1142    let mut catches: Vec<CatchClause<'_>> = Vec::new();
1143    let mut fin_body: &[Form] = &[];
1144
1145    for (i, form) in args.iter().enumerate() {
1146        if let Some(parts) = form.as_list()
1147            && let Some(s) = parts.first().and_then(|f| f.as_symbol())
1148        {
1149            if s == "catch" {
1150                if i < body_end {
1151                    body_end = i;
1152                }
1153                // The catch type may be a symbol (`Throwable`, `java.lang.Exception`),
1154                // the ClojureScript `:default` catch-all keyword, or a reader
1155                // conditional `#?(:rust Exception :clj ...)` whose selected branch
1156                // resolves to one of those.
1157                let type_sym = match parts.get(1) {
1158                    Some(f) => match catch_target(f) {
1159                        Some(name) => name,
1160                        None => match &f.unmeta().kind {
1161                            FormKind::ReaderCond {
1162                                splicing: false,
1163                                clauses,
1164                            } => match select_reader_cond(clauses).and_then(catch_target) {
1165                                Some(name) => name,
1166                                None => continue,
1167                            },
1168                            _ => continue,
1169                        },
1170                    },
1171                    None => continue,
1172                };
1173                let binding = match parts.get(2).and_then(|f| f.as_symbol()) {
1174                    Some(s) => s,
1175                    None => continue,
1176                };
1177                catches.push(CatchClause {
1178                    type_sym,
1179                    binding,
1180                    body: &parts[3..],
1181                });
1182                continue;
1183            }
1184            if s == "finally" {
1185                if i < body_end {
1186                    body_end = i;
1187                }
1188                fin_body = &parts[1..];
1189                continue;
1190            }
1191        }
1192    }
1193
1194    (&args[..body_end], catches, fin_body)
1195}
1196
1197// ── defn ──────────────────────────────────────────────────────────────────────
1198
1199pub fn eval_defn(args: &[Form], env: &mut Env, private: bool) -> EvalResult {
1200    // The name may carry reader metadata, e.g. `(defn ^:async fetch ...)`.
1201    let name_form = args
1202        .first()
1203        .ok_or_else(|| EvalError::Runtime("defn requires a symbol name".into()))?;
1204    let (name_metas, name_sym) = name_form.peel_meta();
1205    let (name, mut is_async) = match &name_sym.kind {
1206        FormKind::Symbol(s) => (s.clone(), name_metas.iter().any(|m| m.requests_async())),
1207        _ => return Err(EvalError::Runtime("defn name must be a symbol".into())),
1208    };
1209    // Optional docstring and/or metadata map after the name.
1210    // Valid orderings: (defn name body...), (defn name "doc" body...),
1211    // (defn name {:meta ...} body...), (defn name "doc" {:meta ...} body...).
1212    let mut rest_start = 1;
1213    let mut docstring: Option<String> = None;
1214    if rest_start < args.len()
1215        && let Some(s) = args[rest_start].as_string()
1216    {
1217        docstring = Some(s.to_string());
1218        rest_start += 1;
1219    }
1220    let mut attr_meta: Option<Value> = None;
1221    if rest_start < args.len() && args[rest_start].as_map().is_some() {
1222        // An attr-map such as `{:async true}` can also request async dispatch.
1223        is_async |= args[rest_start].requests_async();
1224        attr_meta = Some(eval(&args[rest_start], env)?);
1225        rest_start += 1;
1226    }
1227    // Build (fn* name ...)
1228    let mut fn_args = vec![Form::new(
1229        FormKind::Symbol(name.to_string()),
1230        args[0].span.clone(),
1231    )];
1232    fn_args.extend_from_slice(&args[rest_start..]);
1233    // Under no-gc: the Fn object must live in the StaticArena since the Var
1234    // intern outlives all scratch regions.
1235    #[cfg(feature = "no-gc")]
1236    let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1237    let mut fn_val = eval_fn(&fn_args, env)?;
1238    if is_async && let Value::Fn(ref mut f) = fn_val {
1239        f.get_mut().is_async = true;
1240    }
1241    let var = env
1242        .globals
1243        .intern(&env.current_ns, Arc::from(name.as_str()), fn_val.clone());
1244    let mut meta = attr_meta;
1245    if let Some(doc) = &docstring {
1246        meta = merge_meta(meta, Some(doc_meta(doc)));
1247    }
1248    meta = merge_meta(meta, arglists_meta(&fn_val, 0));
1249    if private {
1250        meta = merge_meta(meta, Some(private_meta()));
1251    }
1252    if let Some(meta_val) = meta {
1253        var.get().set_meta(meta_val);
1254    }
1255    Ok(Value::Var(var))
1256}
1257
1258// ── defmacro ──────────────────────────────────────────────────────────────────
1259
1260/// Prepend `&form` and `&env` Form symbols to an arity form's parameter vector.
1261///
1262/// Handles:
1263/// - Single-arity vector `[params...]` → `[&form &env params...]`
1264/// - Multi-arity clause list `([params...] body...)` → `([&form &env params...] body...)`
1265fn prepend_macro_params(form: &Form) -> Form {
1266    let span = form.span.clone();
1267    match &form.unmeta().kind {
1268        FormKind::Vector(params) => {
1269            let mut new_params = vec![
1270                Form::new(FormKind::Symbol("&form".to_string()), span.clone()),
1271                Form::new(FormKind::Symbol("&env".to_string()), span.clone()),
1272            ];
1273            new_params.extend_from_slice(params);
1274            Form::new(FormKind::Vector(new_params), span)
1275        }
1276        FormKind::List(forms) => {
1277            // Arity clause: ([params...] body...) — prepend to first element (params vector).
1278            if let Some(first) = forms.first() {
1279                let new_params_form = prepend_macro_params(first);
1280                let mut new_forms = vec![new_params_form];
1281                new_forms.extend_from_slice(&forms[1..]);
1282                Form::new(FormKind::List(new_forms), span)
1283            } else {
1284                form.clone()
1285            }
1286        }
1287        _ => form.clone(),
1288    }
1289}
1290
1291fn eval_defmacro(args: &[Form], env: &mut Env) -> EvalResult {
1292    // The name may carry reader metadata, e.g. `(defmacro ^:private foo ...)`,
1293    // possibly stacked (`^:a ^:b foo`).
1294    let mut current = args
1295        .first()
1296        .ok_or_else(|| EvalError::Runtime("defmacro requires a symbol at position 0".into()))?
1297        .clone();
1298    let mut name_meta: Option<Value> = None;
1299    while let FormKind::Meta(meta_form, inner) = current.kind {
1300        let meta_val = compile_meta_form(&meta_form, env)?;
1301        name_meta = merge_meta(name_meta, Some(meta_val));
1302        current = *inner;
1303    }
1304    let name = match &current.kind {
1305        FormKind::Symbol(s) => s.clone(),
1306        _ => {
1307            return Err(EvalError::Runtime(
1308                "defmacro requires a symbol at position 0".into(),
1309            ));
1310        }
1311    };
1312
1313    let mut rest_start = 1;
1314    let mut docstring: Option<String> = None;
1315    if rest_start < args.len()
1316        && let FormKind::Str(s) = &args[rest_start].kind
1317    {
1318        docstring = Some(s.clone());
1319        rest_start += 1;
1320    }
1321    let mut attr_meta = None;
1322    if rest_start < args.len() && matches!(args[rest_start].kind, FormKind::Map(_)) {
1323        attr_meta = Some(eval(&args[rest_start], env)?);
1324        rest_start += 1;
1325    }
1326    // Prepend implicit &form and &env params to each arity.
1327    let mut fn_args = vec![Form::new(
1328        FormKind::Symbol(name.to_string()),
1329        args[0].span.clone(),
1330    )];
1331    for form in &args[rest_start..] {
1332        fn_args.push(prepend_macro_params(form));
1333    }
1334    // Under no-gc: the Macro object must live in the StaticArena since the Var
1335    // intern outlives all scratch regions.
1336    #[cfg(feature = "no-gc")]
1337    let _static_ctx = cljrs_gc::alloc_ctx::StaticCtxGuard::new();
1338    let fn_val = eval_fn(&fn_args, env)?;
1339
1340    // Convert Fn → Macro by setting is_macro = true.
1341    let macro_val = match fn_val {
1342        Value::Fn(f) => {
1343            let mut mfn = f.get().clone();
1344            mfn.is_macro = true;
1345            Value::Macro(GcPtr::new(mfn))
1346        }
1347        other => other,
1348    };
1349
1350    let var = env
1351        .globals
1352        .intern(&env.current_ns, Arc::from(name.as_str()), macro_val.clone());
1353    let mut meta = merge_meta(name_meta, attr_meta);
1354    if let Some(doc) = &docstring {
1355        meta = merge_meta(meta, Some(doc_meta(doc)));
1356    }
1357    // Skip the implicit &form/&env params when showing the macro's signature.
1358    meta = merge_meta(meta, arglists_meta(&macro_val, 2));
1359    if let Some(m) = meta {
1360        var.get().set_meta(m);
1361    }
1362    Ok(Value::Var(var))
1363}
1364
1365// ── defonce ───────────────────────────────────────────────────────────────────
1366
1367fn eval_defonce(args: &[Form], env: &mut Env) -> EvalResult {
1368    if args.is_empty() {
1369        return Err(EvalError::Runtime("defonce requires a name".into()));
1370    }
1371    // Share `def`'s name extraction so a metadata-carrying symbol such as
1372    // `(defonce ^:private registry (atom {}))` is accepted here too.
1373    let (name, _meta) = extract_def_name(&args[0], env)?;
1374    // If already bound, return immediately.
1375    if let Some(var) = defonce_existing(&name, env) {
1376        return Ok(var);
1377    }
1378    eval_def(args, env)
1379}
1380
1381// ── and / or ──────────────────────────────────────────────────────────────────
1382
1383fn eval_and(args: &[Form], env: &mut Env) -> EvalResult {
1384    let mut result = Value::Bool(true);
1385    for form in args {
1386        result = eval(form, env)?;
1387        if matches!(result, Value::Nil | Value::Bool(false)) {
1388            return Ok(result);
1389        }
1390    }
1391    Ok(result)
1392}
1393
1394fn eval_or(args: &[Form], env: &mut Env) -> EvalResult {
1395    let mut last = Value::Nil;
1396    for form in args {
1397        last = eval(form, env)?;
1398        if !matches!(last, Value::Nil | Value::Bool(false)) {
1399            return Ok(last);
1400        }
1401    }
1402    Ok(last)
1403}
1404
1405// ── require ───────────────────────────────────────────────────────────────────
1406
1407fn eval_require(args: &[Form], env: &mut Env) -> EvalResult {
1408    for arg in args {
1409        let val = eval(arg, env)?;
1410        let spec = parse_require_spec_val(val).map_err(EvalError::Runtime)?;
1411        load_ns(env.globals.clone(), &spec, &env.current_ns)?;
1412    }
1413    Ok(Value::Nil)
1414}
1415
1416/// Parse a `RequireSpec` from an already-evaluated `Value`.
1417/// Accepts: `'some.ns`, `['some.ns :as alias]`, `['some.ns :refer [syms]]`,
1418/// `['some.ns :refer :all]`, and versioned forms like `'some.ns@abc1234` or
1419/// `['some.ns@abc1234 :as alias]`.
1420fn parse_require_spec_val(val: Value) -> Result<RequireSpec, String> {
1421    match val {
1422        Value::Symbol(s) => {
1423            let sym = s.get();
1424            Ok(RequireSpec {
1425                ns: sym.name.clone(),
1426                version: sym.version.clone(),
1427                alias: None,
1428                refer: RequireRefer::None,
1429            })
1430        }
1431        Value::Vector(v) => {
1432            let items: Vec<Value> = v.get().iter().cloned().collect();
1433            if items.is_empty() {
1434                return Err("require spec vector must not be empty".into());
1435            }
1436            let (ns, version) = match &items[0] {
1437                Value::Symbol(s) => {
1438                    let sym = s.get();
1439                    (sym.name.clone(), sym.version.clone())
1440                }
1441                other => {
1442                    return Err(format!(
1443                        "require spec: first element must be a symbol, got {}",
1444                        other.type_name()
1445                    ));
1446                }
1447            };
1448            let mut alias = None;
1449            let mut refer = RequireRefer::None;
1450            let mut i = 1;
1451            while i < items.len() {
1452                match &items[i] {
1453                    Value::Keyword(k) if k.get().name.as_ref() == "as" => {
1454                        i += 1;
1455                        alias = Some(match items.get(i) {
1456                            Some(Value::Symbol(s)) => s.get().name.clone(),
1457                            _ => return Err("require :as expects a symbol".into()),
1458                        });
1459                    }
1460                    Value::Keyword(k) if k.get().name.as_ref() == "refer" => {
1461                        i += 1;
1462                        refer = match items.get(i) {
1463                            Some(Value::Keyword(k2)) if k2.get().name.as_ref() == "all" => {
1464                                RequireRefer::All
1465                            }
1466                            Some(Value::Vector(rv)) => {
1467                                let names: Vec<Arc<str>> = rv
1468                                    .get()
1469                                    .iter()
1470                                    .map(|v| match v {
1471                                        Value::Symbol(s) => Ok(s.get().name.clone()),
1472                                        other => Err(format!(
1473                                            "require :refer expects symbols, got {}",
1474                                            other.type_name()
1475                                        )),
1476                                    })
1477                                    .collect::<Result<_, _>>()?;
1478                                RequireRefer::Named(names)
1479                            }
1480                            _ => {
1481                                return Err(
1482                                    "require :refer expects :all or a vector of symbols".into()
1483                                );
1484                            }
1485                        };
1486                    }
1487                    other => {
1488                        return Err(format!(
1489                            "require spec: unexpected option {}",
1490                            other.type_name()
1491                        ));
1492                    }
1493                }
1494                i += 1;
1495            }
1496            Ok(RequireSpec {
1497                ns,
1498                version,
1499                alias,
1500                refer,
1501            })
1502        }
1503        other => Err(format!(
1504            "require expects a symbol or vector, got {}",
1505            other.type_name()
1506        )),
1507    }
1508}
1509
1510/// The form a require-spec element denotes: a reader conditional resolves to
1511/// its selected branch, `None` when no branch matches this platform. Any other
1512/// form is itself.
1513fn spec_element(form: &Form) -> Option<&Form> {
1514    match &form.kind {
1515        FormKind::ReaderCond { clauses, .. } => select_reader_cond(clauses),
1516        _ => Some(form),
1517    }
1518}
1519
1520/// Parse a `RequireSpec` from a raw `Form` (unevaluated, used in `ns` macro).
1521/// Also handles versioned namespace symbols such as `my.ns@abc1234`.
1522///
1523/// Public so the AOT compiler can establish an entry namespace from the same
1524/// parse `eval_ns` uses. A second implementation there would drift: it already
1525/// did, dropping `:refer` and `@version` from structurally emitted requires.
1526pub fn parse_require_spec_form(form: &Form) -> Result<RequireSpec, String> {
1527    match &form.kind {
1528        FormKind::Symbol(s) => {
1529            let sym = cljrs_value::Symbol::parse(s);
1530            Ok(RequireSpec {
1531                ns: sym.name.clone(),
1532                version: sym.version.clone(),
1533                alias: None,
1534                refer: RequireRefer::None,
1535            })
1536        }
1537        FormKind::Vector(items) => {
1538            if items.is_empty() {
1539                return Err("require spec vector must not be empty".into());
1540            }
1541            let head = spec_element(&items[0]).ok_or_else(|| {
1542                "require spec: no reader-conditional branch matched for the namespace".to_string()
1543            })?;
1544            let (ns, version) = match &head.kind {
1545                FormKind::Symbol(s) => {
1546                    let sym = cljrs_value::Symbol::parse(s);
1547                    (sym.name.clone(), sym.version.clone())
1548                }
1549                _ => return Err("require spec: first element must be a symbol".into()),
1550            };
1551            let mut alias = None;
1552            let mut refer = RequireRefer::None;
1553            let mut i = 1;
1554            while i < items.len() {
1555                // An option whose conditional selects nothing is dropped; the
1556                // namespace slot above cannot be, so it errors instead.
1557                let Some(item) = spec_element(&items[i]) else {
1558                    i += 1;
1559                    continue;
1560                };
1561                match &item.kind {
1562                    FormKind::Keyword(k) if k == "as" => {
1563                        i += 1;
1564                        alias = Some(match items.get(i).map(|f| &f.kind) {
1565                            Some(FormKind::Symbol(s)) => Arc::from(s.as_str()),
1566                            _ => return Err("require :as expects a symbol".into()),
1567                        });
1568                    }
1569                    FormKind::Keyword(k) if k == "refer" => {
1570                        i += 1;
1571                        refer = match items.get(i).map(|f| &f.kind) {
1572                            Some(FormKind::Keyword(k2)) if k2 == "all" => RequireRefer::All,
1573                            Some(FormKind::Vector(rv)) => {
1574                                let names: Vec<Arc<str>> = rv
1575                                    .iter()
1576                                    .map(|f| match &f.kind {
1577                                        FormKind::Symbol(s) => Ok(Arc::from(s.as_str())),
1578                                        _ => Err("require :refer expects symbols".to_string()),
1579                                    })
1580                                    .collect::<Result<_, _>>()?;
1581                                RequireRefer::Named(names)
1582                            }
1583                            _ => return Err("require :refer expects :all or a vector".into()),
1584                        };
1585                    }
1586                    _ => return Err(format!("require spec: unexpected form at position {i}")),
1587                }
1588                i += 1;
1589            }
1590            Ok(RequireSpec {
1591                ns,
1592                version,
1593                alias,
1594                refer,
1595            })
1596        }
1597        _ => Err("require spec must be a symbol or vector".into()),
1598    }
1599}
1600
1601// ── ns ────────────────────────────────────────────────────────────────────────
1602
1603/// Extract the ns name and optional metadata from the `ns` macro's name form.
1604/// Handles plain symbols and `^meta` shorthand / map forms, e.g.
1605/// `(ns ^{:doc "..."} my.ns ...)` or `(ns ^:no-doc my.ns ...)`.
1606fn extract_ns_name_form(form: Option<&Form>, env: &mut Env) -> EvalResult<(String, Option<Value>)> {
1607    let mut current = form
1608        .ok_or_else(|| EvalError::Runtime("ns requires a symbol at position 0".into()))?
1609        .clone();
1610    let mut meta_acc: Option<Value> = None;
1611    while let FormKind::Meta(meta_form, inner) = current.kind {
1612        let meta_val = compile_meta_form(&meta_form, env)?;
1613        meta_acc = merge_meta(meta_acc, Some(meta_val));
1614        current = *inner;
1615    }
1616    match &current.kind {
1617        FormKind::Symbol(s) => Ok((s.clone(), meta_acc)),
1618        _ => Err(EvalError::Runtime(
1619            "ns requires a symbol at position 0".into(),
1620        )),
1621    }
1622}
1623
1624/// Merge two optional metadata maps, with `overlay` entries taking
1625/// precedence over `base` entries (matching Clojure's `(merge base overlay)`).
1626fn merge_meta(base: Option<Value>, overlay: Option<Value>) -> Option<Value> {
1627    match (base, overlay) {
1628        (None, None) => None,
1629        (Some(b), None) => Some(b),
1630        (None, Some(o)) => Some(o),
1631        (Some(Value::Map(b)), Some(Value::Map(o))) => {
1632            let mut merged = b;
1633            for (k, v) in o.iter() {
1634                merged = merged.assoc(k.clone(), v.clone());
1635            }
1636            Some(Value::Map(merged))
1637        }
1638        (_, Some(o)) => Some(o),
1639    }
1640}
1641
1642/// Parse the body of a `(:refer-clojure ...)` clause into the filter applied
1643/// to the automatic `clojure.core` refer.  Accepts `:exclude`, `:only` and
1644/// `:rename`, each once, in any order.
1645fn parse_refer_clojure_clause(items: &[Form]) -> Result<ReferClojureFilter, String> {
1646    let mut filter = ReferClojureFilter::default();
1647    let items = expand_reader_conds(items);
1648    let mut i = 0;
1649    while i < items.len() {
1650        let FormKind::Keyword(k) = &items[i].kind else {
1651            return Err(":refer-clojure expects keyword options (:exclude, :only, :rename)".into());
1652        };
1653        let arg = items
1654            .get(i + 1)
1655            .ok_or_else(|| format!(":refer-clojure :{k} expects a value"))?;
1656        match k.as_str() {
1657            "exclude" => filter.exclude = symbol_name_set(arg, "exclude")?,
1658            "only" => filter.only = Some(symbol_name_set(arg, "only")?),
1659            "rename" => {
1660                let FormKind::Map(entries) = &arg.kind else {
1661                    return Err(":refer-clojure :rename expects a map".into());
1662                };
1663                if entries.len() % 2 != 0 {
1664                    return Err(":refer-clojure :rename expects an even-sized map".into());
1665                }
1666                for pair in entries.chunks(2) {
1667                    match (&pair[0].kind, &pair[1].kind) {
1668                        (FormKind::Symbol(from), FormKind::Symbol(to)) => {
1669                            filter
1670                                .rename
1671                                .insert(Arc::from(from.as_str()), Arc::from(to.as_str()));
1672                        }
1673                        _ => {
1674                            return Err(
1675                                ":refer-clojure :rename expects symbol keys and values".into()
1676                            );
1677                        }
1678                    }
1679                }
1680            }
1681            other => return Err(format!(":refer-clojure does not support :{other}")),
1682        }
1683        i += 2;
1684    }
1685    Ok(filter)
1686}
1687
1688/// Read a vector of symbols (an `:exclude`/`:only` list) as a set of names.
1689fn symbol_name_set(form: &Form, opt: &str) -> Result<HashSet<Arc<str>>, String> {
1690    let FormKind::Vector(items) = &form.kind else {
1691        return Err(format!(":refer-clojure :{opt} expects a vector of symbols"));
1692    };
1693    expand_reader_conds(items)
1694        .iter()
1695        .map(|f| match &f.kind {
1696            FormKind::Symbol(sym) => Ok(Arc::from(sym.as_str())),
1697            _ => Err(format!(":refer-clojure :{opt} expects symbols")),
1698        })
1699        .collect()
1700}
1701
1702fn eval_ns(args: &[Form], env: &mut Env) -> EvalResult {
1703    let (name, name_meta) = extract_ns_name_form(args.first(), env)?;
1704    env.globals.get_or_create_ns(&name);
1705    env.current_ns = Arc::from(name.as_str());
1706    // Auto-refer clojure.core (Clojure default behaviour).
1707    if name != "clojure.core" {
1708        env.globals.refer_core(&name);
1709    }
1710    sync_star_ns(env);
1711
1712    // Optional docstring, then optional attr-map, before reference clauses.
1713    let mut rest = &args[1..];
1714    if matches!(rest.first().map(|f| &f.kind), Some(FormKind::Str(_))) {
1715        rest = &rest[1..];
1716    }
1717    let mut attr_meta = None;
1718    if matches!(rest.first().map(|f| &f.kind), Some(FormKind::Map(_))) {
1719        attr_meta = Some(eval(&rest[0], env)?);
1720        rest = &rest[1..];
1721    }
1722
1723    if let Some(m) = merge_meta(name_meta, attr_meta) {
1724        let ns_ptr = env.globals.get_or_create_ns(&env.current_ns);
1725        ns_ptr.get().set_meta(m);
1726    }
1727
1728    // `:refer-clojure` first: it narrows the automatic core refer done above,
1729    // and an explicit `:require ... :refer` below must be able to override it.
1730    // Re-evaluating an `ns` form without the clause clears a filter left by an
1731    // earlier evaluation, restoring the full core refer.
1732    //
1733    // More than one `:refer-clojure` clause is not meaningful, so the last one
1734    // wins rather than accumulating.  (Clojure runs each clause as a separate
1735    // `refer` call, where a second clause silently *re-adds* what the first
1736    // excluded; there is no reading of that under which both clauses do what
1737    // they say.)
1738    let mut refer_clojure = None;
1739    for clause in rest {
1740        if let FormKind::List(items) = &clause.kind
1741            && matches!(items.first().map(|f| &f.kind), Some(FormKind::Keyword(k)) if k == "refer-clojure")
1742        {
1743            refer_clojure =
1744                Some(parse_refer_clojure_clause(&items[1..]).map_err(EvalError::Runtime)?);
1745        }
1746    }
1747    if name != "clojure.core" {
1748        env.globals
1749            .set_refer_clojure_filter(&name, refer_clojure)
1750            .map_err(EvalError::Runtime)?;
1751    }
1752
1753    for clause in rest {
1754        if let FormKind::List(items) = &clause.kind {
1755            match items.first().map(|f| &f.kind) {
1756                Some(FormKind::Keyword(k)) if k == "require" => {
1757                    // Expand reader conditionals among require specs
1758                    let expanded = expand_reader_conds(&items[1..]);
1759                    for spec_form in &expanded {
1760                        let spec =
1761                            parse_require_spec_form(spec_form).map_err(EvalError::Runtime)?;
1762                        load_ns(env.globals.clone(), &spec, &name)?;
1763                    }
1764                }
1765                Some(FormKind::Keyword(k)) if k == "import" => {
1766                    for spec in &expand_reader_conds(&items[1..]) {
1767                        import_types(env, &name, spec);
1768                    }
1769                }
1770                // `:refer-clojure` was handled in the pass above; other clauses
1771                // (`:use`) — skip for now.
1772                _ => {}
1773            }
1774        }
1775    }
1776
1777    let ns_ptr = env.globals.get_or_create_ns(&env.current_ns);
1778    Ok(Value::Namespace(ns_ptr))
1779}
1780
1781/// Apply one `(:import ...)` spec (`[pkg Name ...]`, `(pkg Name ...)` or
1782/// `pkg.Name`) by referring each named record or deftype into `dst_ns`.
1783///
1784/// A type's dispatch tag is qualified by its defining namespace, so an
1785/// unqualified `Name` only reaches that tag through a var `dst_ns` can
1786/// resolve; without the refer, `(extend-type Name ...)` in the importing
1787/// namespace registers its methods under a tag no instance carries.
1788fn import_types(env: &Env, dst_ns: &str, spec: &Form) {
1789    match &spec.unmeta().kind {
1790        FormKind::Vector(items) | FormKind::List(items) => {
1791            let mut syms = items.iter().filter_map(Form::as_symbol);
1792            if let Some(pkg) = syms.next() {
1793                for name in syms {
1794                    import_type(env, dst_ns, pkg, name);
1795                }
1796            }
1797        }
1798        FormKind::Symbol(s) => {
1799            if let Some((pkg, name)) = s.rsplit_once('.') {
1800                import_type(env, dst_ns, pkg, name);
1801            }
1802        }
1803        _ => {}
1804    }
1805}
1806
1807/// Refer the type `name` defined in namespace `pkg` into `dst_ns`. `pkg` is
1808/// also tried with `_` read as `-`, the JVM's package spelling of a namespace.
1809/// Anything that is not a loaded record or deftype (a host class in a `.cljc`
1810/// file, say) is left alone, as `:import` was before it referred anything.
1811fn import_type(env: &Env, dst_ns: &str, pkg: &str, name: &str) {
1812    let demunged = pkg.replace('_', "-");
1813    for ns in [pkg, demunged.as_str()] {
1814        let tag = format!("{ns}.{name}");
1815        let names_type = matches!(
1816            env.globals.lookup_in_ns(ns, name),
1817            Some(Value::Symbol(s)) if s.get().to_string() == tag
1818        );
1819        if names_type {
1820            env.globals.refer_named(dst_ns, ns, &[Arc::from(name)]);
1821            return;
1822        }
1823    }
1824}
1825
1826// ── load-file ─────────────────────────────────────────────────────────────────
1827
1828fn eval_load_file(args: &[Form], env: &mut Env) -> EvalResult {
1829    if args.is_empty() {
1830        return Err(EvalError::Runtime(
1831            "load-file requires a path argument".into(),
1832        ));
1833    }
1834    let path_val = eval(&args[0], env)?;
1835    let path = match &path_val {
1836        Value::Str(s) => s.get().clone(),
1837        v => {
1838            return Err(EvalError::Runtime(format!(
1839                "load-file: expected string, got {}",
1840                v.type_name()
1841            )));
1842        }
1843    };
1844    let src = std::fs::read_to_string(&path)
1845        .map_err(|e| EvalError::Runtime(format!("load-file: {e}")))?;
1846    let mut parser = cljrs_reader::Parser::new(src, path.clone());
1847    let forms = parser
1848        .parse_all()
1849        .map_err(|e| EvalError::Runtime(format!("load-file parse error: {e}")))?;
1850    let mut result = Value::Nil;
1851    for form in forms {
1852        let _alloc_frame = cljrs_gc::push_alloc_frame();
1853        result = eval(&form, env)?;
1854    }
1855    Ok(result)
1856}
1857
1858// ── letfn ─────────────────────────────────────────────────────────────────────
1859
1860fn eval_letfn(args: &[Form], env: &mut Env) -> EvalResult {
1861    push_letfn_frame(args, env)?;
1862    let result = eval_body(&args[1..], env);
1863    env.pop_frame();
1864    result
1865}
1866
1867/// Push a local frame binding every fn of `(letfn [fns…] body…)`, mutually
1868/// visible. On success the caller evaluates the body and pops the frame; on
1869/// error the frame has already been popped.
1870///
1871/// Public so the async evaluator can run the body with a yielding evaluator.
1872pub fn push_letfn_frame(args: &[Form], env: &mut Env) -> EvalResult<()> {
1873    // (letfn [(f [params] body...) ...] body...)
1874    //
1875    // Three passes, because a closure here captures VALUES, not cells:
1876    // `eval_fn` snapshots `env.all_local_bindings()`, so a name bound after the
1877    // closure was built is invisible to it forever. Binding each fn as it was
1878    // built therefore gave letfn `let`-like sequential scope — a backward
1879    // reference resolved, a forward one or a mutual pair raised "unbound
1880    // symbol", which defeats the only reason letfn exists.
1881    let bindings = match args.first().and_then(|f| f.as_vector()) {
1882        Some(v) => expand_reader_conds_cow(v).into_owned(),
1883        None => return Err(EvalError::Runtime("letfn requires a binding vector".into())),
1884    };
1885
1886    env.push_frame();
1887
1888    // Pass 1: bind every name to nil, so the pass-2 snapshot CONTAINS all of
1889    // them. A capture list cannot grow after the fact; it can only be corrected.
1890    for binding in &bindings {
1891        if let Some(parts) = binding.as_list() {
1892            if parts.is_empty() {
1893                continue;
1894            }
1895            let Some(name) = parts[0].as_symbol() else {
1896                env.pop_frame();
1897                return Err(EvalError::Runtime(
1898                    "letfn binding name must be a symbol".into(),
1899                ));
1900            };
1901            env.bind(Arc::from(name), Value::Nil);
1902        }
1903    }
1904
1905    // Pass 2: build the closures. Each captures the real value of any sibling
1906    // already built and nil for the rest.
1907    let mut built: Vec<(Arc<str>, Value)> = Vec::new();
1908    for binding in &bindings {
1909        if let Some(parts) = binding.as_list() {
1910            if parts.is_empty() {
1911                continue;
1912            }
1913            // parts[0] is the name, so eval_fn sees this as a NAMED fn and wires
1914            // up its self-reference; pass 3 handles every other direction.
1915            let fn_val = match eval_fn(parts, env) {
1916                Ok(v) => v,
1917                Err(e) => {
1918                    env.pop_frame();
1919                    return Err(e);
1920                }
1921            };
1922            let name: Arc<str> = match parts[0].as_symbol() {
1923                Some(s) => Arc::from(s),
1924                None => unreachable!("pass 1 rejected every non-symbol name"),
1925            };
1926            env.bind(Arc::clone(&name), fn_val.clone());
1927            built.push((name, fn_val));
1928        }
1929    }
1930
1931    // Pass 3: replace the nil placeholders each closure captured with the
1932    // sibling it actually names. This is what makes the scope MUTUAL rather
1933    // than sequential, and it necessarily builds a reference cycle between
1934    // co-recursive fns — which is inherent to letfn, not an artifact here.
1935    for (_, fn_val) in &built {
1936        if let Value::Fn(ptr) = fn_val {
1937            let mut ptr = ptr.clone();
1938            let f = ptr.get_mut();
1939            for i in 0..f.closed_over_names.len() {
1940                let captured = f.closed_over_names[i].clone();
1941                if let Some((_, real)) = built.iter().find(|(n, _)| *n == captured) {
1942                    f.closed_over_vals[i] = real.clone();
1943                }
1944            }
1945        }
1946    }
1947
1948    Ok(())
1949}
1950
1951// ── in-ns ─────────────────────────────────────────────────────────────────────
1952
1953fn eval_in_ns(args: &[Form], env: &mut Env) -> EvalResult {
1954    // (in-ns 'foo.bar)
1955    if args.is_empty() {
1956        return Err(EvalError::Runtime("in-ns requires a namespace name".into()));
1957    }
1958    let ns_val = eval(&args[0], env)?;
1959    let ns_name = extract_ns_name(&ns_val)?;
1960    env.globals.get_or_create_ns(&ns_name);
1961    env.globals.refer_core(&ns_name);
1962    env.current_ns = Arc::from(ns_name.as_str());
1963    sync_star_ns(env);
1964    let ns_ptr = env.globals.get_or_create_ns(&env.current_ns);
1965    Ok(Value::Namespace(ns_ptr))
1966}
1967
1968// ── alias ─────────────────────────────────────────────────────────────────────
1969
1970fn eval_alias(args: &[Form], env: &mut Env) -> EvalResult {
1971    // (alias 'short 'some.long.ns)
1972    if args.len() < 2 {
1973        return Err(EvalError::Runtime(
1974            "alias requires alias-sym and namespace-sym".into(),
1975        ));
1976    }
1977    let alias_val = eval(&args[0], env)?;
1978    let ns_val = eval(&args[1], env)?;
1979
1980    let alias_name = extract_ns_name(&alias_val)?;
1981    let full_ns = extract_ns_name(&ns_val)?;
1982
1983    let ns_ptr = env.globals.get_or_create_ns(&env.current_ns);
1984    let mut aliases = ns_ptr.get().aliases.lock().unwrap();
1985    aliases.insert(Arc::from(alias_name.as_str()), Arc::from(full_ns.as_str()));
1986    Ok(Value::Nil)
1987}
1988
1989/// Extract a namespace-name string from a Value::Symbol, Value::Str, or Value::Keyword.
1990fn extract_ns_name(v: &Value) -> EvalResult<String> {
1991    match v {
1992        Value::Symbol(s) => {
1993            // Use the full name (e.g. "clojure.core").
1994            Ok(s.get().name.as_ref().to_string())
1995        }
1996        Value::Str(s) => Ok(s.get().clone()),
1997        Value::Keyword(k) => Ok(k.get().name.as_ref().to_string()),
1998        other => Err(EvalError::Runtime(format!(
1999            "expected a symbol or string for namespace name, got {}",
2000            other.type_name()
2001        ))),
2002    }
2003}
2004
2005// ── protocol* ─────────────────────────────────────────────────────────────────
2006
2007/// Read a `{:name "m" :min-arity n :variadic b}` map into a `ProtocolMethod`.
2008fn protocol_method_of(spec: &Value) -> EvalResult<ProtocolMethod> {
2009    let Value::Map(m) = spec.unwrap_meta() else {
2010        return Err(EvalError::Runtime(format!(
2011            "protocol* method spec must be a map, got {}",
2012            spec.type_name()
2013        )));
2014    };
2015    let field = |k: &str| m.get(&Value::keyword(Keyword::simple(k)));
2016    let name: Arc<str> = match field("name") {
2017        Some(Value::Str(s)) => Arc::from(s.get().as_str()),
2018        Some(Value::Symbol(s)) => Arc::from(s.get().name.as_ref()),
2019        Some(Value::Keyword(k)) => Arc::from(k.get().name.as_ref()),
2020        _ => {
2021            return Err(EvalError::Runtime(
2022                "protocol* method spec needs a :name".into(),
2023            ));
2024        }
2025    };
2026    let min_arity = match field("min-arity") {
2027        Some(Value::Long(n)) if n >= 0 => n as usize,
2028        _ => 1,
2029    };
2030    let variadic = !matches!(
2031        field("variadic"),
2032        None | Some(Value::Nil) | Some(Value::Bool(false))
2033    );
2034    Ok(ProtocolMethod {
2035        name,
2036        min_arity,
2037        variadic,
2038    })
2039}
2040
2041/// `(protocol* Name method-specs extend-via-metadata?)` — mint a protocol.
2042///
2043/// `method-specs` evaluates to a sequence of `{:name :min-arity :variadic}`
2044/// maps. The protocol is created in the CURRENT namespace, which is the whole
2045/// reason this stays a special form: `Protocol.ns` is what qualifies a method
2046/// name for extend-via-metadata dispatch, and a builtin fn cannot see the
2047/// environment. The protocol is returned, not interned — `defprotocol` is the
2048/// Clojure macro that `def`s it along with a dispatch fn per method.
2049fn eval_protocol_star(args: &[Form], env: &mut Env) -> EvalResult {
2050    if args.len() < 2 {
2051        return Err(EvalError::Runtime(
2052            "protocol* requires a name and method specs".into(),
2053        ));
2054    }
2055    // Name metadata belongs on the var `defprotocol` binds, not here.
2056    let (name, _) = require_sym_meta(args, 0, "protocol*", env)?;
2057    let specs = crate::interp::eval::eval(&args[1], env)?;
2058    let specs: Vec<Value> = match specs.unwrap_meta() {
2059        Value::Vector(v) => v.get().iter().cloned().collect(),
2060        Value::Nil => Vec::new(),
2061        v => {
2062            return Err(EvalError::Runtime(format!(
2063                "protocol* method specs must be a vector, got {}",
2064                v.type_name()
2065            )));
2066        }
2067    };
2068    let methods = specs
2069        .iter()
2070        .map(protocol_method_of)
2071        .collect::<EvalResult<Vec<_>>>()?;
2072    let extend_via_metadata = match args.get(2) {
2073        Some(f) => !matches!(
2074            crate::interp::eval::eval(f, env)?,
2075            Value::Nil | Value::Bool(false)
2076        ),
2077        None => false,
2078    };
2079    let proto = Protocol::new(
2080        Arc::from(name.as_str()),
2081        env.current_ns.clone(),
2082        methods,
2083        extend_via_metadata,
2084    );
2085    Ok(Value::Protocol(GcPtr::new(proto)))
2086}
2087
2088/// Build a `CljxFn` from the tail of a method-impl list: `(name [params] body...)`.
2089/// `parts[0]` is the method name symbol (ignored here — caller handles it).
2090/// `parts[1]` is the params vector.
2091/// `parts[2..]` is the body.
2092/// Bring a defrecord's FIELDS into scope in a method body, as
2093/// `(let* [f (:f this) ...] body...)`.
2094///
2095/// The bare field symbol is the idiomatic form — `(mutable? [_] (valid-sha? sha))`
2096/// — and it read as an unbound symbol, because a method impl is built as an
2097/// ordinary fn whose only bindings are its own params. Clojure compiles the
2098/// fields as instance fields of the generated class, so they are simply in
2099/// scope.
2100///
2101/// A field whose name a PARAM already takes is skipped: the param shadows the
2102/// field in Clojure, and binding it here would shadow the param instead.
2103/// Returns None when there is nothing to bind, or when the first param is not
2104/// a plain symbol (a destructured `this` has no name to read the fields from).
2105fn synth_field_scope(
2106    params_form: &Form,
2107    fields: &[Arc<str>],
2108    mutable_fields: &[Arc<str>],
2109    body: &[Form],
2110) -> Option<Vec<Form>> {
2111    let param_forms = match &params_form.kind {
2112        FormKind::Vector(v) => v,
2113        _ => return None,
2114    };
2115    let this_name = match param_forms.first().map(|f| &f.kind) {
2116        Some(FormKind::Symbol(s)) => s.clone(),
2117        _ => return None,
2118    };
2119    let param_names: Vec<&str> = param_forms
2120        .iter()
2121        .filter_map(|f| match &f.kind {
2122            FormKind::Symbol(s) => Some(s.as_str()),
2123            _ => None,
2124        })
2125        .collect();
2126
2127    let span = params_form.span.clone();
2128    let is_mut = |name: &str| mutable_fields.iter().any(|m| m.as_ref() == name);
2129    let mut bindings: Vec<Form> = Vec::new();
2130    for field in fields {
2131        if param_names.contains(&field.as_ref()) {
2132            continue;
2133        }
2134        bindings.push(Form::new(FormKind::Symbol(field.to_string()), span.clone()));
2135        // A mutable field reads through `(.-field this)` — the live cell; an
2136        // immutable one through `(:field this)` — the field map. Both snapshot
2137        // at method entry; `set!` refreshes the local for later reads.
2138        let accessor = if is_mut(field) {
2139            FormKind::List(vec![
2140                Form::new(FormKind::Symbol(format!(".-{field}")), span.clone()),
2141                Form::new(FormKind::Symbol(this_name.clone()), span.clone()),
2142            ])
2143        } else {
2144            FormKind::List(vec![
2145                Form::new(FormKind::Keyword(field.to_string()), span.clone()),
2146                Form::new(FormKind::Symbol(this_name.clone()), span.clone()),
2147            ])
2148        };
2149        bindings.push(Form::new(accessor, span.clone()));
2150    }
2151    // With mutable fields present, bind a hidden handle to `this` so `set!` can
2152    // find the instance whose cell to update.
2153    if !mutable_fields.is_empty() {
2154        bindings.push(Form::new(
2155            FormKind::Symbol(DEFTYPE_SELF.to_string()),
2156            span.clone(),
2157        ));
2158        bindings.push(Form::new(FormKind::Symbol(this_name.clone()), span.clone()));
2159    }
2160    if bindings.is_empty() {
2161        return None;
2162    }
2163
2164    let mut let_forms = vec![
2165        Form::new(FormKind::Symbol("let*".to_string()), span.clone()),
2166        Form::new(FormKind::Vector(bindings), span.clone()),
2167    ];
2168    let_forms.extend_from_slice(body);
2169    Some(vec![Form::new(FormKind::List(let_forms), span)])
2170}
2171
2172fn build_impl_fn(
2173    parts: &[Form],
2174    fields: &[Arc<str>],
2175    mutable_fields: &[Arc<str>],
2176    env: &mut Env,
2177) -> EvalResult<Value> {
2178    if parts.len() < 2 {
2179        return Err(EvalError::Runtime(
2180            "protocol method impl requires params and body".into(),
2181        ));
2182    }
2183    // parts[1] should be the params vector.
2184    let params_form = &parts[1];
2185    let body = &parts[2..];
2186    let scoped;
2187    let body: &[Form] = if fields.is_empty() {
2188        body
2189    } else {
2190        match synth_field_scope(params_form, fields, mutable_fields, body) {
2191            Some(v) => {
2192                scoped = v;
2193                &scoped
2194            }
2195            None => body,
2196        }
2197    };
2198    let arity = parse_arity(params_form, body)?;
2199    let (closed_over_names, closed_over_vals) = env.all_local_bindings();
2200    let fn_name: Option<Arc<str>> = parts[0].as_symbol().map(Arc::from);
2201    let cljrs_fn = CljxFn::new(
2202        fn_name,
2203        vec![arity],
2204        closed_over_names,
2205        closed_over_vals,
2206        false,
2207        Arc::clone(&env.current_ns),
2208    );
2209    Ok(Value::Fn(GcPtr::new(cljrs_fn)))
2210}
2211
2212// ── binding ───────────────────────────────────────────────────────────────────
2213
2214fn eval_binding(args: &[Form], env: &mut Env) -> EvalResult {
2215    let pairs = match args.first().and_then(|f| f.as_vector()) {
2216        Some(v) => expand_pairs(v)
2217            .map_err(|_| EvalError::Runtime("binding vector must have even count".into()))?
2218            .into_owned(),
2219        None => return Err(EvalError::Runtime("binding requires a vector".into())),
2220    };
2221
2222    let mut frame: HashMap<usize, Value> = HashMap::new();
2223    for pair in pairs.chunks(2) {
2224        let Some(sym_str) = pair[0].as_symbol() else {
2225            return Err(EvalError::Runtime("binding targets must be symbols".into()));
2226        };
2227        let parsed = cljrs_value::Symbol::parse(sym_str);
2228        let ns_part: Arc<str> = env.resolve_ns_or_current(parsed.namespace.as_deref());
2229        let var_ptr = env
2230            .globals
2231            .lookup_var_in_ns(&ns_part, &parsed.name)
2232            .ok_or_else(|| EvalError::UnboundSymbol(sym_str.to_string()))?;
2233        let val = eval(&pair[1], env)?;
2234        frame.insert(crate::env::dynamics::var_key_of(&var_ptr), val);
2235    }
2236
2237    let _guard = crate::env::dynamics::push_frame(frame);
2238    eval_body(&args[1..], env)
2239    // _guard drops here → pop_frame()
2240}
2241
2242// ── deftype / defrecord shared construction ─────────────────────────────────────
2243
2244/// Hidden `let*` binding a `deftype` method body carries when the type has
2245/// mutable fields: a handle to `this`, so `set!` can locate the instance whose
2246/// interior-mutable cell to update.
2247const DEFTYPE_SELF: &str = "__deftype_self__";
2248
2249/// Does a field's `^meta` mark it `^:unsynchronized-mutable` or
2250/// `^:volatile-mutable`? Instances are single-threaded here, so the two are
2251/// treated identically — only whether the field is mutable at all matters.
2252fn meta_form_is_mutable(meta: &Form) -> bool {
2253    let is_mut_kw = |k: &str| k == "unsynchronized-mutable" || k == "volatile-mutable";
2254    match &meta.kind {
2255        FormKind::Keyword(k) => is_mut_kw(k),
2256        FormKind::Map(entries) => entries.chunks(2).any(|kv| {
2257            matches!(&kv[0].kind, FormKind::Keyword(k) if is_mut_kw(k))
2258                && !matches!(
2259                    kv.get(1).map(|f| &f.kind),
2260                    None | Some(FormKind::Bool(false)) | Some(FormKind::Nil)
2261                )
2262        }),
2263        // Metadata that reached this form through a macro is QUOTED: it is
2264        // already a value, and re-analysing it would resolve its contents as
2265        // code (see `value_to_form`). A field vector written in source arrives
2266        // unquoted; one a macro emitted arrives quoted. Both describe the same
2267        // field, so both have to be read.
2268        FormKind::Quote(inner) => meta_form_is_mutable(inner),
2269        _ => false,
2270    }
2271}
2272
2273/// A single field spec: its name and whether it is mutable.
2274fn field_spec_of(form: &Form) -> Option<(Arc<str>, bool)> {
2275    match &form.kind {
2276        FormKind::Symbol(s) => Some((Arc::from(s.as_str()), false)),
2277        FormKind::Meta(meta, inner) => {
2278            let here = meta_form_is_mutable(meta);
2279            field_spec_of(inner).map(|(name, inner_mut)| (name, inner_mut || here))
2280        }
2281        _ => None,
2282    }
2283}
2284
2285/// Parse a `deftype` `[field ...]` vector into `(name, mutable?)` specs.
2286fn parse_field_specs(form: &Form, ctx: &str) -> EvalResult<Vec<(Arc<str>, bool)>> {
2287    // `as_vector` reports the shape under any `^meta`, so a marker on the
2288    // vector itself — `(defrecord R ^:marker [x])` — stays transparent.
2289    let Some(fields) = form.as_vector() else {
2290        return Err(EvalError::Runtime(format!(
2291            "{ctx} requires a field vector as second arg"
2292        )));
2293    };
2294    fields
2295        .iter()
2296        .map(|f| {
2297            field_spec_of(f)
2298                .ok_or_else(|| EvalError::Runtime(format!("{ctx} field names must be symbols")))
2299        })
2300        .collect()
2301}
2302
2303// ── deftype* (defrecord / deftype are bootstrap macros over it) ─────────────────
2304
2305/// The irreducible datatype primitive: mint a type tag and register method impls
2306/// against it, with the fields in scope in each body and mutable fields backed by
2307/// live cells. It does NOT synthesise constructors or intern the type symbol —
2308/// that sugar lives in the `deftype` bootstrap macro (`->T`, `(def T 'T)`), which
2309/// is what makes deftype a particular case of a Clojure macro over this form.
2310fn eval_deftype_star(args: &[Form], env: &mut Env) -> EvalResult {
2311    // (deftype* TypeName [field ...] Proto (method [this] body) ...)
2312    if args.len() < 2 {
2313        return Err(EvalError::Runtime(
2314            "deftype* requires a name and field vector".into(),
2315        ));
2316    }
2317    // Type metadata (e.g. ^:private) has no var to hold it; unwrapped so the
2318    // name reads, and deliberately not applied anywhere it would not belong.
2319    let (type_name, _) = require_sym_meta(args, 0, "deftype*", env)?;
2320    let type_tag = qualified_type_tag(&type_name, env);
2321
2322    let specs = parse_field_specs(&args[1], "deftype*")?;
2323    let field_names: Vec<Arc<str>> = specs.iter().map(|(n, _)| n.clone()).collect();
2324    let mutable_names: Vec<Arc<str>> = specs
2325        .iter()
2326        .filter(|(_, m)| *m)
2327        .map(|(n, _)| n.clone())
2328        .collect();
2329
2330    // Register protocol/interface method impls, with the fields in scope in
2331    // each body — same machinery as defrecord/reify. Mutable fields read
2332    // through the live cell and are writable with `set!`.
2333    register_impls_for_tag(&type_tag, &args[2..], &field_names, &mutable_names, env)?;
2334    // Return the minted tag so a caller (e.g. the `reify` macro) can feed it
2335    // straight to `make-type-instance` — a single dataflow source for the tag,
2336    // rather than a second textual reference that a gensym could desync.
2337    Ok(Value::string(type_tag.to_string()))
2338}
2339
2340/// The dispatch tag of a record or deftype: its name qualified by the defining
2341/// namespace, `my.ns.Point`, as the JVM names the generated class. Two
2342/// namespaces may each define a `Point`; with a bare-name tag the second one's
2343/// protocol impls replaced the first one's, and `instance?` could not tell
2344/// their instances apart.
2345fn qualified_type_tag(type_name: &str, env: &Env) -> Arc<str> {
2346    Arc::from(format!("{}.{}", env.current_ns, type_name))
2347}
2348
2349// ── register_impls_for_tag ────────────────────────────────────────────────────
2350
2351/// Resolve a protocol NAME symbol in an impl position (extend-type, extend-protocol,
2352/// reify/defrecord), honouring the current namespace's `:require :as` aliases and
2353/// fully-qualified names — not just an unqualified lookup in the current ns.
2354///
2355/// `(defrecord R [] mp/IThing (-do [_] ...))` failed with "mp/IThing is not a
2356/// protocol" even though the protocol was loaded and (resolve 'mini.proto/IThing)
2357/// was truthy: the old code looked up the whole string "mp/IThing" as an intern of
2358/// the CURRENT ns, where it is neither interned nor referred. A qualified protocol
2359/// symbol must resolve through its own namespace, exactly as `eval` resolves any
2360/// other qualified symbol.
2361fn resolve_protocol_sym(env: &Env, s: &str) -> Option<GcPtr<Protocol>> {
2362    let parsed = cljrs_value::Symbol::parse(s);
2363    let val = match parsed.namespace.as_deref() {
2364        Some(ns_part) => {
2365            let ns = env.resolve_ns_part(ns_part);
2366            env.globals.lookup_in_ns(&ns, &parsed.name)
2367        }
2368        None => env.globals.lookup_in_ns(&env.current_ns, s),
2369    };
2370    match val {
2371        Some(Value::Protocol(p)) => Some(p),
2372        _ => None,
2373    }
2374}
2375
2376/// Parse `Proto (method [params] body) ...` segments and register them under `type_tag`.
2377/// Shared by `defrecord` and `reify`.
2378fn register_impls_for_tag(
2379    type_tag: &Arc<str>,
2380    forms: &[Form],
2381    fields: &[Arc<str>],
2382    mutable_fields: &[Arc<str>],
2383    env: &mut Env,
2384) -> EvalResult<()> {
2385    let mut current_proto: Option<GcPtr<cljrs_value::Protocol>> = None;
2386
2387    for form in forms {
2388        match &form.unmeta().kind {
2389            FormKind::Symbol(s) => match resolve_protocol_sym(env, s) {
2390                Some(p) => current_proto = Some(p),
2391                None => {
2392                    return Err(EvalError::Runtime(format!(
2393                        "reify/defrecord: {} is not a protocol",
2394                        s
2395                    )));
2396                }
2397            },
2398            FormKind::List(parts) => {
2399                let proto = current_proto.as_ref().ok_or_else(|| {
2400                    EvalError::Runtime("reify/defrecord: method impl before protocol name".into())
2401                })?;
2402                if parts.is_empty() {
2403                    continue;
2404                }
2405                let method_name: Arc<str> = match parts[0].as_symbol() {
2406                    Some(s) => Arc::from(s),
2407                    None => continue,
2408                };
2409                let fn_val = build_impl_fn(parts, fields, mutable_fields, env)?;
2410                let mut impls = proto.get().impls.lock().unwrap();
2411                impls
2412                    .entry(type_tag.clone())
2413                    .or_default()
2414                    .insert(method_name, fn_val);
2415                drop(impls);
2416                cljrs_value::bump_protocol_generation();
2417            }
2418            _ => {}
2419        }
2420    }
2421    Ok(())
2422}
2423
2424// ── helpers ───────────────────────────────────────────────────────────────────
2425
2426/// Update the root binding of `*ns*` in `clojure.core` to the current namespace.
2427/// Called whenever `env.current_ns` changes (ns, in-ns, standard_env setup).
2428pub fn sync_star_ns(env: &mut Env) {
2429    if let Some(star_ns_var) = env.globals.lookup_var("clojure.core", "*ns*") {
2430        let ns_ptr = env.globals.get_or_create_ns(&env.current_ns);
2431        star_ns_var.get().bind(Value::Namespace(ns_ptr));
2432    }
2433}
2434
2435/// The symbol at `idx`, unwrapping any `^meta` wrapper, together with the
2436/// metadata it carried.
2437///
2438/// `(defprotocol ^:private Driver ...)` reads as `Meta(:private, Symbol("Driver"))`,
2439/// so matching `FormKind::Symbol` alone rejects a form Clojure accepts. malli's
2440/// `malli.impl.regex` opens with five such protocols, which made all of malli
2441/// unloadable.
2442///
2443/// The metadata is RETURNED rather than discarded: dropping it would trade a
2444/// loud error for a silent loss of `^:private`, and callers that intern a var
2445/// attach it there.
2446fn require_sym_meta(
2447    args: &[Form],
2448    idx: usize,
2449    form_name: &str,
2450    env: &mut Env,
2451) -> EvalResult<(String, Option<Value>)> {
2452    fn peel(form: &Form, env: &mut Env) -> EvalResult<Option<(String, Option<Value>)>> {
2453        match &form.kind {
2454            FormKind::Symbol(s) => Ok(Some((s.clone(), None))),
2455            // `^:a ^:b x` nests Meta forms; unwrap all, outer mark winning.
2456            FormKind::Meta(meta_form, inner) => {
2457                let meta_val = compile_meta_form(meta_form, env)?;
2458                match peel(inner, env)? {
2459                    Some((name, inner_meta)) => {
2460                        Ok(Some((name, merge_meta(inner_meta, Some(meta_val)))))
2461                    }
2462                    None => Ok(None),
2463                }
2464            }
2465            _ => Ok(None),
2466        }
2467    }
2468    let err = || EvalError::Runtime(format!("{form_name} requires a symbol at position {idx}"));
2469    match args.get(idx) {
2470        Some(form) => peel(form, env)?.ok_or_else(err),
2471        None => Err(err()),
2472    }
2473}
2474
2475// ── with-out-str ──────────────────────────────────────────────────────────────
2476
2477fn eval_with_out_str(body: &[Form], env: &mut Env) -> EvalResult {
2478    crate::builtins::builtins::push_output_capture();
2479    let result = eval_body(body, env);
2480    let captured = crate::builtins::builtins::pop_output_capture().unwrap_or_default();
2481    // Propagate errors but still pop the capture buffer
2482    result?;
2483    Ok(Value::string(captured))
2484}
2485
2486// ── await ─────────────────────────────────────────────────────────────────────
2487
2488/// Blocking deref in sync context; yielding deref in async context.
2489///
2490/// When `cljrs-async` is loaded, `eval_async` intercepts `await` forms before
2491/// the sync evaluator reaches this handler, so this path is only taken in
2492/// non-async (sync) code. It blocks the OS thread until the future/promise
2493/// resolves — equivalent to `(deref val)`.
2494fn eval_await(args: &[Form], env: &mut Env) -> EvalResult {
2495    if args.is_empty() {
2496        return Err(EvalError::Runtime("await requires one argument".into()));
2497    }
2498    let val = eval(&args[0], env)?;
2499    match val {
2500        Value::Future(f) => {
2501            let mut guard = f.get().state.lock().unwrap();
2502            loop {
2503                match &*guard {
2504                    FutureState::Done(v) => {
2505                        f.get().mark_observed();
2506                        return Ok(v.clone());
2507                    }
2508                    FutureState::Failed(v) => {
2509                        f.get().mark_observed();
2510                        return Err(EvalError::Thrown(v.clone()));
2511                    }
2512                    FutureState::GasExhausted => {
2513                        f.get().mark_observed();
2514                        return Err(EvalError::GasExhausted);
2515                    }
2516                    FutureState::Cancelled => {
2517                        return Err(EvalError::Thrown(CljxFuture::cancelled_error()));
2518                    }
2519                    FutureState::Running => {
2520                        guard = f.get().cond.wait(guard).unwrap();
2521                    }
2522                }
2523            }
2524        }
2525        Value::Promise(p) => Ok(p.get().deref_blocking()),
2526        other => Ok(other),
2527    }
2528}