postscriptum 0.1.0

Multi-interpreted-language scripting engine for Rust with Rhai and Python backends
Documentation
//! # postscriptum
//!
//! A multi-interpreted-language scripting engine for Rust, with **Rhai** and
//! **Python** backends, working on both native and WASM targets. This crate is
//! **Bevy-free**.
//!
//! The core abstraction is the [`ScriptEngine`] trait: a stateful interpreter
//! that evaluates a script and returns the result as a string. Wrap it in a
//! [`ThreadSafeEngine`] to share it across threads, and expose Rust functions
//! to scripts through a [`FunctionBundle`].
//!
//! See the [`rhai`] module for a runnable example (requires the `rhai` feature).

/// Error types for postscriptum.
pub mod error;

/// The [Rhai](https://rhai.rs) scripting backend.
///
/// ## Example
///
/// ```
/// use postscriptum::{EngineType, FunctionBundle, get_engine_with_bundle};
///
/// let mut bundle = FunctionBundle::new(EngineType::Rhai);
/// bundle.add_rhai_fn1::<fn(i64) -> i64, i64, i64>("double", |x: i64| x * 2);
///
/// let mut engine = get_engine_with_bundle(EngineType::Rhai, &bundle);
/// assert_eq!(engine.eval("double(21)").unwrap(), "42");
/// ```
#[cfg(feature = "rhai")]
pub mod rhai;

/// The Python backend (native via `pyo3`, WASM via Pyodide).
#[cfg(feature = "python")]
pub mod python;

/// A unified bundle of Rust functions callable from scripts.
pub mod function_bundle;

#[cfg(target_arch = "wasm32")]
pub mod wasm_utils;

pub use error::{Error, Result};
pub use function_bundle::FunctionBundle;

use std::any::Any;
use std::sync::{Arc, Mutex};

/// The core interface every scripting backend implements.
///
/// `eval` runs `code` and returns the result as a string. Engines keep their
/// interpreter state between calls, so variables persist across evaluations.
pub trait ScriptEngine: Any {
    /// Evaluate `code` and return the result as a string.
    fn eval(&mut self, code: &str) -> Result<String>;

    /// Allow downcasting to the concrete engine type.
    fn as_any(&mut self) -> &mut dyn Any;
}

/// Wrapper that makes non-`Send` engines usable across threads.
///
/// Internally an `Arc<Mutex<Box<dyn ScriptEngine>>>`; clones share the same
/// underlying engine.
// The `unsafe impl Send/Sync` below is exactly the point: the inner engine is
// non-`Send`, so the `Arc` sharing it deliberately relies on the mutex + our
// explicit `Send`/`Sync` impls.
#[derive(Clone)]
pub struct ThreadSafeEngine {
    engine: Arc<Mutex<Box<dyn ScriptEngine>>>,
}

// Safety: Arc<Mutex<...>> ensures thread safety for non-Send/Sync types
unsafe impl Send for ThreadSafeEngine {}
unsafe impl Sync for ThreadSafeEngine {}

impl ThreadSafeEngine {
    /// Wrap an existing engine.
    // The engine is non-`Send`; the `Arc<Mutex<…>>` + `unsafe impl Send/Sync` is
    // the intended thread-safety mechanism (see the struct docs).
    #[allow(clippy::arc_with_non_send_sync)]
    pub fn new(engine: Box<dyn ScriptEngine>) -> Self {
        ThreadSafeEngine {
            engine: Arc::new(Mutex::new(engine)),
        }
    }

    /// Create a thread-safe engine of the given type, registering `bundle`'s
    /// functions. This wraps [`get_engine_with_bundle`].
    pub fn new_with_bundle(engine_type: EngineType, bundle: &FunctionBundle) -> Self {
        ThreadSafeEngine::new(get_engine_with_bundle(engine_type, bundle))
    }

    /// Evaluate `code` on the wrapped engine, returning the result string.
    pub fn eval(&self, code: &str) -> Result<String> {
        let mut engine = self.engine.lock().map_err(|_| Error::MutexPoisoned)?;
        engine.eval(code)
    }
}

/// The set of scripting backends available.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum EngineType {
    /// The [Rhai](https://rhai.rs) scripting engine (pure Rust).
    #[cfg(feature = "rhai")]
    Rhai,
    /// The CPython engine (native via `pyo3`, WASM via Pyodide).
    #[cfg(feature = "python")]
    Python,
    // Add more: Lua, Js
}

/// Create a bare engine of the given type (no registered functions).
pub fn get_engine(engine_type: EngineType) -> Box<dyn ScriptEngine> {
    match engine_type {
        #[cfg(feature = "rhai")]
        EngineType::Rhai => Box::new(rhai::RhaiEngine::new()),
        #[cfg(feature = "python")]
        EngineType::Python => Box::new(python::PythonEngine::new()),
        // Extend here for other engines
    }
}

/// Create an engine of the given type with `bundle`'s functions registered.
///
/// This is the canonical way to build a bundle-registered engine;
/// [`ThreadSafeEngine::new_with_bundle`] wraps the result.
pub fn get_engine_with_bundle(
    engine_type: EngineType,
    bundle: &FunctionBundle,
) -> Box<dyn ScriptEngine> {
    match engine_type {
        #[cfg(feature = "rhai")]
        EngineType::Rhai => {
            // For Rhai, use the constructor that allows bundle registration
            Box::new(rhai::RhaiEngine::with_bundle(bundle))
        }
        #[cfg(feature = "python")]
        EngineType::Python => {
            // For Python, create the engine and register the bundle
            let mut engine = python::PythonEngine::new();
            let _ = engine.register_bundle(bundle);
            Box::new(engine)
        }
    }
}