Skip to main content

xur_runtime/registry/
into_native.rs

1//! Turning Rust functions into native functions, for each arity.
2
3use facet::Facet;
4
5use super::{CallFn, Context, Signature};
6use crate::convert::{from_value, into_value};
7use crate::{RuntimeError, Value};
8
9/// Methods taking `&T`, for [`TypeBuilder::method`].
10pub trait IntoNativeMethod<T, Marker> {
11    fn into_native(self) -> (Signature, Box<CallFn>);
12}
13
14/// Methods taking `&mut T`, for [`TypeBuilder::method_mut`].
15pub trait IntoNativeMethodMut<T, Marker> {
16    fn into_native(self) -> (Signature, Box<CallFn>);
17}
18
19/// Functions that can be registered with [`ModuleBuilder::function`]: any
20/// `Fn(A, B, ...) -> R` (up to six arguments) whose types implement
21/// [`Facet`]. `Marker` only distinguishes the implementations.
22pub trait IntoNativeFn<Marker> {
23    fn into_native(self) -> (Signature, Box<CallFn>);
24}
25
26macro_rules! impl_into_native_fn {
27    ($($arg:ident),*) => {
28        impl<F, R, $($arg),*> IntoNativeFn<fn($($arg),*) -> R> for F
29        where
30            F: Fn($($arg),*) -> R + Send + Sync + 'static,
31            R: Facet<'static> + Send + 'static,
32            $($arg: Facet<'static>,)*
33        {
34            fn into_native(self) -> (Signature, Box<CallFn>) {
35                let signature = Signature {
36                    params: vec![$($arg::SHAPE),*],
37                    ret: R::SHAPE,
38                    param_names: Vec::new(),
39                };
40                let arity = signature.params.len();
41                let call = move |cx: &mut dyn Context, args: &[Value]| {
42                    #[allow(non_snake_case)]
43                    let [$($arg),*] = args else {
44                        return Err(RuntimeError::new(format!(
45                            "expected {arity} argument(s), found {}",
46                            args.len()
47                        )));
48                    };
49                    let result = self($(from_value::<$arg>(cx, $arg)?),*);
50                    into_value(cx, result)
51                };
52                (signature, Box::new(call))
53            }
54        }
55
56        impl<F, T, R, $($arg),*> IntoNativeMethod<T, fn($($arg),*) -> R> for F
57        where
58            F: Fn(&T, $($arg),*) -> R + Send + Sync + 'static,
59            T: Facet<'static> + Send + 'static,
60            R: Facet<'static> + Send + 'static,
61            $($arg: Facet<'static>,)*
62        {
63            // Arguments are bound to variables named after their types.
64            #[allow(non_snake_case)]
65            fn into_native(self) -> (Signature, Box<CallFn>) {
66                impl_into_native_fn!(@method self, T, R, with, $($arg),*)
67            }
68        }
69
70        impl<F, T, R, $($arg),*> IntoNativeMethodMut<T, fn($($arg),*) -> R> for F
71        where
72            F: Fn(&mut T, $($arg),*) -> R + Send + Sync + 'static,
73            T: Facet<'static> + Send + 'static,
74            R: Facet<'static> + Send + 'static,
75            $($arg: Facet<'static>,)*
76        {
77            // Arguments are bound to variables named after their types.
78            #[allow(non_snake_case)]
79            fn into_native(self) -> (Signature, Box<CallFn>) {
80                impl_into_native_fn!(@method self, T, R, with_mut, $($arg),*)
81            }
82        }
83    };
84    // The body shared by `&self` and `&mut self` methods, which differ only
85    // in how the receiver is borrowed.
86    (@method $f:ident, $ty:ident, $ret:ident, $with:ident, $($arg:ident),*) => {{
87        let signature = Signature {
88            params: vec![$ty::SHAPE, $($arg::SHAPE),*],
89            ret: $ret::SHAPE,
90            param_names: Vec::new(),
91        };
92        let arity = signature.params.len();
93        let call = move |cx: &mut dyn Context, args: &[Value]| {
94            #[allow(non_snake_case)]
95            let [receiver, $($arg),*] = args else {
96                return Err(RuntimeError::new(format!(
97                    "expected {arity} argument(s), found {}",
98                    args.len()
99                )));
100            };
101            $(let $arg = from_value::<$arg>(cx, $arg)?;)*
102            let Value::Native(object) = receiver else {
103                return Err(RuntimeError::new(format!(
104                    "expected `{}`, found {}",
105                    $ty::SHAPE,
106                    receiver.kind()
107                )));
108            };
109            let result = object.$with(|this| $f(this, $($arg),*)).ok_or_else(|| {
110                RuntimeError::new(format!("expected `{}`, found another native type", $ty::SHAPE))
111            })?;
112            into_value(cx, result)
113        };
114        (signature, Box::new(call) as Box<CallFn>)
115    }};
116}
117
118impl_into_native_fn!();
119impl_into_native_fn!(A);
120impl_into_native_fn!(A, B);
121impl_into_native_fn!(A, B, C);
122impl_into_native_fn!(A, B, C, D);
123impl_into_native_fn!(A, B, C, D, E);
124impl_into_native_fn!(A, B, C, D, E, G);