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                };
39                let arity = signature.params.len();
40                let call = move |cx: &mut dyn Context, args: &[Value]| {
41                    #[allow(non_snake_case)]
42                    let [$($arg),*] = args else {
43                        return Err(RuntimeError::new(format!(
44                            "expected {arity} argument(s), found {}",
45                            args.len()
46                        )));
47                    };
48                    let result = self($(from_value::<$arg>(cx, $arg)?),*);
49                    into_value(cx, result)
50                };
51                (signature, Box::new(call))
52            }
53        }
54
55        impl<F, T, R, $($arg),*> IntoNativeMethod<T, fn($($arg),*) -> R> for F
56        where
57            F: Fn(&T, $($arg),*) -> R + Send + Sync + 'static,
58            T: Facet<'static> + Send + 'static,
59            R: Facet<'static> + Send + 'static,
60            $($arg: Facet<'static>,)*
61        {
62            // Arguments are bound to variables named after their types.
63            #[allow(non_snake_case)]
64            fn into_native(self) -> (Signature, Box<CallFn>) {
65                impl_into_native_fn!(@method self, T, R, with, $($arg),*)
66            }
67        }
68
69        impl<F, T, R, $($arg),*> IntoNativeMethodMut<T, fn($($arg),*) -> R> for F
70        where
71            F: Fn(&mut T, $($arg),*) -> R + Send + Sync + 'static,
72            T: Facet<'static> + Send + 'static,
73            R: Facet<'static> + Send + 'static,
74            $($arg: Facet<'static>,)*
75        {
76            // Arguments are bound to variables named after their types.
77            #[allow(non_snake_case)]
78            fn into_native(self) -> (Signature, Box<CallFn>) {
79                impl_into_native_fn!(@method self, T, R, with_mut, $($arg),*)
80            }
81        }
82    };
83    // The body shared by `&self` and `&mut self` methods, which differ only
84    // in how the receiver is borrowed.
85    (@method $f:ident, $ty:ident, $ret:ident, $with:ident, $($arg:ident),*) => {{
86        let signature = Signature {
87            params: vec![$ty::SHAPE, $($arg::SHAPE),*],
88            ret: $ret::SHAPE,
89        };
90        let arity = signature.params.len();
91        let call = move |cx: &mut dyn Context, args: &[Value]| {
92            #[allow(non_snake_case)]
93            let [receiver, $($arg),*] = args else {
94                return Err(RuntimeError::new(format!(
95                    "expected {arity} argument(s), found {}",
96                    args.len()
97                )));
98            };
99            $(let $arg = from_value::<$arg>(cx, $arg)?;)*
100            let Value::Native(object) = receiver else {
101                return Err(RuntimeError::new(format!(
102                    "expected `{}`, found {}",
103                    $ty::SHAPE,
104                    receiver.kind()
105                )));
106            };
107            let result = object.$with(|this| $f(this, $($arg),*)).ok_or_else(|| {
108                RuntimeError::new(format!("expected `{}`, found another native type", $ty::SHAPE))
109            })?;
110            into_value(cx, result)
111        };
112        (signature, Box::new(call) as Box<CallFn>)
113    }};
114}
115
116impl_into_native_fn!();
117impl_into_native_fn!(A);
118impl_into_native_fn!(A, B);
119impl_into_native_fn!(A, B, C);
120impl_into_native_fn!(A, B, C, D);
121impl_into_native_fn!(A, B, C, D, E);
122impl_into_native_fn!(A, B, C, D, E, G);