Skip to main content

cel_runtime/
value_type.rs

1//! Describes complete recursive identities independently of interpreter descriptors.
2//!
3//! Witnesses name concrete Rust representations without requiring foreign types
4//! to implement a trait. Capability adapters are optional and checked separately:
5//!
6//! ```
7//! use cel_runtime::value_type::{ArrayOf, Leaf, ValueRepr, ValueType};
8//! let array = ValueType::array(ValueType::cloneable_leaf::<String>());
9//! assert!(array.same_shape(&ArrayOf::<Leaf<String>>::value_type()));
10//! ```
11
12use std::alloc::Layout;
13use std::any::TypeId;
14use std::fmt::{Debug, Write};
15use std::marker::PhantomData;
16use std::sync::Arc;
17
18use crate::array::RawArray;
19use crate::c_stack_list::CStackListHeadLimit;
20use crate::tuple_value::TupleLayout;
21use crate::{Array, CNil, CStackList};
22
23#[cfg(test)]
24thread_local! {
25    /// Counts descriptor comparisons on this test thread, including recursive calls.
26    pub(crate) static SHAPE_COMPARISONS: std::cell::Cell<usize> = const {
27        std::cell::Cell::new(0)
28    };
29}
30
31/// Seals representation witnesses and limits list tails to canonical lists.
32mod sealed {
33    use super::{AssociatedType, ValueRepr};
34
35    /// Prevents downstream implementations from inventing unsafe representations.
36    pub trait Sealed {}
37
38    /// Supplies source-ordered fields only for canonical list witnesses.
39    pub trait List: ValueRepr {
40        /// Appends this list's source-ordered fields.
41        ///
42        /// - Complexity: O(n) time and space for n fields.
43        fn fields(fields: &mut Vec<AssociatedType>);
44    }
45}
46
47/// Names a trusted concrete representation without wrapping its runtime value.
48///
49/// Only this crate implements the trait; use [`Leaf`] for any foreign host type.
50///
51/// # Examples
52///
53/// ```
54/// use cel_runtime::value_type::{ArrayOf, Leaf, ValueRepr};
55/// use cel_runtime::Array;
56/// let _: <ArrayOf<Leaf<i32>> as ValueRepr>::Value = Array::from_vec(vec![1]);
57/// ```
58pub trait ValueRepr: sealed::Sealed {
59    /// The concrete, owned Rust representation.
60    type Value: 'static;
61
62    /// Returns the complete identity, layout, and ownership plan.
63    ///
64    /// Leaves have no optional capabilities by default.
65    ///
66    /// - Complexity: O(n) time and space for n nodes in the descriptor tree.
67    ///
68    /// # Examples
69    ///
70    /// ```
71    /// use cel_runtime::value_type::{Leaf, ValueRepr, ValueType};
72    /// assert!(Leaf::<i32>::value_type().same_shape(&ValueType::leaf::<i32>()));
73    /// ```
74    fn value_type() -> ValueType;
75}
76
77/// Names an opaque host leaf of type `T`, including explicitly registered `()`.
78///
79/// Aggregate-looking host types remain opaque when explicitly named as leaves.
80///
81/// # Examples
82///
83/// ```
84/// use cel_runtime::value_type::{Leaf, ValueRepr};
85/// let _: <Leaf<String> as ValueRepr>::Value = String::new();
86/// ```
87pub struct Leaf<T>(PhantomData<fn() -> T>);
88
89/// Names a homogeneous array whose elements use witness `E`.
90///
91/// # Examples
92///
93/// ```
94/// use cel_runtime::value_type::{ArrayOf, Leaf, ValueRepr};
95/// use cel_runtime::Array;
96/// let _: <ArrayOf<Leaf<u8>> as ValueRepr>::Value = Array::from_vec(vec![1]);
97/// ```
98pub struct ArrayOf<E>(PhantomData<fn() -> E>);
99
100/// Names canonical source unit, represented by `CNil<()>`, not a host `()`.
101///
102/// # Examples
103///
104/// ```
105/// use cel_runtime::{IntoCStackList, value_type::{Nil, ValueRepr}};
106/// let _: <Nil as ValueRepr>::Value = ().into_c_stack_list();
107/// ```
108pub struct Nil;
109
110/// Names a source-first tuple head `H` followed by canonical list tail `T`.
111///
112/// # Examples
113///
114/// ```
115/// use cel_runtime::{IntoCStackList, value_type::{Cons, Leaf, Nil, ValueRepr}};
116/// let _: <Cons<Leaf<i32>, Nil> as ValueRepr>::Value = (1,).into_c_stack_list();
117/// ```
118///
119/// Noncanonical tails cannot authorize a representation:
120///
121/// ```compile_fail
122/// use cel_runtime::value_type::{Cons, Leaf, ValueRepr};
123/// let _ = Cons::<Leaf<i32>, Leaf<()>>::value_type();
124/// ```
125pub struct Cons<H, T>(PhantomData<fn() -> (H, T)>);
126
127/// Names a canonical tuple argument list, sealed to [`Nil`] and [`Cons`].
128///
129/// # Examples
130/// ```
131/// use cel_runtime::{ArgumentList, Cons, Leaf, Nil};
132/// fn list<A: ArgumentList>() {}
133/// list::<Cons<Leaf<i32>, Nil>>();
134/// ```
135pub trait ArgumentList: ValueRepr + sealed::List {}
136impl<T: sealed::List> ArgumentList for T {}
137
138/// Names a callable with a complete canonical parameter and result signature.
139///
140/// The shared carrier always clones, regardless of argument/result capabilities.
141/// Equality and default construction are not implied.
142///
143/// # Examples
144/// ```
145/// use cel_runtime::{FnOf, Nil, Leaf, ValueRepr, Callable, CNil};
146/// let _: <FnOf<Nil, Leaf<i32>> as ValueRepr>::Value =
147///     Callable::from_fn(|_: &CNil<()>| Ok(7));
148/// ```
149///
150/// Non-list arguments cannot authorize a callable representation:
151/// ```compile_fail
152/// use cel_runtime::{FnOf, Leaf, ValueRepr};
153/// let _ = FnOf::<Leaf<()>, Leaf<i32>>::value_type();
154/// ```
155pub struct FnOf<A, R>(PhantomData<fn() -> (A, R)>);
156
157impl<A: ArgumentList, R: ValueRepr> sealed::Sealed for FnOf<A, R> {}
158impl<A: ArgumentList, R: ValueRepr> ValueRepr for FnOf<A, R> {
159    type Value = crate::Callable<A::Value, R::Value>;
160
161    /// Describes every parameter and result node with canonical carrier ownership.
162    ///
163    /// - Complexity: O(n) time and storage for n signature nodes.
164    fn value_type() -> ValueType {
165        let args = A::value_type();
166        ValueType::callable(
167            args.tuple_elements()
168                .expect("sealed canonical argument list")
169                .iter()
170                .map(|field| field.value_type.clone())
171                .collect(),
172            R::value_type(),
173        )
174    }
175}
176
177impl<T: 'static> sealed::Sealed for Leaf<T> {}
178impl<T: 'static> ValueRepr for Leaf<T> {
179    /// Describes the explicitly registered opaque host representation.
180    fn value_type() -> ValueType {
181        ValueType::leaf::<T>()
182    }
183    type Value = T;
184}
185
186impl<E: ValueRepr> sealed::Sealed for ArrayOf<E> {}
187impl<E: ValueRepr> ValueRepr for ArrayOf<E> {
188    type Value = Array<E::Value>;
189    /// Describes this array and its complete concrete element representation.
190    ///
191    /// - Complexity: O(n) time and space for n element descriptor nodes.
192    fn value_type() -> ValueType {
193        ValueType::array(E::value_type())
194    }
195}
196
197impl sealed::Sealed for Nil {}
198impl ValueRepr for Nil {
199    type Value = CNil<()>;
200    /// Describes canonical source unit with its empty-list ownership plan.
201    fn value_type() -> ValueType {
202        ValueType::tuple(Vec::new()).expect("empty canonical tuple fits Layout")
203    }
204}
205impl sealed::List for Nil {
206    /// Appends no fields for canonical source unit.
207    fn fields(_: &mut Vec<AssociatedType>) {}
208}
209
210impl<H: ValueRepr, T: sealed::List> sealed::Sealed for Cons<H, T> where T::Value: CStackListHeadLimit
211{}
212impl<H: ValueRepr, T: sealed::List> ValueRepr for Cons<H, T>
213where
214    T::Value: CStackListHeadLimit,
215{
216    type Value = CStackList<H::Value, T::Value>;
217    /// Describes source-ordered fields using their canonical recursive layout.
218    ///
219    /// - Complexity: O(n) time and space for n descriptor nodes.
220    fn value_type() -> ValueType {
221        let mut fields = Vec::new();
222        <Self as sealed::List>::fields(&mut fields);
223        let descriptor = ValueType::tuple(fields).expect("concrete Rust list fits Layout");
224        debug_assert_eq!(descriptor.layout(), Layout::new::<Self::Value>());
225        descriptor
226    }
227}
228impl<H: ValueRepr, T: sealed::List> sealed::List for Cons<H, T>
229where
230    T::Value: CStackListHeadLimit,
231{
232    /// Appends the head descriptor followed by the canonical tail's descriptors.
233    ///
234    /// - Complexity: O(n) time and space for n descriptor nodes.
235    fn fields(fields: &mut Vec<AssociatedType>) {
236        fields.push(AssociatedType {
237            offset: 0,
238            value_type: H::value_type(),
239        });
240        T::fields(fields);
241    }
242}
243
244/// Identifies a value structurally, independently of aggregate storage markers.
245///
246/// Callable metadata includes every parameter and the result. Its private
247/// ownership plan uses the shared `DynClosure` carrier, exactly matching the
248/// transparent [`crate::Callable`] facade authorized by [`FnOf`].
249///
250/// # Examples
251///
252/// ```
253/// use cel_runtime::value_type::{ValueKind, ValueType};
254/// assert!(matches!(ValueType::leaf::<i32>().kind(), ValueKind::Leaf(_)));
255/// ```
256#[derive(Clone, Debug)]
257pub enum ValueKind {
258    /// A single explicitly registered opaque Rust type.
259    Leaf(TypeId),
260    /// Source-ordered fields with canonical physical offsets.
261    Tuple(Vec<AssociatedType>),
262    /// One complete homogeneous element descriptor.
263    Array(ValueType),
264    /// Complete semantic callable signature for the shared closure carrier.
265    Callable {
266        /// Parameter types in source order.
267        parameters: Vec<ValueType>,
268        /// The complete result type, including source unit or aggregates.
269        result: Box<ValueType>,
270    },
271}
272
273/// Associates a source-ordered tuple field with its canonical physical offset.
274///
275/// [`ValueType::tuple`] replaces supplied offsets; callers cannot forge layout.
276///
277/// # Examples
278///
279/// ```
280/// use cel_runtime::value_type::{AssociatedType, ValueType};
281/// let field = AssociatedType { offset: 0, value_type: ValueType::leaf::<i32>() };
282/// assert!(ValueType::tuple(vec![field]).is_ok());
283/// ```
284#[derive(Clone, Debug)]
285pub struct AssociatedType {
286    /// Byte offset relative to the enclosing canonical list.
287    pub offset: usize,
288    /// Complete field identity and ownership metadata.
289    pub value_type: ValueType,
290}
291
292/// Clones a live concrete value into aligned, disjoint uninitialized storage.
293type CloneHook = unsafe fn(*const u8, *mut u8);
294/// Compares two live values of one validated concrete representation.
295type EqualityHook = unsafe fn(*const u8, *const u8) -> bool;
296/// Formats a live value of one validated concrete representation.
297type DebugHook = unsafe fn(*const u8, &mut String);
298/// Destroys a live leaf of the registered concrete type exactly once.
299type DropHook = unsafe fn(*mut u8);
300
301/// Freezes one descriptor's ownership and independent capability plans.
302#[derive(Clone, Debug)]
303struct Plan {
304    /// Retains the complete recursive representation identity.
305    kind: ValueKind,
306    /// Retains the representation's exact allocation layout.
307    layout: Layout,
308    /// Destroys a concrete opaque leaf; containers use their recursive children.
309    leaf_drop: Option<DropHook>,
310    /// Clones a concrete leaf when that optional capability is registered.
311    clone_hook: Option<CloneHook>,
312    /// Compares concrete leaves when that optional capability is registered.
313    equality_hook: Option<EqualityHook>,
314    /// Formats a concrete leaf when that optional capability is registered.
315    debug_hook: Option<DebugHook>,
316    /// Caches whether every node has the required cloning capabilities.
317    cloneable: bool,
318    /// Caches whether every node has the required comparison capabilities.
319    comparable: bool,
320    /// Caches whether every node has the required formatting capabilities.
321    debuggable: bool,
322    /// Moves an exact concrete scalar box through the checked host boundary.
323    host_leaf: Option<crate::host_value_bridge::LeafBridge>,
324}
325
326/// Owns immutable recursive identity, canonical layout, and trusted operations.
327///
328/// Capabilities never change type identity. Cloning a descriptor shares its
329/// frozen plan; capability installation returns an independently updated plan.
330///
331/// # Examples
332///
333/// ```
334/// use cel_runtime::value_type::ValueType;
335/// let a = ValueType::array(ValueType::leaf::<i32>());
336/// let b = ValueType::array(ValueType::cloneable_leaf::<i32>());
337/// assert!(a.same_shape(&b));
338/// ```
339#[derive(Clone, Debug)]
340pub struct ValueType(Arc<Plan>);
341
342impl ValueType {
343    /// Sets an opaque leaf's diagnostic name without changing identity or capabilities.
344    ///
345    /// Structural descriptors retain their recursively defined names.
346    ///
347    /// # Examples
348    /// ```
349    /// let ty = cel_runtime::ValueType::leaf::<i32>().with_type_name("Integer");
350    /// assert_eq!(ty.type_name(), "Integer");
351    /// ```
352    pub fn with_type_name(mut self, name: impl Into<std::borrow::Cow<'static, str>>) -> Self {
353        if let Some(host) = Arc::make_mut(&mut self.0).host_leaf.as_mut() {
354            host.name = name.into();
355        }
356        self
357    }
358
359    /// Rejects erased whole-value owners as opaque canonical elements.
360    ///
361    /// # Errors
362    /// Rejects an `OwnedValue` leaf at any recursive node; owners require a checked whole-value boundary.
363    /// - Complexity: O(n) traversal for n descriptor nodes.
364    pub(crate) fn validate_canonical(&self) -> anyhow::Result<()> {
365        match self.kind() {
366            ValueKind::Leaf(id) => anyhow::ensure!(
367                *id != TypeId::of::<crate::OwnedValue>(),
368                "whole-value owners cannot be opaque canonical elements"
369            ),
370            ValueKind::Array(element) => element.validate_canonical()?,
371            ValueKind::Tuple(fields) => {
372                for field in fields {
373                    field.value_type.validate_canonical()?;
374                }
375            }
376            ValueKind::Callable { parameters, result } => {
377                for parameter in parameters {
378                    parameter.validate_canonical()?;
379                }
380                result.validate_canonical()?;
381            }
382        }
383        Ok(())
384    }
385
386    /// Returns whether the complete frozen plan supports borrowed argument cloning.
387    ///
388    /// # Examples
389    /// ```
390    /// assert!(cel_runtime::ValueType::cloneable_leaf::<i32>().can_clone_for_argument());
391    /// ```
392    pub fn can_clone_for_argument(&self) -> bool {
393        self.can_clone()
394    }
395    /// Returns a diagnostic carrier identity; structural casts require witnesses.
396    ///
397    /// # Examples
398    /// ```
399    /// assert_eq!(cel_runtime::ValueType::leaf::<i32>().type_id(), std::any::TypeId::of::<i32>());
400    /// ```
401    pub fn type_id(&self) -> TypeId {
402        match self.kind() {
403            ValueKind::Leaf(id) => *id,
404            ValueKind::Tuple(_) => TypeId::of::<crate::CNil<()>>(),
405            ValueKind::Array(_) => TypeId::of::<RawArray>(),
406            ValueKind::Callable { .. } => TypeId::of::<crate::DynClosure>(),
407        }
408    }
409
410    /// Returns a human-readable diagnostic representation name.
411    ///
412    /// # Examples
413    /// ```
414    /// assert_eq!(cel_runtime::ValueType::leaf::<i32>().type_name(), "i32");
415    /// ```
416    pub fn type_name(&self) -> &str {
417        match self.kind() {
418            ValueKind::Leaf(_) => self.host_leaf().map_or("opaque", |host| host.name()),
419            ValueKind::Tuple(_) => "canonical tuple",
420            ValueKind::Array(_) => "canonical array",
421            ValueKind::Callable { .. } => "callable",
422        }
423    }
424
425    /// Returns the canonical representation size.
426    ///
427    /// # Examples
428    /// ```
429    /// assert_eq!(cel_runtime::ValueType::leaf::<i32>().size(), 4);
430    /// ```
431    pub fn size(&self) -> usize {
432        self.layout().size()
433    }
434
435    /// Returns the canonical representation alignment.
436    ///
437    /// # Examples
438    /// ```
439    /// assert_eq!(cel_runtime::ValueType::leaf::<u8>().align(), 1);
440    /// ```
441    pub fn align(&self) -> usize {
442        self.layout().align()
443    }
444
445    /// Borrows source-ordered canonical tuple fields, including empty source unit.
446    ///
447    /// # Examples
448    /// ```
449    /// assert!(cel_runtime::ValueType::leaf::<i32>().tuple_elements().is_none());
450    /// ```
451    pub fn tuple_elements(&self) -> Option<&[AssociatedType]> {
452        match self.kind() {
453            ValueKind::Tuple(fields) => Some(fields),
454            _ => None,
455        }
456    }
457
458    /// Borrows the complete canonical array element descriptor.
459    ///
460    /// # Examples
461    /// ```
462    /// assert!(cel_runtime::ValueType::array(cel_runtime::ValueType::leaf::<i32>()).array_element().is_some());
463    /// ```
464    pub fn array_element(&self) -> Option<&ValueType> {
465        match self.kind() {
466            ValueKind::Array(element) => Some(element),
467            _ => None,
468        }
469    }
470
471    /// Registers a borrowed canonical argument read using this complete clone plan.
472    ///
473    /// # Errors
474    /// Rejects unavailable cloning or an unrepresentable destination frame.
475    /// - Complexity: O(n) registration for n existing stack slots.
476    ///
477    /// # Examples
478    /// ```
479    /// let mut body = cel_runtime::DynSegment::new::<()>();
480    /// cel_runtime::ValueType::cloneable_leaf::<i32>().push_argument(&mut body, 0).unwrap();
481    /// ```
482    pub fn push_argument(
483        &self,
484        segment: &mut crate::DynSegment,
485        index: usize,
486    ) -> anyhow::Result<()> {
487        segment.push_argument(index, self.clone())
488    }
489
490    /// Checks the borrowed whole-value clone capability.
491    ///
492    /// # Errors
493    /// Rejects a descriptor whose frozen plan cannot clone its representation.
494    pub(crate) fn validate_clone(&self) -> anyhow::Result<()> {
495        anyhow::ensure!(self.can_clone(), "argument clone capability unavailable");
496        Ok(())
497    }
498
499    /// Describes an opaque host leaf without requiring optional capabilities.
500    ///
501    /// # Examples
502    ///
503    /// ```
504    /// use cel_runtime::value_type::ValueType;
505    /// assert!(!ValueType::leaf::<i32>().same_shape(&ValueType::leaf::<u32>()));
506    /// ```
507    pub fn leaf<T: 'static>() -> Self {
508        Self(Arc::new(Plan {
509            kind: ValueKind::Leaf(TypeId::of::<T>()),
510            layout: Layout::new::<T>(),
511            leaf_drop: Some(drop_leaf::<T>),
512            clone_hook: None,
513            equality_hook: None,
514            debug_hook: None,
515            cloneable: false,
516            comparable: false,
517            debuggable: false,
518            host_leaf: Some(crate::host_value_bridge::LeafBridge::new::<T>()),
519        }))
520    }
521
522    /// Describes an opaque host leaf with cloning but no other capabilities.
523    ///
524    /// # Examples
525    ///
526    /// ```
527    /// use cel_runtime::value_type::ValueType;
528    /// let _ = ValueType::cloneable_leaf::<String>();
529    /// ```
530    pub fn cloneable_leaf<T: Clone + 'static>() -> Self {
531        Self::leaf::<T>()
532            .with_clone::<Leaf<T>>()
533            .expect("identical leaf representation")
534    }
535
536    /// Describes a known signature using the existing shared closure carrier.
537    ///
538    /// Cloning shares the compiled body, independent of parameter/result clone
539    /// capabilities. Equality is unavailable; formatting describes the carrier.
540    /// This constructor installs ownership directly from the statically known
541    /// carrier, not from an opaque leaf witness.
542    ///
543    /// - Complexity: O(1), transferring ownership of the signature.
544    ///
545    /// # Examples
546    /// ```
547    /// use cel_runtime::{ValueType, FnOf, Nil, Leaf, ValueRepr};
548    /// assert!(ValueType::callable(vec![], ValueType::leaf::<i32>())
549    ///     .same_shape(&FnOf::<Nil, Leaf<i32>>::value_type()));
550    /// ```
551    pub fn callable(parameters: Vec<ValueType>, result: ValueType) -> Self {
552        Self(Arc::new(Plan {
553            kind: ValueKind::Callable {
554                parameters,
555                result: Box::new(result),
556            },
557            layout: Layout::new::<crate::DynClosure>(),
558            leaf_drop: Some(drop_leaf::<crate::DynClosure>),
559            clone_hook: Some(clone_leaf::<crate::DynClosure>),
560            equality_hook: None,
561            debug_hook: Some(debug_leaf::<crate::DynClosure>),
562            cloneable: true,
563            comparable: false,
564            debuggable: true,
565            host_leaf: None,
566        }))
567    }
568
569    /// Describes a homogeneous array using the fixed owning header.
570    ///
571    /// Recursive capabilities are present exactly when the element supports them.
572    ///
573    /// # Examples
574    ///
575    /// ```
576    /// use cel_runtime::value_type::{ArrayOf, Leaf, ValueRepr, ValueType};
577    /// assert!(ValueType::array(ValueType::leaf::<i32>())
578    ///     .same_shape(&ArrayOf::<Leaf<i32>>::value_type()));
579    /// ```
580    pub fn array(element: ValueType) -> Self {
581        let cloneable = element.0.cloneable;
582        let comparable = element.0.comparable;
583        let debuggable = element.0.debuggable;
584        Self(Arc::new(Plan {
585            kind: ValueKind::Array(element),
586            layout: Layout::new::<RawArray>(),
587            leaf_drop: None,
588            clone_hook: None,
589            equality_hook: None,
590            debug_hook: None,
591            cloneable,
592            comparable,
593            debuggable,
594            host_leaf: None,
595        }))
596    }
597
598    /// Computes canonical tuple layout from source-ordered fields.
599    ///
600    /// Supplied offsets are ignored. Empty input describes canonical source unit.
601    ///
602    /// - Complexity: O(n) time and space for n immediate fields.
603    ///
604    /// # Errors
605    ///
606    /// Returns an error if the recursive padded layout exceeds [`Layout`]'s bounds.
607    ///
608    /// # Examples
609    ///
610    /// ```
611    /// use cel_runtime::value_type::{Nil, ValueRepr, ValueType};
612    /// assert!(ValueType::tuple(vec![]).unwrap().same_shape(&Nil::value_type()));
613    /// ```
614    pub fn tuple(mut elements: Vec<AssociatedType>) -> anyhow::Result<Self> {
615        let fields: Vec<_> = elements
616            .iter()
617            .map(|field| field.value_type.layout())
618            .collect();
619        let layout = TupleLayout::from_fields(&fields)?;
620        for (field, offset) in elements.iter_mut().zip(layout.offsets) {
621            field.offset = offset;
622        }
623        let cloneable = elements.iter().all(|field| field.value_type.0.cloneable);
624        let comparable = elements.iter().all(|field| field.value_type.0.comparable);
625        let debuggable = elements.iter().all(|field| field.value_type.0.debuggable);
626        Ok(Self(Arc::new(Plan {
627            kind: ValueKind::Tuple(elements),
628            layout: layout.layout,
629            leaf_drop: None,
630            clone_hook: None,
631            equality_hook: None,
632            debug_hook: None,
633            cloneable,
634            comparable,
635            debuggable,
636            host_leaf: None,
637        })))
638    }
639
640    /// Borrows the complete semantic shape without permitting mutation.
641    ///
642    /// # Examples
643    ///
644    /// ```
645    /// use cel_runtime::value_type::{Nil, ValueKind, ValueRepr};
646    /// assert!(matches!(Nil::value_type().kind(), ValueKind::Tuple(_)));
647    /// ```
648    pub fn kind(&self) -> &ValueKind {
649        &self.0.kind
650    }
651
652    /// Returns the validated complete physical layout.
653    ///
654    /// # Examples
655    ///
656    /// ```
657    /// use cel_runtime::value_type::ValueType;
658    /// assert_eq!(ValueType::leaf::<u64>().layout(), std::alloc::Layout::new::<u64>());
659    /// ```
660    pub fn layout(&self) -> Layout {
661        self.0.layout
662    }
663
664    /// Compares complete semantic identities and every physical field layout.
665    ///
666    /// Capability differences do not affect identity. Equal size and alignment
667    /// alone never authorize a cast.
668    ///
669    /// - Complexity: O(n) time and O(d) call space for n nodes and nesting depth d.
670    ///
671    /// # Examples
672    ///
673    /// ```
674    /// use cel_runtime::value_type::ValueType;
675    /// assert!(!ValueType::array(ValueType::leaf::<i32>())
676    ///     .same_shape(&ValueType::array(ValueType::leaf::<u32>())));
677    /// ```
678    pub fn same_shape(&self, other: &Self) -> bool {
679        #[cfg(test)]
680        SHAPE_COMPARISONS.with(|count| count.set(count.get().saturating_add(1)));
681        self.layout() == other.layout() && same_kind(self.kind(), other.kind())
682    }
683
684    /// Checks concrete identity for a legacy conversion that names only a host leaf.
685    ///
686    /// Structural values require explicit representation witnesses, regardless
687    /// of a shared carrier ID or equal layout. This checks metadata only and
688    /// does not change the existing typed segment conversion.
689    ///
690    /// # Errors
691    ///
692    /// Returns an error for structural descriptors or a different leaf identity.
693    ///
694    /// # Examples
695    ///
696    /// ```
697    /// use std::any::TypeId;
698    /// use cel_runtime::value_type::ValueType;
699    /// assert!(ValueType::leaf::<String>()
700    ///     .validate_opaque_leaf(TypeId::of::<String>()).is_ok());
701    /// assert!(ValueType::tuple(vec![]).unwrap()
702    ///     .validate_opaque_leaf(TypeId::of::<()>()).is_err());
703    /// ```
704    pub fn validate_opaque_leaf(&self, type_id: TypeId) -> anyhow::Result<()> {
705        anyhow::ensure!(
706            matches!(self.kind(), ValueKind::Leaf(id) if *id == type_id),
707            "value requires a matching opaque leaf or an explicit structural witness"
708        );
709        Ok(())
710    }
711
712    /// Installs a concrete clone adapter after validating the entire witness.
713    ///
714    /// - Complexity: O(n) time and space for n descriptor nodes.
715    ///
716    /// # Errors
717    ///
718    /// Returns an error on any semantic or physical representation mismatch.
719    ///
720    /// # Examples
721    ///
722    /// ```
723    /// use cel_runtime::value_type::{Leaf, ValueType};
724    /// assert!(ValueType::leaf::<i32>().with_clone::<Leaf<i32>>().is_ok());
725    /// ```
726    pub fn with_clone<R: ValueRepr>(mut self) -> anyhow::Result<Self>
727    where
728        R::Value: Clone,
729    {
730        self.validate::<R>()?;
731        let plan = Arc::make_mut(&mut self.0);
732        plan.clone_hook = Some(clone_leaf::<R::Value>);
733        plan.cloneable = true;
734        Ok(self)
735    }
736
737    /// Installs concrete equality independently of cloning and formatting.
738    ///
739    /// - Complexity: O(n) time and space for n descriptor nodes.
740    ///
741    /// # Errors
742    ///
743    /// Returns an error on any semantic or physical representation mismatch.
744    ///
745    /// # Examples
746    ///
747    /// ```
748    /// use cel_runtime::value_type::{Leaf, ValueType};
749    /// assert!(ValueType::leaf::<i32>().with_equality::<Leaf<i32>>().is_ok());
750    /// ```
751    pub fn with_equality<R: ValueRepr>(mut self) -> anyhow::Result<Self>
752    where
753        R::Value: PartialEq,
754    {
755        self.validate::<R>()?;
756        let plan = Arc::make_mut(&mut self.0);
757        plan.equality_hook = Some(equal_leaf::<R::Value>);
758        plan.comparable = true;
759        Ok(self)
760    }
761
762    /// Installs concrete debug formatting independently of other capabilities.
763    ///
764    /// - Complexity: O(n) time and space for n descriptor nodes.
765    ///
766    /// # Errors
767    ///
768    /// Returns an error on any semantic or physical representation mismatch.
769    ///
770    /// # Examples
771    ///
772    /// ```
773    /// use cel_runtime::value_type::{Leaf, ValueType};
774    /// assert!(ValueType::leaf::<i32>().with_debug::<Leaf<i32>>().is_ok());
775    /// ```
776    pub fn with_debug<R: ValueRepr>(mut self) -> anyhow::Result<Self>
777    where
778        R::Value: Debug,
779    {
780        self.validate::<R>()?;
781        let plan = Arc::make_mut(&mut self.0);
782        plan.debug_hook = Some(debug_leaf::<R::Value>);
783        plan.debuggable = true;
784        Ok(self)
785    }
786
787    /// Validates a concrete adapter before any raw operations are installed.
788    ///
789    /// - Complexity: O(n) time and space for n witness nodes.
790    ///
791    /// # Errors
792    ///
793    /// Returns an error if the full descriptor differs from the sealed witness.
794    pub(crate) fn validate<R: ValueRepr>(&self) -> anyhow::Result<()> {
795        anyhow::ensure!(
796            self.same_shape(&R::value_type()),
797            "value representation mismatch"
798        );
799        Ok(())
800    }
801
802    /// Returns whether the frozen plan can clone every required child.
803    pub(crate) fn can_clone(&self) -> bool {
804        self.0.cloneable
805    }
806
807    /// Returns whether this complete descriptor supplies value equality.
808    ///
809    /// # Examples
810    /// ```
811    /// assert!(!cel_runtime::ValueType::leaf::<i32>().can_compare());
812    /// ```
813    pub fn can_compare(&self) -> bool {
814        self.0.comparable
815    }
816
817    /// Returns whether the frozen plan can format every required child.
818    pub(crate) fn can_debug(&self) -> bool {
819        self.0.debuggable
820    }
821
822    /// Returns the optional prevalidated whole-representation clone adapter.
823    pub(crate) fn clone_hook(&self) -> Option<CloneHook> {
824        self.0.clone_hook
825    }
826
827    /// Returns the optional prevalidated whole-representation equality adapter.
828    pub(crate) fn equality_hook(&self) -> Option<EqualityHook> {
829        self.0.equality_hook
830    }
831
832    /// Returns the optional prevalidated whole-representation formatting adapter.
833    pub(crate) fn debug_hook(&self) -> Option<DebugHook> {
834        self.0.debug_hook
835    }
836
837    /// Returns the concrete leaf or callable destructor, absent for tuples and arrays.
838    pub(crate) fn leaf_drop(&self) -> Option<DropHook> {
839        self.0.leaf_drop
840    }
841
842    /// Borrows concrete host adapters installed while the leaf type is known.
843    pub(crate) fn host_leaf(&self) -> Option<&crate::host_value_bridge::LeafBridge> {
844        self.0.host_leaf.as_ref()
845    }
846}
847
848/// Compares recursive shapes, including callable argument and result identities.
849///
850/// - Complexity: O(n) time and O(d) call space for n nodes and depth d.
851fn same_kind(left: &ValueKind, right: &ValueKind) -> bool {
852    match (left, right) {
853        (ValueKind::Leaf(a), ValueKind::Leaf(b)) => a == b,
854        (ValueKind::Array(a), ValueKind::Array(b)) => a.same_shape(b),
855        (ValueKind::Tuple(a), ValueKind::Tuple(b)) => {
856            a.len() == b.len()
857                && a.iter()
858                    .zip(b)
859                    .all(|(a, b)| a.offset == b.offset && a.value_type.same_shape(&b.value_type))
860        }
861        (
862            ValueKind::Callable {
863                parameters: a,
864                result: ar,
865            },
866            ValueKind::Callable {
867                parameters: b,
868                result: br,
869            },
870        ) => {
871            a.len() == b.len() && a.iter().zip(b).all(|(a, b)| a.same_shape(b)) && ar.same_shape(br)
872        }
873        _ => false,
874    }
875}
876
877/// Destroys one live leaf.
878///
879/// - Complexity: The concrete type's destructor costs apply.
880///
881/// # Safety
882///
883/// `pointer` must address an exclusively owned, aligned, live `T`.
884unsafe fn drop_leaf<T>(pointer: *mut u8) {
885    unsafe { pointer.cast::<T>().drop_in_place() };
886}
887
888/// Clones a live value into a disjoint, aligned uninitialized destination.
889///
890/// - Complexity: The concrete type's clone time and allocation costs apply.
891///
892/// # Safety
893///
894/// `source` must address a live `T`; `destination` must hold uninitialized `T`
895/// storage. On panic no destination value is initialized.
896unsafe fn clone_leaf<T: Clone>(source: *const u8, destination: *mut u8) {
897    unsafe {
898        destination
899            .cast::<T>()
900            .write((&*source.cast::<T>()).clone())
901    };
902}
903
904/// Compares two live values without taking ownership.
905///
906/// - Complexity: The concrete type's equality costs apply.
907///
908/// # Safety
909///
910/// Both pointers must address aligned live values of `T` for this call.
911unsafe fn equal_leaf<T: PartialEq>(left: *const u8, right: *const u8) -> bool {
912    unsafe { *left.cast::<T>() == *right.cast::<T>() }
913}
914
915/// Appends one live value's debug representation without taking ownership.
916///
917/// - Complexity: The concrete formatter's time and output storage costs apply.
918///
919/// # Safety
920///
921/// `pointer` must address an aligned live value of `T` for this call.
922unsafe fn debug_leaf<T: Debug>(pointer: *const u8, output: &mut String) {
923    unsafe { write!(output, "{:?}", *pointer.cast::<T>()) }
924        .expect("debug formatter writes to a string");
925}
926
927#[cfg(test)]
928mod tests {
929    use super::{ValueKind, ValueType, same_kind};
930
931    /// Rejects structural descriptors when a legacy host conversion names only a leaf.
932    #[test]
933    fn complete_factory_legacy_leaf_validation_requires_concrete_identity() {
934        use std::any::TypeId;
935        assert!(
936            ValueType::leaf::<()>()
937                .validate_opaque_leaf(TypeId::of::<()>())
938                .is_ok()
939        );
940        assert!(
941            ValueType::leaf::<i32>()
942                .validate_opaque_leaf(TypeId::of::<u32>())
943                .is_err()
944        );
945        for (structural, marker) in [
946            (
947                ValueType::tuple(vec![]).unwrap(),
948                TypeId::of::<crate::CNil<()>>(),
949            ),
950            (
951                ValueType::array(ValueType::leaf::<i32>()),
952                TypeId::of::<crate::Array<i32>>(),
953            ),
954            (
955                ValueType::callable(vec![], ValueType::leaf::<()>()),
956                TypeId::of::<crate::DynClosure>(),
957            ),
958        ] {
959            assert!(structural.validate_opaque_leaf(marker).is_err());
960        }
961    }
962
963    /// Builds semantic callable metadata without constructing an execution carrier.
964    fn signature(parameter: ValueType, result: ValueType) -> ValueKind {
965        ValueKind::Callable {
966            parameters: vec![parameter],
967            result: Box::new(result),
968        }
969    }
970
971    /// Verifies complete callable parameter and result shapes participate in identity.
972    #[test]
973    fn callable_signatures_compare_every_shape() {
974        let signature_a = signature(
975            ValueType::array(ValueType::leaf::<i32>()),
976            ValueType::tuple(vec![]).unwrap(),
977        );
978        assert!(same_kind(
979            &signature_a,
980            &signature(
981                ValueType::array(ValueType::leaf::<i32>()),
982                ValueType::tuple(vec![]).unwrap(),
983            )
984        ));
985        assert!(!same_kind(
986            &signature_a,
987            &signature(
988                ValueType::array(ValueType::leaf::<u32>()),
989                ValueType::tuple(vec![]).unwrap(),
990            )
991        ));
992        assert!(!same_kind(
993            &signature_a,
994            &signature(
995                ValueType::array(ValueType::leaf::<i32>()),
996                ValueType::leaf::<()>(),
997            )
998        ));
999        assert!(!same_kind(
1000            &signature_a,
1001            &ValueKind::Callable {
1002                parameters: vec![],
1003                result: Box::new(ValueType::tuple(vec![]).unwrap()),
1004            }
1005        ));
1006    }
1007}