1use facet::{Facet, Shape};
4
5use super::{CallFn, Context, Signature};
6use crate::marshal::{FromArg, IntoXurValue, TypeDesc};
7use crate::{RuntimeError, Value};
8
9fn shape_or_unit(s: Option<&'static Shape>) -> &'static Shape {
10 s.unwrap_or(<() as Facet>::SHAPE)
11}
12
13fn arity_error(min: usize, max: usize, found: usize) -> RuntimeError {
16 if min == max {
17 RuntimeError::new(format!("expected {min} argument(s), found {found}"))
18 } else {
19 RuntimeError::new(format!(
20 "expected {min} to {max} argument(s), found {found}"
21 ))
22 }
23}
24
25pub trait IntoNativeMethod<T, Marker> {
27 fn into_native(self) -> (Signature, Box<CallFn>);
28}
29
30pub trait IntoNativeMethodMut<T, Marker> {
32 fn into_native(self) -> (Signature, Box<CallFn>);
33}
34
35pub trait IntoNativeFn<Marker> {
60 fn into_native(self) -> (Signature, Box<CallFn>);
61}
62
63macro_rules! impl_into_native_fn {
64 ($($arg:ident),*) => {
65 impl<F, R, $($arg),*> IntoNativeFn<fn($($arg),*) -> R> for F
66 where
67 F: Fn($($arg),*) -> R + Send + Sync + 'static,
68 R: IntoXurValue,
69 $($arg: FromArg,)*
70 {
71 fn into_native(self) -> (Signature, Box<CallFn>) {
72 let min = 0usize $(+ <$arg as FromArg>::REQUIRED as usize)*;
73 let signature = Signature {
74 params: vec![$(shape_or_unit(<$arg as FromArg>::SHAPE)),*],
75 ret: shape_or_unit(<R as IntoXurValue>::SHAPE),
76 param_names: Vec::new(),
77 param_types: vec![$(<$arg as FromArg>::type_desc()),*],
78 ret_type: <R as IntoXurValue>::type_desc(),
79 required: min,
80 };
81 let max = signature.params.len();
82 let call = move |cx: &mut dyn Context, args: &[Value]| {
83 if args.len() < min || args.len() > max {
84 return Err(arity_error(min, max, args.len()));
85 }
86 #[allow(non_snake_case, unused_mut, unused_variables)]
87 let mut rest = args.iter();
88 $(
89 #[allow(non_snake_case)]
90 let $arg = <$arg as FromArg>::from_arg(cx, rest.next())?;
91 )*
92 let result = self($($arg),*);
93 result.into_xur_value(cx)
94 };
95 (signature, Box::new(call))
96 }
97 }
98
99 impl<F, T, R, $($arg),*> IntoNativeMethod<T, fn($($arg),*) -> R> for F
100 where
101 F: Fn(&T, $($arg),*) -> R + Send + Sync + 'static,
102 T: Facet<'static> + Send + 'static,
103 R: IntoXurValue,
104 $($arg: FromArg,)*
105 {
106 #[allow(non_snake_case)]
107 fn into_native(self) -> (Signature, Box<CallFn>) {
108 impl_into_native_fn!(@method self, T, R, with, $($arg),*)
109 }
110 }
111
112 impl<F, T, R, $($arg),*> IntoNativeMethodMut<T, fn($($arg),*) -> R> for F
113 where
114 F: Fn(&mut T, $($arg),*) -> R + Send + Sync + 'static,
115 T: Facet<'static> + Send + 'static,
116 R: IntoXurValue,
117 $($arg: FromArg,)*
118 {
119 #[allow(non_snake_case)]
120 fn into_native(self) -> (Signature, Box<CallFn>) {
121 impl_into_native_fn!(@method self, T, R, with_mut, $($arg),*)
122 }
123 }
124 };
125 (@method $f:ident, $ty:ident, $ret:ident, $with:ident, $($arg:ident),*) => {{
126 let min = 1usize $(+ <$arg as FromArg>::REQUIRED as usize)*;
127 let signature = Signature {
128 params: vec![$ty::SHAPE, $(shape_or_unit(<$arg as FromArg>::SHAPE)),*],
129 ret: shape_or_unit(<$ret as IntoXurValue>::SHAPE),
130 param_names: Vec::new(),
131 param_types: vec![TypeDesc::Shape($ty::SHAPE), $(<$arg as FromArg>::type_desc()),*],
132 ret_type: <$ret as IntoXurValue>::type_desc(),
133 required: min,
134 };
135 let max = signature.params.len();
136 let call = move |cx: &mut dyn Context, args: &[Value]| {
137 if args.len() < min || args.len() > max {
138 return Err(arity_error(min, max, args.len()));
139 }
140 #[allow(unused_mut)]
141 let mut rest = args.iter();
142 let receiver = rest.next().expect("min >= 1 guarantees a receiver");
143 $(
144 #[allow(non_snake_case)]
145 let $arg = <$arg as FromArg>::from_arg(cx, rest.next())?;
146 )*
147 let object = match receiver {
148 Value::Native(object) => object,
149 Value::NativeEnum(ne) => &ne.object,
150 _ => {
151 return Err(RuntimeError::new(format!(
152 "expected `{}`, found {}",
153 $ty::SHAPE,
154 receiver.kind()
155 )));
156 }
157 };
158 let result = object.$with(|this| $f(this, $($arg),*)).ok_or_else(|| {
159 RuntimeError::new(format!("expected `{}`, found another native type", $ty::SHAPE))
160 })?;
161 result.into_xur_value(cx)
162 };
163 (signature, Box::new(call) as Box<CallFn>)
164 }};
165}
166
167impl_into_native_fn!();
168impl_into_native_fn!(A);
169impl_into_native_fn!(A, B);
170impl_into_native_fn!(A, B, C);
171impl_into_native_fn!(A, B, C, D);
172impl_into_native_fn!(A, B, C, D, E);
173impl_into_native_fn!(A, B, C, D, E, G);
174
175use crate::value::lock;
180use std::sync::Arc;
181
182pub trait BuiltinRecv {
189 fn with<R>(value: &Value, f: impl FnOnce(&Self) -> R) -> Result<R, RuntimeError>;
191}
192
193impl BuiltinRecv for [u8] {
194 fn with<R>(value: &Value, f: impl FnOnce(&[u8]) -> R) -> Result<R, RuntimeError> {
195 let Value::Bytes(bytes) = value else {
196 return Err(RuntimeError::new(format!(
197 "expected bytes, found {}",
198 value.kind()
199 )));
200 };
201 Ok(f(&lock(bytes)))
202 }
203}
204
205impl BuiltinRecv for str {
206 fn with<R>(value: &Value, f: impl FnOnce(&str) -> R) -> Result<R, RuntimeError> {
207 let Value::Str(s) = value else {
208 return Err(RuntimeError::new(format!(
209 "expected string, found {}",
210 value.kind()
211 )));
212 };
213 Ok(f(s))
214 }
215}
216
217impl BuiltinRecv for [Value] {
218 fn with<R>(value: &Value, f: impl FnOnce(&[Value]) -> R) -> Result<R, RuntimeError> {
219 let Value::List(list) = value else {
220 return Err(RuntimeError::new(format!(
221 "expected list, found {}",
222 value.kind()
223 )));
224 };
225 Ok(f(&lock(list)))
226 }
227}
228
229impl BuiltinRecv for crate::XurList {
230 fn with<R>(value: &Value, f: impl FnOnce(&Self) -> R) -> Result<R, RuntimeError> {
231 let Value::List(list) = value else {
232 return Err(RuntimeError::new(format!(
233 "expected list, found {}",
234 value.kind()
235 )));
236 };
237 Ok(f(&crate::XurList(Arc::clone(list))))
238 }
239}
240
241impl BuiltinRecv for crate::XurBytes {
242 fn with<R>(value: &Value, f: impl FnOnce(&Self) -> R) -> Result<R, RuntimeError> {
243 let Value::Bytes(bytes) = value else {
244 return Err(RuntimeError::new(format!(
245 "expected bytes, found {}",
246 value.kind()
247 )));
248 };
249 Ok(f(&crate::XurBytes(Arc::clone(bytes))))
250 }
251}
252
253pub trait BuiltinRecvMut {
255 fn with_mut<R>(value: &Value, f: impl FnOnce(&mut Self) -> R) -> Result<R, RuntimeError>;
256}
257
258impl BuiltinRecvMut for Vec<u8> {
259 fn with_mut<R>(value: &Value, f: impl FnOnce(&mut Vec<u8>) -> R) -> Result<R, RuntimeError> {
260 let Value::Bytes(bytes) = value else {
261 return Err(RuntimeError::new(format!(
262 "expected bytes, found {}",
263 value.kind()
264 )));
265 };
266 Ok(f(&mut lock(bytes)))
267 }
268}
269
270impl BuiltinRecvMut for Vec<Value> {
271 fn with_mut<R>(value: &Value, f: impl FnOnce(&mut Vec<Value>) -> R) -> Result<R, RuntimeError> {
272 let Value::List(list) = value else {
273 return Err(RuntimeError::new(format!(
274 "expected list, found {}",
275 value.kind()
276 )));
277 };
278 Ok(f(&mut lock(list)))
279 }
280}
281
282pub trait IntoBuiltinMethod<Recv: ?Sized, Marker> {
285 fn into_native(self) -> (Signature, Box<CallFn>);
286}
287
288pub trait IntoBuiltinMethodMut<Recv, Marker> {
291 fn into_native(self) -> (Signature, Box<CallFn>);
292}
293
294macro_rules! impl_builtin_method {
295 ($($arg:ident),*) => {
296 impl<F, Recv, R, $($arg),*> IntoBuiltinMethod<Recv, fn($($arg),*) -> R> for F
297 where
298 F: Fn(&Recv, $($arg),*) -> R + Send + Sync + 'static,
299 Recv: BuiltinRecv + ?Sized + 'static,
300 R: IntoXurValue,
301 $($arg: FromArg,)*
302 {
303 #[allow(non_snake_case)]
304 fn into_native(self) -> (Signature, Box<CallFn>) {
305 let min = 1usize $(+ <$arg as FromArg>::REQUIRED as usize)*;
306 let signature = Signature {
307 params: vec![$(shape_or_unit(<$arg as FromArg>::SHAPE)),*],
308 ret: shape_or_unit(<R as IntoXurValue>::SHAPE),
309 param_names: Vec::new(),
310 param_types: vec![$(<$arg as FromArg>::type_desc()),*],
311 ret_type: <R as IntoXurValue>::type_desc(),
312 required: min - 1,
314 };
315 let max = signature.params.len() + 1;
316 let call = move |cx: &mut dyn Context, args: &[Value]| {
317 if args.len() < min || args.len() > max {
318 return Err(arity_error(min, max, args.len()));
319 }
320 #[allow(unused_mut)]
321 let mut rest = args.iter();
322 let receiver = rest.next().expect("min >= 1 guarantees a receiver");
323 $(
324 #[allow(non_snake_case)]
325 let $arg = <$arg as FromArg>::from_arg(cx, rest.next())?;
326 )*
327 let result = Recv::with(receiver, |recv| self(recv, $($arg),*))?;
328 result.into_xur_value(cx)
329 };
330 (signature, Box::new(call))
331 }
332 }
333
334 impl<F, Recv, R, $($arg),*> IntoBuiltinMethodMut<Recv, fn($($arg),*) -> R> for F
335 where
336 F: Fn(&mut Recv, $($arg),*) -> R + Send + Sync + 'static,
337 Recv: BuiltinRecvMut + 'static,
338 R: IntoXurValue,
339 $($arg: FromArg,)*
340 {
341 #[allow(non_snake_case)]
342 fn into_native(self) -> (Signature, Box<CallFn>) {
343 let min = 1usize $(+ <$arg as FromArg>::REQUIRED as usize)*;
344 let signature = Signature {
345 params: vec![$(shape_or_unit(<$arg as FromArg>::SHAPE)),*],
346 ret: shape_or_unit(<R as IntoXurValue>::SHAPE),
347 param_names: Vec::new(),
348 param_types: vec![$(<$arg as FromArg>::type_desc()),*],
349 ret_type: <R as IntoXurValue>::type_desc(),
350 required: min - 1,
352 };
353 let max = signature.params.len() + 1;
354 let call = move |cx: &mut dyn Context, args: &[Value]| {
355 if args.len() < min || args.len() > max {
356 return Err(arity_error(min, max, args.len()));
357 }
358 #[allow(unused_mut)]
359 let mut rest = args.iter();
360 let receiver = rest.next().expect("min >= 1 guarantees a receiver");
361 $(
362 #[allow(non_snake_case)]
363 let $arg = <$arg as FromArg>::from_arg(cx, rest.next())?;
364 )*
365 let result = Recv::with_mut(receiver, |recv| self(recv, $($arg),*))?;
366 result.into_xur_value(cx)
367 };
368 (signature, Box::new(call))
369 }
370 }
371 };
372}
373
374impl_builtin_method!();
375impl_builtin_method!(A);
376impl_builtin_method!(A, B);
377impl_builtin_method!(A, B, C);
378impl_builtin_method!(A, B, C, D);
379impl_builtin_method!(A, B, C, D, E);
380impl_builtin_method!(A, B, C, D, E, G);