Skip to main content

cel_runtime/
raw_segment.rs

1//! Registers owned captures and executes an explicitly typed raw frame.
2//!
3//! Registration records no dynamic operand types. The caller establishes the
4//! complete types and padding before entering the unsafe execution boundary.
5//!
6//! ```
7//! use cel_runtime::RawSegment;
8//! let mut body = RawSegment::new();
9//! body.push_op0(|| String::from("left"));
10//! body.push_op1(|value: String| value + "/right", false);
11//! assert_eq!(unsafe { body.call0::<String>() }?, "left/right");
12//!
13//! let mut checked = RawSegment::new();
14//! checked.raw0(|_| Ok(3f64));
15//! checked.raw1(|_, value: f64| Ok(value.abs()), false);
16//! checked.raw0(|_| Ok(2f64));
17//! checked.raw2(|_, first: f64, second: f64| Ok(first - second), false, false);
18//! checked.raw0(|_| Ok(4f64));
19//! checked.raw0(|_| Ok(7f64));
20//! checked.raw3(|_, first: f64, second: f64, third: f64| Ok((first, second, third)),
21//!     false, false, false);
22//! assert_eq!(unsafe { checked.call0::<(f64, f64, f64)>() }?, (1.0, 4.0, 7.0));
23//! # Ok::<(), anyhow::Error>(())
24//! ```
25
26use crate::raw_sequence::RawSequence;
27use crate::raw_stack::RawStack;
28use anyhow::Result;
29use std::cmp::max;
30
31/// Executes one instruction and returns the next instruction-state position.
32type Operation = fn(&RawSequence, usize, &mut RawStack) -> Result<usize>;
33
34/// Advances the state cursor before destroying one stored instruction capture.
35type StorageDrop = fn(&mut RawSequence, &mut usize);
36
37/// Owns the remaining instruction-state destruction during unwinding.
38struct StorageCleanup<'a> {
39    /// Exclusively borrows the remaining captures' backing allocation.
40    storage: &'a mut RawSequence,
41    /// Visits the remaining capture destructors once each.
42    droppers: std::slice::Iter<'a, StorageDrop>,
43    /// Tracks the next capture's byte position before invoking its destructor.
44    position: usize,
45}
46
47impl StorageCleanup<'_> {
48    /// Destroys the remaining captures in insertion order.
49    ///
50    /// - Complexity: O(n) plus destruction costs for n remaining captures.
51    fn drop_remaining(&mut self) {
52        // Consume each dropper before invoking a potentially panicking destructor.
53        for destroy in self.droppers.by_ref() {
54            destroy(self.storage, &mut self.position);
55        }
56    }
57}
58
59impl Drop for StorageCleanup<'_> {
60    /// Resumes capture destruction if a previous destructor unwinds.
61    ///
62    /// - Complexity: O(n) plus destruction costs for n remaining captures.
63    fn drop(&mut self) {
64        self.drop_remaining();
65    }
66}
67
68/// A segment represents a sequence of operations that can be executed.
69///
70/// Each operation is stored along with its data in the segment's storage,
71/// and can manipulate values on a stack during execution.
72/// Destruction releases instruction captures in insertion order, including
73/// remaining captures when one destructor panics.
74/// Captures need not be `Send` or `Sync`, so the erased program remains thread-confined.
75///
76/// # Examples
77/// See the [module tutorial](self).
78pub struct RawSegment {
79    /// Dispatches each captured operation in registration order.
80    ops: Vec<Operation>,
81    /// Owns the captures' aligned byte representations.
82    storage: RawSequence,
83    /// Destroys each corresponding capture in registration order.
84    dropper: Vec<StorageDrop>,
85    /// Bounds the alignment of every value emitted by a registered operation.
86    base_alignment: usize,
87    /// Retains the optional caller-owned byte origin and owned input count.
88    frame: Option<(usize, usize)>,
89    /// Prevents erased non-`Send`/non-`Sync` captures from crossing thread boundaries.
90    thread_bound: std::marker::PhantomData<std::rc::Rc<()>>,
91}
92
93impl Default for RawSegment {
94    /// Creates an empty segment.
95    fn default() -> Self {
96        Self::new()
97    }
98}
99
100impl RawSegment {
101    /// Creates a new empty segment.
102    ///
103    /// # Examples
104    /// See [`RawSegment`].
105    #[must_use]
106    pub fn new() -> Self {
107        RawSegment {
108            ops: Vec::new(),
109            storage: RawSequence::new(),
110            dropper: Vec::new(),
111            base_alignment: 1,
112            frame: None,
113            thread_bound: std::marker::PhantomData,
114        }
115    }
116
117    /// Returns the maximum alignment required by any value pushed onto the stack while executing this segment.
118    pub(crate) fn base_alignment(&self) -> usize {
119        self.base_alignment
120    }
121
122    /// Updates the stack base alignment to be at least `alignment`.
123    pub(crate) fn update_base_alignment(&mut self, alignment: usize) {
124        debug_assert!(alignment.is_power_of_two());
125        self.base_alignment = max(self.base_alignment, alignment);
126    }
127
128    /// Sets the caller-owned byte prefix and number of owned input values.
129    pub(crate) fn set_frame(&mut self, origin: usize, owned_inputs: usize) {
130        self.frame = Some((origin, owned_inputs));
131    }
132
133    /// Binds the initial frame unless an enclosing segment already supplied it.
134    pub(crate) fn bind_frame(&mut self, origin: usize, owned_inputs: usize) {
135        self.frame.get_or_insert((origin, owned_inputs));
136    }
137
138    /// Returns the byte length occupied by instruction closure state.
139    #[cfg(test)]
140    pub(crate) fn storage_size(&self) -> usize {
141        self.storage.len()
142    }
143
144    /// Pushes a value into the segment's storage and registers its dropper.
145    ///
146    /// - Complexity: Amortized O(size of `T` + alignment of `T`) capture storage;
147    ///   raising alignment also relocates all stored capture bytes.
148    fn push_storage<T>(&mut self, value: T)
149    where
150        T: 'static,
151    {
152        self.dropper.reserve(1);
153        self.storage.push(value);
154        self.dropper
155            .push(|storage, p| unsafe { storage.drop_next::<T>(p) });
156    }
157
158    /// Pushes a closure that manipulates the stack directly and returns `()`.
159    ///
160    /// Operation errors propagate at execution after frame cleanup.
161    /// - Complexity: The capture insertion cost of [`Self::push_op0`].
162    ///
163    /// # Examples
164    /// ```
165    /// use cel_runtime::RawSegment;
166    /// let mut body = RawSegment::new();
167    /// body.raw0_(|stack| { stack.push(7u8); Ok(()) });
168    /// assert_eq!(unsafe { body.call0::<u8>() }?, 7);
169    /// # Ok::<(), anyhow::Error>(())
170    /// ```
171    pub fn raw0_<F>(&mut self, op: F)
172    where
173        F: Fn(&mut RawStack) -> Result<()> + 'static,
174    {
175        self.push_storage(op);
176        self.ops.push(|storage, p, stack| {
177            let (f, r) = unsafe { storage.next::<F>(p) };
178            f(stack)?;
179            Ok(r)
180        });
181    }
182
183    /// Pushes a fallible closure that manipulates the remaining stack and returns `R`.
184    ///
185    /// Operation errors propagate at execution after frame cleanup.
186    /// - Complexity: The capture insertion cost of [`Self::push_op0`].
187    ///
188    /// # Examples
189    /// See [`RawSegment`].
190    pub fn raw0<R, F>(&mut self, op: F)
191    where
192        F: Fn(&mut RawStack) -> Result<R> + 'static,
193        R: 'static,
194    {
195        self.push_storage(op);
196        self.ops.push(|storage, p, stack| {
197            let (f, r) = unsafe { storage.next::<F>(p) };
198            let result = f(stack)?;
199            stack.push(result);
200            Ok(r)
201        });
202        self.base_alignment = max(self.base_alignment, align_of::<R>());
203    }
204
205    /// Pushes a nullary operation that returns a value of type `R`.
206    ///
207    /// - Complexity: Amortized O(size of `F` + alignment of `F`) capture storage;
208    ///   raising capture alignment additionally moves all stored capture bytes.
209    ///
210    /// # Examples
211    /// See [`RawSegment`].
212    pub fn push_op0<R, F>(&mut self, op: F)
213    where
214        F: Fn() -> R + 'static,
215        R: 'static,
216    {
217        self.push_storage(op);
218        self.ops.push(|storage, p, stack| {
219            let (f, r) = unsafe { storage.next::<F>(p) };
220            stack.push(f());
221            Ok(r)
222        });
223        self.base_alignment = max(self.base_alignment, align_of::<R>());
224    }
225
226    /// Pushes the op-dispatch closure for a unary infallible operation with compile-time padding.
227    fn push_op1_<const PADDING0: bool, T, R, F>(&mut self)
228    where
229        F: Fn(T) -> R + 'static,
230        T: 'static,
231        R: 'static,
232    {
233        self.ops.push(|storage, p, stack| {
234            let (f, r) = unsafe { storage.next::<F>(p) };
235            let x: T = unsafe { stack.pop(PADDING0) };
236            stack.push(f(x));
237            Ok(r)
238        });
239    }
240
241    /// Pushes the op-dispatch closure for a unary fallible operation with compile-time padding.
242    fn push_op1r_<const PADDING0: bool, T, R, F>(&mut self)
243    where
244        F: Fn(&mut RawStack, T) -> Result<R> + 'static,
245        T: 'static,
246        R: 'static,
247    {
248        self.ops.push(|storage, p, stack| {
249            let (f, r) = unsafe { storage.next::<F>(p) };
250            let x: T = unsafe { stack.pop(PADDING0) };
251            let result = f(stack, x)?;
252            stack.push(result);
253            Ok(r)
254        });
255    }
256
257    /// Pushes a unary operation that takes one argument of type T and returns a value of type R.
258    ///
259    /// `padding0` describes the consumed operand's preceding alignment padding.
260    /// - Complexity: The capture insertion cost of [`Self::push_op0`].
261    ///
262    /// # Examples
263    /// See [`RawSegment`].
264    pub fn push_op1<T, R, F>(&mut self, op: F, padding0: bool)
265    where
266        F: Fn(T) -> R + 'static,
267        T: 'static,
268        R: 'static,
269    {
270        self.push_storage(op);
271        if padding0 {
272            self.push_op1_::<true, T, R, F>();
273        } else {
274            self.push_op1_::<false, T, R, F>();
275        }
276        self.base_alignment = max(self.base_alignment, align_of::<R>());
277    }
278
279    /// Pushes a fallible unary operation that can manipulate the remaining stack.
280    ///
281    /// `padding0` describes the consumed operand's preceding alignment padding.
282    /// Operation errors propagate at execution after frame cleanup.
283    /// - Complexity: The capture insertion cost of [`Self::push_op0`].
284    ///
285    /// # Examples
286    /// See [`RawSegment`].
287    pub fn raw1<T, R, F>(&mut self, op: F, padding0: bool)
288    where
289        F: Fn(&mut RawStack, T) -> Result<R> + 'static,
290        T: 'static,
291        R: 'static,
292    {
293        self.push_storage(op);
294        if padding0 {
295            self.push_op1r_::<true, T, R, F>();
296        } else {
297            self.push_op1r_::<false, T, R, F>();
298        }
299        self.base_alignment = max(self.base_alignment, align_of::<R>());
300    }
301
302    /// Pushes the op-dispatch closure for a unary drop operation with compile-time padding.
303    fn drop1_<const PADDING0: bool, T, F>(&mut self)
304    where
305        F: Fn(T) + 'static,
306        T: 'static,
307    {
308        self.ops.push(|storage, p, stack| {
309            let (f, r) = unsafe { storage.next::<F>(p) };
310            let x: T = unsafe { stack.pop(PADDING0) };
311            f(x); // drop the result
312            Ok(r)
313        });
314    }
315
316    /// Pushes an operation that consumes one stack value without producing a result.
317    ///
318    /// `padding0` describes the consumed operand's preceding alignment padding.
319    /// - Complexity: The capture insertion cost of [`Self::push_op0`].
320    ///
321    /// # Examples
322    /// ```
323    /// use cel_runtime::RawSegment;
324    /// let mut body = RawSegment::new();
325    /// body.push_op0(|| String::from("temporary"));
326    /// body.drop1(|value: String| drop(value), false);
327    /// body.push_op0(|| true);
328    /// assert!(unsafe { body.call0::<bool>() }?);
329    /// # Ok::<(), anyhow::Error>(())
330    /// ```
331    pub fn drop1<T, F>(&mut self, op: F, padding0: bool)
332    where
333        F: Fn(T) + 'static,
334        T: 'static,
335    {
336        self.push_storage(op);
337        if padding0 {
338            self.drop1_::<true, T, F>();
339        } else {
340            self.drop1_::<false, T, F>();
341        }
342    }
343
344    /// Pushes the op-dispatch closure for a binary infallible operation with compile-time padding.
345    fn push_op2_<const PADDING0: bool, const PADDING1: bool, T, U, R, F>(&mut self)
346    where
347        F: Fn(T, U) -> R + 'static,
348        T: 'static,
349        U: 'static,
350        R: 'static,
351    {
352        self.ops.push(|storage, p, stack| {
353            let (f, r) = unsafe { storage.next::<F>(p) };
354            let y: U = unsafe { stack.pop(PADDING1) };
355            let x: T = unsafe { stack.pop(PADDING0) };
356            stack.push(f(x, y));
357            Ok(r)
358        });
359    }
360
361    /// Pushes a binary operation that takes two arguments of types T and U and returns a value of
362    /// type R.
363    ///
364    /// Callback arguments and padding flags follow operand source order.
365    /// - Complexity: The capture insertion cost of [`Self::push_op0`].
366    ///
367    /// # Examples
368    /// ```
369    /// use cel_runtime::RawSegment;
370    /// let mut body = RawSegment::new();
371    /// body.push_op2(|first: String, second: u8| (first, second), false, false);
372    /// assert_eq!(unsafe { body.call2::<_, _, (String, u8)>((String::from("first"), 7u8)) }?,
373    ///     (String::from("first"), 7));
374    /// # Ok::<(), anyhow::Error>(())
375    /// ```
376    pub fn push_op2<T, U, R, F>(&mut self, op: F, padding0: bool, padding1: bool)
377    where
378        F: Fn(T, U) -> R + 'static,
379        T: 'static,
380        U: 'static,
381        R: 'static,
382    {
383        self.push_storage(op);
384        match (padding0, padding1) {
385            (false, false) => self.push_op2_::<false, false, T, U, R, F>(),
386            (false, true) => self.push_op2_::<false, true, T, U, R, F>(),
387            (true, false) => self.push_op2_::<true, false, T, U, R, F>(),
388            (true, true) => self.push_op2_::<true, true, T, U, R, F>(),
389        }
390        self.base_alignment = max(self.base_alignment, align_of::<R>());
391    }
392
393    /// Pushes the op-dispatch closure for a binary fallible operation with compile-time padding.
394    fn push_op2r_<const PADDING0: bool, const PADDING1: bool, T, U, R, F>(&mut self)
395    where
396        F: Fn(&mut RawStack, T, U) -> Result<R> + 'static,
397        T: 'static,
398        U: 'static,
399        R: 'static,
400    {
401        self.ops.push(|storage, p, stack| {
402            let (f, r) = unsafe { storage.next::<F>(p) };
403            let y: U = unsafe { stack.pop(PADDING1) };
404            let x: T = unsafe { stack.pop(PADDING0) };
405            let result = f(stack, x, y)?;
406            stack.push(result);
407            Ok(r)
408        });
409    }
410
411    /// Pushes a fallible binary operation that can manipulate the remaining stack.
412    ///
413    /// Arguments and padding flags follow source order. Operation errors propagate
414    /// at execution after frame cleanup.
415    /// - Complexity: The capture insertion cost of [`Self::push_op0`].
416    ///
417    /// # Examples
418    /// See [`RawSegment`].
419    pub fn raw2<T, U, R, F>(&mut self, op: F, padding0: bool, padding1: bool)
420    where
421        F: Fn(&mut RawStack, T, U) -> Result<R> + 'static,
422        T: 'static,
423        U: 'static,
424        R: 'static,
425    {
426        self.push_storage(op);
427        match (padding0, padding1) {
428            (false, false) => self.push_op2r_::<false, false, T, U, R, F>(),
429            (false, true) => self.push_op2r_::<false, true, T, U, R, F>(),
430            (true, false) => self.push_op2r_::<true, false, T, U, R, F>(),
431            (true, true) => self.push_op2r_::<true, true, T, U, R, F>(),
432        }
433        self.base_alignment = max(self.base_alignment, align_of::<R>());
434    }
435
436    /// Pushes a ternary operation that takes three arguments of types T, U, and V and returns a
437    /// value of type R.
438    #[expect(clippy::many_single_char_names, reason = "patterned code")]
439    fn push_op3_<const PADDING0: bool, const PADDING1: bool, const PADDING2: bool, T, U, V, R, F>(
440        &mut self,
441    ) where
442        F: Fn(T, U, V) -> R + 'static,
443        T: 'static,
444        U: 'static,
445        V: 'static,
446        R: 'static,
447    {
448        self.ops.push(|storage, p, stack| {
449            let (f, r) = unsafe { storage.next::<F>(p) };
450            let z: V = unsafe { stack.pop(PADDING2) };
451            let y: U = unsafe { stack.pop(PADDING1) };
452            let x: T = unsafe { stack.pop(PADDING0) };
453            stack.push(f(x, y, z));
454            Ok(r)
455        });
456    }
457
458    /// Pushes a ternary operation that takes three arguments of types T, U, and V and returns a value of type R.
459    ///
460    /// Arguments and padding flags follow source order.
461    /// - Complexity: The capture insertion cost of [`Self::push_op0`].
462    ///
463    /// # Examples
464    /// ```
465    /// use cel_runtime::RawSegment;
466    /// let mut body = RawSegment::new();
467    /// body.push_op0(|| 1u8);
468    /// body.push_op0(|| 2u8);
469    /// body.push_op0(|| 3u8);
470    /// body.push_op3(|first: u8, second: u8, third: u8| (first, second, third), false, false, false);
471    /// assert_eq!(unsafe { body.call0::<(u8, u8, u8)>() }?, (1, 2, 3));
472    /// # Ok::<(), anyhow::Error>(())
473    /// ```
474    pub fn push_op3<T, U, V, R, F>(&mut self, op: F, padding0: bool, padding1: bool, padding2: bool)
475    where
476        F: Fn(T, U, V) -> R + 'static,
477        T: 'static,
478        U: 'static,
479        V: 'static,
480        R: 'static,
481    {
482        self.push_storage(op);
483
484        match (padding0, padding1, padding2) {
485            (false, false, false) => self.push_op3_::<false, false, false, T, U, V, R, F>(),
486            (false, false, true) => self.push_op3_::<false, false, true, T, U, V, R, F>(),
487            (false, true, false) => self.push_op3_::<false, true, false, T, U, V, R, F>(),
488            (false, true, true) => self.push_op3_::<false, true, true, T, U, V, R, F>(),
489            (true, false, false) => self.push_op3_::<true, false, false, T, U, V, R, F>(),
490            (true, false, true) => self.push_op3_::<true, false, true, T, U, V, R, F>(),
491            (true, true, false) => self.push_op3_::<true, true, false, T, U, V, R, F>(),
492            (true, true, true) => self.push_op3_::<true, true, true, T, U, V, R, F>(),
493        }
494        self.base_alignment = max(self.base_alignment, align_of::<R>());
495    }
496
497    /// Pushes the op-dispatch closure for a ternary fallible operation with compile-time padding.
498    #[expect(clippy::many_single_char_names, reason = "patterned code")]
499    fn push_op3r_<const PADDING0: bool, const PADDING1: bool, const PADDING2: bool, T, U, V, R, F>(
500        &mut self,
501    ) where
502        F: Fn(&mut RawStack, T, U, V) -> Result<R> + 'static,
503        T: 'static,
504        U: 'static,
505        V: 'static,
506        R: 'static,
507    {
508        self.ops.push(|storage, p, stack| {
509            let (f, r) = unsafe { storage.next::<F>(p) };
510            let z: V = unsafe { stack.pop(PADDING2) };
511            let y: U = unsafe { stack.pop(PADDING1) };
512            let x: T = unsafe { stack.pop(PADDING0) };
513            let result = f(stack, x, y, z)?;
514            stack.push(result);
515            Ok(r)
516        });
517    }
518
519    /// Pushes a fallible ternary operation that can manipulate the remaining stack.
520    ///
521    /// Arguments and padding flags follow source order. Operation errors propagate
522    /// at execution after frame cleanup.
523    /// - Complexity: The capture insertion cost of [`Self::push_op0`].
524    ///
525    /// # Examples
526    /// See [`RawSegment`].
527    pub fn raw3<T, U, V, R, F>(&mut self, op: F, padding0: bool, padding1: bool, padding2: bool)
528    where
529        F: Fn(&mut RawStack, T, U, V) -> Result<R> + 'static,
530        T: 'static,
531        U: 'static,
532        V: 'static,
533        R: 'static,
534    {
535        self.push_storage(op);
536        match (padding0, padding1, padding2) {
537            (false, false, false) => self.push_op3r_::<false, false, false, T, U, V, R, F>(),
538            (false, false, true) => self.push_op3r_::<false, false, true, T, U, V, R, F>(),
539            (false, true, false) => self.push_op3r_::<false, true, false, T, U, V, R, F>(),
540            (false, true, true) => self.push_op3r_::<false, true, true, T, U, V, R, F>(),
541            (true, false, false) => self.push_op3r_::<true, false, false, T, U, V, R, F>(),
542            (true, false, true) => self.push_op3r_::<true, false, true, T, U, V, R, F>(),
543            (true, true, false) => self.push_op3r_::<true, true, false, T, U, V, R, F>(),
544            (true, true, true) => self.push_op3r_::<true, true, true, T, U, V, R, F>(),
545        }
546        self.base_alignment = max(self.base_alignment, align_of::<R>());
547    }
548
549    /// Executes all operations in the segment on the supplied stack.
550    ///
551    /// # Errors
552    /// Halts execution and returns an error if any operation returns an error.
553    ///
554    /// # Safety
555    ///
556    /// The stack's alignment, origin, operand types, and padding must match every
557    /// operation. Callback accesses must preserve the frame's ownership.
558    /// Violating these requirements can cause undefined behavior.
559    ///
560    /// - Complexity: O(n) dispatches plus callback costs for n operations.
561    ///
562    /// # Examples
563    /// ```
564    /// use cel_runtime::{RawSegment, RawStack};
565    /// let mut body = RawSegment::new();
566    /// body.push_op0(|| String::from("owned"));
567    /// let mut stack = RawStack::with_base_alignment(std::mem::align_of::<String>());
568    /// unsafe { body.call0_stack(&mut stack) }?;
569    /// assert_eq!(unsafe { stack.pop::<String>(false) }, "owned");
570    /// # Ok::<(), anyhow::Error>(())
571    /// ```
572    pub unsafe fn call0_stack(&self, stack: &mut RawStack) -> Result<()> {
573        let (origin, depth) = self.frame.map_or((0, 0), |(origin, inputs)| {
574            (
575                origin,
576                stack
577                    .depth()
578                    .checked_sub(inputs)
579                    .expect("valid input frame"),
580            )
581        });
582        stack.with_unwind(origin, depth, |stack| {
583            let mut p = 0;
584            for op in &self.ops {
585                p = op(&self.storage, p, stack)?;
586            }
587            Ok(())
588        })
589    }
590
591    /// Executes all operations in the segment and returns the final result.
592    ///
593    /// # Errors
594    /// Halts execution and returns an error if any operation returns an error.
595    ///
596    /// # Safety
597    /// Operations must accept an empty initial stack and end in a live `T`
598    /// with no preceding alignment gap.
599    /// All operand types and padding must match their registered operations.
600    /// Violating these requirements can cause undefined behavior.
601    ///
602    /// - Complexity: O(n) dispatches plus callback costs for n operations;
603    ///   allocates the maximum live stack.
604    ///
605    /// # Examples
606    /// See [`RawSegment`].
607    pub unsafe fn call0<T>(&self) -> Result<T>
608    where
609        T: 'static,
610    {
611        let mut stack = RawStack::with_base_alignment(self.base_alignment);
612        unsafe {
613            self.call0_stack(&mut stack)?;
614        }
615        Ok(unsafe { stack.pop(false) })
616    }
617
618    /// Executes all operations in the segment with one argument of type A and returns the final
619    /// result.
620    ///
621    /// # Errors
622    /// Halts execution and returns an error if any operation returns an error.
623    ///
624    /// # Safety
625    /// Operations must accept the initial `A` and end in a live `T`
626    /// with no preceding alignment gap.
627    /// All operand types and padding must match their registered operations.
628    /// Violating these requirements can cause undefined behavior.
629    ///
630    /// - Complexity: The execution and allocation costs of [`Self::call0`].
631    ///
632    /// # Examples
633    /// ```
634    /// use cel_runtime::RawSegment;
635    /// let mut body = RawSegment::new();
636    /// body.push_op1(|value: String| value.len(), false);
637    /// assert_eq!(unsafe { body.call1::<_, usize>(String::from("owned")) }?, 5);
638    /// # Ok::<(), anyhow::Error>(())
639    /// ```
640    pub unsafe fn call1<A: 'static, T>(&self, arg: A) -> Result<T>
641    where
642        T: 'static,
643    {
644        let mut stack = RawStack::with_base_alignment(self.base_alignment.max(align_of::<A>()));
645        stack.push(arg);
646        unsafe { self.call0_stack(&mut stack)? };
647        Ok(unsafe { stack.pop(false) })
648    }
649
650    /// Executes all operations in the segment with two arguments of types A and B and returns the
651    /// final result.
652    ///
653    /// # Errors
654    /// Halts execution and returns an error if any operation returns an error.
655    ///
656    /// # Safety
657    /// Operations must accept the initial source-ordered `(A, B)` and end in a
658    /// live `T` with no preceding alignment gap. Operand types and padding must match every
659    /// registered operation. Violating these requirements can cause undefined behavior.
660    ///
661    /// - Complexity: The execution and allocation costs of [`Self::call0`].
662    ///
663    /// # Examples
664    /// See [`Self::push_op2`].
665    pub unsafe fn call2<A: 'static, B: 'static, T>(&self, arg: (A, B)) -> Result<T>
666    where
667        T: 'static,
668    {
669        let mut stack = RawStack::with_base_alignment(
670            self.base_alignment
671                .max(align_of::<A>())
672                .max(align_of::<B>()),
673        );
674        stack.push(arg.0);
675        stack.push(arg.1);
676        unsafe { self.call0_stack(&mut stack)? };
677        Ok(unsafe { stack.pop(false) })
678    }
679}
680
681impl Drop for RawSegment {
682    /// Releases instruction captures, preserving cleanup across destructor unwinding.
683    ///
684    /// - Complexity: O(n) plus destruction costs for n captures.
685    fn drop(&mut self) {
686        let mut cleanup = StorageCleanup {
687            storage: &mut self.storage,
688            droppers: self.dropper.iter(),
689            position: 0,
690        };
691        cleanup.drop_remaining();
692    }
693}
694
695#[cfg(test)]
696mod tests {
697    use super::*;
698
699    /// Supports captured values whose alignment exceeds the initial storage alignment.
700    #[test]
701    fn instruction_capture_alignment_grows_without_losing_earlier_state() {
702        /// Requires a wider alignment than the initial instruction buffer.
703        #[repr(align(8192))]
704        struct Aligned(u8);
705
706        impl Aligned {
707            /// Reads the captured value without narrowing the closure's capture.
708            fn value(&self) -> u8 {
709                self.0
710            }
711        }
712
713        let captured = Aligned(42);
714        let earlier = String::from("retained");
715        let mut segment = RawSegment::new();
716        segment.push_op0(move || earlier.clone());
717        segment.push_op0(move || captured.value());
718        segment.push_op2(|first: String, second: u8| (first, second), false, false);
719        assert_eq!(
720            unsafe { segment.call0::<(String, u8)>() }.unwrap(),
721            (String::from("retained"), 42)
722        );
723    }
724
725    /// Aligns the supplied arguments even when instructions produce only bytes.
726    #[test]
727    fn over_aligned_call_arguments() {
728        /// Requires a stricter alignment than the operation result.
729        #[repr(align(4096))]
730        struct Aligned(u8);
731
732        let mut one = RawSegment::new();
733        one.push_op1(|value: Aligned| value.0, false);
734        assert_eq!(unsafe { one.call1::<_, u8>(Aligned(42)) }.unwrap(), 42);
735
736        let mut two = RawSegment::new();
737        two.push_op2(|first: Aligned, second: u8| (first.0, second), false, false);
738        assert_eq!(
739            unsafe { two.call2::<_, _, (u8, u8)>((Aligned(42), 7u8)) }.unwrap(),
740            (42, 7)
741        );
742        let mut reversed = RawSegment::new();
743        reversed.push_op2(|first: u8, second: Aligned| (first, second.0), false, true);
744        assert_eq!(
745            unsafe { reversed.call2::<_, _, (u8, u8)>((7u8, Aligned(42))) }.unwrap(),
746            (7, 42)
747        );
748    }
749
750    /// Releases later instruction captures when an earlier capture destructor panics.
751    #[test]
752    fn capture_destruction_continues_after_panic() {
753        use std::{cell::RefCell, rc::Rc};
754
755        /// Records destruction and optionally starts unwinding.
756        struct Capture {
757            id: u8,
758            panic: bool,
759            destroyed: Rc<RefCell<Vec<u8>>>,
760        }
761
762        impl Drop for Capture {
763            /// Records this capture before any requested panic.
764            fn drop(&mut self) {
765                self.destroyed.borrow_mut().push(self.id);
766                assert!(!self.panic, "capture destructor panic");
767            }
768        }
769
770        let destroyed = Rc::new(RefCell::new(Vec::new()));
771        let mut segment = RawSegment::new();
772        for id in 0..3 {
773            let capture = Capture {
774                id,
775                panic: id == 1,
776                destroyed: destroyed.clone(),
777            };
778            segment.push_op0(move || {
779                let _keep_capture = &capture;
780                42u32
781            });
782        }
783        assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(segment))).is_err());
784        assert_eq!(*destroyed.borrow(), [0, 1, 2]);
785    }
786
787    /// Returns the value produced by a nullary instruction.
788    #[test]
789    fn nullary_operation() {
790        let mut segment = RawSegment::new();
791        segment.push_op0(|| 42);
792        unsafe {
793            assert_eq!(segment.call0::<i32>().unwrap(), 42);
794        }
795    }
796
797    /// Replaces a pushed scalar with its unary-operation result.
798    #[test]
799    fn unary_operation() {
800        let mut segment = RawSegment::new();
801        segment.push_op0(|| 42);
802        segment.push_op1(|x: i32| x * 2, false);
803        unsafe {
804            assert_eq!(segment.call0::<i32>().unwrap(), 84);
805        }
806    }
807
808    /// Consumes two pushed scalars and returns the binary-operation result.
809    #[test]
810    fn binary_operation() {
811        let mut segment = RawSegment::new();
812        segment.push_op0(|| 10);
813        segment.push_op0(|| 5);
814        segment.push_op2(|x: i32, y: i32| x + y, false, false);
815        unsafe {
816            assert_eq!(segment.call0::<i32>().unwrap(), 15);
817        }
818    }
819
820    /// Consumes three pushed scalars and returns the ternary-operation result.
821    #[test]
822    fn ternary_operation() {
823        let mut segment = RawSegment::new();
824        segment.push_op0(|| 2);
825        segment.push_op0(|| 3);
826        segment.push_op0(|| 4);
827        segment.push_op3(|x: i32, y: i32, z: i32| x + y + z, false, false, false);
828        unsafe {
829            assert_eq!(segment.call0::<i32>().unwrap(), 9);
830        }
831    }
832
833    /// Threads intermediate results through composed nullary, unary and binary instructions.
834    #[test]
835    fn complex_chain() {
836        let mut segment = RawSegment::new();
837        segment.push_op0(|| 10);
838        segment.push_op1(|x: i32| x * 2, false);
839        segment.push_op0(|| 5);
840        segment.push_op2(|x: i32, y: i32| x + y, false, false);
841        unsafe {
842            assert_eq!(segment.call0::<i32>().unwrap(), 25);
843        }
844    }
845}