Skip to main content

cljrs_runtime/env/
async_hook.rs

1//! Hook trait for the optional async runtime (`cljrs-async`).
2//!
3//! Core crates never import Tokio. When `cljrs-async` is linked, it calls
4//! `GlobalEnv::set_async_runtime` to install itself. The evaluator then
5//! delegates `^:async` fn dispatch through this trait.
6
7use cljrs_value::Value;
8
9use crate::env::env::Env;
10
11use crate::env::error::EvalResult;
12
13/// Interface implemented by `cljrs-async` and registered with `GlobalEnv`.
14///
15/// All methods are called from the LocalSet thread, so `Value` / `Env` need
16/// not be `Send`. The trait itself must be `Send + Sync` so the
17/// `Arc<dyn AsyncRuntime>` inside `GlobalEnv` can be shared.
18pub trait AsyncRuntime: Send + Sync {
19    /// Spawn a call to an `^:async` function as a LocalSet task.
20    ///
21    /// `callee` is the `Value::Fn` being invoked, `args` are the already-
22    /// evaluated arguments, `env` is the calling environment. Returns a
23    /// `Value::Future` immediately; the body runs concurrently.
24    fn spawn_async_call(&self, callee: Value, args: Vec<Value>, env: Env) -> Value;
25
26    /// Block the current OS thread until a value can be taken from the channel.
27    ///
28    /// Used by the IR interpreter's sync-context fallback for `ChanTake`.
29    /// Returns `Value::Nil` on a closed channel.
30    fn chan_take_blocking(&self, chan: Value) -> EvalResult;
31
32    /// Block the current OS thread until the value is accepted by the channel.
33    ///
34    /// Used by the IR interpreter's sync-context fallback for `ChanPut`.
35    fn chan_put_blocking(&self, chan: Value, val: Value) -> EvalResult<()>;
36}
37
38// ── Async JIT compile hook ──────────────────────────────────────────────────
39//
40// `cljrs-async` drives `^:async` dispatch but cannot compile (it sits below
41// `cljrs-jit`).  `cljrs-jit::init` installs this hook; the async dispatcher
42// invokes it (once per arity) to lower + compile + register a native poll
43// function for the called `^:async` arity.  A no-op when the JIT is absent, so
44// dispatch keeps tree-walking via `eval_async`.
45
46/// Signature of the async-JIT compile hook: `(callee_fn, nargs, env)`.
47pub type AsyncCompileHook = fn(&Value, usize, &mut Env);
48
49static ASYNC_COMPILE_HOOK: std::sync::OnceLock<AsyncCompileHook> = std::sync::OnceLock::new();
50
51/// Install the async-JIT compile hook (called once by `cljrs-jit::init`).
52pub fn set_async_compile_hook(hook: AsyncCompileHook) {
53    let _ = ASYNC_COMPILE_HOOK.set(hook);
54}
55
56/// The installed async-JIT compile hook, if any.
57pub fn async_compile_hook() -> Option<AsyncCompileHook> {
58    ASYNC_COMPILE_HOOK.get().copied()
59}