yomi_core/package/
functions.rs1use super::*;
4
5pub trait IntoReturn {
7 fn ret_ty() -> Ty;
9 fn into_return(self) -> Result<Value, CommandError>;
11}
12
13impl<T: IntoValue> IntoReturn for T {
14 fn ret_ty() -> Ty {
15 T::ty()
16 }
17 fn into_return(self) -> Result<Value, CommandError> {
18 Ok(self.into_value())
19 }
20}
21
22impl<T: IntoValue> IntoReturn for Result<T, CommandError> {
23 fn ret_ty() -> Ty {
24 T::ty()
25 }
26 fn into_return(self) -> Result<Value, CommandError> {
27 self.map(IntoValue::into_value)
28 }
29}
30
31pub(super) fn bad_args(name: &str) -> CommandError {
33 CommandError::with_code("core.bad_args", [("name", name.into())])
34}
35
36pub trait EffectFn<P: Package, Args, R> {
38 fn arg_types() -> Vec<Ty>;
40 fn ret_ty() -> Ty;
42 fn call(&self, ctx: &mut Ctx<'_, P>, args: &[Value]) -> Result<Value, CommandError>;
44}
45
46pub trait QueryFn<P: Package, Args, R> {
48 fn arg_types() -> Vec<Ty>;
50 fn ret_ty() -> Ty;
52 fn call(&self, ctx: &Ctx<'_, P>, args: &[Value]) -> Result<Value, CommandError>;
54}
55
56macro_rules! impl_fns {
58 ($n:expr; $($A:ident $a:ident $i:tt),*) => {
59 impl<P: Package, F, R, $($A),*> EffectFn<P, ($($A,)*), R> for F
60 where
61 F: Fn(&mut Ctx<'_, P>, $($A),*) -> R,
62 R: IntoReturn,
63 $($A: FromValue,)*
64 {
65 fn arg_types() -> Vec<Ty> {
66 vec![$($A::ty()),*]
67 }
68 fn ret_ty() -> Ty {
69 R::ret_ty()
70 }
71 fn call(&self, ctx: &mut Ctx<'_, P>, args: &[Value]) -> Result<Value, CommandError> {
72 if args.len() != $n {
73 return Err(bad_args(P::NAME));
74 }
75 $(let $a = $A::from_value(&args[$i]).ok_or_else(|| bad_args(P::NAME))?;)*
76 self(ctx, $($a),*).into_return()
77 }
78 }
79
80 impl<P: Package, F, R, $($A),*> QueryFn<P, ($($A,)*), R> for F
81 where
82 F: Fn(&Ctx<'_, P>, $($A),*) -> R,
83 R: IntoReturn,
84 $($A: FromValue,)*
85 {
86 fn arg_types() -> Vec<Ty> {
87 vec![$($A::ty()),*]
88 }
89 fn ret_ty() -> Ty {
90 R::ret_ty()
91 }
92 fn call(&self, ctx: &Ctx<'_, P>, args: &[Value]) -> Result<Value, CommandError> {
93 if args.len() != $n {
94 return Err(bad_args(P::NAME));
95 }
96 $(let $a = $A::from_value(&args[$i]).ok_or_else(|| bad_args(P::NAME))?;)*
97 self(ctx, $($a),*).into_return()
98 }
99 }
100 };
101}
102
103impl_fns!(0;);
104impl_fns!(1; A1 a1 0);
105impl_fns!(2; A1 a1 0, A2 a2 1);
106impl_fns!(3; A1 a1 0, A2 a2 1, A3 a3 2);
107impl_fns!(4; A1 a1 0, A2 a2 1, A3 a3 2, A4 a4 3);
108impl_fns!(5; A1 a1 0, A2 a2 1, A3 a3 2, A4 a4 3, A5 a5 4);
109impl_fns!(6; A1 a1 0, A2 a2 1, A3 a3 2, A4 a4 3, A5 a5 4, A6 a6 5);