Skip to main content

datex_core/traits/
callable.rs

1use crate::{
2    prelude::*,
3    runtime::cache::shared_references_cache::SharedReferencesCache,
4    traits::{
5        convert_value_container::ConvertValueContainer,
6        get_datex_type::GetDatexType,
7    },
8    types::r#type::Type,
9    values::{
10        core_values::callable::error::CallableError,
11        value_container::ValueContainer,
12    },
13};
14use seq_macro::seq;
15
16pub trait IntoDatexCallable<Args, R> {
17    /// Returns a vector of tuples containing the parameter names (if any) and their corresponding [Type]s.
18    fn parameters(
19        context: &mut SharedReferencesCache,
20    ) -> Vec<(Option<String>, Type)>;
21    /// Invokes the callable with the provided arguments and returns a [Result] containing either the return value or a [CallableError].
22    fn invoke(&self, args: Vec<ValueContainer>) -> Result<R, CallableError>;
23}
24
25macro_rules! impl_datex_callable {
26    ($n:literal) => {
27        seq!(N in 0..$n {
28            impl<F, R, #(A~N,)*> IntoDatexCallable<(#(A~N,)*), R> for F
29            where
30                F: Fn(#(A~N,)*) -> R,
31                #(
32                    A~N: GetDatexType + ConvertValueContainer,
33                )*
34            {
35                fn parameters(
36                    #[allow(unused_variables)]
37                    context: &mut SharedReferencesCache,
38                ) -> Vec<(Option<String>, Type)> {
39                    vec![#((None, A~N::datex_type(context)),)*]
40                }
41                fn invoke(
42                    &self,
43                    args: Vec<ValueContainer>,
44                ) -> Result<R, CallableError> {
45                    // check that number of args is correct
46                    if args.len() != $n {
47                        return Err(CallableError::InvalidSignature);
48                    }
49                    #[allow(unused)]
50                    let mut args = args.into_iter();
51                    #(
52                        let arg~N: A~N = args
53                            .next()
54                            .unwrap()
55                            .try_into_value()
56                            .map_err(|_| CallableError::InvalidSignature)?;
57                    )*
58                    Ok(self(#(arg~N,)*))
59                }
60            }
61        });
62    };
63}
64
65impl_datex_callable!(0);
66impl_datex_callable!(1);
67impl_datex_callable!(2);
68impl_datex_callable!(3);
69impl_datex_callable!(4);
70impl_datex_callable!(5);
71impl_datex_callable!(6);
72impl_datex_callable!(7);
73impl_datex_callable!(8);
74impl_datex_callable!(9);
75impl_datex_callable!(10);
76
77#[cfg(test)]
78mod tests {
79
80    // FIXME
81    // #[test]
82    // fn simple_call() {
83    //     let func = |x: u8, y: u8| x + y;
84    //     let result = func.invoke(vec![1u8.into(), 2u8.into()]).unwrap();
85    //     assert_eq!(result, 3);
86    // }
87    //
88    // #[test]
89    // fn order() {
90    //     let func = |a: u8, b: u8, c: u8, d: u8, e: u8| vec![a, b, c, d, e];
91    //     let result = func
92    //         .invoke(vec![
93    //             1u8.into(),
94    //             2u8.into(),
95    //             3u8.into(),
96    //             4u8.into(),
97    //             5u8.into(),
98    //         ])
99    //         .unwrap();
100    //     assert_eq!(result, vec![1, 2, 3, 4, 5]);
101    // }
102    //
103    // #[test]
104    // fn invalid_signature_args_count() {
105    //     let func = |x: u8, y: u8| x + y;
106    //     // only one instead of two args
107    //     let result = func.invoke(vec![1u8.into()]);
108    //     assert!(matches!(result, Err(CallableError::InvalidSignature)));
109    // }
110    //
111    // #[test]
112    // fn invalid_signature_wrong_type() {
113    //     let func = |x: u8, y: u8| x + y;
114    //     // second arg is a text instead of u8
115    //     let result = func.invoke(vec![1u8.into(), "test".into()]);
116    //     assert!(matches!(result, Err(CallableError::InvalidSignature)));
117    // }
118    //
119    // #[test]
120    // fn error_result() {
121    //     let func = |should_fail: bool| -> Result<u8, ExecutionError> {
122    //         if should_fail {
123    //             Err(ExecutionError::RequiresAsyncExecution)
124    //         } else {
125    //             Ok(42)
126    //         }
127    //     };
128    //     let result = func.invoke(vec![true.into()]).unwrap();
129    //     assert!(matches!(
130    //         result,
131    //         Err(ExecutionError::RequiresAsyncExecution)
132    //     ));
133    // }
134}