pub mod error;
#[cfg(feature = "rhai")]
pub mod rhai;
#[cfg(feature = "python")]
pub mod python;
pub mod function_bundle;
#[cfg(target_arch = "wasm32")]
pub mod wasm_utils;
pub use error::{Error, ExprIssue, ExprIssueKind, LimitKind, Result, ValidationError};
pub use function_bundle::FunctionBundle;
pub const DEFAULT_MAX_SOURCE_LEN: usize = 8 * 1024;
#[cfg(feature = "rhai")]
pub use rhai::{
BoundedRhaiEngine, CompiledExpr, DEFAULT_MAX_ARRAY_SIZE, DEFAULT_MAX_CALL_LEVELS,
DEFAULT_MAX_MAP_SIZE, DEFAULT_MAX_OPERATIONS, DEFAULT_MAX_STRING_SIZE, from_dynamic_value,
to_dynamic_value,
};
use std::any::Any;
use std::sync::{Arc, Mutex};
pub trait ScriptEngine: Any {
fn eval(&mut self, code: &str) -> Result<String>;
fn as_any(&mut self) -> &mut dyn Any;
}
#[derive(Clone)]
pub struct ThreadSafeEngine {
engine: Arc<Mutex<Box<dyn ScriptEngine>>>,
}
unsafe impl Send for ThreadSafeEngine {}
unsafe impl Sync for ThreadSafeEngine {}
impl ThreadSafeEngine {
#[allow(clippy::arc_with_non_send_sync)]
pub fn new(engine: Box<dyn ScriptEngine>) -> Self {
ThreadSafeEngine {
engine: Arc::new(Mutex::new(engine)),
}
}
pub fn new_with_bundle(engine_type: EngineType, bundle: &FunctionBundle) -> Self {
ThreadSafeEngine::new(get_engine_with_bundle(engine_type, bundle))
}
pub fn eval(&self, code: &str) -> Result<String> {
let mut engine = self.engine.lock().map_err(|_| Error::MutexPoisoned)?;
engine.eval(code)
}
}
pub(crate) fn check_var_name(name: &str) -> Result<()> {
let mut chars = name.chars();
let first_ok = chars.next().is_some_and(|c| c.is_ascii_alphabetic());
if !first_ok || !chars.all(|c| c.is_ascii_alphanumeric() || c == '_') {
return Err(Error::InvalidName(name.to_string()));
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum EngineType {
#[cfg(feature = "rhai")]
Rhai,
#[cfg(feature = "python")]
Python,
}
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()),
}
}
pub fn get_engine_with_bundle(
engine_type: EngineType,
bundle: &FunctionBundle,
) -> Box<dyn ScriptEngine> {
match engine_type {
#[cfg(feature = "rhai")]
EngineType::Rhai => {
Box::new(rhai::RhaiEngine::with_bundle(bundle))
}
#[cfg(feature = "python")]
EngineType::Python => {
let mut engine = python::PythonEngine::new();
let _ = engine.register_bundle(bundle);
Box::new(engine)
}
}
}