rhai/src/fn_register.rs

270 lines
9.6 KiB
Rust
Raw Normal View History

2020-03-08 12:54:02 +01:00
//! Module which defines the function registration mechanism.
2016-02-29 22:43:45 +01:00
#![allow(non_snake_case)]
2020-04-12 17:00:06 +02:00
use crate::any::{Dynamic, Variant};
2020-05-11 07:36:50 +02:00
use crate::engine::Engine;
use crate::fn_native::{FnCallArgs, NativeFunction, NativeFunctionABI::*};
2020-03-04 15:00:01 +01:00
use crate::result::EvalAltResult;
use crate::token::Position;
use crate::utils::calc_fn_spec;
2020-03-18 15:03:50 +01:00
use crate::stdlib::{any::TypeId, boxed::Box, iter::empty, mem, string::ToString};
2016-02-29 22:43:45 +01:00
2020-03-04 15:00:01 +01:00
/// A trait to register custom functions with the `Engine`.
2017-12-20 12:16:14 +01:00
pub trait RegisterFn<FN, ARGS, RET> {
2020-03-04 15:00:01 +01:00
/// Register a custom function with the `Engine`.
2020-03-19 06:52:10 +01:00
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
2020-03-19 06:52:10 +01:00
/// use rhai::{Engine, RegisterFn};
///
/// // Normal function
/// fn add(x: i64, y: i64) -> i64 {
/// x + y
/// }
///
/// let mut engine = Engine::new();
///
/// // You must use the trait rhai::RegisterFn to get this method.
/// engine.register_fn("add", add);
///
/// assert_eq!(engine.eval::<i64>("add(40, 2)")?, 42);
///
/// // You can also register a closure.
/// engine.register_fn("sub", |x: i64, y: i64| x - y );
///
/// assert_eq!(engine.eval::<i64>("sub(44, 2)")?, 42);
/// # Ok(())
/// # }
/// ```
2017-12-20 12:16:14 +01:00
fn register_fn(&mut self, name: &str, f: FN);
2016-02-29 22:43:45 +01:00
}
2020-03-04 15:00:01 +01:00
/// A trait to register custom functions that return `Dynamic` values with the `Engine`.
pub trait RegisterDynamicFn<FN, ARGS> {
2020-03-04 15:00:01 +01:00
/// Register a custom function returning `Dynamic` values with the `Engine`.
2020-03-19 06:52:10 +01:00
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
2020-03-19 06:52:10 +01:00
/// use rhai::{Engine, Dynamic, RegisterDynamicFn};
///
/// // Function that returns a Dynamic value
/// fn return_the_same_as_dynamic(x: i64) -> Dynamic {
2020-04-12 17:00:06 +02:00
/// Dynamic::from(x)
2020-03-19 06:52:10 +01:00
/// }
///
/// let mut engine = Engine::new();
///
/// // You must use the trait rhai::RegisterDynamicFn to get this method.
/// engine.register_dynamic_fn("get_any_number", return_the_same_as_dynamic);
///
/// assert_eq!(engine.eval::<i64>("get_any_number(42)")?, 42);
/// # Ok(())
/// # }
/// ```
fn register_dynamic_fn(&mut self, name: &str, f: FN);
}
2016-02-29 22:43:45 +01:00
/// A trait to register fallible custom functions returning `Result<_, Box<EvalAltResult>>` with the `Engine`.
pub trait RegisterResultFn<FN, ARGS, RET> {
2020-03-19 06:52:10 +01:00
/// Register a custom fallible function with the `Engine`.
///
/// # Example
///
/// ```
/// use rhai::{Engine, RegisterResultFn, EvalAltResult};
///
/// // Normal function
/// fn div(x: i64, y: i64) -> Result<i64, Box<EvalAltResult>> {
2020-03-19 06:52:10 +01:00
/// if y == 0 {
/// // '.into()' automatically converts to 'Box<EvalAltResult::ErrorRuntime>'
2020-03-25 04:24:06 +01:00
/// Err("division by zero!".into())
2020-03-19 06:52:10 +01:00
/// } else {
/// Ok(x / y)
/// }
/// }
///
/// let mut engine = Engine::new();
///
/// // You must use the trait rhai::RegisterResultFn to get this method.
/// engine.register_result_fn("div", div);
///
/// engine.eval::<i64>("div(42, 0)")
/// .expect_err("expecting division by zero error!");
/// ```
fn register_result_fn(&mut self, name: &str, f: FN);
}
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
// based purely on parameter types of traits (Fn, FnOnce and FnMut).
2020-03-25 04:24:06 +01:00
//
// For example:
//
// `RegisterFn<FN, (Mut<A>, B, Ref<C>), R>`
//
// 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 &mut.
2020-05-11 07:36:50 +02:00
#[inline(always)]
2020-05-12 10:32:22 +02:00
pub fn by_ref<T: Variant + Clone>(data: &mut Dynamic) -> &mut T {
// Directly cast the &mut Dynamic into &mut T to access the underlying data.
data.downcast_mut::<T>().unwrap()
2020-03-24 09:57:35 +01:00
}
/// Dereference into value.
2020-05-11 07:36:50 +02:00
#[inline(always)]
2020-05-12 10:32:22 +02:00
pub fn by_value<T: Variant + Clone>(data: &mut Dynamic) -> T {
// 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.
2020-05-05 09:00:10 +02:00
mem::take(data).cast::<T>()
}
/// This macro creates a closure wrapping a registered function.
macro_rules! make_func {
($fn:ident : $abi:expr ; $map:expr ; $($par:ident => $convert:expr),*) => {
2020-05-11 07:36:50 +02:00
// ^ function pointer
// ^ function ABI type
// ^ result mapping function
// ^ function parameter generic type name (A, B, C etc.)
// ^ dereferencing function
2020-05-11 07:36:50 +02:00
NativeFunction::new(Box::new(move |args: &mut FnCallArgs, pos: Position| {
2020-05-11 04:29:33 +02:00
// The arguments are assumed to be of the correct number and types!
#[allow(unused_variables, unused_mut)]
let mut drain = args.iter_mut();
$(
// Downcast every element, panic in case of a type mismatch (which shouldn't happen).
// Call the user-supplied function using ($convert) to access it either by value or by reference.
let $par = ($convert)(drain.next().unwrap());
)*
// Call the function with each parameter value
let r = $fn($($par),*);
// Map the result
$map(r, pos)
}), $abi);
};
}
/// To Dynamic mapping function.
2020-05-11 07:36:50 +02:00
#[inline(always)]
pub fn map_dynamic<T: Variant + Clone>(
data: T,
_pos: Position,
) -> Result<Dynamic, Box<EvalAltResult>> {
Ok(data.into_dynamic())
}
/// To Dynamic mapping function.
2020-05-11 07:36:50 +02:00
#[inline(always)]
pub fn map_identity(data: Dynamic, _pos: Position) -> Result<Dynamic, Box<EvalAltResult>> {
Ok(data)
}
/// To `Result<Dynamic, Box<EvalAltResult>>` mapping function.
2020-05-11 07:36:50 +02:00
#[inline(always)]
pub fn map_result<T: Variant + Clone>(
data: Result<T, Box<EvalAltResult>>,
pos: Position,
) -> Result<Dynamic, Box<EvalAltResult>> {
data.map(|v| v.into_dynamic())
2020-04-24 06:39:24 +02:00
.map_err(|err| EvalAltResult::set_position(err, pos))
}
2017-12-20 12:16:14 +01:00
macro_rules! def_register {
() => {
def_register!(imp Pure;);
2017-12-20 12:16:14 +01:00
};
(imp $abi:expr ; $($par:ident => $mark:ty => $param:ty => $clone:expr),*) => {
// ^ function ABI type
// ^ function parameter generic type name (A, B, C etc.)
// ^ function parameter marker type (T, Ref<T> or Mut<T>)
// ^ function parameter actual type (T, &T or &mut T)
// ^ dereferencing function
impl<
2020-04-12 17:00:06 +02:00
$($par: Variant + Clone,)*
2020-04-03 11:17:00 +02:00
#[cfg(feature = "sync")]
FN: Fn($($param),*) -> RET + Send + Sync + 'static,
#[cfg(not(feature = "sync"))]
2017-12-20 12:16:14 +01:00
FN: Fn($($param),*) -> RET + 'static,
2020-04-03 11:17:00 +02:00
2020-04-12 17:00:06 +02:00
RET: Variant + Clone
2020-04-16 17:31:48 +02:00
> RegisterFn<FN, ($($mark,)*), RET> for Engine
2017-12-20 12:16:14 +01:00
{
fn register_fn(&mut self, name: &str, f: FN) {
let func = make_func!(f : $abi ; map_dynamic ; $($par => $clone),*);
let hash = calc_fn_spec(empty(), name, [$(TypeId::of::<$par>()),*].iter().cloned());
self.base_package.functions.insert(hash, Box::new(func));
}
}
impl<
2020-04-12 17:00:06 +02:00
$($par: Variant + Clone,)*
2020-04-03 11:17:00 +02:00
#[cfg(feature = "sync")]
FN: Fn($($param),*) -> Dynamic + Send + Sync + 'static,
#[cfg(not(feature = "sync"))]
FN: Fn($($param),*) -> Dynamic + 'static,
2020-04-16 17:31:48 +02:00
> RegisterDynamicFn<FN, ($($mark,)*)> for Engine
{
fn register_dynamic_fn(&mut self, name: &str, f: FN) {
let func = make_func!(f : $abi ; map_identity ; $($par => $clone),*);
let hash = calc_fn_spec(empty(), name, [$(TypeId::of::<$par>()),*].iter().cloned());
self.base_package.functions.insert(hash, Box::new(func));
2017-12-20 12:16:14 +01:00
}
}
impl<
2020-04-12 17:00:06 +02:00
$($par: Variant + Clone,)*
2020-04-03 11:17:00 +02:00
#[cfg(feature = "sync")]
FN: Fn($($param),*) -> Result<RET, Box<EvalAltResult>> + Send + Sync + 'static,
2020-04-03 11:17:00 +02:00
#[cfg(not(feature = "sync"))]
FN: Fn($($param),*) -> Result<RET, Box<EvalAltResult>> + 'static,
2020-04-03 11:17:00 +02:00
2020-04-12 17:00:06 +02:00
RET: Variant + Clone
2020-04-16 17:31:48 +02:00
> RegisterResultFn<FN, ($($mark,)*), RET> for Engine
{
fn register_result_fn(&mut self, name: &str, f: FN) {
let func = make_func!(f : $abi ; map_result ; $($par => $clone),*);
let hash = calc_fn_spec(empty(), name, [$(TypeId::of::<$par>()),*].iter().cloned());
self.base_package.functions.insert(hash, Box::new(func));
}
}
2017-12-20 12:16:14 +01:00
//def_register!(imp_pop $($par => $mark => $param),*);
};
($p0:ident $(, $p:ident)*) => {
def_register!(imp Pure ; $p0 => $p0 => $p0 => by_value $(, $p => $p => $p => by_value)*);
def_register!(imp Method ; $p0 => Mut<$p0> => &mut $p0 => by_ref $(, $p => $p => $p => by_value)*);
// handle the first parameter ^ 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);