postscriptum 0.1.1

Multi-interpreted-language scripting engine for Rust with Rhai and Python backends
Documentation
pub mod function_bundle;

cfg_if::cfg_if! {
    if #[cfg(target_arch = "wasm32")] {
        pub mod wasm_function_bundle;
    }
}

use super::{FunctionBundle, ScriptEngine};
use crate::{Error, LimitKind, Result};

cfg_if::cfg_if! { if #[cfg(not(target_arch = "wasm32"))] {
    mod native;
    use pyo3::prelude::*;
    use pyo3::types::{PyCode, PyDict};
    use native::create_context;
}}

cfg_if::cfg_if! { if #[cfg(target_arch = "wasm32")] {
    mod wasm;
    use std::cell::RefCell;
}}

pub struct PythonEngine {
    #[cfg(not(target_arch = "wasm32"))]
    pub globals: Py<PyDict>,
    // Empty struct for native, has initialized field for WASM
    #[cfg(target_arch = "wasm32")]
    _initialized: bool, // renamed to avoid unused warning on WASM
    /// Names bound through [`Self::set_var`] (WASM only): `clear()`
    /// unbinds exactly these (the shared `__main__` namespace cannot
    /// be wiped safely). Interior mutability — `set_var` takes `&self`.
    #[cfg(target_arch = "wasm32")]
    bound_names: RefCell<Vec<String>>,
}

/// A pre-compiled Python snippet (G4): validate once (syntax errors
/// surface WITHOUT executing anything), evaluate many times via
/// [`PythonEngine::eval_compiled`].
///
/// Native holds a real code object; WASM holds validated source (code
/// objects are impractical over Pyodide's `runPython` — documented
/// gap, string eval as fallback, byte-identity still holds).
///
/// `Clone` is deliberately NOT derived (`Py<PyCode>` is not `Clone`):
/// compile once, reuse by reference.
#[derive(Debug)]
pub struct PyCodeHandle {
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) code: Py<PyCode>,
    /// True when the object is `eval`-mode (same object `py.eval`
    /// would produce for a single expression).
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) eval_mode: bool,
    /// True when running binds `__result__` (rewritten form
    /// compiled); false = raw source, result extracted like string
    /// eval. See `native.rs` for the exact mirror contract.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) has_result: bool,
    /// Original (trimmed) source: fallback chain + WASM evaluation.
    pub(crate) src: String,
}

impl PythonEngine {
    pub fn new() -> Self {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let globals = create_context();
            Self { globals }
        }
        #[cfg(target_arch = "wasm32")]
        {
            // We can't guarantee Pyodide is loaded at this time, so we just mark as uninitialized
            PythonEngine {
                _initialized: false,
                bound_names: RefCell::new(Vec::new()),
            }
        }
    }

    pub fn with_bundle(bundle: &FunctionBundle) -> Result<Self> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            native::create_with_bundle(bundle).map_err(|e| Error::Python(e.to_string()))
        }

        #[cfg(target_arch = "wasm32")]
        {
            // For WASM, we create the engine and then register the bundle if it's available
            let mut engine = Self {
                _initialized: false,
                bound_names: RefCell::new(Vec::new()),
            };
            // Try to register the bundle immediately - this will work if Pyodide is already loaded
            wasm::register_bundle(&mut engine, bundle)?;
            Ok(engine)
        }
    }

    // Register a function bundle with this Python engine
    pub fn register_bundle(&mut self, bundle: &FunctionBundle) -> Result<()> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            native::register_bundle(self, bundle).map_err(|e| Error::Python(e.to_string()))
        }

        #[cfg(target_arch = "wasm32")]
        {
            // For WASM, we register with Pyodide when the bundle is available
            wasm::register_bundle(self, bundle)?;
            // Update the initialized status after successful registration
            self._initialized = true;
            Ok(())
        }
    }

    /// Bounded-eval entry point: always refuses with
    /// [`Error::LimitUnsupported`].
    ///
    /// CPython offers no safe in-process fuel cap (no op counter;
    /// killing a GIL-holding thread is unsound; `sys.settrace`-based
    /// stepping is bypassable and racy), so bounded evaluation is
    /// refused by contract rather than faked with a timeout. This is
    /// the documented policy: Python stays gated-but-allowed for
    /// longer scripts under code-signature accountability.
    ///
    /// Shared by the native (pyo3) and WASM (Pyodide) backends — the
    /// refusal is about the language runtime, not the embedding.
    pub fn with_limits() -> Result<Self> {
        Err(Error::LimitUnsupported {
            backend: super::EngineType::Python,
            limit: "resource budgets",
        })
    }

    /// Bind a JSON value in the shared globals under `name` (G3).
    ///
    /// The name must satisfy the shared identifier precondition
    /// ([`Error::InvalidName`] otherwise — the WASM backend
    /// interpolates it into code, so both backends reject
    /// identically). Overwrites live bindings; persists across
    /// evals (scope conservation falls out of the shared dict).
    pub fn set_var(&self, name: &str, value: serde_json::Value) -> Result<()> {
        crate::check_var_name(name)?;
        #[cfg(not(target_arch = "wasm32"))]
        {
            native::set_var(self, name, &value)
        }

        #[cfg(target_arch = "wasm32")]
        {
            wasm::set_var(self, name, &value)
        }
    }

    /// Evaluate and return typed JSON (G3) — the alternative to lossy
    /// `to_string()`. Bare-statement runs yield `Null`;
    /// unconvertible results yield [`Error::UnconvertibleValue`],
    /// never a panic. Native AND Pyodide paths.
    pub fn eval_json(&mut self, code: &str) -> Result<serde_json::Value> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            native::eval_json(self, code)
        }

        #[cfg(target_arch = "wasm32")]
        {
            wasm::eval_json(self, code)
        }
    }

    /// Compile once per query (G4): validates WITHOUT executing
    /// (Quartertone uses this for code it never runs), enforces the
    /// source cap in bytes ([`Error::ResourceExhausted`] with
    /// [`LimitKind::Source`]), and returns a handle for
    /// [`Self::eval_compiled`].
    pub fn compile_py(&self, src: &str) -> Result<PyCodeHandle> {
        if src.len() > crate::DEFAULT_MAX_SOURCE_LEN {
            return Err(Error::ResourceExhausted {
                backend: super::EngineType::Python,
                kind: LimitKind::Source,
            });
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            native::compile_py(src)
        }

        #[cfg(target_arch = "wasm32")]
        {
            wasm::compile_py(src)
        }
    }

    /// Evaluate a handle from [`Self::compile_py`] (G4): byte-identical
    /// to [`Self::eval_json`] on the same source (mirror contract —
    /// pinned by test), minus re-parsing the first step.
    pub fn eval_compiled(&mut self, handle: &PyCodeHandle) -> Result<serde_json::Value> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            native::eval_compiled(self, handle)
        }

        #[cfg(target_arch = "wasm32")]
        {
            wasm::eval_compiled(self, handle)
        }
    }

    /// Fork into an independent engine (G6).
    ///
    /// Native: a fresh globals dict with a SHALLOW copy — rebound
    /// names are isolated, mutable values are aliased (documented).
    /// WASM: a fresh handle SHARING Pyodide's `__main__` namespace
    /// (documented non-isolation — volatile callers needing real
    /// isolation run Rhai).
    pub fn fork(&self) -> Result<Self> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            native::fork(self)
        }

        #[cfg(target_arch = "wasm32")]
        {
            wasm::fork(self)
        }
    }

    /// Empty the scope (G6): the next eval referencing a cleared
    /// binding fails.
    ///
    /// Native: total (`dict.clear()`). WASM: removes names bound
    /// through [`Self::set_var`] on this handle only (user-bound
    /// names persist — wiping the shared `__main__` namespace would
    /// affect every handle).
    pub fn clear(&mut self) -> Result<()> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            native::clear(self)
        }

        #[cfg(target_arch = "wasm32")]
        {
            wasm::clear(self)
        }
    }
}

/// Quote JSON text as a Python `"…"` string literal (shared helper
/// for the WASM backend, unit-tested natively).
///
/// Correct for ALL `serde_json` output: it never emits `\/`, and
/// `\"`, `\\`, `\n`, `\uXXXX`, … mean the same in JSON and Python,
/// so escaping `\` and `"` round-trips exactly.
#[cfg(any(test, target_arch = "wasm32"))]
pub(super) fn py_string_literal(json_text: &str) -> String {
    let mut out = String::with_capacity(json_text.len() + 2);
    out.push('"');
    for c in json_text.chars() {
        match c {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            _ => out.push(c),
        }
    }
    out.push('"');
    out
}

#[cfg(all(test, feature = "python"))]
mod tests {
    use super::py_string_literal;

    #[test]
    fn py_string_literal_escapes_exactly() {
        assert_eq!(py_string_literal(""), "\"\"");
        assert_eq!(py_string_literal("abc"), "\"abc\"");
        assert_eq!(py_string_literal("a\"b"), "\"a\\\"b\"");
        assert_eq!(py_string_literal("a\\b"), "\"a\\\\b\"");
        // serde_json control escapes pass through (same meaning both sides).
        assert_eq!(py_string_literal("a\\nb"), "\"a\\\\nb\"");
        assert_eq!(py_string_literal("a\\u0001b"), "\"a\\\\u0001b\"");
        // Single quotes need no escaping inside double quotes.
        assert_eq!(py_string_literal("it's"), "\"it's\"");
        // Non-ASCII passes through raw (valid in Python literals).
        assert_eq!(py_string_literal("héllo"), "\"héllo\"");
    }
}

impl Default for PythonEngine {
    fn default() -> Self {
        Self::new()
    }
}

impl ScriptEngine for PythonEngine {
    fn eval(&mut self, code: &str) -> Result<String> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            native::eval(self, code)
        }

        #[cfg(target_arch = "wasm32")]
        {
            wasm::eval(self, code)
        }
    }

    fn as_any(&mut self) -> &mut dyn std::any::Any {
        self
    }
}