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