Skip to main content

postscriptum/
lib.rs

1//! # postscriptum
2//!
3//! A multi-interpreted-language scripting engine for Rust, with **Rhai** and
4//! **Python** backends, working on both native and WASM targets. This crate is
5//! **Bevy-free**.
6//!
7//! The core abstraction is the [`ScriptEngine`] trait: a stateful interpreter
8//! that evaluates a script and returns the result as a string. Wrap it in a
9//! [`ThreadSafeEngine`] to share it across threads, and expose Rust functions
10//! to scripts through a [`FunctionBundle`].
11//!
12//! See the [`rhai`] module for a runnable example (requires the `rhai` feature).
13
14/// Error types for postscriptum.
15pub mod error;
16
17/// The [Rhai](https://rhai.rs) scripting backend.
18///
19/// ## Example
20///
21/// ```
22/// use postscriptum::{EngineType, FunctionBundle, get_engine_with_bundle};
23///
24/// let mut bundle = FunctionBundle::new(EngineType::Rhai);
25/// bundle.add_rhai_fn1::<fn(i64) -> i64, i64, i64>("double", |x: i64| x * 2);
26///
27/// let mut engine = get_engine_with_bundle(EngineType::Rhai, &bundle);
28/// assert_eq!(engine.eval("double(21)").unwrap(), "42");
29/// ```
30#[cfg(feature = "rhai")]
31pub mod rhai;
32
33/// The Python backend (native via `pyo3`, WASM via Pyodide).
34#[cfg(feature = "python")]
35pub mod python;
36
37/// A unified bundle of Rust functions callable from scripts.
38pub mod function_bundle;
39
40#[cfg(target_arch = "wasm32")]
41pub mod wasm_utils;
42
43pub use error::{Error, ExprIssue, ExprIssueKind, LimitKind, Result, ValidationError};
44pub use function_bundle::FunctionBundle;
45
46/// Starting default for the source-length cap in bytes (Quartertone
47/// bound): enforced host-side before compiling/evaluating on both
48/// backends. Dynamically settable everywhere it matters (builder
49/// field on `BoundedRhaiEngine`, parameter on Python compile) — a
50/// starting value, not fixed policy.
51pub const DEFAULT_MAX_SOURCE_LEN: usize = 8 * 1024;
52
53#[cfg(feature = "rhai")]
54pub use rhai::{
55    BoundedRhaiEngine, CompiledExpr, DEFAULT_MAX_ARRAY_SIZE, DEFAULT_MAX_CALL_LEVELS,
56    DEFAULT_MAX_MAP_SIZE, DEFAULT_MAX_OPERATIONS, DEFAULT_MAX_STRING_SIZE, from_dynamic_value,
57    to_dynamic_value,
58};
59
60use std::any::Any;
61use std::sync::{Arc, Mutex};
62
63/// The core interface every scripting backend implements.
64///
65/// `eval` runs `code` and returns the result as a string. Engines keep their
66/// interpreter state between calls, so variables persist across evaluations.
67pub trait ScriptEngine: Any {
68    /// Evaluate `code` and return the result as a string.
69    fn eval(&mut self, code: &str) -> Result<String>;
70
71    /// Allow downcasting to the concrete engine type.
72    fn as_any(&mut self) -> &mut dyn Any;
73}
74
75/// Wrapper that makes non-`Send` engines usable across threads.
76///
77/// Internally an `Arc<Mutex<Box<dyn ScriptEngine>>>`; clones share the same
78/// underlying engine.
79// The `unsafe impl Send/Sync` below is exactly the point: the inner engine is
80// non-`Send`, so the `Arc` sharing it deliberately relies on the mutex + our
81// explicit `Send`/`Sync` impls.
82#[derive(Clone)]
83pub struct ThreadSafeEngine {
84    engine: Arc<Mutex<Box<dyn ScriptEngine>>>,
85}
86
87// Safety: Arc<Mutex<...>> ensures thread safety for non-Send/Sync types
88unsafe impl Send for ThreadSafeEngine {}
89unsafe impl Sync for ThreadSafeEngine {}
90
91impl ThreadSafeEngine {
92    /// Wrap an existing engine.
93    // The engine is non-`Send`; the `Arc<Mutex<…>>` + `unsafe impl Send/Sync` is
94    // the intended thread-safety mechanism (see the struct docs).
95    #[allow(clippy::arc_with_non_send_sync)]
96    pub fn new(engine: Box<dyn ScriptEngine>) -> Self {
97        ThreadSafeEngine {
98            engine: Arc::new(Mutex::new(engine)),
99        }
100    }
101
102    /// Create a thread-safe engine of the given type, registering `bundle`'s
103    /// functions. This wraps [`get_engine_with_bundle`].
104    pub fn new_with_bundle(engine_type: EngineType, bundle: &FunctionBundle) -> Self {
105        ThreadSafeEngine::new(get_engine_with_bundle(engine_type, bundle))
106    }
107
108    /// Evaluate `code` on the wrapped engine, returning the result string.
109    pub fn eval(&self, code: &str) -> Result<String> {
110        let mut engine = self.engine.lock().map_err(|_| Error::MutexPoisoned)?;
111        engine.eval(code)
112    }
113}
114
115/// Shared `set_var` precondition (both backends reject the same
116/// names so one view definition runs on either):
117/// `^[A-Za-z][A-Za-z0-9_]*$` — a valid Python identifier AND parseable
118/// as a rhai variable (`_`-leading identifiers never parse in rhai,
119/// hence excluded even though Python would accept them).
120pub(crate) fn check_var_name(name: &str) -> Result<()> {
121    let mut chars = name.chars();
122    let first_ok = chars.next().is_some_and(|c| c.is_ascii_alphabetic());
123    if !first_ok || !chars.all(|c| c.is_ascii_alphanumeric() || c == '_') {
124        return Err(Error::InvalidName(name.to_string()));
125    }
126    Ok(())
127}
128
129/// The set of scripting backends available.
130#[derive(Debug, Clone, PartialEq, Eq, Hash)]
131pub enum EngineType {
132    /// The [Rhai](https://rhai.rs) scripting engine (pure Rust).
133    #[cfg(feature = "rhai")]
134    Rhai,
135    /// The CPython engine (native via `pyo3`, WASM via Pyodide).
136    #[cfg(feature = "python")]
137    Python,
138    // Add more: Lua, Js
139}
140
141/// Create a bare engine of the given type (no registered functions).
142pub fn get_engine(engine_type: EngineType) -> Box<dyn ScriptEngine> {
143    match engine_type {
144        #[cfg(feature = "rhai")]
145        EngineType::Rhai => Box::new(rhai::RhaiEngine::new()),
146        #[cfg(feature = "python")]
147        EngineType::Python => Box::new(python::PythonEngine::new()),
148        // Extend here for other engines
149    }
150}
151
152/// Create an engine of the given type with `bundle`'s functions registered.
153///
154/// This is the canonical way to build a bundle-registered engine;
155/// [`ThreadSafeEngine::new_with_bundle`] wraps the result.
156pub fn get_engine_with_bundle(
157    engine_type: EngineType,
158    bundle: &FunctionBundle,
159) -> Box<dyn ScriptEngine> {
160    match engine_type {
161        #[cfg(feature = "rhai")]
162        EngineType::Rhai => {
163            // For Rhai, use the constructor that allows bundle registration
164            Box::new(rhai::RhaiEngine::with_bundle(bundle))
165        }
166        #[cfg(feature = "python")]
167        EngineType::Python => {
168            // For Python, create the engine and register the bundle
169            let mut engine = python::PythonEngine::new();
170            let _ = engine.register_bundle(bundle);
171            Box::new(engine)
172        }
173    }
174}