rhai/src/fn_register.rs

70 lines
2.6 KiB
Rust
Raw Normal View History

2017-12-20 12:16:14 +01:00
use std::any::TypeId;
2016-02-29 22:43:45 +01:00
2019-09-18 12:21:07 +02:00
use crate::any::Any;
use crate::engine::{Engine, EvalAltResult};
2016-02-29 22:43:45 +01:00
2017-12-20 12:16:14 +01:00
pub trait RegisterFn<FN, ARGS, RET> {
fn register_fn(&mut self, name: &str, f: FN);
2016-02-29 22:43:45 +01:00
}
2017-12-20 12:16:14 +01:00
pub struct Ref<A>(A);
pub struct Mut<A>(A);
2017-12-20 12:16:14 +01:00
macro_rules! count_args {
() => {0usize};
($head:ident $($tail:ident)*) => {1usize + count_args!($($tail)*)};
}
2017-12-20 12:16:14 +01:00
macro_rules! def_register {
() => {
def_register!(imp);
};
(imp $($par:ident => $mark:ty => $param:ty => $clone:expr),*) => {
impl<$($par,)* FN, RET> RegisterFn<FN, ($($mark,)*), RET> for Engine
where
$($par: Any + Clone,)*
FN: Fn($($param),*) -> RET + 'static,
RET: Any,
{
fn register_fn(&mut self, name: &str, f: FN) {
2019-09-18 12:21:07 +02:00
let fun = move |mut args: Vec<&mut dyn Any>| {
2017-12-20 12:16:14 +01:00
// Check for length at the beginning to avoid
// per-element bound checks.
if args.len() != count_args!($($par)*) {
return Err(EvalAltResult::ErrorFunctionArgMismatch);
}
2019-09-18 12:21:07 +02:00
#[allow(unused_variables, unused_mut)]
2017-12-20 12:16:14 +01:00
let mut drain = args.drain(..);
$(
// Downcast every element, return in case of a type mismatch
let $par = ((*drain.next().unwrap()).downcast_mut() as Option<&mut $par>)
.ok_or(EvalAltResult::ErrorFunctionArgMismatch)?;
)*
// Call the user-supplied function using ($clone) to
// potentially clone the value, otherwise pass the reference.
2019-09-18 12:21:07 +02:00
Ok(Box::new(f($(($clone)($par)),*)) as Box<dyn Any>)
2017-12-20 12:16:14 +01:00
};
2017-12-20 14:35:44 +01:00
self.register_fn_raw(name.to_owned(), Some(vec![$(TypeId::of::<$par>()),*]), Box::new(fun));
2017-12-20 12:16:14 +01:00
}
}
//def_register!(imp_pop $($par => $mark => $param),*);
};
($p0:ident $(, $p:ident)*) => {
def_register!(imp $p0 => $p0 => $p0 => Clone::clone $(, $p => $p => $p => Clone::clone)*);
def_register!(imp $p0 => Ref<$p0> => &$p0 => |x| { x } $(, $p => $p => $p => Clone::clone)*);
def_register!(imp $p0 => Mut<$p0> => &mut $p0 => |x| { x } $(, $p => $p => $p => Clone::clone)*);
def_register!($($p),*);
};
// (imp_pop) => {};
// (imp_pop $head:ident => $head_mark:ty => $head_param:ty $(,$tail:ident => $tail_mark:ty => $tp:ty)*) => {
// def_register!(imp $($tail => $tail_mark => $tp),*);
// };
}
2017-12-20 12:16:14 +01:00
#[cfg_attr(rustfmt, rustfmt_skip)]
2017-12-20 22:16:53 +01:00
def_register!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S);