Skip to main content

cljrs_runtime/env/
callback.rs

1//! Thread-local eval context for Rust→Clojure callbacks.
2//!
3//! When a native (Rust) builtin needs to call a Clojure function — for example,
4//! a comparator passed to `sort-by` — it can use [`invoke`] to do so.  The eval
5//! context is pushed automatically before every native function call and popped
6//! afterward, so `invoke` is always available inside builtins.
7
8use std::cell::RefCell;
9use std::sync::Arc;
10
11use cljrs_value::{Value, ValueError, ValueResult};
12
13use crate::env::env::{Env, GlobalEnv};
14
15// ── Thread-local context stack ───────────────────────────────────────────────
16
17struct EvalContext {
18    globals: Arc<GlobalEnv>,
19    current_ns: Arc<str>,
20    /// True when the active call originates from inside an `^:async` function
21    /// body. Lets blocking builtins (`deref`) reject use that should be `await`.
22    is_async: bool,
23}
24
25thread_local! {
26    static EVAL_CONTEXT: RefCell<Vec<EvalContext>> = const { RefCell::new(Vec::new()) };
27}
28cljrs_gc::mutator_slot!("cljrs-runtime/EVAL_CONTEXT", refcell EVAL_CONTEXT: Vec<EvalContext>);
29
30/// Push the current eval context before calling a native function.
31pub fn push_eval_context(env: &Env) {
32    EVAL_CONTEXT.with(|stack| {
33        stack.borrow_mut().push(EvalContext {
34            globals: env.globals.clone(),
35            current_ns: env.current_ns.clone(),
36            is_async: env.is_async,
37        });
38    });
39}
40
41/// True when the innermost active eval context is inside an `^:async` function
42/// body. Returns `false` when there is no active context.
43pub fn current_is_async() -> bool {
44    EVAL_CONTEXT.with(|stack| stack.borrow().last().is_some_and(|ec| ec.is_async))
45}
46
47/// Pop the eval context after a native function returns.
48pub fn pop_eval_context() {
49    EVAL_CONTEXT.with(|stack| {
50        stack.borrow_mut().pop();
51    });
52}
53
54/// Capture the current eval context so it can be installed on another thread.
55///
56/// Returns `None` if there is no active context.
57pub fn capture_eval_context() -> Option<(Arc<GlobalEnv>, Arc<str>)> {
58    EVAL_CONTEXT.with(|stack| {
59        let s = stack.borrow();
60        let ec = s.last()?;
61        Some((ec.globals.clone(), ec.current_ns.clone()))
62    })
63}
64
65/// Install a previously captured eval context on the current thread.
66///
67/// Call this at the start of a spawned thread so that `invoke` works.
68pub fn install_eval_context(globals: Arc<GlobalEnv>, ns: Arc<str>) {
69    EVAL_CONTEXT.with(|stack| {
70        stack.borrow_mut().push(EvalContext {
71            globals,
72            current_ns: ns,
73            // Cross-thread installs (agent/future worker threads) run blocking,
74            // synchronous work — never an async-yielding context.
75            is_async: false,
76        });
77    });
78}
79
80/// RAII guard that pops one eval context on drop (including on unwind).
81///
82/// Returned by [`install_eval_context_guard`]; use it when the push and pop
83/// must stay balanced across early returns or panics.
84pub struct EvalContextGuard {
85    _priv: (),
86}
87
88impl Drop for EvalContextGuard {
89    fn drop(&mut self) {
90        pop_eval_context();
91    }
92}
93
94/// Like [`install_eval_context`], but returns a guard that pops the context
95/// when dropped.
96///
97/// Used by the JIT-native dispatch seam: native code resolves globals and
98/// calls function values through rt_abi bridges that all require an eval
99/// context on the calling thread.
100pub fn install_eval_context_guard(globals: Arc<GlobalEnv>, ns: Arc<str>) -> EvalContextGuard {
101    install_eval_context(globals, ns);
102    EvalContextGuard { _priv: () }
103}
104
105// ── Public API ───────────────────────────────────────────────────────────────
106
107/// Call a Clojure-callable `Value` with the given arguments.
108///
109/// This can be called from any Rust code running inside an active evaluation
110/// (i.e., inside a builtin function, a `Thunk::force`, etc.).
111///
112/// # Errors
113///
114/// Returns `Err` if called outside an eval context, or if the callee raises
115/// an error.
116/// Execute a closure with access to a temporary `Env` constructed from the
117/// current eval context.
118///
119/// This is used by the IR interpreter for calling builtins that need an `Env`
120/// (e.g., for nested `apply_value` calls from inside a `NativeFunction`
121/// closure).
122///
123/// # Errors
124///
125/// Returns `Err` if called outside an eval context.
126pub fn with_eval_context<F, R>(f: F) -> Result<R, crate::env::error::EvalError>
127where
128    F: FnOnce(&mut Env) -> Result<R, crate::env::error::EvalError>,
129{
130    let (globals, ns) = EVAL_CONTEXT.with(|stack| {
131        let s = stack.borrow();
132        let ec = s.last().ok_or_else(|| {
133            crate::env::error::EvalError::Runtime(
134                "with_eval_context called outside eval context".to_string(),
135            )
136        })?;
137        Ok::<_, crate::env::error::EvalError>((ec.globals.clone(), ec.current_ns.clone()))
138    })?;
139    let mut env = Env::new(globals, &ns);
140    f(&mut env)
141}
142
143pub fn invoke(f: &Value, args: Vec<Value>) -> ValueResult<Value> {
144    let (globals, ns) = EVAL_CONTEXT.with(|stack| {
145        let s = stack.borrow();
146        let ec = s
147            .last()
148            .ok_or_else(|| ValueError::Other("invoke called outside eval context".into()))?;
149        Ok((ec.globals.clone(), ec.current_ns.clone()))
150    })?;
151    let mut env = Env::new(globals, &ns);
152    // Fast path for Clojure functions: call directly through the GlobalEnv
153    // function pointer, bypassing the large apply_value stack frame.
154    // Unwrap metadata so a WithMeta-wrapped fn is callable.
155    let f = f.unwrap_meta();
156    let result = if let Value::Fn(cljx_fn) = f {
157        // Honor `^:async` dispatch (spawn the body, return a Future) just like
158        // `apply_value` — otherwise a compiled/native caller invoking an async
159        // fn would run its body synchronously and never get a Future.
160        if let Some(fut) = crate::env::apply::dispatch_if_async(f, &args, &env) {
161            Ok(fut)
162        } else {
163            env.call_cljrs_fn(cljx_fn.get(), &args)
164        }
165    } else {
166        crate::env::apply::apply_value(f, args, &mut env)
167    };
168    result.map_err(|e| match e {
169        crate::env::error::EvalError::Thrown(v) => ValueError::Thrown(v),
170        crate::env::error::EvalError::GasExhausted => ValueError::GasExhausted,
171        crate::env::error::EvalError::MemoryLimitExceeded(fault) => {
172            // Compiled callers drop most errors on the floor; keep the
173            // fault in the runtime-fault slot so the compiled-code entry
174            // seam still reports it.
175            cljrs_gc::governor::confirm_runtime_fault(fault);
176            ValueError::MemoryLimitExceeded(fault)
177        }
178        other => ValueError::Other(format!("{other}")),
179    })
180}