1use std::marker::PhantomData;
10use std::mem::MaybeUninit;
11
12use crate::{ArgumentList, DynClosure, PreparedSegment, ValueRepr};
13
14#[repr(transparent)]
36pub struct Callable<Args, R> {
37 carrier: DynClosure,
39 signature: PhantomData<fn(&Args) -> R>,
41}
42
43impl<Args, R> Clone for Callable<Args, R> {
44 fn clone(&self) -> Self {
46 Self {
47 carrier: self.carrier.clone(),
48 signature: PhantomData,
49 }
50 }
51}
52
53impl<Args: 'static, R: 'static> Callable<Args, R> {
54 pub fn from_fn(f: fn(&Args) -> anyhow::Result<R>) -> Self {
59 unsafe fn dispatch<Args: 'static, R: 'static>(
65 body: *mut (),
66 args: *const u8,
67 result: *mut u8,
68 ) -> anyhow::Result<()> {
69 let f = unsafe { &*body.cast::<fn(&Args) -> anyhow::Result<R>>() };
70 let value = f(unsafe { &*args.cast::<Args>() })?;
71 unsafe { result.cast::<R>().write(value) };
72 Ok(())
73 }
74
75 Self {
76 carrier: unsafe { DynClosure::from_frame_body(Box::new(f), dispatch::<Args, R>, None) },
78 signature: PhantomData,
79 }
80 }
81
82 pub fn from_prepared<A, Result>(body: PreparedSegment<A, Result>) -> Self
94 where
95 A: ArgumentList<Value = Args> + 'static,
96 Result: ValueRepr<Value = R> + 'static,
97 {
98 unsafe fn dispatch<A: ValueRepr + 'static, R: ValueRepr + 'static>(
104 body: *mut (),
105 args: *const u8,
106 result: *mut u8,
107 ) -> anyhow::Result<()> {
108 let body = unsafe { &mut *body.cast::<PreparedSegment<A, R>>() };
109 let value = body.call(unsafe { &*args.cast::<A::Value>() })?;
110 unsafe { result.cast::<R::Value>().write(value) };
111 Ok(())
112 }
113 let args = A::value_type();
114 let parameters = args
115 .tuple_elements()
116 .expect("sealed canonical argument list")
117 .iter()
118 .map(|field| field.value_type.clone())
119 .collect();
120 let signature = crate::dyn_closure::ClosureSignature {
121 parameters,
122 result: Result::value_type(),
123 };
124 Self {
125 carrier: unsafe {
128 DynClosure::from_frame_body(Box::new(body), dispatch::<A, Result>, Some(signature))
129 },
130 signature: PhantomData,
131 }
132 }
133
134 pub fn call(&self, args: &Args) -> anyhow::Result<R> {
146 let mut result = MaybeUninit::<R>::uninit();
147 unsafe {
150 self.carrier
151 .call_frame_trusted(std::ptr::from_ref(args).cast(), result.as_mut_ptr().cast())?;
152 Ok(result.assume_init())
153 }
154 }
155}
156
157#[cfg(test)]
158mod tests {
159 use super::*;
160 use crate::{Array, ArrayOf, Cons, DynSegment, FnOf, IntoCStackList, Leaf, Nil, ValueType};
161 use std::cell::OnceCell;
162 use std::rc::{Rc, Weak};
163
164 type MixedArguments = Cons<Leaf<u8>, Cons<Leaf<u64>, Cons<Leaf<String>, Nil>>>;
166 type MixedFrame = <MixedArguments as ValueRepr>::Value;
168 type MixedFunction = FnOf<MixedArguments, Leaf<String>>;
170
171 fn mixed_closure() -> DynClosure {
173 let mut body = DynSegment::new::<()>();
174 body.push_argument(0, ValueType::cloneable_leaf::<u8>())
175 .unwrap();
176 body.push_argument(1, ValueType::cloneable_leaf::<u64>())
177 .unwrap();
178 body.push_argument(2, ValueType::cloneable_leaf::<String>())
179 .unwrap();
180 body.op3r(|tag: u8, word: u64, text: String| {
181 anyhow::ensure!(tag != 0, "zero tag");
182 assert_ne!(tag, u8::MAX, "typed interpreted body panic");
183 Ok(format!("{tag}/{word}/{text}"))
184 })
185 .unwrap();
186 DynClosure::typed(
187 vec![
188 ValueType::cloneable_leaf::<u8>(),
189 ValueType::cloneable_leaf::<u64>(),
190 ValueType::cloneable_leaf::<String>(),
191 ],
192 body,
193 )
194 .unwrap()
195 }
196
197 fn mixed_invocation(closure: DynClosure) -> PreparedSegment<MixedArguments, Leaf<String>> {
199 let mut body = DynSegment::new::<()>();
200 body.push_closure(closure).unwrap();
201 body.push_argument(0, ValueType::cloneable_leaf::<u8>())
202 .unwrap();
203 body.push_argument(1, ValueType::cloneable_leaf::<u64>())
204 .unwrap();
205 body.push_argument(2, ValueType::cloneable_leaf::<String>())
206 .unwrap();
207 body.invoke_closure(3).unwrap();
208 body.prepare::<MixedArguments, Leaf<String>>().unwrap()
209 }
210
211 fn mixed_callable(closure: DynClosure) -> Callable<MixedFrame, String> {
213 let mut factory = DynSegment::new::<()>();
214 factory.push_closure(closure).unwrap();
215 factory
216 .prepare::<Nil, MixedFunction>()
217 .unwrap()
218 .call(&().into_c_stack_list())
219 .unwrap()
220 }
221
222 #[test]
224 fn typed_interpreted_frames_rebind_and_recover() {
225 let closure = mixed_closure();
226 let direct = mixed_callable(closure.clone());
227 let mut emitted = mixed_invocation(closure);
228 let first = (7u8, 1001u64, String::from("alpha")).into_c_stack_list();
229 let second = (9u8, 7002u64, String::from("second-longer")).into_c_stack_list();
230 let rejected = (0u8, 3003u64, String::from("reject")).into_c_stack_list();
231 let panicking = (u8::MAX, 4004u64, String::from("panic")).into_c_stack_list();
232 let recovered = (11u8, 9004u64, String::from("recovered")).into_c_stack_list();
233
234 assert_eq!(direct.call(&first).unwrap(), "7/1001/alpha");
235 assert_eq!(emitted.call(&second).unwrap(), "9/7002/second-longer");
236 assert!(direct.call(&rejected).is_err());
237 assert!(emitted.call(&rejected).is_err());
238 assert!(
239 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
240 emitted.call(&panicking)
241 }))
242 .is_err()
243 );
244 assert_eq!(emitted.call(&recovered).unwrap(), "11/9004/recovered");
245 assert_eq!(direct.call(&second).unwrap(), "9/7002/second-longer");
246 for (frame, expected) in [
247 (&first, (7, 1001, "alpha")),
248 (&second, (9, 7002, "second-longer")),
249 (&rejected, (0, 3003, "reject")),
250 (&panicking, (u8::MAX, 4004, "panic")),
251 (&recovered, (11, 9004, "recovered")),
252 ] {
253 assert_eq!((frame.1, frame.0.1, frame.0.0.1.as_str()), expected);
254 }
255 }
256
257 #[test]
259 fn typed_interpreted_nested_frames_and_reentry() {
260 let target = Rc::new(OnceCell::<Weak<Callable<MixedFrame, String>>>::new());
261 let reentrant = target.clone();
262 let mut body = DynSegment::new::<()>();
263 body.push_closure(mixed_closure()).unwrap();
264 body.just(5u8);
265 body.just(600u64);
266 body.just(String::from("nested"));
267 body.invoke_closure(3).unwrap();
268 body.push_argument(2, ValueType::cloneable_leaf::<String>())
269 .unwrap();
270 body.op2(|nested: String, outer: String| format!("{nested}|parent:{outer}"))
271 .unwrap();
272 body.push_argument(0, ValueType::cloneable_leaf::<u8>())
273 .unwrap();
274 body.push_argument(1, ValueType::cloneable_leaf::<u64>())
275 .unwrap();
276 body.op3r(move |rendered: String, tag: u8, word: u64| {
277 if tag == 13 {
278 let function = reentrant.get().unwrap().upgrade().unwrap();
279 return function
280 .call(&(99u8, 999u64, String::from("reentrant")).into_c_stack_list());
281 }
282 Ok(format!("{tag}/{word}:{rendered}"))
283 })
284 .unwrap();
285 let closure = DynClosure::typed(
286 vec![
287 ValueType::cloneable_leaf::<u8>(),
288 ValueType::cloneable_leaf::<u64>(),
289 ValueType::cloneable_leaf::<String>(),
290 ],
291 body,
292 )
293 .unwrap();
294 let direct = Rc::new(mixed_callable(closure.clone()));
295 target.set(Rc::downgrade(&direct)).unwrap();
296 let mut emitted = mixed_invocation(closure);
297 let first = (7u8, 1001u64, String::from("alpha")).into_c_stack_list();
298 let recursive = (13u8, 2002u64, String::from("recursive")).into_c_stack_list();
299 let after = (9u8, 7002u64, String::from("after")).into_c_stack_list();
300 assert_eq!(
301 emitted.call(&first).unwrap(),
302 "7/1001:5/600/nested|parent:alpha"
303 );
304 let error = emitted.call(&recursive).unwrap_err();
305 assert!(error.to_string().contains("already executing"));
306 assert_eq!(
307 direct.call(&after).unwrap(),
308 "9/7002:5/600/nested|parent:after"
309 );
310 assert_eq!(first.0.0.1, "alpha");
311 assert_eq!(recursive.0.0.1, "recursive");
312 assert_eq!(after.0.0.1, "after");
313 }
314
315 #[test]
317 fn trusted_callable_calls_never_compare_descriptors() {
318 type Args = Cons<ArrayOf<Leaf<i32>>, Nil>;
320 type Function = FnOf<Args, ArrayOf<Leaf<i32>>>;
322 fn native(args: &<Args as ValueRepr>::Value) -> anyhow::Result<Array<i32>> {
324 Ok(args.1.clone())
325 }
326 let mut body = DynSegment::new::<()>();
327 body.push_argument(0, ValueType::array(ValueType::cloneable_leaf::<i32>()))
328 .unwrap();
329 let interpreted =
330 Callable::from_prepared(body.prepare::<Args, ArrayOf<Leaf<i32>>>().unwrap());
331 let args = (Array::from_vec(vec![7]),).into_c_stack_list();
332 for f in [Callable::from_fn(native), interpreted] {
333 let direct = f.clone();
334 let mut body = DynSegment::new::<()>();
335 body.op0_repr::<Function, _>(move || f.clone()).unwrap();
336 body.push_argument(0, ValueType::array(ValueType::cloneable_leaf::<i32>()))
337 .unwrap();
338 body.invoke_closure(1).unwrap();
339 let mut body = body.prepare::<Args, ArrayOf<Leaf<i32>>>().unwrap();
340 crate::value_type::SHAPE_COMPARISONS.with(|n| n.set(0));
341 for _ in 0..3 {
342 assert_eq!(direct.call(&args).unwrap().as_slice(), [7]);
343 assert_eq!(body.call(&args).unwrap().as_slice(), [7]);
344 }
345 crate::value_type::SHAPE_COMPARISONS.with(|n| assert_eq!(n.get(), 0));
346 }
347
348 let mut body = DynSegment::new::<()>();
349 body.just(7i32);
350 let closure = DynClosure::typed(vec![], body).unwrap();
351 let mut outer = DynSegment::new::<()>();
352 outer.push_closure(closure).unwrap();
353 let mut outer = outer.prepare::<Nil, FnOf<Nil, Leaf<i32>>>().unwrap();
354 let f = outer.call(&().into_c_stack_list()).unwrap();
355 drop(outer);
356 crate::value_type::SHAPE_COMPARISONS.with(|n| n.set(0));
357 assert_eq!(f.call(&().into_c_stack_list()).unwrap(), 7);
358 assert_eq!(f.call(&().into_c_stack_list()).unwrap(), 7);
359 crate::value_type::SHAPE_COMPARISONS.with(|n| assert_eq!(n.get(), 0));
360 }
361}