rhai/src/fn_register.rs

241 lines
12 KiB
Rust
Raw Normal View History

2020-03-08 12:54:02 +01:00
//! Module which defines the function registration mechanism.
#![allow(non_snake_case)]
2020-11-16 16:10:14 +01:00
use crate::dynamic::{DynamicWriteLock, Variant};
2021-06-17 03:50:32 +02:00
use crate::fn_call::FnCallArgs;
use crate::fn_native::{CallableFunction, FnAny, SendSync};
use crate::r#unsafe::unsafe_try_cast;
use crate::token::Position;
2021-03-15 05:39:06 +01:00
use crate::{Dynamic, EvalAltResult, NativeCallContext};
2021-04-17 09:15:54 +02:00
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{any::TypeId, mem};
2016-02-29 22:43:45 +01:00
2020-03-25 04:24:06 +01:00
// These types are used to build a unique _marker_ tuple type for each combination
// of function parameter types in order to make each trait implementation unique.
// That is because stable Rust currently does not allow distinguishing implementations
2020-11-25 02:36:06 +01:00
// based purely on parameter types of traits (`Fn`, `FnOnce` and `FnMut`).
2020-03-25 04:24:06 +01:00
//
// For example:
//
// `NativeFunction<(Mut<A>, B, Ref<C>), R>`
2020-03-25 04:24:06 +01:00
//
// will have the function prototype constraint to:
//
// `FN: (&mut A, B, &C) -> R`
//
// These types are not actually used anywhere.
pub struct Mut<T>(T);
//pub struct Ref<T>(T);
/// Dereference into DynamicWriteLock
2020-05-11 07:36:50 +02:00
#[inline(always)]
2021-06-12 16:47:43 +02:00
#[must_use]
pub fn by_ref<T: Variant + Clone>(data: &mut Dynamic) -> DynamicWriteLock<T> {
// Directly cast the &mut Dynamic into DynamicWriteLock to access the underlying data.
2021-05-22 13:14:24 +02:00
data.write_lock::<T>()
.expect("never fails because the type was checked")
2020-03-24 09:57:35 +01:00
}
/// Dereference into value.
2020-05-11 07:36:50 +02:00
#[inline(always)]
2021-06-12 16:47:43 +02:00
#[must_use]
2020-05-12 10:32:22 +02:00
pub fn by_value<T: Variant + Clone>(data: &mut Dynamic) -> T {
if TypeId::of::<T>() == TypeId::of::<&str>() {
// If T is `&str`, data must be `ImmutableString`, so map directly to it
data.flatten_in_place();
let ref_str = data
.as_str_ref()
2021-05-22 13:14:24 +02:00
.expect("never fails because argument passed by value should not be shared");
let ref_t = unsafe { mem::transmute::<_, &T>(&ref_str) };
ref_t.clone()
} else if TypeId::of::<T>() == TypeId::of::<String>() {
// If T is `String`, data must be `ImmutableString`, so map directly to it
2021-05-22 13:14:24 +02:00
let value = mem::take(data)
.as_string()
2021-05-22 13:14:24 +02:00
.expect("never fails because the type was checked");
unsafe_try_cast(value).expect("never fails because the type was checked")
} else {
// We consume the argument and then replace it with () - the argument is not supposed to be used again.
// This way, we avoid having to clone the argument again, because it is already a clone when passed here.
mem::take(data).cast::<T>()
}
}
2021-03-15 05:39:06 +01:00
/// Trait to register custom Rust functions.
pub trait RegisterNativeFunction<Args, Result> {
2021-03-24 03:02:50 +01:00
/// Convert this function into a [`CallableFunction`].
2021-06-12 16:47:43 +02:00
#[must_use]
2021-03-24 03:02:50 +01:00
fn into_callable_function(self) -> CallableFunction;
2021-03-15 15:19:21 +01:00
/// Get the type ID's of this function's parameters.
2021-06-12 16:47:43 +02:00
#[must_use]
2021-03-15 05:39:06 +01:00
fn param_types() -> Box<[TypeId]>;
2021-07-25 16:56:05 +02:00
/// _(metadata)_ Get the type names of this function's parameters.
/// Exported under the `metadata` feature only.
#[cfg(feature = "metadata")]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-03-15 15:19:21 +01:00
fn param_names() -> Box<[&'static str]>;
2021-07-25 16:56:05 +02:00
/// _(metadata)_ Get the type ID of this function's return value.
/// Exported under the `metadata` feature only.
#[cfg(feature = "metadata")]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-03-15 15:19:21 +01:00
fn return_type() -> TypeId;
2021-07-25 16:56:05 +02:00
/// _(metadata)_ Get the type name of this function's return value.
/// Exported under the `metadata` feature only.
#[cfg(feature = "metadata")]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-03-15 15:19:21 +01:00
fn return_type_name() -> &'static str;
}
#[inline]
2021-06-12 16:47:43 +02:00
#[must_use]
2021-05-15 05:56:19 +02:00
fn is_setter(_fn_name: &str) -> bool {
#[cfg(not(feature = "no_object"))]
if _fn_name.starts_with(crate::engine::FN_SET) {
return true;
}
#[cfg(not(feature = "no_index"))]
if _fn_name.starts_with(crate::engine::FN_IDX_SET) {
return true;
}
false
}
2017-12-20 12:16:14 +01:00
macro_rules! def_register {
() => {
2020-05-19 16:25:57 +02:00
def_register!(imp from_pure :);
2017-12-20 12:16:14 +01:00
};
(imp $abi:ident : $($par:ident => $arg:expr => $mark:ty => $param:ty => $let:stmt => $clone:expr),*) => {
// ^ function ABI type
// ^ function parameter generic type name (A, B, C etc.)
2020-10-02 08:55:02 +02:00
// ^ call argument(like A, *B, &mut C etc)
// ^ function parameter marker type (T, Ref<T> or Mut<T>)
// ^ function parameter actual type (T, &T or &mut T)
// ^ argument let statement
impl<
FN: Fn($($param),*) -> RET + SendSync + 'static,
$($par: Variant + Clone,)*
2020-04-12 17:00:06 +02:00
RET: Variant + Clone
> RegisterNativeFunction<($($mark,)*), ()> for FN {
2021-03-15 15:19:21 +01:00
#[inline(always)] fn param_types() -> Box<[TypeId]> { vec![$(TypeId::of::<$par>()),*].into_boxed_slice() }
2021-04-17 09:15:54 +02:00
#[cfg(feature = "metadata")] #[inline(always)] fn param_names() -> Box<[&'static str]> { vec![$(std::any::type_name::<$par>()),*].into_boxed_slice() }
#[cfg(feature = "metadata")] #[inline(always)] fn return_type() -> TypeId { TypeId::of::<RET>() }
2021-04-17 09:15:54 +02:00
#[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::<RET>() }
2021-03-16 11:16:40 +01:00
#[inline(always)] fn into_callable_function(self) -> CallableFunction {
CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| {
2021-05-15 05:56:19 +02:00
if args.len() == 2 && args[0].is_read_only() && is_setter(ctx.fn_name()) {
return EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into();
}
2021-03-15 05:39:06 +01:00
// The arguments are assumed to be of the correct number and types!
let mut _drain = args.iter_mut();
2021-05-22 13:14:24 +02:00
$($let $par = ($clone)(_drain.next().expect("never fails because arguments list is fixed")); )*
2021-03-15 05:39:06 +01:00
// Call the function with each argument value
let r = self($($arg),*);
// Map the result
Ok(r.into_dynamic())
}) as Box<FnAny>)
}
}
impl<
FN: for<'a> Fn(NativeCallContext<'a>, $($param),*) -> RET + SendSync + 'static,
2020-04-12 17:00:06 +02:00
$($par: Variant + Clone,)*
RET: Variant + Clone
> RegisterNativeFunction<(NativeCallContext<'static>, $($mark,)*), ()> for FN {
2021-03-15 15:19:21 +01:00
#[inline(always)] fn param_types() -> Box<[TypeId]> { vec![$(TypeId::of::<$par>()),*].into_boxed_slice() }
2021-04-17 09:15:54 +02:00
#[cfg(feature = "metadata")] #[inline(always)] fn param_names() -> Box<[&'static str]> { vec![$(std::any::type_name::<$par>()),*].into_boxed_slice() }
#[cfg(feature = "metadata")] #[inline(always)] fn return_type() -> TypeId { TypeId::of::<RET>() }
2021-04-17 09:15:54 +02:00
#[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::<RET>() }
2021-03-16 11:16:40 +01:00
#[inline(always)] fn into_callable_function(self) -> CallableFunction {
2021-03-15 05:39:06 +01:00
CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| {
2021-05-15 05:56:19 +02:00
if args.len() == 2 && args[0].is_read_only() && is_setter(ctx.fn_name()) {
return EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into();
}
2021-03-15 05:39:06 +01:00
// The arguments are assumed to be of the correct number and types!
let mut _drain = args.iter_mut();
2021-05-22 13:14:24 +02:00
$($let $par = ($clone)(_drain.next().expect("never fails because arguments list is fixed")); )*
2021-03-15 05:39:06 +01:00
// Call the function with each argument value
let r = self(ctx, $($arg),*);
// Map the result
Ok(r.into_dynamic())
}) as Box<FnAny>)
}
}
impl<
2021-03-15 05:39:06 +01:00
FN: Fn($($param),*) -> Result<RET, Box<EvalAltResult>> + SendSync + 'static,
$($par: Variant + Clone,)*
2021-03-15 05:39:06 +01:00
RET: Variant + Clone
> RegisterNativeFunction<($($mark,)*), Result<RET, Box<EvalAltResult>>> for FN {
2021-03-15 15:19:21 +01:00
#[inline(always)] fn param_types() -> Box<[TypeId]> { vec![$(TypeId::of::<$par>()),*].into_boxed_slice() }
2021-04-17 09:15:54 +02:00
#[cfg(feature = "metadata")] #[inline(always)] fn param_names() -> Box<[&'static str]> { vec![$(std::any::type_name::<$par>()),*].into_boxed_slice() }
#[cfg(feature = "metadata")] #[inline(always)] fn return_type() -> TypeId { TypeId::of::<Result<RET, Box<EvalAltResult>>>() }
2021-04-17 09:15:54 +02:00
#[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::<Result<RET, Box<EvalAltResult>>>() }
2021-03-16 11:16:40 +01:00
#[inline(always)] fn into_callable_function(self) -> CallableFunction {
CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| {
2021-05-15 05:56:19 +02:00
if args.len() == 2 && args[0].is_read_only() && is_setter(ctx.fn_name()) {
return EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into();
}
2021-03-15 05:39:06 +01:00
// The arguments are assumed to be of the correct number and types!
let mut _drain = args.iter_mut();
2021-05-22 13:14:24 +02:00
$($let $par = ($clone)(_drain.next().expect("never fails because arguments list is fixed")); )*
2021-03-15 05:39:06 +01:00
// Call the function with each argument value
self($($arg),*).map(Dynamic::from)
}) as Box<FnAny>)
}
}
impl<
2021-03-15 05:39:06 +01:00
FN: for<'a> Fn(NativeCallContext<'a>, $($param),*) -> Result<RET, Box<EvalAltResult>> + SendSync + 'static,
$($par: Variant + Clone,)*
2021-03-15 05:39:06 +01:00
RET: Variant + Clone
> RegisterNativeFunction<(NativeCallContext<'static>, $($mark,)*), Result<RET, Box<EvalAltResult>>> for FN {
2021-03-15 15:19:21 +01:00
#[inline(always)] fn param_types() -> Box<[TypeId]> { vec![$(TypeId::of::<$par>()),*].into_boxed_slice() }
2021-04-17 09:15:54 +02:00
#[cfg(feature = "metadata")] #[inline(always)] fn param_names() -> Box<[&'static str]> { vec![$(std::any::type_name::<$par>()),*].into_boxed_slice() }
#[cfg(feature = "metadata")] #[inline(always)] fn return_type() -> TypeId { TypeId::of::<Result<RET, Box<EvalAltResult>>>() }
2021-04-17 09:15:54 +02:00
#[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::<Result<RET, Box<EvalAltResult>>>() }
2021-03-16 11:16:40 +01:00
#[inline(always)] fn into_callable_function(self) -> CallableFunction {
2021-03-15 05:39:06 +01:00
CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| {
2021-05-15 05:56:19 +02:00
if args.len() == 2 && args[0].is_read_only() && is_setter(ctx.fn_name()) {
return EvalAltResult::ErrorAssignmentToConstant(Default::default(), Position::NONE).into();
}
2021-03-15 05:39:06 +01:00
// The arguments are assumed to be of the correct number and types!
let mut _drain = args.iter_mut();
2021-05-22 13:14:24 +02:00
$($let $par = ($clone)(_drain.next().expect("never fails because arguments list is fixed")); )*
2021-03-15 05:39:06 +01:00
// Call the function with each argument value
self(ctx, $($arg),*).map(Dynamic::from)
}) as Box<FnAny>)
}
}
2017-12-20 12:16:14 +01:00
//def_register!(imp_pop $($par => $mark => $param),*);
};
($p0:ident $(, $p:ident)*) => {
def_register!(imp from_pure : $p0 => $p0 => $p0 => $p0 => let $p0 => by_value $(, $p => $p => $p => $p => let $p => by_value)*);
2021-03-07 15:10:54 +01:00
def_register!(imp from_method : $p0 => &mut $p0 => Mut<$p0> => &mut $p0 => let mut $p0 => by_ref $(, $p => $p => $p => $p => let $p => by_value)*);
// ^ CallableFunction constructor
// ^ first parameter passed through
// ^ others passed by value (by_value)
2017-12-20 12:16:14 +01:00
2020-04-09 12:45:49 +02:00
// Currently does not support first argument which is a reference, as there will be
// conflicting implementations since &T: Any and T: Any cannot be distinguished
//def_register!(imp $p0 => Ref<$p0> => &$p0 => by_ref $(, $p => $p => $p => by_value)*);
2017-12-20 12:16:14 +01:00
def_register!($($p),*);
};
}
def_register!(A, B, C, D, E, F, G, H, J, K, L, M, N, P, Q, R, S, T, U, V);