Skip to main content

cel_runtime/
callable.rs

1//! Calls native and prepared bodies through one statically fixed signature.
2//!
3//! ```
4//! use cel_runtime::{Callable, CNil, EmptyList};
5//! let f = Callable::from_fn(|_: &CNil<()>| Ok(7i32));
6//! assert_eq!(f.call(&CNil::<()>::root_empty()).unwrap(), 7);
7//! ```
8
9use std::marker::PhantomData;
10use std::mem::MaybeUninit;
11
12use crate::{ArgumentList, DynClosure, PreparedSegment, ValueRepr};
13
14/// Shares a callable whose borrowed arguments and owned result have fixed Rust types.
15///
16/// Every instantiation has exactly the canonical [`DynClosure`] representation.
17/// Clones share execution state, not arguments or results. Recursive entry into
18/// the same carrier returns an error; different carriers can call one another.
19///
20/// # Examples
21///
22/// ```
23/// use cel_runtime::Callable;
24/// let f = Callable::from_fn(|x: &i32| Ok(*x));
25/// assert_eq!(f.clone().call(&7).unwrap(), 7);
26/// ```
27///
28/// Wrong Rust arguments cannot enter the body:
29///
30/// ```compile_fail
31/// use cel_runtime::Callable;
32/// let f = Callable::from_fn(|x: &i32| Ok(*x));
33/// f.call(&"not an integer");
34/// ```
35#[repr(transparent)]
36pub struct Callable<Args, R> {
37    /// Shares the exact native or interpreted body under its trusted binding.
38    carrier: DynClosure,
39    /// Associates the carrier with its validated canonical argument/result witnesses.
40    signature: PhantomData<fn(&Args) -> R>,
41}
42
43impl<Args, R> Clone for Callable<Args, R> {
44    /// Shares the carrier without imposing clone bounds on the signature.
45    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    /// Shares a native function pointer with this exact borrowed/owned signature.
55    ///
56    /// # Examples
57    /// See the module example.
58    pub fn from_fn(f: fn(&Args) -> anyhow::Result<R>) -> Self {
59        /// Invokes the construction-bound native function with a matching raw frame.
60        ///
61        /// # Safety
62        /// `body` stores this exact function pointer, `args` borrows `Args`, and
63        /// `result` is aligned uninitialized storage for `R`.
64        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            // SAFETY: This payload and dispatcher share the exact fn signature.
77            carrier: unsafe { DynClosure::from_frame_body(Box::new(f), dispatch::<Args, R>, None) },
78            signature: PhantomData,
79        }
80    }
81
82    /// Shares an independently prepared body with matching canonical arguments.
83    ///
84    /// - Complexity: O(n) descriptor construction for n argument/result type nodes.
85    ///
86    /// # Examples
87    /// ```
88    /// use cel_runtime::{Callable, DynSegment, Nil, Leaf, CNil, EmptyList};
89    /// let mut body = DynSegment::new::<()>(); body.just(7i32);
90    /// let f = Callable::from_prepared(body.prepare::<Nil, Leaf<i32>>().unwrap());
91    /// assert_eq!(f.call(&CNil::<()>::root_empty()).unwrap(), 7);
92    /// ```
93    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        /// Invokes an already prepared body and initializes the result only on success.
99        ///
100        /// # Safety
101        /// `body` stores exactly `PreparedSegment<A, R>` and both raw pointers
102        /// match its preparation-validated concrete representations.
103        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            // SAFETY: Preparation validates the signature and concrete frames;
126            // this exact payload remains paired with its monomorphized dispatcher.
127            carrier: unsafe {
128                DynClosure::from_frame_body(Box::new(body), dispatch::<A, Result>, Some(signature))
129            },
130            signature: PhantomData,
131        }
132    }
133
134    /// Borrows arguments and returns an independent result without checking signatures.
135    ///
136    /// # Errors
137    /// Returns an error on reentrant entry into this shared carrier, or propagates
138    /// the original body error. Errors and unwinding release the execution guard
139    /// so later calls remain valid.
140    /// - Complexity: Body-dependent work; interpreted calls set up O(a) pointers
141    ///   for a arguments.
142    ///
143    /// # Examples
144    /// See the module example.
145    pub fn call(&self, args: &Args) -> anyhow::Result<R> {
146        let mut result = MaybeUninit::<R>::uninit();
147        // SAFETY: Only the exact native signature or matching prepared witnesses
148        // construct this facade. The carrier cannot escape through a mutable API.
149        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    /// Describes source-ordered arguments with distinct sizes, alignments, and ownership.
165    type MixedArguments = Cons<Leaf<u8>, Cons<Leaf<u64>, Cons<Leaf<String>, Nil>>>;
166    /// Stores the canonical borrowed frame for the mixed-layout argument contract.
167    type MixedFrame = <MixedArguments as ValueRepr>::Value;
168    /// Describes a mixed-layout callable that returns an independently owned string.
169    type MixedFunction = FnOf<MixedArguments, Leaf<String>>;
170
171    /// Builds an ordered rendering body with a zero-tag error and reserved panic tag.
172    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    /// Emits an invocation that borrows all three mixed-layout arguments.
198    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    /// Escapes a typed interpreted carrier through its public canonical callable witness.
212    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    /// Rebinds borrowed frames through direct/emitted calls and recovers after errors and panic.
223    #[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    /// Restores outer arguments after typed nested calls and rejects same-carrier reentry.
258    #[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    /// Both typed body kinds and emitted invocation perform zero descriptor comparisons.
316    #[test]
317    fn trusted_callable_calls_never_compare_descriptors() {
318        /// Describes the borrowed array argument shared by the compared call routes.
319        type Args = Cons<ArrayOf<Leaf<i32>>, Nil>;
320        /// Describes the callable's argument and independently owned array result.
321        type Function = FnOf<Args, ArrayOf<Leaf<i32>>>;
322        /// Returns an independently owned copy of the borrowed array.
323        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}