rhai/src/fn_native.rs

448 lines
14 KiB
Rust
Raw Normal View History

//! Module defining interfaces to native-Rust functions.
2020-05-11 07:36:50 +02:00
use crate::any::Dynamic;
use crate::engine::Engine;
2020-07-26 07:51:09 +02:00
use crate::module::Module;
2020-08-05 16:53:01 +02:00
use crate::parser::{FnAccess, ScriptFnDef};
2020-07-26 10:10:38 +02:00
use crate::plugin::PluginFunction;
2020-05-11 07:36:50 +02:00
use crate::result::EvalAltResult;
use crate::token::{is_valid_identifier, Position};
2020-07-26 07:51:09 +02:00
use crate::utils::ImmutableString;
2020-05-11 07:36:50 +02:00
2020-07-26 07:51:09 +02:00
#[cfg(not(feature = "no_function"))]
2020-08-05 16:53:01 +02:00
use crate::{calc_fn_hash, module::FuncReturn, utils::StaticVec};
2020-07-26 07:51:09 +02:00
2020-08-05 16:53:01 +02:00
use crate::stdlib::{boxed::Box, convert::TryFrom, fmt, string::String, vec::Vec};
2020-07-26 07:51:09 +02:00
#[cfg(not(feature = "no_function"))]
2020-08-05 16:53:01 +02:00
use crate::stdlib::{iter::empty, mem};
2020-07-26 04:03:59 +02:00
#[cfg(not(feature = "sync"))]
use crate::stdlib::rc::Rc;
#[cfg(feature = "sync")]
use crate::stdlib::sync::Arc;
2020-05-11 07:36:50 +02:00
2020-06-18 12:39:28 +02:00
/// Trait that maps to `Send + Sync` only under the `sync` feature.
2020-05-12 10:32:22 +02:00
#[cfg(feature = "sync")]
2020-05-21 11:11:01 +02:00
pub trait SendSync: Send + Sync {}
/// Trait that maps to `Send + Sync` only under the `sync` feature.
2020-05-12 10:32:22 +02:00
#[cfg(feature = "sync")]
2020-05-21 11:11:01 +02:00
impl<T: Send + Sync> SendSync for T {}
2020-05-12 10:32:22 +02:00
2020-06-18 12:39:28 +02:00
/// Trait that maps to `Send + Sync` only under the `sync` feature.
2020-05-12 10:32:22 +02:00
#[cfg(not(feature = "sync"))]
2020-05-21 11:11:01 +02:00
pub trait SendSync {}
/// Trait that maps to `Send + Sync` only under the `sync` feature.
2020-05-12 10:32:22 +02:00
#[cfg(not(feature = "sync"))]
2020-05-21 11:11:01 +02:00
impl<T> SendSync for T {}
2020-05-12 10:32:22 +02:00
/// Immutable reference-counted container
2020-05-12 10:32:22 +02:00
#[cfg(not(feature = "sync"))]
2020-05-21 11:11:01 +02:00
pub type Shared<T> = Rc<T>;
/// Immutable reference-counted container
2020-05-12 10:32:22 +02:00
#[cfg(feature = "sync")]
2020-05-21 11:11:01 +02:00
pub type Shared<T> = Arc<T>;
2020-05-12 10:32:22 +02:00
2020-05-26 08:14:03 +02:00
/// Consume a `Shared` resource and return a mutable reference to the wrapped value.
/// If the resource is shared (i.e. has other outstanding references), a cloned copy is used.
2020-05-25 11:01:39 +02:00
pub fn shared_make_mut<T: Clone>(value: &mut Shared<T>) -> &mut T {
#[cfg(not(feature = "sync"))]
2020-07-04 16:53:00 +02:00
return Rc::make_mut(value);
2020-05-25 11:01:39 +02:00
#[cfg(feature = "sync")]
2020-07-04 16:53:00 +02:00
return Arc::make_mut(value);
2020-05-25 11:01:39 +02:00
}
2020-08-08 10:24:10 +02:00
/// Consume a `Shared` resource if is unique (i.e. not shared).
2020-08-08 11:04:21 +02:00
pub fn shared_try_take<T>(value: Shared<T>) -> Result<T, Shared<T>> {
2020-08-08 10:24:10 +02:00
#[cfg(not(feature = "sync"))]
return Rc::try_unwrap(value);
#[cfg(feature = "sync")]
return Arc::try_unwrap(value);
}
2020-05-26 08:14:03 +02:00
/// Consume a `Shared` resource, assuming that it is unique (i.e. not shared).
///
/// # Panics
///
/// Panics if the resource is shared (i.e. has other outstanding references).
2020-08-08 11:04:21 +02:00
pub fn shared_take<T>(value: Shared<T>) -> T {
2020-08-08 10:24:10 +02:00
shared_try_take(value).map_err(|_| ()).unwrap()
2020-05-25 11:01:39 +02:00
}
2020-05-21 11:11:01 +02:00
pub type FnCallArgs<'a> = [&'a mut Dynamic];
2020-05-12 10:32:22 +02:00
2020-07-23 09:49:09 +02:00
/// A general function pointer, which may carry additional (i.e. curried) argument values
/// to be passed onto a function during a call.
2020-07-22 17:12:09 +02:00
#[derive(Debug, Clone, Default)]
pub struct FnPtr(ImmutableString, Vec<Dynamic>);
2020-06-25 12:07:57 +02:00
impl FnPtr {
/// Create a new function pointer.
2020-07-22 17:12:09 +02:00
pub(crate) fn new_unchecked<S: Into<ImmutableString>>(name: S, curry: Vec<Dynamic>) -> Self {
Self(name.into(), curry)
}
2020-06-25 12:07:57 +02:00
/// Get the name of the function.
pub fn fn_name(&self) -> &str {
self.get_fn_name().as_ref()
}
/// Get the name of the function.
pub(crate) fn get_fn_name(&self) -> &ImmutableString {
&self.0
}
2020-07-23 04:12:51 +02:00
/// Get the underlying data of the function pointer.
pub(crate) fn take_data(self) -> (ImmutableString, Vec<Dynamic>) {
(self.0, self.1)
2020-06-29 17:55:28 +02:00
}
2020-07-23 09:49:09 +02:00
/// Get the curried arguments.
pub fn curry(&self) -> &[Dynamic] {
2020-07-22 17:12:09 +02:00
&self.1
}
2020-07-23 09:49:09 +02:00
/// Call the function pointer with curried arguments (if any).
///
/// If this function is a script-defined function, it must not be marked private.
2020-07-26 07:51:09 +02:00
///
2020-07-23 09:49:09 +02:00
/// ## WARNING
///
/// All the arguments are _consumed_, meaning that they're replaced by `()`.
/// This is to avoid unnecessarily cloning the arguments.
/// Do not use the arguments after this call. If they are needed afterwards,
/// clone them _before_ calling this function.
2020-07-26 07:51:09 +02:00
#[cfg(not(feature = "no_function"))]
pub fn call_dynamic(
&self,
engine: &Engine,
lib: impl AsRef<Module>,
2020-07-23 09:49:09 +02:00
this_ptr: Option<&mut Dynamic>,
mut arg_values: impl AsMut<[Dynamic]>,
) -> FuncReturn<Dynamic> {
let mut args_data = self
.1
.iter()
.cloned()
2020-07-23 09:49:09 +02:00
.chain(arg_values.as_mut().iter_mut().map(|v| mem::take(v)))
.collect::<StaticVec<_>>();
let has_this = this_ptr.is_some();
let args_len = args_data.len();
let mut args = args_data.iter_mut().collect::<StaticVec<_>>();
if let Some(obj) = this_ptr {
args.insert(0, obj);
}
let fn_name = self.0.as_str();
let hash_script = calc_fn_hash(empty(), fn_name, args_len, empty());
engine
.exec_fn_call(
&mut Default::default(),
lib.as_ref(),
fn_name,
hash_script,
args.as_mut(),
has_this,
has_this,
true,
None,
&None,
0,
)
.map(|(v, _)| v)
2020-06-29 17:55:28 +02:00
}
2020-06-25 12:07:57 +02:00
}
impl fmt::Display for FnPtr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Fn({})", self.0)
}
}
impl TryFrom<ImmutableString> for FnPtr {
type Error = Box<EvalAltResult>;
fn try_from(value: ImmutableString) -> Result<Self, Self::Error> {
if is_valid_identifier(value.chars()) {
2020-07-22 17:12:09 +02:00
Ok(Self(value, Default::default()))
} else {
2020-08-06 04:17:32 +02:00
EvalAltResult::ErrorFunctionNotFound(value.into(), Position::none()).into()
}
}
}
impl TryFrom<String> for FnPtr {
type Error = Box<EvalAltResult>;
fn try_from(value: String) -> Result<Self, Self::Error> {
let s: ImmutableString = value.into();
Self::try_from(s)
}
}
impl TryFrom<&str> for FnPtr {
type Error = Box<EvalAltResult>;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let s: ImmutableString = value.into();
Self::try_from(s)
2020-06-25 12:07:57 +02:00
}
}
/// A general function trail object.
2020-05-19 16:25:57 +02:00
#[cfg(not(feature = "sync"))]
pub type FnAny = dyn Fn(&Engine, &Module, &mut FnCallArgs) -> Result<Dynamic, Box<EvalAltResult>>;
2020-06-25 12:07:57 +02:00
/// A general function trail object.
2020-05-19 16:25:57 +02:00
#[cfg(feature = "sync")]
pub type FnAny =
dyn Fn(&Engine, &Module, &mut FnCallArgs) -> Result<Dynamic, Box<EvalAltResult>> + Send + Sync;
2020-05-19 16:25:57 +02:00
2020-06-18 12:39:28 +02:00
/// A standard function that gets an iterator from a type.
2020-05-21 11:11:01 +02:00
pub type IteratorFn = fn(Dynamic) -> Box<dyn Iterator<Item = Dynamic>>;
2020-05-19 16:25:57 +02:00
2020-07-02 06:47:24 +02:00
#[cfg(feature = "sync")]
pub type SharedPluginFunction = Arc<dyn PluginFunction + Send + Sync>;
#[cfg(not(feature = "sync"))]
pub type SharedPluginFunction = Rc<dyn PluginFunction>;
2020-06-18 12:39:28 +02:00
/// A standard callback function.
2020-06-02 07:33:16 +02:00
#[cfg(not(feature = "sync"))]
pub type Callback<T, R> = Box<dyn Fn(&T) -> R + 'static>;
2020-06-18 12:39:28 +02:00
/// A standard callback function.
2020-06-02 07:33:16 +02:00
#[cfg(feature = "sync")]
pub type Callback<T, R> = Box<dyn Fn(&T) -> R + Send + Sync + 'static>;
/// A type encapsulating a function callable by Rhai.
2020-05-19 16:25:57 +02:00
#[derive(Clone)]
pub enum CallableFunction {
/// A pure native Rust function with all arguments passed by value.
2020-05-21 11:11:01 +02:00
Pure(Shared<FnAny>),
/// A native Rust object method with the first argument passed by reference,
/// and the rest passed by value.
2020-05-21 11:11:01 +02:00
Method(Shared<FnAny>),
/// An iterator function.
2020-05-20 13:27:23 +02:00
Iterator(IteratorFn),
2020-07-02 06:47:24 +02:00
/// A plugin-defined function,
Plugin(SharedPluginFunction),
/// A script-defined function.
2020-07-04 10:21:15 +02:00
#[cfg(not(feature = "no_function"))]
Script(Shared<ScriptFnDef>),
}
impl fmt::Debug for CallableFunction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Pure(_) => write!(f, "NativePureFunction"),
Self::Method(_) => write!(f, "NativeMethod"),
Self::Iterator(_) => write!(f, "NativeIterator"),
2020-07-02 06:47:24 +02:00
Self::Plugin(_) => write!(f, "PluginFunction"),
2020-07-04 10:21:15 +02:00
#[cfg(not(feature = "no_function"))]
2020-06-11 16:18:30 +02:00
Self::Script(fn_def) => fmt::Debug::fmt(fn_def, f),
}
}
}
impl fmt::Display for CallableFunction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Pure(_) => write!(f, "NativePureFunction"),
Self::Method(_) => write!(f, "NativeMethod"),
Self::Iterator(_) => write!(f, "NativeIterator"),
2020-07-02 06:47:24 +02:00
Self::Plugin(_) => write!(f, "PluginFunction"),
2020-07-04 10:21:15 +02:00
#[cfg(not(feature = "no_function"))]
CallableFunction::Script(s) => fmt::Display::fmt(s, f),
}
}
}
impl CallableFunction {
/// Is this a pure native Rust function?
pub fn is_pure(&self) -> bool {
match self {
2020-05-19 16:25:57 +02:00
Self::Pure(_) => true,
Self::Method(_) | Self::Iterator(_) => false,
Self::Plugin(p) => !p.is_method_call(),
2020-07-04 10:21:15 +02:00
#[cfg(not(feature = "no_function"))]
Self::Script(_) => false,
}
}
2020-06-26 04:39:18 +02:00
/// Is this a native Rust method function?
pub fn is_method(&self) -> bool {
match self {
2020-05-19 16:25:57 +02:00
Self::Method(_) => true,
Self::Pure(_) | Self::Iterator(_) => false,
Self::Plugin(p) => p.is_method_call(),
2020-07-04 10:21:15 +02:00
#[cfg(not(feature = "no_function"))]
Self::Script(_) => false,
}
2020-05-11 07:36:50 +02:00
}
/// Is this an iterator function?
pub fn is_iter(&self) -> bool {
match self {
2020-05-19 16:25:57 +02:00
Self::Iterator(_) => true,
2020-07-05 12:12:35 +02:00
Self::Pure(_) | Self::Method(_) | Self::Plugin(_) => false,
2020-07-04 10:21:15 +02:00
#[cfg(not(feature = "no_function"))]
Self::Script(_) => false,
}
2020-05-11 07:36:50 +02:00
}
/// Is this a Rhai-scripted function?
pub fn is_script(&self) -> bool {
match self {
2020-08-05 16:53:01 +02:00
#[cfg(not(feature = "no_function"))]
2020-05-19 16:25:57 +02:00
Self::Script(_) => true,
2020-08-05 16:53:01 +02:00
2020-07-02 06:47:24 +02:00
Self::Pure(_) | Self::Method(_) | Self::Iterator(_) | Self::Plugin(_) => false,
}
}
/// Is this a plugin-defined function?
pub fn is_plugin_fn(&self) -> bool {
match self {
Self::Plugin(_) => true,
2020-05-19 16:25:57 +02:00
Self::Pure(_) | Self::Method(_) | Self::Iterator(_) => false,
2020-08-06 04:31:15 +02:00
#[cfg(not(feature = "no_function"))]
Self::Script(_) => false,
}
}
2020-07-31 06:11:16 +02:00
/// Is this a native Rust function?
pub fn is_native(&self) -> bool {
match self {
Self::Pure(_) | Self::Method(_) => true,
2020-08-06 04:31:15 +02:00
Self::Plugin(_) => true,
2020-07-31 06:11:16 +02:00
Self::Iterator(_) => true,
#[cfg(not(feature = "no_function"))]
Self::Script(_) => false,
}
}
/// Get the access mode.
pub fn access(&self) -> FnAccess {
match self {
2020-07-29 08:17:40 +02:00
Self::Plugin(_) => FnAccess::Public,
2020-07-28 13:11:37 +02:00
Self::Pure(_) | Self::Method(_) | Self::Iterator(_) => FnAccess::Public,
2020-08-05 16:53:01 +02:00
#[cfg(not(feature = "no_function"))]
2020-07-28 13:11:37 +02:00
Self::Script(f) => f.access,
}
}
/// Get a reference to a native Rust function.
///
/// # Panics
///
/// Panics if the `CallableFunction` is not `Pure` or `Method`.
2020-05-19 16:25:57 +02:00
pub fn get_native_fn(&self) -> &FnAny {
match self {
2020-05-19 16:25:57 +02:00
Self::Pure(f) | Self::Method(f) => f.as_ref(),
2020-07-05 12:12:35 +02:00
Self::Iterator(_) | Self::Plugin(_) => unreachable!(),
2020-07-04 10:21:15 +02:00
#[cfg(not(feature = "no_function"))]
Self::Script(_) => unreachable!(),
}
}
/// Get a shared reference to a script-defined function definition.
///
/// # Panics
///
/// Panics if the `CallableFunction` is not `Script`.
2020-07-04 10:21:15 +02:00
#[cfg(not(feature = "no_function"))]
pub fn get_shared_fn_def(&self) -> Shared<ScriptFnDef> {
match self {
2020-07-02 06:47:24 +02:00
Self::Pure(_) | Self::Method(_) | Self::Iterator(_) | Self::Plugin(_) => unreachable!(),
Self::Script(f) => f.clone(),
}
}
/// Get a reference to a script-defined function definition.
///
/// # Panics
///
/// Panics if the `CallableFunction` is not `Script`.
pub fn get_fn_def(&self) -> &ScriptFnDef {
match self {
2020-07-02 06:47:24 +02:00
Self::Pure(_) | Self::Method(_) | Self::Iterator(_) | Self::Plugin(_) => unreachable!(),
2020-08-05 16:53:01 +02:00
#[cfg(not(feature = "no_function"))]
2020-05-19 16:25:57 +02:00
Self::Script(f) => f,
}
}
/// Get a reference to an iterator function.
///
/// # Panics
///
/// Panics if the `CallableFunction` is not `Iterator`.
2020-05-20 13:27:23 +02:00
pub fn get_iter_fn(&self) -> IteratorFn {
match self {
2020-05-20 13:27:23 +02:00
Self::Iterator(f) => *f,
2020-07-05 12:12:35 +02:00
Self::Pure(_) | Self::Method(_) | Self::Plugin(_) => unreachable!(),
#[cfg(not(feature = "no_function"))]
Self::Script(_) => unreachable!(),
2020-07-02 06:47:24 +02:00
}
}
/// Get a reference to a plugin function.
///
/// # Panics
///
/// Panics if the `CallableFunction` is not `Plugin`.
pub fn get_plugin_fn<'s>(&'s self) -> SharedPluginFunction {
match self {
Self::Plugin(f) => f.clone(),
2020-07-05 12:12:35 +02:00
Self::Pure(_) | Self::Method(_) | Self::Iterator(_) => unreachable!(),
2020-07-04 10:21:15 +02:00
#[cfg(not(feature = "no_function"))]
Self::Script(_) => unreachable!(),
}
2020-05-11 07:36:50 +02:00
}
2020-05-19 16:25:57 +02:00
/// Create a new `CallableFunction::Pure`.
pub fn from_pure(func: Box<FnAny>) -> Self {
Self::Pure(func.into())
}
/// Create a new `CallableFunction::Method`.
pub fn from_method(func: Box<FnAny>) -> Self {
Self::Method(func.into())
}
2020-07-02 06:47:24 +02:00
#[cfg(feature = "sync")]
/// Create a new `CallableFunction::Plugin`.
pub fn from_plugin(plugin: impl PluginFunction + 'static + Send + Sync) -> Self {
Self::Plugin(Arc::new(plugin))
}
#[cfg(not(feature = "sync"))]
/// Create a new `CallableFunction::Plugin`.
pub fn from_plugin(plugin: impl PluginFunction + 'static) -> Self {
Self::Plugin(Rc::new(plugin))
}
2020-05-11 07:36:50 +02:00
}
impl From<IteratorFn> for CallableFunction {
fn from(func: IteratorFn) -> Self {
Self::Iterator(func)
}
}
impl From<ScriptFnDef> for CallableFunction {
2020-08-05 16:53:01 +02:00
fn from(_func: ScriptFnDef) -> Self {
#[cfg(feature = "no_function")]
unreachable!();
#[cfg(not(feature = "no_function"))]
Self::Script(_func.into())
}
}
impl From<Shared<ScriptFnDef>> for CallableFunction {
2020-08-05 16:53:01 +02:00
fn from(_func: Shared<ScriptFnDef>) -> Self {
#[cfg(feature = "no_function")]
unreachable!();
#[cfg(not(feature = "no_function"))]
Self::Script(_func)
}
}