Skip to main content

cel_runtime/
dyn_segment.rs

1//! Builds checked instructions for the canonical raw interpreter.
2//!
3//! Ordinary operations name opaque Rust leaves. Structural operations name a
4//! sealed representation witness; `prepare` checks the whole borrowed frame once.
5//! ```
6//! use cel_runtime::{DynSegment, Nil, Leaf, IntoCStackList};
7//! let mut body = DynSegment::new::<()>();
8//! body.just(42i32);
9//! let mut body = body.prepare::<Nil, Leaf<i32>>().unwrap();
10//! assert_eq!(body.call(&().into_c_stack_list()).unwrap(), 42);
11//! ```
12
13use std::any::{Any, TypeId};
14use std::cell::Cell;
15
16use anyhow::{Result, anyhow, ensure};
17
18use crate::canonical_operation::OperationPlan;
19use crate::container_execution::{ContainerPlan, ResultPlan, StackFramePlan, stack_position};
20use crate::host_value_bridge::HostValuePlan;
21use crate::owned_value::OwnedValue;
22use crate::{
23    AssociatedType, CNil, CStackList, CStackListHeadLimit, CStackListHeadPadded, IntoCStackList,
24    Leaf, List, RawSegment, RawStack, ReverseList, ValueKind, ValueRepr, ValueType,
25};
26
27thread_local! {
28    /// Borrows the innermost call's already validated positional argument pointers.
29    static ARGUMENTS: Cell<*const *const u8> = const { Cell::new(std::ptr::null()) };
30}
31
32/// Restores an enclosing raw argument context on return, error, or unwind.
33struct ArgumentGuard(*const *const u8);
34
35impl ArgumentGuard {
36    /// Installs pointers that remain live until this guard is destroyed.
37    fn install(arguments: &[*const u8]) -> Self {
38        Self(ARGUMENTS.with(|slot| slot.replace(arguments.as_ptr())))
39    }
40}
41
42impl Drop for ArgumentGuard {
43    /// Restores the preceding call's borrowed argument frame.
44    fn drop(&mut self) {
45        ARGUMENTS.with(|slot| slot.set(self.0));
46    }
47}
48
49/// Describes a live canonical stack slot.
50#[derive(Clone, Debug)]
51pub struct StackInfo {
52    /// Whether the slot follows alignment padding.
53    pub padding: bool,
54    /// Complete recursive identity, layout, and ownership metadata.
55    pub value_type: ValueType,
56}
57
58/// Formats recursive source-order type names for construction errors.
59///
60/// - Complexity: O(n + s) time and O(d + s) space for n descriptor nodes,
61///   nesting depth d, and rendered name length s.
62fn descriptor_name(ty: &ValueType) -> String {
63    let mut output = String::new();
64    append_descriptor_name(ty, &mut output);
65    output
66}
67
68/// Appends a descriptor name without allocating intermediate strings or collections.
69///
70/// - Complexity: O(n + s) time and O(d) call space for n descriptor nodes,
71///   nesting depth d, and s appended bytes, excluding output growth.
72fn append_descriptor_name(ty: &ValueType, output: &mut String) {
73    match ty.kind() {
74        ValueKind::Array(element) => {
75            output.push('[');
76            append_descriptor_name(element, output);
77            output.push(']');
78        }
79        ValueKind::Tuple(fields) => {
80            output.push('(');
81            for (index, field) in fields.iter().enumerate() {
82                if index != 0 {
83                    output.push_str(", ");
84                }
85                append_descriptor_name(&field.value_type, output);
86            }
87            output.push(')');
88        }
89        _ => output.push_str(ty.type_name()),
90    }
91}
92
93/// Enumerates opaque leaf types in a concrete preloaded stack list.
94pub trait ToTypeIdList: List {
95    /// Returns source-ordered leaf slots.
96    ///
97    /// - Complexity: O(n) slots for n list elements.
98    fn to_stack_info_list() -> Vec<StackInfo>;
99}
100
101impl ToTypeIdList for CNil<()> {
102    /// Returns an empty preloaded stack.
103    fn to_stack_info_list() -> Vec<StackInfo> {
104        Vec::new()
105    }
106}
107
108impl<H: 'static, T: ToTypeIdList + 'static + CStackListHeadLimit> ToTypeIdList
109    for CStackList<H, T>
110{
111    /// Enumerates tail storage followed by the opaque head.
112    ///
113    /// - Complexity: O(n) slots for n list elements.
114    fn to_stack_info_list() -> Vec<StackInfo> {
115        let mut result = T::to_stack_info_list();
116        result.push(StackInfo {
117            padding: Self::HEAD_PADDED,
118            value_type: ValueType::leaf::<H>(),
119        });
120        result
121    }
122}
123
124/// Owns validated raw instructions and complete canonical stack metadata.
125///
126/// `new::<()>()` starts an independent body with borrowed positional reads.
127/// Other `new` argument lists retain the direct, preloaded opaque-leaf ABI.
128pub struct DynSegment {
129    /// Owns emitted operations and their captures.
130    pub(crate) segment: RawSegment,
131    /// Retains preloaded argument identities in source order.
132    pub(crate) argument_ids: Vec<TypeId>,
133    /// Describes every current live stack value in physical push order.
134    pub(crate) stack_ids: Vec<StackInfo>,
135    /// Marks the caller-owned byte prefix beneath this fragment.
136    pub(crate) base_stack_index: usize,
137    /// Records positional borrowed reads and their complete required shapes.
138    pub(crate) argument_reads: Vec<(usize, ValueType)>,
139    /// Records byte boundaries for construction-time layout, without runtime ownership.
140    stack_ends: Vec<usize>,
141}
142
143impl DynSegment {
144    /// Creates a segment with an optional preloaded opaque-leaf stack.
145    ///
146    /// # Panics
147    /// Rejects preloaded erased whole-value owner carriers; import those at a checked external boundary.
148    ///
149    /// # Examples
150    /// ```
151    /// let _ = cel_runtime::DynSegment::new::<()>();
152    /// ```
153    pub fn new<Args: IntoCStackList>() -> Self
154    where
155        ReverseList<Args::Output>: ToTypeIdList,
156    {
157        let stack_ids = ReverseList::<Args::Output>::to_stack_info_list();
158        let mut segment = RawSegment::new();
159        segment.update_base_alignment(1);
160        for info in &stack_ids {
161            info.value_type
162                .validate_canonical()
163                .expect("preloaded dynamic arguments must be canonical or ordinary opaque leaves");
164            segment.update_base_alignment(info.value_type.align());
165        }
166        segment.set_frame(0, stack_ids.len());
167        let mut stack_ends = Vec::with_capacity(stack_ids.len() + 1);
168        stack_ends.push(0);
169        for info in &stack_ids {
170            stack_ends.push(
171                stack_position(*stack_ends.last().unwrap(), info.value_type.layout())
172                    .expect("validated preloaded stack")
173                    .1,
174            );
175        }
176        Self {
177            segment,
178            argument_ids: stack_ids
179                .iter()
180                .map(|info| info.value_type.type_id())
181                .collect(),
182            stack_ids,
183            base_stack_index: 0,
184            argument_reads: Vec::new(),
185            stack_ends,
186        }
187    }
188
189    /// Creates a conditional fragment above the ambient stack below the condition.
190    ///
191    /// - Precondition: at least one operand is present.
192    ///
193    /// # Examples
194    /// See [`Self::join2`].
195    pub fn new_fragment(&self) -> Self {
196        debug_assert!(!self.stack_ids.is_empty());
197        let mut result = Self::new::<()>();
198        result.base_stack_index = self.stack_offset_before_top(1).expect("condition present");
199        result.stack_ends[0] = result.base_stack_index;
200        result.segment.set_frame(result.base_stack_index, 0);
201        result
202    }
203
204    /// Returns the current canonical stack byte length.
205    ///
206    /// # Examples
207    /// ```
208    /// assert_eq!(cel_runtime::DynSegment::new::<()>().current_stack_offset(), 0);
209    /// ```
210    pub fn current_stack_offset(&self) -> usize {
211        self.offset_after(self.stack_ids.len())
212    }
213
214    /// Returns the byte length preceding the top `n` operands.
215    ///
216    /// # Errors
217    /// Rejects insufficient operands.
218    ///
219    /// # Examples
220    /// ```
221    /// assert!(cel_runtime::DynSegment::new::<()>().stack_offset_before_top(1).is_err());
222    /// ```
223    pub fn stack_offset_before_top(&self, n: usize) -> Result<usize> {
224        let count = self
225            .stack_ids
226            .len()
227            .checked_sub(n)
228            .ok_or_else(|| anyhow!("not enough operands"))?;
229        Ok(self.offset_after(count))
230    }
231
232    /// Computes the canonical position following a known slot prefix.
233    fn offset_after(&self, count: usize) -> usize {
234        self.stack_ends[count]
235    }
236
237    /// Binds ambient cleanup and source-ordered operands without mutating metadata.
238    ///
239    /// # Errors
240    /// Rejects insufficient operands or an unrepresentable frame.
241    /// - Complexity: O(n) time and space for operand/result descriptor nodes.
242    fn operation(&self, arity: usize, result: ValueType) -> Result<OperationPlan> {
243        let first = self
244            .stack_ids
245            .len()
246            .checked_sub(arity)
247            .ok_or_else(|| anyhow!("not enough operands"))?;
248        let operands: Vec<_> = self.stack_ids[first..]
249            .iter()
250            .map(|info| info.value_type.clone())
251            .collect();
252        OperationPlan::at(
253            self.base_stack_index,
254            self.offset_after(first),
255            first,
256            &operands,
257            result,
258        )
259    }
260
261    /// Replaces emitted operands with their validated canonical result slot.
262    ///
263    /// - Complexity: O(a + d) for a removed operands and d result descriptor nodes.
264    fn replace(&mut self, arity: usize, result: ValueType) {
265        self.stack_ids.truncate(self.stack_ids.len() - arity);
266        self.stack_ends.truncate(self.stack_ids.len() + 1);
267        let before = self.current_stack_offset();
268        let (offset, end) = stack_position(before, result.layout()).expect("validated result");
269        self.segment.update_base_alignment(result.align());
270        self.stack_ids.push(StackInfo {
271            padding: offset != before,
272            value_type: result,
273        });
274        self.stack_ends.push(end);
275    }
276
277    /// Borrows up to the top `n` complete descriptors.
278    ///
279    /// # Examples
280    /// ```
281    /// let body = cel_runtime::DynSegment::new::<()>();
282    /// assert!(body.peek_stack_infos(0).is_empty());
283    /// ```
284    pub fn peek_stack_infos(&self, n: usize) -> &[StackInfo] {
285        &self.stack_ids[self.stack_ids.len().saturating_sub(n)..]
286    }
287
288    /// Returns a diagnostic dispatch identity, never a structural cast authority.
289    ///
290    /// # Examples
291    /// ```
292    /// assert!(cel_runtime::DynSegment::new::<()>().peek_output_type_id().is_none());
293    /// ```
294    pub fn peek_output_type_id(&self) -> Option<TypeId> {
295        Some(self.stack_ids.last()?.value_type.type_id())
296    }
297
298    /// Returns the source tuple arity, including zero for canonical unit.
299    ///
300    /// # Examples
301    /// ```
302    /// assert!(cel_runtime::DynSegment::new::<()>().peek_tuple_arity().is_none());
303    /// ```
304    pub fn peek_tuple_arity(&self) -> Option<usize> {
305        Some(self.stack_ids.last()?.value_type.tuple_elements()?.len())
306    }
307
308    /// Registers a nullary opaque-leaf host operation.
309    ///
310    /// # Panics
311    /// Rejects erased whole-value owner results or unrepresentable frames. Use `op0_repr`
312    /// for fallible registration and `just_external` for checked owner imports.
313    ///
314    /// # Examples
315    /// ```
316    /// let mut b = cel_runtime::DynSegment::new::<()>();
317    /// b.op0(|| 7i32);
318    /// assert_eq!(b.call0::<i32>().unwrap(), 7);
319    /// ```
320    pub fn op0<R: 'static, F: Fn() -> R + 'static>(&mut self, f: F) {
321        self.op0_repr::<Leaf<R>, _>(f)
322            .expect("opaque result fits raw frame");
323    }
324
325    /// Registers a fallible nullary opaque-leaf operation with ambient cleanup.
326    ///
327    /// # Panics
328    /// Rejects erased whole-value owner results or unrepresentable frames during registration.
329    ///
330    /// # Examples
331    /// ```
332    /// let mut b = cel_runtime::DynSegment::new::<()>();
333    /// b.op0r(|| Ok(7i32));
334    /// ```
335    pub fn op0r<R: 'static, F: Fn() -> Result<R> + 'static>(&mut self, f: F) {
336        self.op0r_repr::<Leaf<R>, _>(f)
337            .expect("opaque result fits raw frame");
338    }
339
340    /// Registers a witnessed nullary operation.
341    ///
342    /// # Errors
343    /// Rejects unrepresentable stack positions.
344    /// - Complexity: O(n) registration work for n ambient slots.
345    ///
346    /// # Examples
347    /// ```
348    /// let mut b = cel_runtime::DynSegment::new::<()>();
349    /// b.op0_repr::<cel_runtime::Nil, _>(|| cel_runtime::IntoCStackList::into_c_stack_list(())).unwrap();
350    /// ```
351    pub fn op0_repr<R: ValueRepr, F: Fn() -> R::Value + 'static>(&mut self, f: F) -> Result<()> {
352        self.op0r_repr::<R, _>(move || Ok(f()))
353    }
354
355    /// Registers a fallible witnessed nullary operation.
356    ///
357    /// # Errors
358    /// Rejects unrepresentable stack positions; host errors propagate on execution.
359    /// - Complexity: O(n) registration work for n ambient slots.
360    ///
361    /// # Examples
362    /// ```
363    /// let mut b = cel_runtime::DynSegment::new::<()>();
364    /// b.op0r_repr::<cel_runtime::Leaf<i32>, _>(|| Ok(7)).unwrap();
365    /// ```
366    pub fn op0r_repr<R: ValueRepr, F: Fn() -> Result<R::Value> + 'static>(
367        &mut self,
368        f: F,
369    ) -> Result<()> {
370        let result = R::value_type();
371        self.operation(0, result.clone())?
372            .emit0::<R, _>(&mut self.segment, f)?;
373        self.replace(0, result);
374        Ok(())
375    }
376
377    /// Registers a unary opaque-leaf operation.
378    ///
379    /// # Errors
380    /// Rejects insufficient or nonmatching opaque operands.
381    /// - Complexity: O(n) registration work for n stack slots.
382    ///
383    /// # Examples
384    /// ```
385    /// let mut b = cel_runtime::DynSegment::new::<()>();
386    /// b.just(1i32); b.op1(|x: i32| x.to_string()).unwrap();
387    /// ```
388    pub fn op1<A: 'static, R: 'static, F: Fn(A) -> R + 'static>(&mut self, f: F) -> Result<()> {
389        self.op1_repr::<Leaf<A>, Leaf<R>, _>(f)
390    }
391
392    /// Registers a fallible unary opaque-leaf operation.
393    ///
394    /// # Errors
395    /// Rejects insufficient or nonmatching operands; execution propagates host errors.
396    /// - Complexity: O(n) registration work for n stack slots.
397    ///
398    /// # Examples
399    /// ```
400    /// let mut b = cel_runtime::DynSegment::new::<()>();
401    /// b.just(1i32); b.op1r(|x: i32| Ok(x)).unwrap();
402    /// ```
403    pub fn op1r<A: 'static, R: 'static, F: Fn(A) -> Result<R> + 'static>(
404        &mut self,
405        f: F,
406    ) -> Result<()> {
407        self.op1r_repr::<Leaf<A>, Leaf<R>, _>(f)
408    }
409
410    /// Registers a unary operation after checking its complete operand witness.
411    ///
412    /// # Errors
413    /// Rejects insufficient operands or recursive representation mismatch.
414    /// - Complexity: O(n) registration work for n frame/descriptor nodes.
415    ///
416    /// # Examples
417    /// ```
418    /// let mut b = cel_runtime::DynSegment::new::<()>();
419    /// b.just(1i32);
420    /// b.op1_repr::<cel_runtime::Leaf<i32>, cel_runtime::Leaf<i32>, _>(|x| x).unwrap();
421    /// ```
422    pub fn op1_repr<A: ValueRepr, R: ValueRepr, F: Fn(A::Value) -> R::Value + 'static>(
423        &mut self,
424        f: F,
425    ) -> Result<()> {
426        self.op1r_repr::<A, R, _>(move |a| Ok(f(a)))
427    }
428
429    /// Registers a fallible unary witnessed operation with error/unwind cleanup.
430    ///
431    /// # Errors
432    /// Rejects insufficient operands or recursive mismatch; propagates host errors on execution.
433    /// - Complexity: O(n) registration work for n frame/descriptor nodes.
434    ///
435    /// # Examples
436    /// ```
437    /// let mut b = cel_runtime::DynSegment::new::<()>();
438    /// b.just(1i32);
439    /// b.op1r_repr::<cel_runtime::Leaf<i32>, cel_runtime::Leaf<i32>, _>(Ok).unwrap();
440    /// ```
441    pub fn op1r_repr<A: ValueRepr, R: ValueRepr, F: Fn(A::Value) -> Result<R::Value> + 'static>(
442        &mut self,
443        f: F,
444    ) -> Result<()> {
445        let result = R::value_type();
446        self.operation(1, result.clone())?
447            .emit1::<A, R, _>(&mut self.segment, f)?;
448        self.replace(1, result);
449        Ok(())
450    }
451
452    /// Registers a binary opaque-leaf operation in source order.
453    ///
454    /// # Errors
455    /// Rejects insufficient or mismatched operands.
456    /// - Complexity: O(n) registration work for n frame/descriptor nodes.
457    ///
458    /// # Examples
459    /// ```
460    /// let mut b = cel_runtime::DynSegment::new::<()>();
461    /// b.just(1f64); b.just(2f64); b.op2(|a: f64, b: f64| a + b).unwrap();
462    /// ```
463    pub fn op2<A: 'static, B: 'static, R: 'static, F: Fn(A, B) -> R + 'static>(
464        &mut self,
465        f: F,
466    ) -> Result<()> {
467        self.op2_repr::<Leaf<A>, Leaf<B>, Leaf<R>, _>(f)
468    }
469
470    /// Registers a fallible binary opaque-leaf operation.
471    ///
472    /// # Errors
473    /// Rejects insufficient/mismatched operands; propagates host errors on execution.
474    /// - Complexity: O(n) registration work for n frame/descriptor nodes.
475    ///
476    /// # Examples
477    /// ```
478    /// let mut b = cel_runtime::DynSegment::new::<()>();
479    /// b.just(1i32); b.just(2i32);
480    /// b.op2r(|a: i32, b: i32| {
481    ///     a.checked_add(b).ok_or_else(|| anyhow::anyhow!("addition overflow"))
482    /// }).unwrap();
483    /// ```
484    pub fn op2r<A: 'static, B: 'static, R: 'static, F: Fn(A, B) -> Result<R> + 'static>(
485        &mut self,
486        f: F,
487    ) -> Result<()> {
488        self.op2r_repr::<Leaf<A>, Leaf<B>, Leaf<R>, _>(f)
489    }
490
491    /// Registers a binary witnessed operation in source order.
492    ///
493    /// # Errors
494    /// Rejects insufficient operands or complete witness mismatch.
495    /// - Complexity: O(n) registration work for n frame/descriptor nodes.
496    ///
497    /// # Examples
498    /// See [`Self::op2`]; use one witness per operand and result.
499    pub fn op2_repr<
500        A: ValueRepr,
501        B: ValueRepr,
502        R: ValueRepr,
503        F: Fn(A::Value, B::Value) -> R::Value + 'static,
504    >(
505        &mut self,
506        f: F,
507    ) -> Result<()> {
508        self.op2r_repr::<A, B, R, _>(move |a, b| Ok(f(a, b)))
509    }
510
511    /// Registers a fallible binary witnessed operation.
512    ///
513    /// # Errors
514    /// Rejects insufficient operands or complete mismatch; execution propagates host errors.
515    /// - Complexity: O(n) registration work for n frame/descriptor nodes.
516    ///
517    /// # Examples
518    /// See [`Self::op2r`]; use one witness per operand and result.
519    pub fn op2r_repr<
520        A: ValueRepr,
521        B: ValueRepr,
522        R: ValueRepr,
523        F: Fn(A::Value, B::Value) -> Result<R::Value> + 'static,
524    >(
525        &mut self,
526        f: F,
527    ) -> Result<()> {
528        let result = R::value_type();
529        self.operation(2, result.clone())?
530            .emit2::<A, B, R, _>(&mut self.segment, f)?;
531        self.replace(2, result);
532        Ok(())
533    }
534
535    /// Registers a ternary opaque-leaf operation in source order.
536    ///
537    /// # Errors
538    /// Rejects insufficient or mismatched operands.
539    /// - Complexity: O(n) registration work for n frame/descriptor nodes.
540    ///
541    /// # Examples
542    /// See [`Self::op2`]; push one additional operand.
543    pub fn op3<A: 'static, B: 'static, C: 'static, R: 'static, F: Fn(A, B, C) -> R + 'static>(
544        &mut self,
545        f: F,
546    ) -> Result<()> {
547        self.op3_repr::<Leaf<A>, Leaf<B>, Leaf<C>, Leaf<R>, _>(f)
548    }
549
550    /// Registers a fallible ternary opaque-leaf operation.
551    ///
552    /// # Errors
553    /// Rejects insufficient/mismatched operands; execution propagates host errors.
554    /// - Complexity: O(n) registration work for n frame/descriptor nodes.
555    ///
556    /// # Examples
557    /// See [`Self::op2r`]; push one additional operand.
558    pub fn op3r<
559        A: 'static,
560        B: 'static,
561        C: 'static,
562        R: 'static,
563        F: Fn(A, B, C) -> Result<R> + 'static,
564    >(
565        &mut self,
566        f: F,
567    ) -> Result<()> {
568        self.op3r_repr::<Leaf<A>, Leaf<B>, Leaf<C>, Leaf<R>, _>(f)
569    }
570
571    /// Registers a ternary witnessed operation in source order.
572    ///
573    /// # Errors
574    /// Rejects insufficient operands or complete witness mismatch.
575    /// - Complexity: O(n) registration work for n frame/descriptor nodes.
576    ///
577    /// # Examples
578    /// See [`Self::op2_repr`]; supply one additional witness.
579    pub fn op3_repr<
580        A: ValueRepr,
581        B: ValueRepr,
582        C: ValueRepr,
583        R: ValueRepr,
584        F: Fn(A::Value, B::Value, C::Value) -> R::Value + 'static,
585    >(
586        &mut self,
587        f: F,
588    ) -> Result<()> {
589        self.op3r_repr::<A, B, C, R, _>(move |a, b, c| Ok(f(a, b, c)))
590    }
591
592    /// Registers a fallible ternary witnessed operation.
593    ///
594    /// # Errors
595    /// Rejects insufficient operands or complete mismatch; execution propagates host errors.
596    /// - Complexity: O(n) registration work for n frame/descriptor nodes.
597    ///
598    /// # Examples
599    /// See [`Self::op2r_repr`]; supply one additional witness.
600    pub fn op3r_repr<
601        A: ValueRepr,
602        B: ValueRepr,
603        C: ValueRepr,
604        R: ValueRepr,
605        F: Fn(A::Value, B::Value, C::Value) -> Result<R::Value> + 'static,
606    >(
607        &mut self,
608        f: F,
609    ) -> Result<()> {
610        let result = R::value_type();
611        self.operation(3, result.clone())?
612            .emit3::<A, B, C, R, _>(&mut self.segment, f)?;
613        self.replace(3, result);
614        Ok(())
615    }
616
617    /// Transfers a canonical array allocation into a concrete host vector.
618    ///
619    /// # Errors
620    /// Rejects insufficient operands or a differing complete element witness.
621    /// - Complexity: O(n) registration work; execution preserves the allocation.
622    ///
623    /// # Examples
624    /// See the `prepared_containers` integration tests.
625    pub fn op1_vec<E: ValueRepr, R: ValueRepr, F: Fn(Vec<E::Value>) -> R::Value + 'static>(
626        &mut self,
627        f: F,
628    ) -> Result<()> {
629        self.op1r_vec::<E, R, _>(move |a| Ok(f(a)))
630    }
631
632    /// Registers a fallible zero-copy canonical-array-to-vector adapter.
633    ///
634    /// # Errors
635    /// Rejects witness mismatch; execution propagates host errors with ambient cleanup.
636    /// - Complexity: O(n) registration work; O(1) ownership transfer.
637    ///
638    /// # Examples
639    /// See [`Self::op1_vec`].
640    pub fn op1r_vec<
641        E: ValueRepr,
642        R: ValueRepr,
643        F: Fn(Vec<E::Value>) -> Result<R::Value> + 'static,
644    >(
645        &mut self,
646        f: F,
647    ) -> Result<()> {
648        let result = R::value_type();
649        self.operation(1, result.clone())?
650            .emit_vec::<E, R, _>(&mut self.segment, f)?;
651        self.replace(1, result);
652        Ok(())
653    }
654
655    /// Borrows the original canonical array payload during a host callback.
656    ///
657    /// The consumed array is destroyed after the callback; the result is owned.
658    /// # Errors
659    /// Rejects insufficient operands or complete element witness mismatch.
660    /// - Complexity: O(n) registration work; O(1) borrowing plus destruction.
661    ///
662    /// # Examples
663    /// See [`Self::op1_vec`].
664    pub fn op1_slice<E: ValueRepr, R: ValueRepr, F: Fn(&[E::Value]) -> R::Value + 'static>(
665        &mut self,
666        f: F,
667    ) -> Result<()> {
668        self.op1r_slice::<E, R, _>(move |a| Ok(f(a)))
669    }
670
671    /// Registers a fallible borrowed-slice adapter with owned result and cleanup.
672    ///
673    /// # Errors
674    /// Rejects complete witness mismatch; execution propagates host errors.
675    /// - Complexity: O(n) registration work; O(1) borrowing plus destruction.
676    ///
677    /// # Examples
678    /// See [`Self::op1_slice`].
679    pub fn op1r_slice<
680        E: ValueRepr,
681        R: ValueRepr,
682        F: Fn(&[E::Value]) -> Result<R::Value> + 'static,
683    >(
684        &mut self,
685        f: F,
686    ) -> Result<()> {
687        let result = R::value_type();
688        self.operation(1, result.clone())?
689            .emit_slice::<E, R, _>(&mut self.segment, f)?;
690        self.replace(1, result);
691        Ok(())
692    }
693
694    /// Pushes a cloned opaque constant on each execution.
695    ///
696    /// # Panics
697    /// Rejects erased whole-value owner constants; use [`Self::just_external`] to import them.
698    ///
699    /// # Examples
700    /// ```
701    /// let mut b = cel_runtime::DynSegment::new::<()>(); b.just(7i32);
702    /// ```
703    pub fn just<T: Clone + 'static>(&mut self, value: T) {
704        self.op0(move || value.clone());
705        self.replace(1, ValueType::cloneable_leaf::<T>());
706    }
707
708    /// Imports an external constant once and emits only trusted canonical cloning.
709    ///
710    /// The descriptor must include every borrowed clone capability. Wrapper headers
711    /// are converted before registration, never during interpreter execution.
712    /// # Errors
713    /// Rejects noncanonical descriptors, unavailable cloning, invalid external
714    /// identity/shape, unsupported external conversions, or frame overflow.
715    /// - Complexity: Boundary validation/import at setup; value cloning on each execution.
716    ///
717    /// # Examples
718    /// ```
719    /// use cel_runtime::{DynSegment, Array, OwnedValue, ValueType, Nil, ArrayOf, Leaf, IntoCStackList};
720    /// let mut body = DynSegment::new::<()>();
721    /// body.just_external(ValueType::array(ValueType::cloneable_leaf::<i32>()),
722    ///     Box::new(OwnedValue::new::<ArrayOf<Leaf<i32>>>(Array::from_vec(vec![7i32])))).unwrap();
723    /// let mut body = body.prepare::<Nil, ArrayOf<Leaf<i32>>>().unwrap();
724    /// assert_eq!(body.call(&().into_c_stack_list()).unwrap().as_slice(), [7]);
725    /// ```
726    pub fn just_external(&mut self, value_type: ValueType, value: Box<dyn Any>) -> Result<()> {
727        value_type.validate_canonical()?;
728        value_type.validate_clone()?;
729        let owner = HostValuePlan::new(value_type.clone())?.import_box(&mut Some(value))?;
730        let result = ResultPlan::new(self.current_stack_offset(), value_type.clone())?;
731        self.segment.update_base_alignment(value_type.align());
732        self.segment.raw0_(move |stack| {
733            // SAFETY: Import validated the exact complete representation and
734            // clone capability before this instruction was registered.
735            unsafe {
736                result.clone_from(stack, owner.as_ptr());
737            }
738            Ok(())
739        });
740        self.replace(0, value_type);
741        Ok(())
742    }
743
744    /// Registers a borrowed opaque-leaf argument read.
745    ///
746    /// # Examples
747    /// ```
748    /// let mut b = cel_runtime::DynSegment::new::<()>();
749    /// b.push_arg::<i32>(0);
750    /// assert_eq!(b.call_dyn::<i32>(&[&7i32]).unwrap(), 7);
751    /// ```
752    pub fn push_arg<T: Clone + 'static>(&mut self, index: usize) {
753        self.push_argument(index, ValueType::cloneable_leaf::<T>())
754            .expect("cloneable leaf");
755    }
756
757    /// Registers a canonical borrowed argument read with its frozen clone plan.
758    ///
759    /// # Errors
760    /// Rejects missing clone capability or unrepresentable frame positions.
761    /// Preparation validates its complete identity against the argument witness.
762    /// - Complexity: O(d) registration for d descriptor nodes; execution has the
763    ///   value's clone cost without temporary whole-value allocation.
764    ///
765    /// # Examples
766    /// ```
767    /// let mut b = cel_runtime::DynSegment::new::<()>();
768    /// b.push_argument(0, cel_runtime::ValueType::cloneable_leaf::<i32>()).unwrap();
769    /// ```
770    pub fn push_argument(&mut self, index: usize, value_type: ValueType) -> Result<()> {
771        value_type.validate_canonical()?;
772        ensure!(
773            value_type.can_clone(),
774            "argument clone capability unavailable"
775        );
776        let result = ResultPlan::new(self.current_stack_offset(), value_type.clone())?;
777        self.segment.update_base_alignment(value_type.align());
778        self.segment.raw0_(move |stack| {
779            // SAFETY: The external boundary or preparation validates the complete
780            // pointer frame; this read's frozen descriptor supplies cloning.
781            unsafe {
782                let source = ARGUMENTS.with(|slot| *slot.get().add(index));
783                result.clone_from(stack, source);
784            }
785            Ok(())
786        });
787        self.argument_reads.push((index, value_type.clone()));
788        self.replace(0, value_type);
789        Ok(())
790    }
791
792    /// Packs source-ordered operands into their canonical concrete list layout.
793    ///
794    /// # Errors
795    /// Rejects insufficient operands, a wrong ambient snapshot, or layout overflow.
796    /// - Complexity: O(n + s) registration and raw moves for n fields and s bytes.
797    ///
798    /// # Examples
799    /// ```
800    /// let mut b = cel_runtime::DynSegment::new::<()>();
801    /// b.just(1i32); b.just(2f64); b.make_tuple(2, 0).unwrap();
802    /// ```
803    pub fn make_tuple(&mut self, n: usize, ambient_start: usize) -> Result<()> {
804        ensure!(
805            self.stack_offset_before_top(n)? == ambient_start,
806            "tuple ambient origin mismatch"
807        );
808        let fields = self
809            .peek_stack_infos(n)
810            .iter()
811            .map(|info| AssociatedType {
812                offset: 0,
813                value_type: info.value_type.clone(),
814            })
815            .collect();
816        let value_type = ValueType::tuple(fields)?;
817        let frame = StackFramePlan::new(ambient_start, value_type.clone())?;
818        let result = ResultPlan::new(ambient_start, value_type.clone())?;
819        self.segment.update_base_alignment(value_type.align());
820        self.segment.raw0_(move |stack| {
821            // SAFETY: The frozen source frame matches every emitted operand.
822            let mut owner = unsafe { frame.take(stack) };
823            unsafe { result.push(stack, &mut owner) };
824            Ok(())
825        });
826        self.replace(n, value_type);
827        Ok(())
828    }
829
830    /// Packs homogeneous operands into a canonical owning array header.
831    ///
832    /// # Errors
833    /// Rejects empty inference, differing complete types, wrong ambient origin,
834    /// insufficient operands, or allocation-layout overflow.
835    /// - Complexity: O(n + s) checks and moves for n elements and s bytes.
836    ///
837    /// # Examples
838    /// ```
839    /// let mut b = cel_runtime::DynSegment::new::<()>();
840    /// b.just(1i32); b.make_array(1, 0).unwrap();
841    /// ```
842    pub fn make_array(&mut self, n: usize, ambient_start: usize) -> Result<()> {
843        ensure!(
844            n != 0,
845            "empty array requires an explicit complete element type"
846        );
847        self.stack_offset_before_top(n)?;
848        let element = self.peek_stack_infos(n)[0].value_type.clone();
849        self.make_typed_array(n, ambient_start, element)
850    }
851
852    /// Packs operands using an explicit complete element descriptor.
853    ///
854    /// # Errors
855    /// Rejects wrong ambient origin, insufficient/differently shaped operands,
856    /// or allocation-layout overflow. Empty arrays need no element capabilities.
857    /// - Complexity: O(n + s) checks and moves for n elements and s bytes.
858    ///
859    /// # Examples
860    /// ```
861    /// let mut b = cel_runtime::DynSegment::new::<()>();
862    /// b.make_typed_array(0, 0, cel_runtime::ValueType::leaf::<i32>()).unwrap();
863    /// ```
864    pub fn make_typed_array(
865        &mut self,
866        n: usize,
867        ambient_start: usize,
868        element: ValueType,
869    ) -> Result<()> {
870        element.validate_canonical()?;
871        ensure!(
872            self.stack_offset_before_top(n)? == ambient_start,
873            "array ambient origin mismatch"
874        );
875        for (index, info) in self.peek_stack_infos(n).iter().enumerate() {
876            ensure!(
877                info.value_type.same_shape(&element),
878                "array element {index} has type {}, expected {}",
879                descriptor_name(&info.value_type),
880                descriptor_name(&element)
881            );
882        }
883        let container = ContainerPlan::array(element.clone(), n)?;
884        let result_type = ValueType::array(element.clone());
885        let result = ResultPlan::new(ambient_start, result_type.clone())?;
886        let mut end = ambient_start;
887        let offsets = (0..n)
888            .map(|_| {
889                let (offset, next) = stack_position(end, element.layout())?;
890                end = next;
891                Ok(offset)
892            })
893            .collect::<Result<Vec<_>>>()?;
894        self.segment.update_base_alignment(result_type.align());
895        self.segment.raw0_(move |stack| {
896            // No user code or fallible operation follows the first child move.
897            let mut owner = unsafe {
898                container.construct(|index, destination| {
899                    stack.read_at(offsets[index], |source| {
900                        std::ptr::copy_nonoverlapping(source, destination, element.size())
901                    });
902                    Ok(())
903                })?
904            };
905            // SAFETY: All children have moved into owner. Restore the ambient
906            // prefix before registering the new result or allowing unwinding.
907            unsafe {
908                stack.release_top(n);
909                stack.truncate_to(ambient_start, false);
910                result.push(stack, &mut owner);
911            }
912            Ok(())
913        });
914        self.replace(n, result_type);
915        Ok(())
916    }
917
918    /// Moves one source-ordered tuple field and destroys every other field.
919    ///
920    /// # Errors
921    /// Rejects a missing tuple or an out-of-range index before emitting.
922    /// - Complexity: O(n) registration/destruction for n fields, plus representation moves.
923    ///
924    /// # Examples
925    /// ```
926    /// let mut b = cel_runtime::DynSegment::new::<()>();
927    /// b.just(1i32); b.just(2f64); b.make_tuple(2, 0).unwrap();
928    /// b.tuple_index(0).unwrap(); assert_eq!(b.call0::<i32>().unwrap(), 1);
929    /// ```
930    pub fn tuple_index(&mut self, index: usize) -> Result<()> {
931        let ty = self
932            .stack_ids
933            .last()
934            .ok_or_else(|| anyhow!("missing tuple"))?
935            .value_type
936            .clone();
937        let fields = ty
938            .tuple_elements()
939            .ok_or_else(|| anyhow!("tuple required"))?;
940        let field = fields
941            .get(index)
942            .ok_or_else(|| anyhow!("tuple index out of range"))?
943            .value_type
944            .clone();
945        let ambient = self.stack_offset_before_top(1)?;
946        let input = ResultPlan::new(ambient, ty)?;
947        let output = ResultPlan::new(ambient, field.clone())?;
948        self.segment.raw0_(move |stack| {
949            let owner = unsafe { input.take(stack) };
950            let mut selected = unsafe { owner.take_field(index) };
951            unsafe { output.push(stack, &mut selected) };
952            Ok(())
953        });
954        self.replace(1, field);
955        Ok(())
956    }
957
958    /// Moves an indexed canonical array element and destroys the consumed array's siblings.
959    ///
960    /// The stack holds the array followed by an opaque index of type `I`.
961    /// No clone capability is required, including for nested tuple/array elements.
962    /// Moving the validated index into its concrete type does not allocate.
963    /// # Errors
964    /// Rejects absent/nonmatching operands during registration. Execution rejects
965    /// negative/unrepresentable or out-of-bounds indices and cleans every operand.
966    /// - Complexity: O(n) setup/destruction for n stack slots or array elements.
967    ///
968    /// # Examples
969    /// ```
970    /// let mut body = cel_runtime::DynSegment::new::<()>();
971    /// body.just(7i32); body.make_array(1, 0).unwrap();
972    /// body.just(0i32); body.array_index::<i32>().unwrap();
973    /// assert_eq!(body.call0::<i32>().unwrap(), 7);
974    /// ```
975    pub fn array_index<I: TryInto<usize> + 'static>(&mut self) -> Result<()> {
976        let first = self
977            .stack_ids
978            .len()
979            .checked_sub(2)
980            .ok_or_else(|| anyhow!("array index requires two operands"))?;
981        self.stack_ids[first + 1]
982            .value_type
983            .validate_opaque_leaf(TypeId::of::<I>())?;
984        let array_type = self.stack_ids[first].value_type.clone();
985        let element = array_type
986            .array_element()
987            .ok_or_else(|| anyhow!("canonical array required"))?
988            .clone();
989        let ambient = self.offset_after(first);
990        let index = ResultPlan::new(self.offset_after(first + 1), ValueType::leaf::<I>())?;
991        let array = ResultPlan::new(ambient, array_type)?;
992        let output = ResultPlan::new(ambient, element.clone())?;
993        self.segment.update_base_alignment(element.align());
994        self.segment.raw0_(move |stack| {
995            // SAFETY: Construction validates the exact opaque I descriptor.
996            let native = unsafe { index.take_typed::<I>(stack) };
997            let array_owner = unsafe { array.take(stack) };
998            let selected = native
999                .try_into()
1000                .map_err(|_| anyhow!("array index is negative or unrepresentable"))
1001                .and_then(|index| unsafe { array_owner.take_array_element(index) });
1002            match selected {
1003                Ok(mut value) => {
1004                    unsafe { output.push(stack, &mut value) };
1005                    Ok(())
1006                }
1007                Err(error) => Err(error),
1008            }
1009        });
1010        self.replace(2, element);
1011        Ok(())
1012    }
1013
1014    /// Destroys the top canonical value without synthesizing a result.
1015    ///
1016    /// Ambient values survive success and are cleaned if a destructor unwinds.
1017    /// # Errors
1018    /// Rejects an empty stack before registration.
1019    /// - Complexity: O(1) setup; value-dependent destruction.
1020    ///
1021    /// # Examples
1022    /// ```
1023    /// let mut body = cel_runtime::DynSegment::new::<()>();
1024    /// body.just(1i32); body.make_array(1, 0).unwrap();
1025    /// body.drop_value().unwrap();
1026    /// body.just(7i32); assert_eq!(body.call0::<i32>().unwrap(), 7);
1027    /// ```
1028    pub fn drop_value(&mut self) -> Result<()> {
1029        let first = self
1030            .stack_ids
1031            .len()
1032            .checked_sub(1)
1033            .ok_or_else(|| anyhow!("missing value"))?;
1034        self.segment.raw0_(|stack| {
1035            stack.drop_top();
1036            Ok(())
1037        });
1038        self.stack_ids.truncate(first);
1039        self.stack_ends.truncate(first + 1);
1040        Ok(())
1041    }
1042
1043    /// Validates a complete value using an explicit matching structural witness.
1044    ///
1045    /// # Errors
1046    /// Rejects an absent or mismatched value; this never authorizes opaque casts.
1047    /// - Complexity: O(n) complete descriptor comparison for n nodes.
1048    ///
1049    /// # Examples
1050    /// ```
1051    /// let mut b = cel_runtime::DynSegment::new::<()>();
1052    /// b.make_tuple(0, 0).unwrap(); b.relabel_repr::<cel_runtime::Nil>().unwrap();
1053    /// ```
1054    pub fn relabel_repr<R: ValueRepr>(&mut self) -> Result<()> {
1055        self.stack_ids
1056            .last()
1057            .ok_or_else(|| anyhow!("missing value"))?
1058            .value_type
1059            .validate::<R>()
1060    }
1061
1062    /// Installs complete registered capabilities without changing the top value's identity.
1063    ///
1064    /// A host registry can retain clone/equality/debug adapters on operation
1065    /// results for checked external export. No instruction or raw cast is emitted.
1066    /// # Errors
1067    /// Rejects a missing value or any recursive identity/layout mismatch.
1068    /// - Complexity: O(n) complete comparison for n descriptor nodes.
1069    ///
1070    /// # Examples
1071    /// ```
1072    /// use cel_runtime::{DynSegment, Leaf, ValueType};
1073    /// let mut body = DynSegment::new::<()>(); body.just(7i32);
1074    /// body.annotate_top(ValueType::cloneable_leaf::<i32>()
1075    ///     .with_equality::<Leaf<i32>>().unwrap()
1076    ///     .with_debug::<Leaf<i32>>().unwrap()).unwrap();
1077    /// ```
1078    pub fn annotate_top(&mut self, value_type: ValueType) -> Result<()> {
1079        let info = self
1080            .stack_ids
1081            .last_mut()
1082            .ok_or_else(|| anyhow!("missing value"))?;
1083        ensure!(
1084            info.value_type.same_shape(&value_type),
1085            "top value annotation representation mismatch"
1086        );
1087        info.value_type = value_type;
1088        Ok(())
1089    }
1090
1091    /// Relabels a canonical tuple as its concrete opaque list using an explicit witness.
1092    ///
1093    /// No bytes move. The witness authorizes the concrete Rust destructor and
1094    /// permits an ordinary typed operation or direct `Segment` conversion.
1095    /// # Errors
1096    /// Rejects a missing/nontuple value or any complete witness mismatch.
1097    /// - Complexity: O(n) complete comparison for n descriptor nodes.
1098    ///
1099    /// # Examples
1100    /// ```
1101    /// let mut body = cel_runtime::DynSegment::new::<()>();
1102    /// body.make_tuple(0, 0).unwrap();
1103    /// body.pop_tuple_as::<cel_runtime::Nil>().unwrap();
1104    /// ```
1105    pub fn pop_tuple_as<R: ValueRepr>(&mut self) -> Result<()> {
1106        let info = self
1107            .stack_ids
1108            .last_mut()
1109            .ok_or_else(|| anyhow!("missing tuple"))?;
1110        ensure!(
1111            info.value_type.tuple_elements().is_some(),
1112            "canonical tuple required"
1113        );
1114        info.value_type.validate::<R>()?;
1115        info.value_type = ValueType::leaf::<R::Value>();
1116        Ok(())
1117    }
1118
1119    /// Relabels a concrete opaque canonical list as a structural tuple using its witness.
1120    ///
1121    /// # Errors
1122    /// Rejects missing values, nontuple witnesses, or a different opaque concrete type.
1123    /// - Complexity: O(n) witness construction for n tuple descriptor nodes.
1124    ///
1125    /// # Examples
1126    /// ```
1127    /// use cel_runtime::{DynSegment, Nil, IntoCStackList};
1128    /// let mut body = DynSegment::new::<()>();
1129    /// body.just(().into_c_stack_list());
1130    /// body.push_tuple::<Nil>().unwrap();
1131    /// ```
1132    pub fn push_tuple<R: ValueRepr>(&mut self) -> Result<()> {
1133        let value_type = R::value_type();
1134        ensure!(
1135            value_type.tuple_elements().is_some(),
1136            "canonical tuple witness required"
1137        );
1138        let info = self
1139            .stack_ids
1140            .last_mut()
1141            .ok_or_else(|| anyhow!("missing concrete list"))?;
1142        info.value_type
1143            .validate_opaque_leaf(TypeId::of::<R::Value>())?;
1144        debug_assert_eq!(info.value_type.layout(), value_type.layout());
1145        info.value_type = value_type;
1146        Ok(())
1147    }
1148
1149    /// Checks that this body starts on an independent empty raw execution stack.
1150    ///
1151    /// # Errors
1152    /// Rejects preloaded arguments or a nonzero fragment origin.
1153    pub(crate) fn validate_independent_body(&self) -> Result<()> {
1154        ensure!(
1155            self.argument_ids.is_empty(),
1156            "independent body must not require preloaded arguments"
1157        );
1158        ensure!(
1159            self.base_stack_index == 0,
1160            "independent body must not require a nonzero ambient stack origin"
1161        );
1162        Ok(())
1163    }
1164
1165    /// Executes the existing raw instruction sequence with trusted argument pointers.
1166    ///
1167    /// # Safety
1168    /// The independent body and every read's complete identity/count/clone plan
1169    /// must have been validated; arguments must stay live until return.
1170    /// # Errors
1171    /// Propagates body errors without changing their context.
1172    /// - Complexity: Body-dependent; no descriptor comparisons or `Any` downcasts.
1173    pub(crate) unsafe fn execute_raw(&mut self, arguments: &[*const u8]) -> Result<RawStack> {
1174        let _guard = ArgumentGuard::install(arguments);
1175        let mut output = RawStack::with_base_alignment(self.segment.base_alignment());
1176        unsafe { self.segment.call0_stack(&mut output)? };
1177        Ok(output)
1178    }
1179
1180    /// Evaluates a result at a checked external host boundary.
1181    ///
1182    /// Structural results return canonical whole-value owners; callable results return
1183    /// their concrete carrier. Interpreter operations never use this conversion.
1184    /// Scalar inputs are borrowed after complete input preflight and cloned only
1185    /// by executed reads; compound inputs borrow checked canonical owners.
1186    ///
1187    /// # Errors
1188    /// Rejects dependent bodies, non-single results, unsupported external shapes,
1189    /// unavailable argument capabilities, or mismatched arguments/results; propagates body errors.
1190    /// - Complexity: Boundary validation and argument clones plus evaluation.
1191    ///
1192    /// # Examples
1193    /// See [`Self::push_arg`].
1194    pub fn call_dyn<R: 'static>(&mut self, inputs: &[&dyn Any]) -> Result<R> {
1195        let result = self.result_type()?;
1196        match result.kind() {
1197            ValueKind::Tuple(fields)
1198                if fields.is_empty() && TypeId::of::<R>() == TypeId::of::<()>() =>
1199            {
1200                drop(self.call_dyn_value(inputs)?);
1201                let unit: Box<dyn Any> = Box::new(());
1202                return Ok(*unit.downcast::<R>().expect("checked host unit identity"));
1203            }
1204            ValueKind::Array(_) | ValueKind::Tuple(_) => {
1205                ensure!(
1206                    TypeId::of::<R>() == TypeId::of::<OwnedValue>(),
1207                    "canonical result owner required"
1208                );
1209                let owner: Box<dyn Any> = Box::new(self.call_dyn_value(inputs)?);
1210                return Ok(*owner
1211                    .downcast::<R>()
1212                    .map_err(|_| anyhow!("canonical result owner required"))?);
1213            }
1214            ValueKind::Callable { .. } => {
1215                ensure!(
1216                    TypeId::of::<R>() == TypeId::of::<crate::DynClosure>(),
1217                    "external callable result type mismatch"
1218                );
1219            }
1220            ValueKind::Leaf(_) => result.validate_opaque_leaf(TypeId::of::<R>())?,
1221        }
1222        let plan = ResultPlan::new(0, self.result_type()?.clone())?;
1223        let mut output = self.call_external(inputs)?;
1224        Ok(unsafe { plan.take_typed::<R>(&mut output) })
1225    }
1226
1227    /// Evaluates an owned canonical value through a checked external argument boundary.
1228    ///
1229    /// # Errors
1230    /// Rejects dependent bodies, non-single results, or invalid external arguments.
1231    /// Propagates operation errors without erasing their context.
1232    /// - Complexity: Boundary validation/cloning plus body evaluation and one raw result move.
1233    ///
1234    /// # Examples
1235    /// ```
1236    /// let mut body = cel_runtime::DynSegment::new::<()>();
1237    /// body.just(7i32);
1238    /// assert_eq!(body.call_dyn_value(&[]).unwrap().try_into_typed::<cel_runtime::Leaf<i32>>().unwrap(), 7);
1239    /// ```
1240    pub fn call_dyn_value(&mut self, inputs: &[&dyn Any]) -> Result<OwnedValue> {
1241        let result = ResultPlan::new(0, self.result_type()?.clone())?;
1242        let mut output = self.call_external(inputs)?;
1243        Ok(unsafe { result.take(&mut output) })
1244    }
1245
1246    /// Validates all external inputs, then borrows canonical storage.
1247    ///
1248    /// Scalar inputs remain borrowed for this call, including nested calls.
1249    /// Only executed scalar reads clone them. Recursive validation completes
1250    /// before any clone or body operation runs.
1251    ///
1252    /// # Errors
1253    /// Rejects dependent bodies or invalid external reads; propagates body errors.
1254    /// - Complexity: O(r + i) preflight for r read descriptor nodes and i inputs,
1255    ///   plus host-value validation and body execution.
1256    fn call_external(&mut self, inputs: &[&dyn Any]) -> Result<RawStack> {
1257        self.validate_independent_body()?;
1258        let mut first_reads: Vec<Option<&ValueType>> = vec![None; inputs.len()];
1259        for (index, ty) in &self.argument_reads {
1260            ensure!(*index < inputs.len(), "missing argument {index}");
1261            if let Some(first) = first_reads[*index] {
1262                ensure!(
1263                    ty.same_shape(first),
1264                    "inconsistent argument {index} representation"
1265                );
1266            } else {
1267                first_reads[*index] = Some(ty);
1268            }
1269        }
1270        let mut pointers = vec![std::ptr::null(); inputs.len()];
1271        for (index, ty) in first_reads.into_iter().enumerate() {
1272            if let Some(ty) = ty {
1273                pointers[index] = HostValuePlan::new(ty.clone())?.validate_any(inputs[index])?;
1274            }
1275        }
1276        unsafe { self.execute_raw(&pointers) }
1277    }
1278
1279    /// Borrows the sole canonical result metadata.
1280    ///
1281    /// # Errors
1282    /// Rejects zero or multiple results.
1283    pub(crate) fn result_type(&self) -> Result<&ValueType> {
1284        ensure!(
1285            self.stack_ids.len() == 1,
1286            "body must produce exactly one value"
1287        );
1288        Ok(&self.stack_ids[0].value_type)
1289    }
1290
1291    /// Executes a checked no-argument host call without consuming type metadata.
1292    ///
1293    /// # Errors
1294    /// Rejects a result mismatch, extra stack values, or required preloaded arguments.
1295    /// - Complexity: Body-dependent evaluation plus boundary checks.
1296    ///
1297    /// # Examples
1298    /// See [`Self::op0`].
1299    pub fn call0<R: 'static>(&mut self) -> Result<R> {
1300        self.call_dyn(&[])
1301    }
1302
1303    /// Executes a preloaded single opaque-leaf argument and result.
1304    ///
1305    /// # Errors
1306    /// Rejects nonmatching argument/result identities, positional reads, or extra results.
1307    /// - Complexity: Body-dependent.
1308    ///
1309    /// # Examples
1310    /// ```
1311    /// let mut b = cel_runtime::DynSegment::new::<(i32,)>();
1312    /// b.op1(|x: i32| x.to_string()).unwrap();
1313    /// assert_eq!(b.call1::<i32, String>(7).unwrap(), "7");
1314    /// ```
1315    pub fn call1<A: 'static, R: 'static>(&mut self, arg: A) -> Result<R> {
1316        ensure!(
1317            self.argument_ids == [TypeId::of::<A>()],
1318            "argument type mismatch"
1319        );
1320        ensure!(
1321            self.argument_reads.is_empty(),
1322            "preloaded call cannot use positional argument reads"
1323        );
1324        self.result_type()?
1325            .validate_opaque_leaf(TypeId::of::<R>())?;
1326        unsafe { self.segment.call1(arg) }
1327    }
1328
1329    /// Prepares a complete borrowed argument list and owned result once.
1330    ///
1331    /// # Errors
1332    /// Rejects dependent bodies, non-list arguments, mismatched reads/results,
1333    /// missing borrowed clone capabilities, or inconsistent reads of one argument.
1334    /// - Complexity: O(n) complete comparisons for n frame/descriptor nodes.
1335    ///
1336    /// # Examples
1337    /// See the module example.
1338    pub fn prepare<A: ValueRepr, R: ValueRepr>(self) -> Result<crate::PreparedSegment<A, R>> {
1339        crate::PreparedSegment::new(self)
1340    }
1341
1342    /// Pushes a known callable with complete metadata and shared body ownership.
1343    ///
1344    /// # Errors
1345    /// Rejects an untyped/invalid closure or unavailable trusted binding.
1346    /// - Complexity: O(n) signature/body validation for n descriptor nodes.
1347    ///
1348    /// # Examples
1349    /// See [`Self::invoke_closure`].
1350    pub fn push_closure(&mut self, closure: crate::DynClosure) -> Result<()> {
1351        let signature = closure
1352            .signature()
1353            .ok_or_else(|| anyhow!("closure signature metadata is unavailable"))?;
1354        closure.validate_body_signature()?;
1355        let ty = ValueType::callable(signature.parameters.clone(), signature.result.clone());
1356        // The lease is retained by the emitted constant, across every alias.
1357        let closure = closure.bind_canonical()?;
1358        self.segment.update_base_alignment(ty.align());
1359        self.segment.raw0_(move |stack| {
1360            stack.push(closure.clone());
1361            Ok(())
1362        });
1363        self.replace(0, ty);
1364        Ok(())
1365    }
1366
1367    /// Invokes a canonical callable below its source-ordered evaluated arguments.
1368    ///
1369    /// Moving the bound callee into its concrete carrier does not allocate.
1370    /// Argument and result transfers retain their erased ownership.
1371    ///
1372    /// # Errors
1373    /// Rejects unavailable/mismatched callable metadata or insufficient operands.
1374    /// Execution propagates body errors, retaining their original context.
1375    /// - Complexity: O(n) setup; body execution plus argument/result raw moves.
1376    ///
1377    /// # Examples
1378    /// ```
1379    /// use cel_runtime::{DynClosure, DynSegment};
1380    /// let mut body = DynSegment::new::<()>(); body.just(7i32);
1381    /// let closure = DynClosure::typed(vec![], body).unwrap();
1382    /// let mut b = DynSegment::new::<()>();
1383    /// b.push_closure(closure).unwrap(); b.invoke_closure(0).unwrap();
1384    /// assert_eq!(b.call0::<i32>().unwrap(), 7);
1385    /// ```
1386    pub fn invoke_closure(&mut self, arity: usize) -> Result<()> {
1387        ensure!(
1388            self.argument_ids.is_empty(),
1389            "closure invocation requires a positional body"
1390        );
1391        let operands = arity
1392            .checked_add(1)
1393            .ok_or_else(|| anyhow!("missing callee"))?;
1394        let first = self
1395            .stack_ids
1396            .len()
1397            .checked_sub(operands)
1398            .ok_or_else(|| anyhow!("missing callee"))?;
1399        let callee_type = self.stack_ids[first].value_type.clone();
1400        let ValueKind::Callable { parameters, result } = callee_type.kind() else {
1401            anyhow::bail!("callable signature required")
1402        };
1403        ensure!(parameters.len() == arity, "closure arity mismatch");
1404        ensure!(
1405            parameters
1406                .iter()
1407                .zip(&self.stack_ids[first + 1..])
1408                .all(|(expected, actual)| expected.same_shape(&actual.value_type)),
1409            "closure argument type mismatch"
1410        );
1411        let result_type = result.as_ref().clone();
1412        let ambient = self.offset_after(first);
1413        let argument_type = ValueType::tuple(
1414            parameters
1415                .iter()
1416                .map(|value_type| AssociatedType {
1417                    offset: 0,
1418                    value_type: value_type.clone(),
1419                })
1420                .collect(),
1421        )?;
1422        let arguments_start = self.offset_after(first + 1);
1423        let frame = StackFramePlan::new(arguments_start, argument_type.clone())?;
1424        let callee = ResultPlan::new(ambient, callee_type.clone())?;
1425        let destination = ResultPlan::new(ambient, result_type.clone())?;
1426        self.segment.update_base_alignment(result_type.align());
1427        let output_type = result_type.clone();
1428        self.segment.raw0_(move |stack| {
1429            // Move every operand to independent guarded owners before user code.
1430            let arguments = unsafe { frame.take(stack) };
1431            // SAFETY: Every validated callable descriptor uses the DynClosure carrier.
1432            let closure = unsafe { callee.take_typed::<crate::DynClosure>(stack) };
1433            // Compiler-produced carriers retain a freeze lease; typed native
1434            // and prepared payloads have no mutable compiler-facing escape.
1435            let allocation = crate::owned_value::Allocation::new(output_type.layout());
1436            let evaluated = unsafe {
1437                closure.call_frame_trusted(arguments.as_ptr(), allocation.pointer.as_ptr())
1438            };
1439            match evaluated {
1440                Ok(()) => {
1441                    let mut result = unsafe {
1442                        crate::OwnedValue::from_allocation(allocation, output_type.clone())
1443                    };
1444                    drop(arguments);
1445                    drop(closure);
1446                    unsafe { destination.push(stack, &mut result) };
1447                    Ok(())
1448                }
1449                Err(error) => {
1450                    drop(arguments);
1451                    drop(closure);
1452                    Err(error)
1453                }
1454            }
1455        });
1456        self.replace(operands, result_type);
1457        Ok(())
1458    }
1459
1460    /// Joins conditional fragments with identical complete results and origins.
1461    ///
1462    /// # Errors
1463    /// Rejects a nonboolean condition, wrong fragment origins, or different results.
1464    /// - Complexity: O(n) setup for n frame/descriptor nodes; executes one branch.
1465    ///
1466    /// # Examples
1467    /// ```
1468    /// let mut b = cel_runtime::DynSegment::new::<()>(); b.just(true);
1469    /// let mut yes = b.new_fragment(); yes.just(1i32);
1470    /// let mut no = b.new_fragment(); no.just(2i32);
1471    /// b.join2(yes, no).unwrap(); assert_eq!(b.call0::<i32>().unwrap(), 1);
1472    /// ```
1473    pub fn join2(&mut self, yes: Self, no: Self) -> Result<()> {
1474        let origin = self.stack_offset_before_top(1)?;
1475        self.stack_ids
1476            .last()
1477            .unwrap()
1478            .value_type
1479            .validate_opaque_leaf(TypeId::of::<bool>())?;
1480        ensure!(
1481            yes.base_stack_index == origin && no.base_stack_index == origin,
1482            "fragment origins must match"
1483        );
1484        ensure!(
1485            yes.argument_ids.is_empty() && no.argument_ids.is_empty(),
1486            "fragments cannot take preloaded arguments"
1487        );
1488        let result = yes.result_type()?.clone();
1489        ensure!(
1490            result.same_shape(no.result_type()?),
1491            "fragment result types must match"
1492        );
1493        let condition = ResultPlan::new(origin, ValueType::leaf::<bool>())?;
1494        self.segment.update_base_alignment(
1495            yes.segment
1496                .base_alignment()
1497                .max(no.segment.base_alignment()),
1498        );
1499        self.argument_reads.extend(yes.argument_reads);
1500        self.argument_reads.extend(no.argument_reads);
1501        self.segment.raw0_(move |stack| {
1502            // SAFETY: Construction validates bool; the bound plan restores the
1503            // exact ambient origin before the cleanup guard is armed.
1504            let value = unsafe { condition.take_typed::<bool>(stack) };
1505            let branch = if value { &yes.segment } else { &no.segment };
1506            unsafe { branch.call0_stack(stack) }
1507        });
1508        self.replace(1, result);
1509        Ok(())
1510    }
1511}
1512
1513#[cfg(test)]
1514mod performance_tests {
1515    use super::*;
1516    use crate::{Array, ArrayOf, Cons, IntoCStackList, Nil};
1517    use std::cell::RefCell;
1518    use std::panic::{AssertUnwindSafe, catch_unwind};
1519    use std::rc::Rc;
1520
1521    /// Rejects missing callees, including unrepresentable arities, without emitting instructions.
1522    #[test]
1523    fn invocation_rejects_missing_callee_without_changing_body() {
1524        let mut body = DynSegment::new::<()>();
1525        body.just(7i32);
1526        for arity in [0, usize::MAX] {
1527            assert!(body.invoke_closure(arity).is_err());
1528            assert_eq!(body.call0::<i32>().unwrap(), 7);
1529        }
1530    }
1531
1532    /// Formats empty and nested descriptors in their source order.
1533    #[test]
1534    fn diagnostic_names_preserve_recursive_shape() {
1535        assert_eq!(descriptor_name(&ValueType::tuple(vec![]).unwrap()), "()");
1536        assert_eq!(
1537            descriptor_name(&ValueType::leaf::<String>()),
1538            std::any::type_name::<String>()
1539        );
1540        let row = ValueType::tuple(vec![
1541            AssociatedType {
1542                offset: 0,
1543                value_type: ValueType::array(ValueType::leaf::<i32>()),
1544            },
1545            AssociatedType {
1546                offset: 0,
1547                value_type: ValueType::tuple(vec![AssociatedType {
1548                    offset: 0,
1549                    value_type: ValueType::leaf::<f64>(),
1550                }])
1551                .unwrap(),
1552            },
1553        ])
1554        .unwrap();
1555        assert_eq!(descriptor_name(&ValueType::array(row)), "[([i32], (f64))]");
1556    }
1557
1558    /// Records only live runtime owners, not borrowed sources or registration values.
1559    #[repr(align(128))]
1560    struct CloneDrop {
1561        name: &'static str,
1562        events: Rc<RefCell<Vec<&'static str>>>,
1563        fail: Rc<Cell<bool>>,
1564        owned: bool,
1565    }
1566
1567    impl Clone for CloneDrop {
1568        /// Creates an aligned owner unless this source requests a clone panic.
1569        fn clone(&self) -> Self {
1570            assert!(!self.fail.get(), "deliberate clone panic");
1571            Self {
1572                name: self.name,
1573                events: self.events.clone(),
1574                fail: self.fail.clone(),
1575                owned: true,
1576            }
1577        }
1578    }
1579
1580    impl Drop for CloneDrop {
1581        /// Records each initialized runtime owner exactly once.
1582        fn drop(&mut self) {
1583            if self.owned {
1584                self.events.borrow_mut().push(self.name);
1585            }
1586        }
1587    }
1588
1589    /// Checks recursive clone rollback, branch origins, reverse cleanup, and replay.
1590    #[test]
1591    fn direct_clone_panic_restores_branch_and_ambient_ownership() {
1592        type Pair = Cons<ArrayOf<Leaf<CloneDrop>>, Cons<Leaf<CloneDrop>, Nil>>;
1593        for external_constant in [false, true] {
1594            let events = Rc::new(RefCell::new(Vec::new()));
1595            let fail = Rc::new(Cell::new(true));
1596            let leaf = |name, fail: Rc<Cell<bool>>, owned| CloneDrop {
1597                name,
1598                events: events.clone(),
1599                fail,
1600                owned,
1601            };
1602            let descriptor = ValueType::tuple(vec![
1603                AssociatedType {
1604                    offset: 0,
1605                    value_type: ValueType::array(ValueType::cloneable_leaf::<CloneDrop>()),
1606                },
1607                AssociatedType {
1608                    offset: 0,
1609                    value_type: ValueType::cloneable_leaf::<CloneDrop>(),
1610                },
1611            ])
1612            .unwrap();
1613            let mut source = Some(
1614                OwnedValue::new::<Pair>(
1615                    (
1616                        Array::from_vec(vec![leaf("child", Rc::new(Cell::new(false)), false)]),
1617                        leaf("panic", fail.clone(), false),
1618                    )
1619                        .into_c_stack_list(),
1620                )
1621                .with_value_type(descriptor.clone())
1622                .unwrap(),
1623            );
1624            let mut body = DynSegment::new::<()>();
1625            for name in ["outer-a", "outer-b"] {
1626                let log = events.clone();
1627                body.op0(move || CloneDrop {
1628                    name,
1629                    events: log.clone(),
1630                    fail: Rc::new(Cell::new(false)),
1631                    owned: true,
1632                });
1633            }
1634            body.just(true);
1635            let mut yes = body.new_fragment();
1636            let log = events.clone();
1637            yes.op0(move || CloneDrop {
1638                name: "branch",
1639                events: log.clone(),
1640                fail: Rc::new(Cell::new(false)),
1641                owned: true,
1642            });
1643            if external_constant {
1644                yes.just_external(descriptor, Box::new(source.take().unwrap()))
1645                    .unwrap();
1646            } else {
1647                yes.push_argument(0, descriptor).unwrap();
1648            }
1649            yes.drop_value().unwrap();
1650            yes.drop_value().unwrap();
1651            yes.just(9u32);
1652            let mut no = body.new_fragment();
1653            no.just(3u32);
1654            body.join2(yes, no).unwrap();
1655            body.op3(|_: CloneDrop, _: CloneDrop, result: u32| result)
1656                .unwrap();
1657
1658            let pointers: Vec<_> = source.iter().map(OwnedValue::as_ptr).collect();
1659            for _ in 0..2 {
1660                let mut stack = RawStack::with_base_alignment(body.segment.base_alignment());
1661                let _arguments = ArgumentGuard::install(&pointers);
1662                // SAFETY: The source and body share the complete bound descriptor.
1663                assert!(
1664                    catch_unwind(AssertUnwindSafe(|| unsafe {
1665                        body.segment.call0_stack(&mut stack)
1666                    }))
1667                    .is_err()
1668                );
1669                assert_eq!(stack.len(), 0);
1670                assert_eq!(
1671                    &*events.borrow(),
1672                    &["child", "branch", "outer-b", "outer-a"]
1673                );
1674                events.borrow_mut().clear();
1675            }
1676            fail.set(false);
1677            let inputs: Vec<&dyn Any> = source.iter().map(|owner| owner as &dyn Any).collect();
1678            assert_eq!(body.call_dyn::<u32>(&inputs).unwrap(), 9);
1679            assert_eq!(
1680                events
1681                    .borrow()
1682                    .iter()
1683                    .filter(|name| **name == "child")
1684                    .count(),
1685                1
1686            );
1687            assert_eq!(
1688                events
1689                    .borrow()
1690                    .iter()
1691                    .filter(|name| **name == "panic")
1692                    .count(),
1693                1
1694            );
1695        }
1696    }
1697
1698    /// Rejects inconsistent descriptors before executing any instruction on every call.
1699    #[test]
1700    fn inconsistent_reads_precede_body_effects() {
1701        let effects = Rc::new(Cell::new(0));
1702        let counter = effects.clone();
1703        let mut body = DynSegment::new::<()>();
1704        body.op0(move || counter.set(counter.get() + 1));
1705        body.drop_value().unwrap();
1706        body.push_arg::<i32>(0);
1707        body.drop_value().unwrap();
1708        body.push_arg::<String>(0);
1709        body.drop_value().unwrap();
1710        body.just(7u32);
1711        for _ in 0..2 {
1712            let error = body.call_dyn::<u32>(&[&1i32]).unwrap_err();
1713            assert!(error.to_string().contains("inconsistent argument 0"));
1714            assert_eq!(effects.get(), 0);
1715        }
1716    }
1717
1718    /// Keeps captureless typed operations free of retained instruction state.
1719    #[test]
1720    fn captureless_operations_retain_no_instruction_state() {
1721        let mut body = DynSegment::new::<()>();
1722        body.just(1i32);
1723        let initial = body.segment.storage_size();
1724        for _ in 0..4_000 {
1725            body.op1(|value: i32| value).unwrap();
1726        }
1727        assert_eq!(body.segment.storage_size(), initial);
1728        assert_eq!(body.call0::<i32>().unwrap(), 1);
1729    }
1730
1731    /// Packs large literal arrays without retaining per-slot cleanup graphs.
1732    #[test]
1733    fn large_literal_arrays_preserve_values() {
1734        for length in [1_000, 2_000, 4_000] {
1735            let mut body = DynSegment::new::<()>();
1736            for _ in 0..length {
1737                body.just(1i32);
1738            }
1739            body.make_array(length, 0).unwrap();
1740            let output = body.call_dyn_value(&[]).unwrap();
1741            assert_eq!(
1742                output
1743                    .try_into_typed::<crate::ArrayOf<Leaf<i32>>>()
1744                    .unwrap()
1745                    .len(),
1746                length
1747            );
1748        }
1749    }
1750
1751    /// Packs large arrays from borrowed reads and imported constants.
1752    #[test]
1753    fn large_cloned_arrays_preserve_values() {
1754        for length in [1_000, 2_000, 4_000] {
1755            for external_constant in [false, true] {
1756                let mut body = DynSegment::new::<()>();
1757                for _ in 0..length {
1758                    if external_constant {
1759                        body.just_external(ValueType::cloneable_leaf::<i32>(), Box::new(1i32))
1760                            .unwrap();
1761                    } else {
1762                        body.push_arg::<i32>(0);
1763                    }
1764                }
1765                body.make_array(length, 0).unwrap();
1766                let result = body.call_dyn_value(&[&1i32]).unwrap();
1767                assert_eq!(
1768                    result.try_into_typed::<ArrayOf<Leaf<i32>>>().unwrap().len(),
1769                    length
1770                );
1771            }
1772        }
1773    }
1774
1775    /// Checks that prepared calls allocate only their erased argument and result frames.
1776    #[test]
1777    fn prepared_callees_avoid_temporary_operand_allocations() {
1778        use crate::{Callable, FnOf};
1779
1780        type Args = Cons<Leaf<u64>, Nil>;
1781        type Function = FnOf<Args, Leaf<u64>>;
1782        /// Adds one through a native borrowed argument frame.
1783        fn increment(args: &<Args as ValueRepr>::Value) -> Result<u64> {
1784            args.1.checked_add(1).ok_or_else(|| anyhow!("overflow"))
1785        }
1786        let mut interpreted = DynSegment::new::<()>();
1787        interpreted.push_arg::<u64>(0);
1788        interpreted.just(1u64);
1789        interpreted
1790            .op2r(|a: u64, b: u64| a.checked_add(b).ok_or_else(|| anyhow!("overflow")))
1791            .unwrap();
1792        let interpreted =
1793            Callable::from_prepared(interpreted.prepare::<Args, Leaf<u64>>().unwrap());
1794        for function in [Callable::from_fn(increment), interpreted] {
1795            for calls in [1u64, 10, 100] {
1796                let mut body = DynSegment::new::<()>();
1797                body.just(17u64);
1798                for _ in 0..calls {
1799                    let function = function.clone();
1800                    body.op0_repr::<Function, _>(move || function.clone())
1801                        .unwrap();
1802                    body.push_arg::<u64>(0);
1803                    body.invoke_closure(1).unwrap();
1804                    body.op2r(|a: u64, b: u64| a.checked_add(b).ok_or_else(|| anyhow!("overflow")))
1805                        .unwrap();
1806                }
1807                let mut prepared = body.prepare::<Args, Leaf<u64>>().unwrap();
1808                let args = (7u64,).into_c_stack_list();
1809                let expected = 17 + calls * 8;
1810                assert_eq!(prepared.call(&args).unwrap(), expected);
1811                crate::owned_value::ALLOCATIONS.with(|count| count.set(0));
1812                for _ in 0..100 {
1813                    assert_eq!(prepared.call(&args).unwrap(), expected);
1814                }
1815                let allocations = crate::owned_value::ALLOCATIONS.with(Cell::get);
1816                assert_eq!(allocations, 200 * calls as usize, "{calls} calls");
1817            }
1818        }
1819    }
1820
1821    /// Checks that prepared indexing allocates only the erased array and selected value.
1822    #[test]
1823    fn prepared_indices_avoid_temporary_operand_allocations() {
1824        for accesses in [1u64, 10, 100] {
1825            let mut body = DynSegment::new::<()>();
1826            body.just(17u64);
1827            for _ in 0..accesses {
1828                let array = Array::from_vec(vec![7u64]);
1829                body.op0_repr::<ArrayOf<Leaf<u64>>, _>(move || array.clone())
1830                    .unwrap();
1831                body.push_arg::<i32>(0);
1832                body.array_index::<i32>().unwrap();
1833                body.op2r(|a: u64, b: u64| a.checked_add(b).ok_or_else(|| anyhow!("overflow")))
1834                    .unwrap();
1835            }
1836            let mut prepared = body.prepare::<Cons<Leaf<i32>, Nil>, Leaf<u64>>().unwrap();
1837            let args = (0i32,).into_c_stack_list();
1838            let expected = 17 + accesses * 7;
1839            assert_eq!(prepared.call(&args).unwrap(), expected);
1840            crate::owned_value::ALLOCATIONS.with(|count| count.set(0));
1841            for _ in 0..100 {
1842                assert_eq!(prepared.call(&args).unwrap(), expected);
1843            }
1844            let allocations = crate::owned_value::ALLOCATIONS.with(Cell::get);
1845            assert_eq!(allocations, 200 * accesses as usize, "{accesses} accesses");
1846        }
1847    }
1848
1849    /// Checks callee, argument, and aligned ambient ownership across retries and unwinding.
1850    #[test]
1851    fn prepared_callee_moves_preserve_error_and_unwind_cleanup() {
1852        use crate::{Callable, FnOf};
1853
1854        type Args = Cons<Leaf<CloneDrop>, Nil>;
1855        type Function = FnOf<Args, Leaf<u64>>;
1856        let events = Rc::new(RefCell::new(Vec::new()));
1857        let mode = Rc::new(Cell::new(0u8));
1858        let leaf = |name| CloneDrop {
1859            name,
1860            events: events.clone(),
1861            fail: Rc::new(Cell::new(false)),
1862            owned: true,
1863        };
1864        let mut body = DynSegment::new::<()>();
1865        let ambient = leaf("ambient");
1866        body.op0(move || ambient.clone());
1867        body.just(9u8);
1868        let callee_events = events.clone();
1869        let callee_mode = mode.clone();
1870        body.op0_repr::<Function, _>(move || {
1871            let sentinel = CloneDrop {
1872                name: "callee",
1873                events: callee_events.clone(),
1874                fail: Rc::new(Cell::new(false)),
1875                owned: true,
1876            };
1877            let mode = callee_mode.clone();
1878            let mut inner = DynSegment::new::<()>();
1879            inner.push_arg::<CloneDrop>(0);
1880            inner
1881                .op1r(move |argument: CloneDrop| {
1882                    let _sentinel = &sentinel;
1883                    drop(argument);
1884                    match mode.get() {
1885                        0 => Ok(7u64),
1886                        1 => Err(anyhow!("callee failure")),
1887                        _ => panic!("callee panic"),
1888                    }
1889                })
1890                .unwrap();
1891            Callable::from_prepared(inner.prepare::<Args, Leaf<u64>>().unwrap())
1892        })
1893        .unwrap();
1894        let argument = leaf("argument");
1895        body.op0(move || argument.clone());
1896        body.invoke_closure(1).unwrap();
1897        body.op3(|ambient: CloneDrop, marker: u8, value: u64| {
1898            assert_eq!(marker, 9);
1899            drop(ambient);
1900            value
1901        })
1902        .unwrap();
1903        let mut prepared = body.prepare::<Nil, Leaf<u64>>().unwrap();
1904        let args = ().into_c_stack_list();
1905        for _ in 0..2 {
1906            for next in [0, 1, 0, 2, 0] {
1907                mode.set(next);
1908                let result = catch_unwind(AssertUnwindSafe(|| prepared.call(&args)));
1909                match next {
1910                    0 => assert_eq!(result.unwrap().unwrap(), 7),
1911                    1 => assert_eq!(result.unwrap().unwrap_err().to_string(), "callee failure"),
1912                    _ => assert!(result.is_err()),
1913                }
1914                let expected = if next == 2 {
1915                    ["argument", "callee", "argument", "ambient"]
1916                } else {
1917                    ["argument", "argument", "callee", "ambient"]
1918                };
1919                assert_eq!(&*events.borrow(), &expected);
1920                events.borrow_mut().clear();
1921            }
1922        }
1923    }
1924
1925    /// Owns an over-aligned index whose conversion can succeed, fail, or unwind.
1926    #[repr(align(128))]
1927    struct TrackedIndex {
1928        mode: u8,
1929        events: Rc<RefCell<Vec<&'static str>>>,
1930    }
1931
1932    impl TryFrom<TrackedIndex> for usize {
1933        type Error = ();
1934
1935        /// Converts valid indices, reports conversion failure, or triggers a test unwind.
1936        fn try_from(index: TrackedIndex) -> std::result::Result<Self, Self::Error> {
1937            match index.mode {
1938                0 => Ok(1),
1939                1 => Err(()),
1940                2 => panic!("index conversion panic"),
1941                _ => Ok(2),
1942            }
1943        }
1944    }
1945
1946    impl Drop for TrackedIndex {
1947        /// Records destruction of the uniquely owned index on every exit.
1948        fn drop(&mut self) {
1949            self.events.borrow_mut().push("index");
1950        }
1951    }
1952
1953    /// Checks index, array, and misaligned ambient ownership across all conversion exits.
1954    #[test]
1955    fn prepared_index_moves_preserve_error_and_unwind_cleanup() {
1956        let events = Rc::new(RefCell::new(Vec::new()));
1957        let mode = Rc::new(Cell::new(0u8));
1958        let mut body = DynSegment::new::<()>();
1959        let log = events.clone();
1960        body.op0(move || CloneDrop {
1961            name: "ambient",
1962            events: log.clone(),
1963            fail: Rc::new(Cell::new(false)),
1964            owned: true,
1965        });
1966        body.just(9u8);
1967        let origin = body.current_stack_offset();
1968        for name in ["first", "last"] {
1969            let log = events.clone();
1970            body.op0(move || CloneDrop {
1971                name,
1972                events: log.clone(),
1973                fail: Rc::new(Cell::new(false)),
1974                owned: true,
1975            });
1976        }
1977        body.make_array(2, origin).unwrap();
1978        let index_events = events.clone();
1979        let index_mode = mode.clone();
1980        body.op0(move || TrackedIndex {
1981            mode: index_mode.get(),
1982            events: index_events.clone(),
1983        });
1984        body.array_index::<TrackedIndex>().unwrap();
1985        body.op3(|ambient: CloneDrop, marker: u8, value: CloneDrop| {
1986            assert_eq!(marker, 9);
1987            drop(ambient);
1988            value
1989        })
1990        .unwrap();
1991        let mut prepared = body.prepare::<Nil, Leaf<CloneDrop>>().unwrap();
1992        let args = ().into_c_stack_list();
1993        for _ in 0..2 {
1994            for next in [0, 1, 0, 2, 0, 3, 0] {
1995                mode.set(next);
1996                let result = catch_unwind(AssertUnwindSafe(|| prepared.call(&args)));
1997                match next {
1998                    0 => drop(result.unwrap().unwrap()),
1999                    1 => assert_eq!(
2000                        result.unwrap().err().unwrap().to_string(),
2001                        "array index is negative or unrepresentable"
2002                    ),
2003                    2 => assert!(result.is_err()),
2004                    _ => assert!(
2005                        result
2006                            .unwrap()
2007                            .err()
2008                            .unwrap()
2009                            .to_string()
2010                            .contains("out of bounds")
2011                    ),
2012                }
2013                let expected = if next == 0 {
2014                    ["index", "first", "ambient", "last"]
2015                } else {
2016                    ["index", "last", "first", "ambient"]
2017                };
2018                assert_eq!(&*events.borrow(), &expected);
2019                events.borrow_mut().clear();
2020            }
2021        }
2022    }
2023
2024    /// Checks that prepared conditionals and short-circuit branches allocate no owners.
2025    #[test]
2026    fn prepared_branches_avoid_temporary_allocations() {
2027        type Inputs = Cons<Leaf<bool>, Cons<Leaf<bool>, Nil>>;
2028        for kind in ["if", "&&", "||"] {
2029            for conditions in [1u64, 10, 100] {
2030                let mut body = DynSegment::new::<()>();
2031                body.just(17u64);
2032                for _ in 0..conditions {
2033                    body.push_arg::<bool>(0);
2034                    let mut yes = body.new_fragment();
2035                    let mut no = body.new_fragment();
2036                    match kind {
2037                        "if" => {
2038                            yes.push_arg::<bool>(1);
2039                            no.push_arg::<bool>(1);
2040                            no.op1(|value: bool| !value).unwrap();
2041                        }
2042                        "&&" => {
2043                            yes.push_arg::<bool>(1);
2044                            no.just(false);
2045                        }
2046                        "||" => {
2047                            yes.just(true);
2048                            no.push_arg::<bool>(1);
2049                        }
2050                        _ => unreachable!(),
2051                    }
2052                    body.join2(yes, no).unwrap();
2053                    body.op2r(|total: u64, value: bool| {
2054                        total
2055                            .checked_add(u64::from(value))
2056                            .ok_or_else(|| anyhow!("overflow"))
2057                    })
2058                    .unwrap();
2059                }
2060                let mut prepared = body.prepare::<Inputs, Leaf<u64>>().unwrap();
2061                for condition in [false, true] {
2062                    for rhs in [false, true] {
2063                        let value = match kind {
2064                            "if" => {
2065                                if condition {
2066                                    rhs
2067                                } else {
2068                                    !rhs
2069                                }
2070                            }
2071                            "&&" => condition && rhs,
2072                            "||" => condition || rhs,
2073                            _ => unreachable!(),
2074                        };
2075                        let expected = 17 + conditions * u64::from(value);
2076                        let inputs = (condition, rhs).into_c_stack_list();
2077                        assert_eq!(prepared.call(&inputs).unwrap(), expected);
2078                        crate::owned_value::ALLOCATIONS.with(|count| count.set(0));
2079                        for _ in 0..100 {
2080                            assert_eq!(prepared.call(&inputs).unwrap(), expected);
2081                        }
2082                        let allocations = crate::owned_value::ALLOCATIONS.with(Cell::get);
2083                        assert_eq!(allocations, 0, "{kind}, {conditions} conditions");
2084                    }
2085                }
2086            }
2087        }
2088    }
2089
2090    /// Checks that scalar reads and imported constants need no temporary owners.
2091    #[test]
2092    fn scalar_cloning_avoids_temporary_allocations() {
2093        for reads in [1, 10, 100] {
2094            for external_constant in [false, true] {
2095                let mut body = DynSegment::new::<()>();
2096                for read in 0..reads {
2097                    if external_constant {
2098                        body.just_external(ValueType::cloneable_leaf::<i32>(), Box::new(1i32))
2099                            .unwrap();
2100                    } else {
2101                        body.push_arg::<i32>(0);
2102                    }
2103                    if read != 0 {
2104                        body.op2r(|a: i32, b: i32| {
2105                            a.checked_add(b).ok_or_else(|| anyhow!("overflow"))
2106                        })
2107                        .unwrap();
2108                    }
2109                }
2110                let mut prepared = body.prepare::<Cons<Leaf<i32>, Nil>, Leaf<i32>>().unwrap();
2111                let input = (1i32,).into_c_stack_list();
2112                assert_eq!(prepared.call(&input).unwrap(), reads);
2113                crate::owned_value::ALLOCATIONS.with(|count| count.set(0));
2114                for _ in 0..100 {
2115                    assert_eq!(prepared.call(&input).unwrap(), reads);
2116                }
2117                let allocations = crate::owned_value::ALLOCATIONS.with(Cell::get);
2118                eprintln!(
2119                    "{reads} reads, constant={external_constant}: {allocations} temporary allocations"
2120                );
2121                assert_eq!(allocations, 0);
2122            }
2123        }
2124    }
2125
2126    /// Checks linear descriptor work on every checked call and none after preparation.
2127    #[test]
2128    fn repeated_read_preflight_is_linear() {
2129        for reads in [1_000, 2_000, 4_000] {
2130            let mut body = DynSegment::new::<()>();
2131            body.push_arg::<i32>(0);
2132            for _ in 1..reads {
2133                body.push_arg::<i32>(0);
2134                body.op2r(|a: i32, b: i32| a.checked_add(b).ok_or_else(|| anyhow!("overflow")))
2135                    .unwrap();
2136            }
2137            for _ in 0..2 {
2138                crate::value_type::SHAPE_COMPARISONS.with(|count| count.set(0));
2139                assert_eq!(body.call_dyn::<i32>(&[&1i32]).unwrap(), reads);
2140                let comparisons = crate::value_type::SHAPE_COMPARISONS.with(Cell::get);
2141                eprintln!("{reads} checked reads: {comparisons} descriptor comparisons");
2142                assert!(comparisons <= 4 * reads as usize + 16);
2143                assert!(body.call_dyn::<i32>(&[]).is_err());
2144                assert!(body.call_dyn::<i32>(&[&1u32]).is_err());
2145            }
2146            let mut prepared = body.prepare::<Cons<Leaf<i32>, Nil>, Leaf<i32>>().unwrap();
2147            crate::value_type::SHAPE_COMPARISONS.with(|count| count.set(0));
2148            assert_eq!(prepared.call(&(1i32,).into_c_stack_list()).unwrap(), reads);
2149            crate::value_type::SHAPE_COMPARISONS.with(|count| assert_eq!(count.get(), 0));
2150        }
2151    }
2152}