quickjs-capi 0.14.1

C ABI compatibility layer: the QuickJS C API on top of the pure-Rust engine
Documentation
//! The host session: what makes a C function callable from a script `qjs` is running.
//!
//! # The problem this solves
//!
//! When `qjs -m test_fib.js` runs `fib(10)`, the call arrives in a C function whose first act
//! is `JS_ToInt32(ctx, &n, argv[0])`. That call needs a `JSContext *` and, behind it, the
//! interpreter that is executing the script. The engine is inside `Interp::run_script` while
//! this happens, and a program that never asked the C API for anything has never published
//! that interpreter — so the C function receives a null context and answers `JS_EXCEPTION`
//! for no stated reason.
//!
//! [`session`] is the fix: for the duration of a script or module run, the interpreter is
//! published (through the same thread-local a C callback uses) along with a context that
//! stands for it. Everything a `.so` module does then works exactly as it does inside an
//! embedding that called `JS_NewContext`.
//!
//! # Why one session per thread
//!
//! A class id lives in a module's static data and is registered against a runtime, so the
//! runtime has to be the same object for every native import in the process — a fresh one per
//! import would hand a module a different `JSRuntime *` each time. One thread-local session
//! per thread matches how the reference's `JSRuntime` is per-process, and keeps the CLI free
//! of any lifetime plumbing.
//!
//! # Why a guard rather than a callback
//!
//! The obvious shape is `enter(ctx, || ctx.eval(src))`, and it does not compile: the borrow
//! of `ctx` that produces the interpreter pointer and the borrow the closure needs are the
//! same one. A guard splits them — the borrow ends when [`session`] returns, and the guard
//! holds raw pointers that are valid because the interpreter lives in the `Context` and does
//! not move.

use std::cell::RefCell;

use engine::Interp;

use crate::runtime::{self, JsContext, JsRuntime};

thread_local! {
    /// The process's host session, created on first use.
    static SESSION: RefCell<Option<Session>> = const { RefCell::new(None) };
}

/// The runtime plus the context that stands for whatever interpreter is running.
struct Session {
    runtime: Box<JsRuntime>,
    context: JsContext,
}

impl Session {
    fn new() -> Session {
        let runtime = JsRuntime::new();
        let pointer = &*runtime as *const JsRuntime as *mut JsRuntime;
        Session {
            runtime,
            context: JsContext::attached(pointer),
        }
    }
}

/// The runtime native modules register their classes against.
///
/// Stable for the life of the thread, which is what a module's static `JSClassID` needs:
/// `JS_GetRuntime` may be called from any of its functions, at any time.
pub fn runtime_ptr() -> *mut JsRuntime {
    SESSION.with(|slot| {
        let mut slot = slot.borrow_mut();
        let session = slot.get_or_insert_with(Session::new);
        &*session.runtime as *const JsRuntime as *mut JsRuntime
    })
}

/// Publish `context`'s interpreter for the C API until the returned guard is dropped.
///
/// The context is also adopted by the session's runtime for the duration, so `JS_NewClass` —
/// which takes a `JSRuntime *` — mirrors its definition into *this* interpreter. That is the
/// one piece of state a native module needs and cannot get any other way.
pub fn session(context: &mut engine::Context<'_>) -> SessionGuard {
    // Taken and erased in one expression, so the `&mut` borrow of `context` ends before this
    // function returns and the caller is free to run the script.
    let interp: *mut Interp<'static> = {
        let interp = context.interp_mut();
        // SAFETY: a `&mut Interp<'a>` and a `&mut Interp<'static>` are one pointer; the
        // lifetime is erased only for the guard to hold, and the guard does not outlive the
        // interpreter's real lifetime because the caller owns it.
        unsafe { std::mem::transmute::<&mut Interp<'_>, &mut Interp<'static>>(interp) as *mut _ }
    };
    let runtime = runtime_ptr();
    SESSION.with(|slot| {
        let mut slot = slot.borrow_mut();
        let session = slot.get_or_insert_with(Session::new);
        let context = &session.context as *const JsContext as *mut JsContext;
        // SAFETY: the session's runtime and context both live in the thread-local, so the
        // pointers stay valid for as long as the guard exists.
        unsafe { (*runtime).adopt_for_session(context) };
        SessionGuard {
            runtime,
            context,
            published: Some(runtime::publish(interp, &session.context)),
        }
    })
}

/// Keeps an interpreter published for as long as it lives.
pub struct SessionGuard {
    runtime: *mut JsRuntime,
    context: *mut JsContext,
    published: Option<runtime::InterpGuard>,
}

impl Drop for SessionGuard {
    fn drop(&mut self) {
        // The publication goes first: a C function must not be able to reach the interpreter
        // after the runtime has forgotten the context it belongs to.
        drop(self.published.take());
        // SAFETY: both pointers were adopted by `session` and are still live in the
        // thread-local.
        unsafe { (*self.runtime).disown(self.context) };
    }
}