Skip to main content

cel_runtime/
segment.rs

1use crate::c_stack_list::{CNil, CStackList};
2use crate::dyn_segment::DynSegment;
3use crate::list_traits::{EmptyList, IntoList, List, ListTypeIteratorAdvance, TypeIdIterator};
4use crate::raw_segment::RawSegment;
5use crate::raw_stack::RawStack;
6use crate::{CStackListHeadLimit, CStackListHeadPadded, ReverseList};
7use anyhow::{Result, ensure};
8use std::any::TypeId;
9use std::result::Result::Ok;
10
11/// Extracts a canonical typed segment's result or its empty-stack marker.
12///
13/// The sealed layout requirement prevents foreign list implementations from
14/// substituting unchecked stack representation metadata.
15///
16/// # Examples
17/// ```
18/// use cel_runtime::{Segment, SegmentCallable};
19/// assert!(Segment::<()>::new().call(()).is_ok());
20/// ```
21pub trait StackResult: List + CStackListHeadLimit {
22    /// Moves the final result out, or returns the empty-stack marker.
23    ///
24    /// - Complexity: O(s + p) time for s head bytes and p head-padding bytes;
25    ///   O(s) result storage.
26    ///
27    /// # Examples
28    /// ```
29    /// use cel_runtime::{CStackList, CNil, RawStack, StackResult};
30    /// type ResultStack = CStackList<String, CNil<()>>;
31    /// let mut stack = RawStack::with_base_alignment(align_of::<String>());
32    /// stack.push(String::from("moved"));
33    /// let result = unsafe { ResultStack::take_result(&mut stack) };
34    /// assert_eq!(result, "moved");
35    /// assert_eq!(stack.len(), 0);
36    /// ```
37    ///
38    /// # Safety
39    /// The raw stack's live values must match this type-level stack exactly.
40    unsafe fn take_result(stack: &mut RawStack) -> Self::Head;
41}
42
43impl StackResult for CNil<()> {
44    /// Returns the empty-stack marker without reading a nonexistent slot.
45    unsafe fn take_result(_stack: &mut RawStack) -> crate::list_traits::Undefined {
46        crate::list_traits::Undefined
47    }
48}
49
50impl<H: 'static, T: List + CStackListHeadLimit> StackResult for CStackList<H, T> {
51    /// Transfers the concrete head out of its owned stack slot.
52    unsafe fn take_result(stack: &mut RawStack) -> H {
53        unsafe { stack.pop::<H>(Self::HEAD_PADDED) }
54    }
55}
56
57/// A type-safe segment that represents a sequence of operations.
58///
59/// The segment takes input arguments of type `Args` and maintains a type stack `Stack` that tracks
60/// the types of values produced by operations.
61///
62/// # Type Parameters
63/// - `Args`: The input argument types, must implement `IntoList`
64/// - `Stack`: The type stack tracking operation results, defaults to the reverse of `Args`
65///
66/// # Examples
67///
68/// ```rust
69/// use cel_runtime::segment::*;
70///
71/// assert_eq!(Segment::<(f64,)>::new() // create a new segment that takes an f64 argument
72///     .op1(|x| x * 2.0)               // push a unary operation that doubles the argument
73///     .op0(|| 10.0)                   // push a nullary operation that returns 10
74///     .op2(|x, y| x + y)              // push a binary operation that adds two arguments
75///     .op1(|x| x.to_string())         // push a unary operation returning a string of the argument
76///     .call((42.0, )).unwrap(),       // call the segment with an argument 42
77///     "94");                          // the result is (42 * 2 + 10).to_string()
78/// ```
79/// # Thread confinement
80///
81/// Captures need not implement `Send` or `Sync`; the erased program remains
82/// thread-confined even when its argument and result types are thread-safe.
83///
84/// ```compile_fail
85/// use cel_runtime::{Segment, SegmentCallable};
86/// let captured = std::rc::Rc::new(7usize);
87/// let body = Segment::<()>::new().op0(move || *captured);
88/// std::thread::spawn(move || body.call(()));
89/// ```
90pub struct Segment<
91    Args: IntoList + 'static,
92    Stack: List = ReverseList<<Args as IntoList>::Output<CNil<()>>>,
93> {
94    /// Owns the instruction stream and its thread-confined captures.
95    segment: RawSegment,
96    /// Binds the argument and current stack types without storing their values.
97    _phantom: std::marker::PhantomData<(Args, Stack)>,
98}
99
100impl<Args: IntoList + 'static> Default for Segment<Args> {
101    /// Constructs an instruction-free segment with the declared initial argument stack.
102    fn default() -> Self {
103        Self::new()
104    }
105}
106
107impl<Args: IntoList + 'static> Segment<Args> {
108    /// Creates a new empty segment with no operations.
109    ///
110    /// # Examples
111    /// ```
112    /// use cel_runtime::{Segment, SegmentCallable};
113    /// assert_eq!(Segment::<(String,)>::new().call((String::from("owned"),))?, "owned");
114    /// # Ok::<(), anyhow::Error>(())
115    /// ```
116    #[must_use]
117    pub fn new() -> Segment<Args> {
118        Segment {
119            segment: RawSegment::new(),
120            _phantom: std::marker::PhantomData,
121        }
122    }
123}
124
125impl<Args: IntoList + 'static, Stack: List + 'static> TryFrom<DynSegment> for Segment<Args, Stack>
126where
127    ReverseList<<Args as IntoList>::Output<CNil<()>>>: ListTypeIteratorAdvance<TypeId>,
128    Stack: ListTypeIteratorAdvance<TypeId>,
129{
130    type Error = anyhow::Error;
131    /// Binds a dynamic preloaded opaque-leaf frame to its exact static signature.
132    ///
133    /// # Errors
134    /// Rejects different argument/result types, non-opaque descriptors,
135    /// borrowed positional reads, and nonzero ambient stack origins.
136    ///
137    /// - Complexity: O(a + s) metadata comparisons for a arguments and s result fields.
138    fn try_from(value: DynSegment) -> Result<Self, Self::Error> {
139        /// Names the physical top-first list corresponding to source-ordered arguments.
140        type ArgList<Args> = ReverseList<<Args as IntoList>::Output<CNil<()>>>;
141
142        ensure!(
143            ArgList::<Args>::LENGTH == value.argument_ids.len()
144                && TypeIdIterator::<ArgList::<Args>>::new().eq(value
145                    .argument_ids
146                    .iter()
147                    .rev()
148                    .copied()),
149            "argument type ids do not match"
150        );
151        for info in &value.stack_ids {
152            info.value_type
153                .validate_opaque_leaf(info.value_type.type_id())?;
154        }
155        ensure!(
156            value.argument_reads.is_empty() && value.base_stack_index == 0,
157            "typed conversion requires a direct preloaded frame without borrowed reads"
158        );
159        ensure!(
160            Stack::LENGTH == value.stack_ids.len()
161                && TypeIdIterator::<Stack>::new().eq(value
162                    .stack_ids
163                    .iter()
164                    .rev()
165                    .map(|info| info.value_type.type_id())),
166            "stack type ids do not match"
167        );
168        Ok(Segment {
169            segment: value.segment,
170            _phantom: std::marker::PhantomData,
171        })
172    }
173}
174
175impl<Args: IntoList + 'static, Stack> Segment<Args, Stack>
176where
177    Stack: StackResult + 'static,
178    Stack::Tail: CStackListHeadLimit,
179{
180    /// Transfers the raw program into the phantom stack produced by its last operation.
181    fn into<NewStack: List + 'static>(self) -> Segment<Args, NewStack> {
182        Segment {
183            segment: self.segment,
184            _phantom: std::marker::PhantomData,
185        }
186    }
187
188    /// Pushes a nullary operation that takes no arguments and returns a value of type R.
189    ///
190    /// - Complexity: Amortized O(size of `F` + alignment of `F`) capture storage;
191    ///   raising capture alignment also relocates the existing stored capture bytes.
192    ///
193    /// # Examples
194    /// See [`Segment`].
195    pub fn op0<R, F>(mut self, op: F) -> Segment<Args, Stack::Push<R>>
196    where
197        F: Fn() -> R + 'static,
198        R: 'static,
199    {
200        self.segment.push_op0(op);
201        self.into()
202    }
203
204    /// Pushes a fallible nullary operation that returns `Result<R>`.
205    ///
206    /// Execution returns the operation's error through [`SegmentCallable::call`].
207    /// - Complexity: The capture-storage insertion cost of [`Self::op0`].
208    ///
209    /// # Examples
210    /// ```
211    /// use cel_runtime::{Segment, SegmentCallable};
212    /// let body = Segment::<()>::new().op0r(|| Ok(String::from("owned")));
213    /// assert_eq!(body.call(())?, "owned");
214    /// # Ok::<(), anyhow::Error>(())
215    /// ```
216    pub fn op0r<R, F>(mut self, op: F) -> Segment<Args, Stack::Push<R>>
217    where
218        F: Fn() -> Result<R> + 'static,
219        R: 'static,
220    {
221        self.segment.raw0(move |_| op());
222        self.into()
223    }
224
225    /// Pushes a unary operation that takes the current stack value and returns a new value.
226    ///
227    /// - Complexity: The capture-storage insertion cost of [`Self::op0`].
228    ///
229    /// # Examples
230    /// See [`Segment`].
231    pub fn op1<R, F>(mut self, op: F) -> Segment<Args, CStackList<R, Stack::Tail>>
232    where
233        Stack: CStackListHeadPadded,
234        F: Fn(Stack::Head) -> R + 'static,
235        R: 'static,
236    {
237        self.segment.push_op1(op, Stack::HEAD_PADDED);
238        self.into()
239    }
240
241    /// Pushes a fallible unary operation that takes the current stack value and returns `Result<R>`.
242    ///
243    /// Execution returns the operation's error through [`SegmentCallable::call`].
244    /// - Complexity: The capture-storage insertion cost of [`Self::op0`].
245    ///
246    /// # Examples
247    /// ```
248    /// use cel_runtime::{Segment, SegmentCallable};
249    /// let body = Segment::<(i32,)>::new().op1r(|value| {
250    ///     value.checked_mul(2).ok_or_else(|| anyhow::anyhow!("overflow"))
251    /// });
252    /// assert_eq!(body.call((21,))?, 42);
253    /// assert!(body.call((i32::MAX,)).is_err());
254    /// # Ok::<(), anyhow::Error>(())
255    /// ```
256    pub fn op1r<R, F>(mut self, op: F) -> Segment<Args, CStackList<R, Stack::Tail>>
257    where
258        Stack: CStackListHeadPadded,
259        F: Fn(Stack::Head) -> Result<R> + 'static,
260        R: 'static,
261    {
262        self.segment.raw1(move |_, x| op(x), Stack::HEAD_PADDED);
263        self.into()
264    }
265    /// Pushes a binary operation that takes the top two stack values and returns a new value.
266    ///
267    /// The earlier source operand becomes the callback's first argument.
268    /// - Complexity: The capture-storage insertion cost of [`Self::op0`].
269    ///
270    /// # Examples
271    /// See [`Segment`].
272    pub fn op2<R, F>(
273        mut self,
274        op: F,
275    ) -> Segment<Args, <<Stack::Tail as List>::Tail as List>::Push<R>>
276    where
277        Stack: CStackListHeadPadded,
278        Stack::Tail: CStackListHeadPadded,
279        F: Fn(<Stack::Tail as List>::Head, Stack::Head) -> R + 'static,
280        R: 'static,
281    {
282        self.segment.push_op2(
283            op,
284            <Stack::Tail as CStackListHeadPadded>::HEAD_PADDED,
285            Stack::HEAD_PADDED,
286        );
287        self.into()
288    }
289
290    /// Executes all operations in the segment and returns the final result.
291    ///
292    /// # Errors
293    /// Propagates operation errors after destroying the live owned frame.
294    ///
295    /// - Complexity: O(n) dispatches plus callback costs for n operations;
296    ///   allocates storage for the maximum live stack.
297    pub(crate) fn call0(&self) -> Result<Stack::Head> {
298        self.finish(RawStack::with_base_alignment(self.segment.base_alignment()))
299    }
300
301    /// Executes the owned frame and extracts its statically described result.
302    ///
303    /// # Errors
304    /// Propagates operation errors after destroying remaining live stack values.
305    ///
306    /// - Complexity: O(n) dispatches plus callback costs for n operations.
307    fn finish(&self, mut stack: RawStack) -> Result<Stack::Head> {
308        unsafe {
309            self.segment.call0_stack(&mut stack)?;
310            Ok(Stack::take_result(&mut stack))
311        }
312    }
313
314    /// Executes a one-argument segment and returns its statically described result.
315    ///
316    /// # Errors
317    /// Propagates operation errors after destroying the live owned frame.
318    ///
319    /// - Complexity: The execution and storage costs of [`Self::call0`].
320    pub(crate) fn call1<A: 'static>(&self, (a,): (A,)) -> Result<Stack::Head> {
321        let mut stack =
322            RawStack::with_base_alignment(self.segment.base_alignment().max(align_of::<A>()));
323        stack.push(a);
324        self.finish(stack)
325    }
326
327    /// Executes a two-argument segment and returns its statically described result.
328    ///
329    /// # Errors
330    /// Propagates operation errors after destroying the live owned frame.
331    ///
332    /// - Complexity: The execution and storage costs of [`Self::call0`].
333    pub(crate) fn call2<A: 'static, B: 'static>(&self, (a, b): (A, B)) -> Result<Stack::Head> {
334        let mut stack = RawStack::with_base_alignment(
335            self.segment
336                .base_alignment()
337                .max(align_of::<A>())
338                .max(align_of::<B>()),
339        );
340        stack.push(a);
341        stack.push(b);
342        self.finish(stack)
343    }
344}
345
346/// Callable segment abstraction for uniform invocation across arities.
347///
348/// This trait invokes statically typed stack segments; [`crate::Callable`] is
349/// the separate shared native/interpreted value facade.
350///
351/// # Examples
352/// ```
353/// use cel_runtime::{Segment, SegmentCallable};
354/// let body = Segment::<()>::new().op0(|| 7i32);
355/// assert_eq!(body.call(()).unwrap(), 7);
356/// ```
357pub trait SegmentCallable<Args> {
358    /// The result type produced by calling with `Args`.
359    type Output;
360    /// Invokes the segment with the supplied arguments.
361    ///
362    /// Implementations return the statically described result or an operation
363    /// error after cleaning the owned execution frame.
364    /// - Complexity: O(n) dispatches plus callback costs for n operations;
365    ///   allocates the maximum live frame.
366    ///
367    /// # Examples
368    /// See [`SegmentCallable`].
369    fn call(&self, args: Args) -> Self::Output;
370}
371
372impl<T: StackResult + 'static> SegmentCallable<()> for Segment<(), T>
373where
374    T::Tail: EmptyList + CStackListHeadLimit,
375{
376    type Output = Result<T::Head>;
377    /// Executes the zero-argument body and returns its single result.
378    ///
379    /// # Errors
380    /// Propagates body errors after frame cleanup.
381    /// - Complexity: The execution and storage costs of [`SegmentCallable::call`].
382    fn call(&self, _args: ()) -> Self::Output {
383        self.call0()
384    }
385}
386
387impl<T: StackResult + 'static, A: 'static> SegmentCallable<(A,)> for Segment<(A,), T>
388where
389    T::Tail: EmptyList + CStackListHeadLimit,
390{
391    type Output = Result<T::Head>;
392    /// Consumes one argument and executes the body to its single result.
393    ///
394    /// # Errors
395    /// Propagates body errors after frame cleanup.
396    /// - Complexity: The execution and storage costs of [`SegmentCallable::call`].
397    fn call(&self, args: (A,)) -> Self::Output {
398        self.call1(args)
399    }
400}
401
402impl<T: StackResult + 'static, A: 'static, B: 'static> SegmentCallable<(A, B)>
403    for Segment<(A, B), T>
404where
405    T::Tail: EmptyList + CStackListHeadLimit,
406{
407    type Output = Result<T::Head>;
408    /// Consumes source-ordered arguments and executes the body to its single result.
409    ///
410    /// # Errors
411    /// Propagates body errors after frame cleanup.
412    /// - Complexity: The execution and storage costs of [`SegmentCallable::call`].
413    fn call(&self, args: (A, B)) -> Self::Output {
414        self.call2(args)
415    }
416}
417
418#[cfg(test)]
419mod tests {
420    use super::*;
421    use anyhow::Result;
422    use std::sync::Arc;
423    use std::sync::atomic::AtomicUsize;
424    use std::sync::atomic::Ordering;
425
426    /// Aligns input storage independently of the result's smaller alignment.
427    #[test]
428    fn over_aligned_arguments() {
429        /// Supplies a value with a stricter alignment than a byte result.
430        #[repr(align(4096))]
431        struct Aligned(u8);
432
433        assert_eq!(
434            Segment::<(Aligned,)>::new()
435                .op1(|value| value.0)
436                .call((Aligned(42),))
437                .unwrap(),
438            42
439        );
440        assert_eq!(
441            Segment::<(u8, Aligned)>::new()
442                .op2(|first, second| (first, second.0))
443                .call((7, Aligned(42)))
444                .unwrap(),
445            (7, 42)
446        );
447        assert_eq!(
448            Segment::<(Aligned, u8)>::new()
449                .op2(|first, second| (first.0, second))
450                .call((Aligned(42), 7))
451                .unwrap(),
452            (42, 7)
453        );
454    }
455
456    /// Returns an unmodified argument even when the segment has no instructions.
457    #[test]
458    fn identity_segment() {
459        for body in [Segment::<(String,)>::new(), Segment::<(String,)>::default()] {
460            assert_eq!(body.call((String::from("owned"),)).unwrap(), "owned");
461        }
462    }
463
464    /// Validates and executes a dynamically checked signed segment through its typed view.
465    #[test]
466    fn segment_from_dyn_segment() -> Result<()> {
467        let mut dyn_segment = DynSegment::new::<(i32,)>();
468        dyn_segment.op0(|| 42);
469        dyn_segment.op2r(|x: i32, y: i32| {
470            x.checked_add(y)
471                .ok_or_else(|| anyhow::anyhow!("addition overflow"))
472        })?;
473        let segment = Segment::<(i32,), CStackList<i32, CNil<()>>>::try_from(dyn_segment)?;
474
475        assert_eq!(segment.call((10,)).unwrap(), 52);
476        Ok(())
477    }
478
479    /// Returns the empty-stack marker from an instruction-free nullary segment.
480    #[test]
481    fn unit_result() {
482        let segment = Segment::new();
483        let result = segment.call(());
484        assert!(result.is_ok());
485    }
486
487    /// Returns the empty-stack marker after consuming one or two input values.
488    #[test]
489    fn consumed_arguments_allow_empty_results() {
490        let mut one = DynSegment::new::<(String,)>();
491        one.drop_value().unwrap();
492        let one = Segment::<(String,), CNil<()>>::try_from(one).unwrap();
493        assert!(one.call((String::from("one"),)).is_ok());
494
495        let mut two = DynSegment::new::<(u8, String)>();
496        two.drop_value().unwrap();
497        two.drop_value().unwrap();
498        let two = Segment::<(u8, String), CNil<()>>::try_from(two).unwrap();
499        assert!(two.call((1, String::from("two"))).is_ok());
500    }
501
502    /// Releases the live intermediate owner when a later nullary operation fails.
503    #[test]
504    fn drop_on_error() {
505        /// Counts independent live owners through a shared destruction log.
506        struct DropCounter(Arc<AtomicUsize>);
507
508        impl Drop for DropCounter {
509            /// Records this owner's destruction once.
510            fn drop(&mut self) {
511                self.0.fetch_add(1, Ordering::SeqCst);
512            }
513        }
514
515        impl Clone for DropCounter {
516            /// Creates another independently dropped owner sharing the observation counter.
517            fn clone(&self) -> Self {
518                DropCounter(self.0.clone())
519            }
520        }
521
522        let drop_count = Arc::new(AtomicUsize::new(0));
523        let tracker = DropCounter(drop_count.clone());
524
525        let segment = Segment::new()
526            .op0(move || tracker.clone())
527            .op0r(|| -> Result<u32> { Err(anyhow::anyhow!("error")) })
528            .op2(|_: DropCounter, _: u32| 42u32);
529
530        assert_eq!(drop_count.load(Ordering::SeqCst), 0); // Nothing dropped yet
531        let result = segment.call(());
532        assert!(matches!(result, Err(e) if e.to_string() == "error"));
533        assert_eq!(drop_count.load(Ordering::SeqCst), 1); // The DropCounter from op0 was dropped
534    }
535
536    /// Propagates a unary parsing error without invoking the dependent operation.
537    #[test]
538    fn op1r_error_does_not_panic() {
539        let parse_and_double = Segment::<(&str,)>::new()
540            .op1r(|s: &str| s.parse::<u32>().map_err(anyhow::Error::from))
541            .op1(|n| n * 2);
542
543        let result = parse_and_double.call(("nope",));
544        assert!(result.is_err());
545    }
546
547    /// Destroys the remaining owned intermediate once after a unary operation fails.
548    #[test]
549    fn op1r_drops_remaining_stack_exactly_once_on_error() {
550        /// Counts independent live owners through a shared destruction log.
551        struct DropCounter(Arc<AtomicUsize>);
552
553        impl Drop for DropCounter {
554            /// Records this owner's destruction once.
555            fn drop(&mut self) {
556                self.0.fetch_add(1, Ordering::SeqCst);
557            }
558        }
559
560        impl Clone for DropCounter {
561            /// Creates another independently dropped owner sharing the observation counter.
562            fn clone(&self) -> Self {
563                DropCounter(self.0.clone())
564            }
565        }
566
567        let drop_count = Arc::new(AtomicUsize::new(0));
568        let tracker = DropCounter(drop_count.clone());
569
570        let segment = Segment::new()
571            .op0(move || tracker.clone())
572            .op0(|| "nope")
573            .op1r(|s: &str| s.parse::<u32>().map_err(anyhow::Error::from))
574            .op2(|_: DropCounter, _: u32| 42u32);
575
576        assert_eq!(drop_count.load(Ordering::SeqCst), 0); // Nothing dropped yet
577        let result = segment.call(());
578        assert!(result.is_err());
579        assert_eq!(drop_count.load(Ordering::SeqCst), 1); // The DropCounter was dropped exactly once
580    }
581
582    /// Preserves heterogeneous source-argument order through a binary operation.
583    #[test]
584    fn binary_operation_args_of_different_types() {
585        let result = Segment::new()
586            .op2(|x, y| format!("{} {}", x, y))
587            .call(("Hello", 12));
588
589        assert_eq!(result.unwrap(), "Hello 12");
590    }
591
592    /// Changes value types while composing infallible arithmetic and formatting operations.
593    #[test]
594    fn type_safe_operations() {
595        let result = Segment::new()
596            .op0(|| 42f64)
597            .op0(|| 10f64)
598            .op2(|x, y| x + y)
599            .op1(|x| x * 2.0)
600            .op1(|x| format!("{}", x))
601            .call(());
602
603        assert_eq!(result.unwrap(), "104");
604    }
605
606    /// Passes a borrowed input through length calculation and formatted output.
607    #[test]
608    fn chain_operations() {
609        let result = Segment::<(&str,)>::new()
610            .op1(|s| s.len())
611            .op1(|n| n * 2)
612            .op1(|n| format!("Length * 2 = {}", n))
613            .call(("Hello",));
614
615        assert_eq!(result.unwrap(), "Length * 2 = 10");
616    }
617
618    /// Executes a checked signed operation on a supplied argument.
619    #[test]
620    fn call_with_args() {
621        let result = Segment::new()
622            .op1r(|x: i32| {
623                x.checked_mul(2)
624                    .ok_or_else(|| anyhow::anyhow!("multiplication overflow"))
625            })
626            .call((21,));
627
628        assert_eq!(result.unwrap(), 42);
629    }
630}