1use super::{HostFnResult, HostFunction, HostFunctionError, HostFunctionSyncBound};
7use crate::{RuntimeValue, Shared, number::Number};
8
9pub trait ValueAdapter: Sized {
14 fn from_runtime_value(value: &RuntimeValue) -> Result<Self, HostFunctionError>;
17
18 fn into_runtime_value(self) -> RuntimeValue;
20}
21
22fn type_mismatch(expected: &str, value: &RuntimeValue) -> HostFunctionError {
23 HostFunctionError::new(format!("expected {expected}, got {}", value.name()))
24}
25
26impl ValueAdapter for RuntimeValue {
27 fn from_runtime_value(value: &RuntimeValue) -> Result<Self, HostFunctionError> {
28 Ok(value.clone())
29 }
30
31 fn into_runtime_value(self) -> RuntimeValue {
32 self
33 }
34}
35
36impl ValueAdapter for i64 {
37 fn from_runtime_value(value: &RuntimeValue) -> Result<Self, HostFunctionError> {
38 match value {
39 RuntimeValue::Number(n) => Ok(n.to_int()),
40 other => Err(type_mismatch("a number", other)),
41 }
42 }
43
44 fn into_runtime_value(self) -> RuntimeValue {
45 RuntimeValue::from(Number::from(self))
46 }
47}
48
49impl ValueAdapter for f64 {
50 fn from_runtime_value(value: &RuntimeValue) -> Result<Self, HostFunctionError> {
51 match value {
52 RuntimeValue::Number(n) => Ok(n.value()),
53 other => Err(type_mismatch("a number", other)),
54 }
55 }
56
57 fn into_runtime_value(self) -> RuntimeValue {
58 RuntimeValue::from(Number::from(self))
59 }
60}
61
62impl ValueAdapter for bool {
63 fn from_runtime_value(value: &RuntimeValue) -> Result<Self, HostFunctionError> {
64 match value {
65 RuntimeValue::Boolean(b) => Ok(*b),
66 other => Err(type_mismatch("a bool", other)),
67 }
68 }
69
70 fn into_runtime_value(self) -> RuntimeValue {
71 RuntimeValue::Boolean(self)
72 }
73}
74
75impl ValueAdapter for String {
76 fn from_runtime_value(value: &RuntimeValue) -> Result<Self, HostFunctionError> {
77 match value {
78 RuntimeValue::String(s) => Ok(s.to_string()),
79 other => Err(type_mismatch("a string", other)),
80 }
81 }
82
83 fn into_runtime_value(self) -> RuntimeValue {
84 RuntimeValue::String(self.into())
85 }
86}
87
88impl<T: ValueAdapter> ValueAdapter for Vec<T> {
89 fn from_runtime_value(value: &RuntimeValue) -> Result<Self, HostFunctionError> {
90 match value {
91 RuntimeValue::Array(items) => items.iter().map(T::from_runtime_value).collect(),
92 other => Err(type_mismatch("an array", other)),
93 }
94 }
95
96 fn into_runtime_value(self) -> RuntimeValue {
97 RuntimeValue::Array(Shared::new(self.into_iter().map(T::into_runtime_value).collect()))
98 }
99}
100
101impl<T: ValueAdapter> ValueAdapter for Option<T> {
102 fn from_runtime_value(value: &RuntimeValue) -> Result<Self, HostFunctionError> {
103 match value {
104 RuntimeValue::None => Ok(None),
105 other => T::from_runtime_value(other).map(Some),
106 }
107 }
108
109 fn into_runtime_value(self) -> RuntimeValue {
110 match self {
111 Some(v) => v.into_runtime_value(),
112 None => RuntimeValue::NONE,
113 }
114 }
115}
116
117pub trait IntoHostFunction<Marker> {
122 fn into_host_fn(self) -> Shared<dyn HostFunction>;
124}
125
126pub struct RawArgs;
128
129impl<F> IntoHostFunction<RawArgs> for F
130where
131 F: Fn(&[RuntimeValue]) -> HostFnResult + HostFunctionSyncBound + 'static,
132{
133 fn into_host_fn(self) -> Shared<dyn HostFunction> {
134 Shared::new(self)
135 }
136}
137
138macro_rules! impl_into_host_fn {
139 ($n:expr; $($T:ident),*) => {
140 impl<Func, R, $($T),*> IntoHostFunction<($($T,)*)> for Func
141 where
142 Func: Fn($($T),*) -> Result<R, HostFunctionError> + HostFunctionSyncBound + 'static,
143 R: ValueAdapter,
144 $($T: ValueAdapter,)*
145 {
146 #[allow(non_snake_case)]
147 fn into_host_fn(self) -> Shared<dyn HostFunction> {
148 Shared::new(move |args: &[RuntimeValue]| -> HostFnResult {
149 if args.len() != $n {
150 return Err(HostFunctionError::new(format!(
151 "expected {} argument(s), got {}",
152 $n,
153 args.len()
154 )));
155 }
156 #[allow(unused_mut, unused_variables)]
157 let mut iter = args.iter();
158 $(let $T = $T::from_runtime_value(iter.next().unwrap())?;)*
159 (self)($($T),*).map(ValueAdapter::into_runtime_value)
160 })
161 }
162 }
163 };
164}
165
166impl_into_host_fn!(0;);
167impl_into_host_fn!(1; A);
168impl_into_host_fn!(2; A, B);
169impl_into_host_fn!(3; A, B, C);
170impl_into_host_fn!(4; A, B, C, D);
171impl_into_host_fn!(5; A, B, C, D, E);
172impl_into_host_fn!(6; A, B, C, D, E, F);
173impl_into_host_fn!(7; A, B, C, D, E, F, G);
174impl_into_host_fn!(8; A, B, C, D, E, F, G, H);
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179 use rstest::rstest;
180
181 type RoundTripFn = fn(&RuntimeValue) -> Result<RuntimeValue, HostFunctionError>;
186
187 fn round_trip<T: ValueAdapter>(value: &RuntimeValue) -> Result<RuntimeValue, HostFunctionError> {
188 T::from_runtime_value(value).map(ValueAdapter::into_runtime_value)
189 }
190
191 #[rstest]
192 #[case::runtime_value(round_trip::<RuntimeValue> as RoundTripFn, RuntimeValue::from(Number::from(42_i64)))]
193 #[case::i64(round_trip::<i64> as RoundTripFn, RuntimeValue::from(Number::from(7_i64)))]
194 #[case::f64(round_trip::<f64> as RoundTripFn, RuntimeValue::from(Number::from(1.5)))]
195 #[case::bool(round_trip::<bool> as RoundTripFn, RuntimeValue::Boolean(true))]
196 #[case::string(round_trip::<String> as RoundTripFn, RuntimeValue::String(Shared::new("hi".to_string())))]
197 #[case::vec(
198 round_trip::<Vec<i64>> as RoundTripFn,
199 RuntimeValue::Array(Shared::new(vec![RuntimeValue::from(Number::from(1_i64)), RuntimeValue::from(Number::from(2_i64))]))
200 )]
201 #[case::option_none(round_trip::<Option<i64>> as RoundTripFn, RuntimeValue::NONE)]
202 #[case::option_some(round_trip::<Option<i64>> as RoundTripFn, RuntimeValue::from(Number::from(3_i64)))]
203 fn test_adapter_roundtrip(#[case] convert: RoundTripFn, #[case] value: RuntimeValue) {
204 assert_eq!(convert(&value).unwrap(), value);
205 }
206
207 #[rstest]
208 #[case::i64_wrong_type(round_trip::<i64> as RoundTripFn, RuntimeValue::Boolean(true))]
209 #[case::f64_wrong_type(round_trip::<f64> as RoundTripFn, RuntimeValue::String(Shared::new("x".to_string())))]
210 #[case::bool_wrong_type(round_trip::<bool> as RoundTripFn, RuntimeValue::NONE)]
211 #[case::string_wrong_type(round_trip::<String> as RoundTripFn, RuntimeValue::Boolean(false))]
212 #[case::vec_wrong_type(round_trip::<Vec<i64>> as RoundTripFn, RuntimeValue::Boolean(true))]
213 #[case::vec_wrong_element_type(
214 round_trip::<Vec<i64>> as RoundTripFn,
215 RuntimeValue::Array(Shared::new(vec![RuntimeValue::Boolean(true)]))
216 )]
217 #[case::option_wrong_inner_type(round_trip::<Option<i64>> as RoundTripFn, RuntimeValue::Boolean(true))]
218 fn test_adapter_type_mismatch_errors(#[case] convert: RoundTripFn, #[case] value: RuntimeValue) {
219 assert!(convert(&value).is_err());
220 }
221
222 #[test]
223 fn test_register_typed_zero_arity() {
224 let f = (|| Ok(true)).into_host_fn();
225 assert_eq!(f.call(&[]).unwrap(), RuntimeValue::Boolean(true));
226 }
227
228 #[test]
229 fn test_register_typed_one_arity() {
230 let f = (|n: i64| Ok(n * 2)).into_host_fn();
231 let result = f.call(&[RuntimeValue::from(Number::from(21_i64))]).unwrap();
232 assert_eq!(result, RuntimeValue::from(Number::from(42_i64)));
233 }
234
235 #[test]
236 fn test_register_typed_two_arity() {
237 let f = (|a: i64, b: i64| Ok(a + b)).into_host_fn();
238 let result = f
239 .call(&[
240 RuntimeValue::from(Number::from(1_i64)),
241 RuntimeValue::from(Number::from(2_i64)),
242 ])
243 .unwrap();
244 assert_eq!(result, RuntimeValue::from(Number::from(3_i64)));
245 }
246
247 #[test]
248 fn test_register_typed_eight_arity() {
249 let f = (|a: i64, b: i64, c: i64, d: i64, e: i64, f: i64, g: i64, h: i64| Ok(a + b + c + d + e + f + g + h))
250 .into_host_fn();
251 let result = f
252 .call(&(1..=8).map(|n| RuntimeValue::from(Number::from(n))).collect::<Vec<_>>())
253 .unwrap();
254 assert_eq!(result, RuntimeValue::from(Number::from(36_i64)));
255 }
256
257 #[test]
258 fn test_register_typed_wrong_arity_errors() {
259 let f = (|n: i64| Ok(n)).into_host_fn();
260 assert!(f.call(&[]).is_err());
261 assert!(
262 f.call(&[
263 RuntimeValue::from(Number::from(1_i64)),
264 RuntimeValue::from(Number::from(2_i64))
265 ])
266 .is_err()
267 );
268 }
269
270 #[test]
271 fn test_register_typed_wrong_type_errors() {
272 let f = (|n: i64| Ok(n)).into_host_fn();
273 assert!(f.call(&[RuntimeValue::Boolean(true)]).is_err());
274 }
275
276 #[test]
277 fn test_raw_args_still_works_via_into_host_fn() {
278 let f = (|args: &[RuntimeValue]| Ok(args[0].clone())).into_host_fn();
279 let result = f.call(&[RuntimeValue::Boolean(true)]).unwrap();
280 assert_eq!(result, RuntimeValue::Boolean(true));
281 }
282}