rhai/src/func/register.rs

242 lines
12 KiB
Rust
Raw Normal View History

2020-03-08 19:54:02 +08:00
//! Module which defines the function registration mechanism.
#![allow(non_snake_case)]
2021-12-20 22:13:00 +08:00
use super::call::FnCallArgs;
use super::callable_function::CallableFunction;
use super::native::{FnAny, SendSync};
2021-11-13 22:36:23 +08:00
use crate::tokenizer::Position;
use crate::types::dynamic::{DynamicWriteLock, Variant};
2022-02-06 23:02:59 +08:00
use crate::{reify, Dynamic, NativeCallContext, RhaiResultOf, ERR};
2021-04-17 15:15:54 +08:00
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{any::TypeId, mem};
2016-02-29 16:43:45 -05:00
2020-03-25 11:24:06 +08: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 09:36:06 +08:00
// based purely on parameter types of traits (`Fn`, `FnOnce` and `FnMut`).
2020-03-25 11:24:06 +08:00
//
// For example:
//
// `NativeFunction<(Mut<A>, B, Ref<C>), R>`
2020-03-25 11:24:06 +08: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 13:36:50 +08:00
#[inline(always)]
2021-06-12 22:47:43 +08: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-11-13 12:23:35 +08:00
data.write_lock::<T>().expect("checked")
2020-03-24 16:57:35 +08:00
}
/// Dereference into value.
2022-02-08 09:25:53 +08:00
#[inline(always)]
2021-06-12 22:47:43 +08:00
#[must_use]
2020-05-12 16:32:22 +08: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();
2021-11-13 12:23:35 +08:00
let ref_str = data.as_str_ref().expect("&str");
2022-02-08 09:25:53 +08:00
// # Safety
//
// We already checked that `T` is `&str`, so it is safe to cast here.
return unsafe { std::mem::transmute_copy::<_, T>(&ref_str) };
}
if TypeId::of::<T>() == TypeId::of::<String>() {
// If T is `String`, data must be `ImmutableString`, so map directly to it
2022-02-08 09:25:53 +08:00
return reify!(mem::take(data).into_string().expect("`ImmutableString`") => T);
}
2022-02-08 09:25:53 +08:00
// 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.
return mem::take(data).cast::<T>();
}
2021-03-15 12:39:06 +08:00
/// Trait to register custom Rust functions.
pub trait RegisterNativeFunction<Args, Result> {
2021-03-24 10:02:50 +08:00
/// Convert this function into a [`CallableFunction`].
2021-06-12 22:47:43 +08:00
#[must_use]
2021-03-24 10:02:50 +08:00
fn into_callable_function(self) -> CallableFunction;
2021-03-15 22:19:21 +08:00
/// Get the type ID's of this function's parameters.
2021-06-12 22:47:43 +08:00
#[must_use]
2021-03-15 12:39:06 +08:00
fn param_types() -> Box<[TypeId]>;
2021-07-25 22:56:05 +08:00
/// _(metadata)_ Get the type names of this function's parameters.
/// Exported under the `metadata` feature only.
#[cfg(feature = "metadata")]
2021-06-12 22:47:43 +08:00
#[must_use]
2021-03-15 22:19:21 +08:00
fn param_names() -> Box<[&'static str]>;
2021-07-25 22:56:05 +08:00
/// _(metadata)_ Get the type ID of this function's return value.
/// Exported under the `metadata` feature only.
#[cfg(feature = "metadata")]
2021-06-12 22:47:43 +08:00
#[must_use]
2021-03-15 22:19:21 +08:00
fn return_type() -> TypeId;
2021-07-25 22:56:05 +08:00
/// _(metadata)_ Get the type name of this function's return value.
/// Exported under the `metadata` feature only.
#[cfg(feature = "metadata")]
2021-06-12 22:47:43 +08:00
#[must_use]
2021-03-15 22:19:21 +08:00
fn return_type_name() -> &'static str;
}
2021-11-13 12:23:35 +08:00
const EXPECT_ARGS: &str = "arguments";
2022-02-23 15:43:27 +08:00
macro_rules! check_constant {
($ctx:ident, $args:ident) => {
#[cfg(any(not(feature = "no_object"), not(feature = "no_index")))]
{
let args_len = $args.len();
if args_len > 0 && $args[0].is_read_only() {
let deny = match $ctx.fn_name() {
#[cfg(not(feature = "no_object"))]
f if args_len == 2 && f.starts_with(crate::engine::FN_SET) => true,
#[cfg(not(feature = "no_index"))]
crate::engine::FN_IDX_SET if args_len == 3 => true,
_ => false,
};
if deny {
return Err(
ERR::ErrorAssignmentToConstant(String::new(), Position::NONE).into(),
);
}
}
}
};
}
2017-12-20 12:16:14 +01:00
macro_rules! def_register {
() => {
2020-05-19 22:25:57 +08: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 14:55:02 +08:00
// ^ call argument(like A, *B, &mut C etc)
2022-01-17 21:51:04 +08:00
// ^ function parameter marker type (A, Ref<B> or Mut<C>)
// ^ function parameter actual type (A, &B or &mut C)
// ^ argument let statement
impl<
FN: Fn($($param),*) -> RET + SendSync + 'static,
$($par: Variant + Clone,)*
2020-04-12 23:00:06 +08:00
RET: Variant + Clone
> RegisterNativeFunction<($($mark,)*), ()> for FN {
2021-03-15 22:19:21 +08:00
#[inline(always)] fn param_types() -> Box<[TypeId]> { vec![$(TypeId::of::<$par>()),*].into_boxed_slice() }
2022-01-17 21:51:04 +08:00
#[cfg(feature = "metadata")] #[inline(always)] fn param_names() -> Box<[&'static str]> { vec![$(std::any::type_name::<$param>()),*].into_boxed_slice() }
#[cfg(feature = "metadata")] #[inline(always)] fn return_type() -> TypeId { TypeId::of::<RET>() }
2021-04-17 15:15:54 +08:00
#[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::<RET>() }
2021-03-16 18:16:40 +08:00
#[inline(always)] fn into_callable_function(self) -> CallableFunction {
CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| {
2021-03-15 12:39:06 +08:00
// The arguments are assumed to be of the correct number and types!
2022-02-23 15:43:27 +08:00
check_constant!(ctx, args);
2021-03-15 12:39:06 +08:00
let mut _drain = args.iter_mut();
2021-11-13 12:23:35 +08:00
$($let $par = ($clone)(_drain.next().expect(EXPECT_ARGS)); )*
2021-03-15 12:39:06 +08:00
// Call the function with each argument value
let r = self($($arg),*);
// Map the result
2022-01-01 19:54:46 +08:00
Ok(Dynamic::from(r))
2021-03-15 12:39:06 +08:00
}) as Box<FnAny>)
}
}
impl<
FN: for<'a> Fn(NativeCallContext<'a>, $($param),*) -> RET + SendSync + 'static,
2020-04-12 23:00:06 +08:00
$($par: Variant + Clone,)*
RET: Variant + Clone
> RegisterNativeFunction<(NativeCallContext<'static>, $($mark,)*), ()> for FN {
2021-03-15 22:19:21 +08:00
#[inline(always)] fn param_types() -> Box<[TypeId]> { vec![$(TypeId::of::<$par>()),*].into_boxed_slice() }
2022-01-17 21:51:04 +08:00
#[cfg(feature = "metadata")] #[inline(always)] fn param_names() -> Box<[&'static str]> { vec![$(std::any::type_name::<$param>()),*].into_boxed_slice() }
#[cfg(feature = "metadata")] #[inline(always)] fn return_type() -> TypeId { TypeId::of::<RET>() }
2021-04-17 15:15:54 +08:00
#[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::<RET>() }
2021-03-16 18:16:40 +08:00
#[inline(always)] fn into_callable_function(self) -> CallableFunction {
2021-03-15 12:39:06 +08:00
CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| {
// The arguments are assumed to be of the correct number and types!
2022-02-23 15:43:27 +08:00
check_constant!(ctx, args);
2021-03-15 12:39:06 +08:00
let mut _drain = args.iter_mut();
2021-11-13 12:23:35 +08:00
$($let $par = ($clone)(_drain.next().expect(EXPECT_ARGS)); )*
2021-03-15 12:39:06 +08:00
// Call the function with each argument value
let r = self(ctx, $($arg),*);
// Map the result
2022-01-01 19:54:46 +08:00
Ok(Dynamic::from(r))
2021-03-15 12:39:06 +08:00
}) as Box<FnAny>)
}
}
impl<
2021-12-25 23:49:14 +08:00
FN: Fn($($param),*) -> RhaiResultOf<RET> + SendSync + 'static,
$($par: Variant + Clone,)*
2021-03-15 12:39:06 +08:00
RET: Variant + Clone
2021-12-25 23:49:14 +08:00
> RegisterNativeFunction<($($mark,)*), RhaiResultOf<RET>> for FN {
2021-03-15 22:19:21 +08:00
#[inline(always)] fn param_types() -> Box<[TypeId]> { vec![$(TypeId::of::<$par>()),*].into_boxed_slice() }
2022-01-17 21:51:04 +08:00
#[cfg(feature = "metadata")] #[inline(always)] fn param_names() -> Box<[&'static str]> { vec![$(std::any::type_name::<$param>()),*].into_boxed_slice() }
2021-12-25 23:49:14 +08:00
#[cfg(feature = "metadata")] #[inline(always)] fn return_type() -> TypeId { TypeId::of::<RhaiResultOf<RET>>() }
#[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::<RhaiResultOf<RET>>() }
2021-03-16 18:16:40 +08:00
#[inline(always)] fn into_callable_function(self) -> CallableFunction {
CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| {
2021-03-15 12:39:06 +08:00
// The arguments are assumed to be of the correct number and types!
2022-02-23 15:43:27 +08:00
check_constant!(ctx, args);
2021-03-15 12:39:06 +08:00
let mut _drain = args.iter_mut();
2021-11-13 12:23:35 +08:00
$($let $par = ($clone)(_drain.next().expect(EXPECT_ARGS)); )*
2021-03-15 12:39:06 +08:00
// Call the function with each argument value
self($($arg),*).map(Dynamic::from)
}) as Box<FnAny>)
}
}
impl<
2021-12-25 23:49:14 +08:00
FN: for<'a> Fn(NativeCallContext<'a>, $($param),*) -> RhaiResultOf<RET> + SendSync + 'static,
$($par: Variant + Clone,)*
2021-03-15 12:39:06 +08:00
RET: Variant + Clone
2021-12-25 23:49:14 +08:00
> RegisterNativeFunction<(NativeCallContext<'static>, $($mark,)*), RhaiResultOf<RET>> for FN {
2021-03-15 22:19:21 +08:00
#[inline(always)] fn param_types() -> Box<[TypeId]> { vec![$(TypeId::of::<$par>()),*].into_boxed_slice() }
2022-01-17 21:51:04 +08:00
#[cfg(feature = "metadata")] #[inline(always)] fn param_names() -> Box<[&'static str]> { vec![$(std::any::type_name::<$param>()),*].into_boxed_slice() }
2021-12-25 23:49:14 +08:00
#[cfg(feature = "metadata")] #[inline(always)] fn return_type() -> TypeId { TypeId::of::<RhaiResultOf<RET>>() }
#[cfg(feature = "metadata")] #[inline(always)] fn return_type_name() -> &'static str { std::any::type_name::<RhaiResultOf<RET>>() }
2021-03-16 18:16:40 +08:00
#[inline(always)] fn into_callable_function(self) -> CallableFunction {
2021-03-15 12:39:06 +08:00
CallableFunction::$abi(Box::new(move |ctx: NativeCallContext, args: &mut FnCallArgs| {
// The arguments are assumed to be of the correct number and types!
2022-02-23 15:43:27 +08:00
check_constant!(ctx, args);
2021-03-15 12:39:06 +08:00
let mut _drain = args.iter_mut();
2021-11-13 12:23:35 +08:00
$($let $par = ($clone)(_drain.next().expect(EXPECT_ARGS)); )*
2021-03-15 12:39:06 +08: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 22:10:54 +08: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 18:45:49 +08: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);