postscriptum 0.1.0

Multi-interpreted-language scripting engine for Rust with Rhai and Python backends
Documentation
cfg_if::cfg_if! {
    if #[cfg(not(target_arch = "wasm32"))] {
        use std::sync::Arc;

        use pyo3::BoundObject;
        use pyo3::prelude::*;
        use pyo3::types::{PyAny, PyCFunction, PyDict, PyTuple};

        /// Convenience alias: a type that can be extracted from a Python argument.
        ///
        /// Conversion errors are turned into `PyErr` inside the wrapper via `.map_err(Into::into)`,
        /// which relies on `FromPyObject::Error: Into<PyErr>` (guaranteed by the trait) — so no
        /// extra bounds are needed here.
        pub trait PyArg: for<'a, 'py> FromPyObject<'a, 'py> + Send + Sync + 'static {}
        impl<T: for<'a, 'py> FromPyObject<'a, 'py> + Send + Sync + 'static> PyArg for T {}

        /// Convenience alias: a type that can be returned from a Python function.
        pub trait PyReturn: for<'py> IntoPyObject<'py> + Send + Sync + 'static {}
        impl<T: for<'py> IntoPyObject<'py> + Send + Sync + 'static> PyReturn for T {}

        /// A single Python-callable function stored as a closure.
        ///
        /// This replaces the previous per-arity `Function0..4` / `wrap_fn0..4` machinery
        /// and its wall of `IntoPyObject` / `FromPyObject` bounds. The closure performs
        /// its own argument extraction and return conversion; the `add_fn0..4` helpers
        /// only need `PyArg` / `PyReturn`, which are satisfied by any standard type.
        #[derive(Clone)]
        pub struct PythonFn {
            pub name: String,
            pub func: Arc<
                dyn Fn(&Bound<'_, PyTuple>, Option<&Bound<'_, PyDict>>) -> PyResult<Py<PyAny>>
                    + Send
                    + Sync,
            >,
        }

        /// Python-specific function bundle.
        #[derive(Clone, Default)]
        pub struct PythonFunctionBundle {
            pub functions: Vec<PythonFn>,
        }

        impl PythonFunctionBundle {
            pub fn new() -> Self {
                Self {
                    functions: Vec::new(),
                }
            }

            pub fn add_fn0<F, R>(&mut self, name: &str, f: F)
            where
                F: Fn() -> R + Send + Sync + 'static,
                R: PyReturn,
            {
                let name = name.to_string();
                self.functions.push(PythonFn {
                    name: name.clone(),
                    func: Arc::new(move |args, _kwargs| {
                        Ok(f().into_pyobject(args.py()).map_err(Into::into)?.into_any().unbind())
                    }),
                });
            }

            pub fn add_fn1<F, A, R>(&mut self, name: &str, f: F)
            where
                F: Fn(A) -> R + Send + Sync + 'static,
                A: PyArg,
                R: PyReturn,
            {
                let name = name.to_string();
                self.functions.push(PythonFn {
                    name: name.clone(),
                    func: Arc::new(move |args, _kwargs| {
                        if args.len() != 1 {
                            return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(format!(
                                "{} takes 1 argument, got {}",
                                name,
                                args.len()
                            )));
                        }
                        let a: A = args.get_item(0)?.extract().map_err(Into::into)?;
                        Ok(f(a).into_pyobject(args.py()).map_err(Into::into)?.into_any().unbind())
                    }),
                });
            }

            pub fn add_fn2<F, A, B, R>(&mut self, name: &str, f: F)
            where
                F: Fn(A, B) -> R + Send + Sync + 'static,
                A: PyArg,
                B: PyArg,
                R: PyReturn,
            {
                let name = name.to_string();
                self.functions.push(PythonFn {
                    name: name.clone(),
                    func: Arc::new(move |args, _kwargs| {
                        if args.len() != 2 {
                            return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(format!(
                                "{} takes 2 arguments, got {}",
                                name,
                                args.len()
                            )));
                        }
                        let a: A = args.get_item(0)?.extract().map_err(Into::into)?;
                        let b: B = args.get_item(1)?.extract().map_err(Into::into)?;
                        Ok(f(a, b).into_pyobject(args.py()).map_err(Into::into)?.into_any().unbind())
                    }),
                });
            }

            pub fn add_fn3<F, A, B, C, R>(&mut self, name: &str, f: F)
            where
                F: Fn(A, B, C) -> R + Send + Sync + 'static,
                A: PyArg,
                B: PyArg,
                C: PyArg,
                R: PyReturn,
            {
                let name = name.to_string();
                self.functions.push(PythonFn {
                    name: name.clone(),
                    func: Arc::new(move |args, _kwargs| {
                        if args.len() != 3 {
                            return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(format!(
                                "{} takes 3 arguments, got {}",
                                name,
                                args.len()
                            )));
                        }
                        let a: A = args.get_item(0)?.extract().map_err(Into::into)?;
                        let b: B = args.get_item(1)?.extract().map_err(Into::into)?;
                        let c: C = args.get_item(2)?.extract().map_err(Into::into)?;
                        Ok(f(a, b, c).into_pyobject(args.py()).map_err(Into::into)?.into_any().unbind())
                    }),
                });
            }

            pub fn add_fn4<F, A, B, C, D, R>(&mut self, name: &str, f: F)
            where
                F: Fn(A, B, C, D) -> R + Send + Sync + 'static,
                A: PyArg,
                B: PyArg,
                C: PyArg,
                D: PyArg,
                R: PyReturn,
            {
                let name = name.to_string();
                self.functions.push(PythonFn {
                    name: name.clone(),
                    func: Arc::new(move |args, _kwargs| {
                        if args.len() != 4 {
                            return Err(PyErr::new::<pyo3::exceptions::PyTypeError, _>(format!(
                                "{} takes 4 arguments, got {}",
                                name,
                                args.len()
                            )));
                        }
                        let a: A = args.get_item(0)?.extract().map_err(Into::into)?;
                        let b: B = args.get_item(1)?.extract().map_err(Into::into)?;
                        let c: C = args.get_item(2)?.extract().map_err(Into::into)?;
                        let d: D = args.get_item(3)?.extract().map_err(Into::into)?;
                        Ok(f(a, b, c, d).into_pyobject(args.py()).map_err(Into::into)?.into_any().unbind())
                    }),
                });
            }

            /// Register all functions in the bundle into the Python interpreter.
            pub fn register(
                &self,
                py: Python<'_>,
                engine: &mut super::PythonEngine,
            ) -> PyResult<()> {
                let globals = engine.globals.bind(py);

                for entry in &self.functions {
                    // Convert name to CString and leak it as &'static CStr
                    let cstring = std::ffi::CString::new(entry.name.clone())
                        .expect("Function name must be valid UTF-8");
                    let static_name: &'static std::ffi::CStr =
                        Box::leak(cstring.into_boxed_c_str());

                    let func = entry.func.clone();
                    let py_func = PyCFunction::new_closure(
                        py,
                        Some(static_name),
                        None,
                        move |args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>| {
                            func(args, kwargs)
                        },
                    )?;

                    globals.set_item(entry.name.as_str(), &py_func)?;
                }

                // Also add functions to the main module so they're globally available
                let main = py.import("__main__")?;
                let main_dict = main.dict();
                for pair in globals.items() {
                    let (key, value): (Bound<'_, PyAny>, Bound<'_, PyAny>) = pair.extract()?;
                    main_dict.set_item(key, value)?;
                }

                Ok(())
            }
        }
    } else {
        // For WASM, use the implementation from the separate wasm_function_bundle module
        // The actual struct is defined there
        pub use crate::python::wasm_function_bundle::PythonFunctionBundle;
        pub use crate::python::wasm_function_bundle::PythonFunction;
    }
}