Skip to main content

adam_lang/
type_registry.rs

1//! Type registry for adam-lang cell declarations.
2//!
3//! [`TypeRegistry`] maps DSL type-name strings to Rust types. Each registration
4//! stores type-erased function pointers covering:
5//! - `push_arg_fn` — registers a [`cel_runtime::DynSegment::push_arg`] op
6//! - `add_cell_fn` — creates a sheet cell from a `Box<dyn Any>` value
7//! - `add_source_fn` — creates a source-kind sheet cell (via [`Sheet::add_source`]) from a
8//!   `Box<dyn Any>` value
9//! - `call_dyn_fn` — an explicit checked host-call convenience for registered leaves
10//! - `default_fn`  — constructs a default `Box<dyn Any>` (when `Default` is available)
11//!
12//! Declare supported nominal applications with [`TypeRegistry::register_type_function`].
13//! Their ordered argument identities select concrete results independently of aliases;
14//! registering an application does not register its result for cell storage.
15//!
16//! Persistent compound storage owns canonical values, not external tuple wrappers.
17//! Sheet construction freezes complete descriptors and raw-frame adapters once;
18//! the legacy external tuple helpers below are host-boundary utilities only.
19//!
20//! # Example
21//!
22//! ```rust
23//! use adam_lang::TypeRegistry;
24//! use std::any::TypeId;
25//!
26//! let reg = TypeRegistry::new();
27//! assert_eq!(reg.get("f64").unwrap().type_id, TypeId::of::<f64>());
28//! ```
29
30use std::any::{Any, TypeId};
31use std::collections::HashMap;
32
33use adam_rs::{CellId, ConditionalId, MatchExpr, RelationshipId, Sheet};
34use cel_parser::type_functions::{TypeFunctionError, TypeFunctionRegistry};
35use cel_parser::{ResolvedLeafType, ResolvedType, TypeResolver};
36use cel_runtime::DynSegment;
37
38pub use cel_parser::TypeIdentity as TypeShape;
39
40/// Registers a `push_arg<T>(index)` op on a segment.
41///
42/// - Complexity: follows [`DynSegment::push_arg`], including segment storage growth.
43///
44/// # Examples
45///
46/// See [`TypeEntry`] for selecting a concrete registration; [`TypeRegistry::get`]
47/// retains the matching adapter and type identity together.
48pub type PushArgFn = fn(&mut DynSegment, usize);
49
50/// Adds a typed cell from a boxed value and returns its handle.
51///
52/// - Precondition: the box contains the exact registered concrete type.
53/// - Complexity: follows [`Sheet::add_cell`].
54///
55/// # Examples
56///
57/// See [`TypeEntry`] for creating a cell through its selected registration.
58pub type AddCellFn = fn(&mut Sheet, Box<dyn Any>) -> CellId;
59
60/// Adds a typed source cell (via [`Sheet::add_source`]) from a boxed value and returns its
61/// handle.
62///
63/// - Precondition: the box contains the exact registered concrete type.
64/// - Complexity: follows [`Sheet::add_source`].
65///
66/// # Examples
67///
68/// See [`TypeEntry`] for creating a source through its selected registration.
69pub type AddSourceFn = fn(&mut Sheet, Box<dyn Any>) -> CellId;
70
71/// Executes a compiled segment with the supplied inputs and boxes the result.
72///
73/// - Complexity: follows dynamic segment evaluation and concrete result cloning.
74///
75/// # Errors
76///
77/// Reports rejected argument or result types and evaluation failures.
78///
79/// # Examples
80///
81/// See [`TypeEntry`] for calling a segment with the registered argument and result adapters.
82pub type CallDynFn = fn(&mut DynSegment, &[&dyn Any]) -> anyhow::Result<Box<dyn Any>>;
83
84/// Calls `Sheet::add_conditional` with the appropriate concrete type.
85///
86/// Each branch carries a single boxed key value and the `RelationshipId`s active for that
87/// branch. The default is a list of `RelationshipId`s active when no branch key matches.
88///
89/// - Precondition: every boxed branch key contains the exact registered concrete type.
90/// - Complexity: O(b + r) time and space for b branches and r relationship identifiers,
91///   plus the sheet's conditional validation.
92///
93/// # Examples
94///
95/// See [`Sheet::add_conditional`] for branch activation and [`TypeRegistry::get`]
96/// for selecting the erased key adapter.
97pub type AddConditionalFn = fn(
98    &mut Sheet,
99    MatchExpr,
100    Vec<(Box<dyn Any>, Vec<RelationshipId>)>,
101    Vec<RelationshipId>,
102) -> Result<ConditionalId, adam_rs::Error>;
103
104/// Per-numeric-type support for a `RangeInclusive<T>`-typed filter expression, keyed by the
105/// range's own `TypeId` — populated in [`TypeRegistry::new`] for exactly the primitives
106/// `cel-parser`'s `..=` operator supports (`cel_parser::op_table`'s `RANGE_INCLUSIVE_SIGNATURES`).
107#[allow(clippy::type_complexity)] // `clamp_fn`/`bounds_fn` are inherently multi-argument fn pointers.
108#[derive(Clone)]
109pub(crate) struct RangeEntry {
110    /// `T`'s own `TypeId` — compared against a filtered cell's declared type by the caller.
111    pub(crate) element_type_id: TypeId,
112    /// Consumes an already evaluated range and clones the candidate or its nearest endpoint.
113    ///
114    /// - Precondition: the range is bound to this registered numeric type and the
115    ///   candidate has `element_type_id`.
116    pub(crate) clamp_fn: fn(cel_runtime::OwnedValue, &dyn Any) -> anyhow::Result<Box<dyn Any>>,
117    /// Consumes an evaluated range and clones both inclusive endpoints.
118    ///
119    /// - Precondition: the result is bound to this registered numeric range type.
120    pub(crate) bounds_fn:
121        fn(cel_runtime::OwnedValue) -> anyhow::Result<(Box<dyn Any>, Box<dyn Any>)>,
122}
123
124/// Metadata for a single type registered in a [`TypeRegistry`].
125///
126/// Cell/source/conditional adapters require boxed values of `type_id`; callers establish
127/// this before dispatch. Checked host calls report runtime mismatches. Erased equality
128/// returns false if either operand has another concrete type.
129///
130/// # Examples
131///
132/// ```
133/// let registry = adam_lang::TypeRegistry::new();
134/// let entry = registry.get("i32").unwrap();
135/// let mut sheet = adam_rs::Sheet::new();
136/// let cell = (entry.add_cell_fn)(&mut sheet, Box::new(7i32));
137/// assert_eq!(*sheet.read::<i32>(cell).unwrap(), 7);
138/// assert!((entry.eq_dyn_fn)(&7i32, &7i32));
139/// assert!(!(entry.eq_dyn_fn)(&"other", &"other"));
140/// let source = (entry.add_source_fn)(&mut sheet, Box::new(8i32));
141/// assert_eq!(*sheet.read::<i32>(source).unwrap(), 8);
142/// let mut segment = cel_runtime::DynSegment::new::<()>();
143/// (entry.push_arg_fn)(&mut segment, 0);
144/// let result = (entry.call_dyn_fn)(&mut segment, &[&9i32]).unwrap();
145/// assert_eq!(*result.downcast::<i32>().unwrap(), 9);
146/// ```
147#[derive(Clone)]
148pub struct TypeEntry {
149    /// Selects native recipe constructors monomorphized for this registered leaf.
150    pub(crate) template: crate::composition::LeafAdapters,
151    /// Moves an exactly bound canonical leaf into its concrete Adam storage.
152    pub(crate) box_owned: unsafe fn(cel_runtime::OwnedValue) -> Box<dyn Any>,
153    /// Runtime type identity.
154    pub type_id: TypeId,
155    /// Rust type name for error messages.
156    pub type_name: &'static str,
157    /// Registers a `push_arg<T>` op at the given argument index.
158    pub push_arg_fn: PushArgFn,
159    /// Creates a sheet cell from a `Box<dyn Any>` holding a `T`.
160    pub add_cell_fn: AddCellFn,
161    /// Creates a source-kind sheet cell (via [`Sheet::add_source`]) from a `Box<dyn Any>` holding
162    /// a `T`.
163    pub add_source_fn: AddSourceFn,
164    /// Calls `DynSegment::call_dyn::<T>` and boxes the result.
165    pub call_dyn_fn: CallDynFn,
166    /// Compares registered values; returns false if either operand has another concrete type.
167    pub eq_dyn_fn: fn(&dyn Any, &dyn Any) -> bool,
168    /// Constructs a default `T` if the type implements `Default`; otherwise `None`.
169    pub default_fn: Option<fn() -> Box<dyn Any>>,
170    /// Calls `Sheet::add_conditional::<T>` with type-erased branch keys.
171    pub add_conditional_fn: AddConditionalFn,
172    /// Builds complete concrete leaf metadata with the registered capabilities.
173    pub value_type_fn: fn() -> cel_runtime::value_type::ValueType,
174}
175
176/// Maps DSL type names to Rust types for adam-lang cell declarations.
177///
178/// Every registered concrete type remains reverse-reachable while at least one of its
179/// names survives. Registering a new alias makes it the preferred reverse name;
180/// replacing that alias selects a surviving name if one exists.
181///
182/// # Example
183///
184/// ```rust
185/// use adam_lang::TypeRegistry;
186///
187/// let mut reg = TypeRegistry::new();
188/// assert!(reg.get("i32").is_some());
189/// assert!(reg.get("unknown").is_none());
190/// ```
191#[derive(Clone)]
192pub struct TypeRegistry {
193    by_name: HashMap<String, TypeEntry>,
194    by_type_id: HashMap<TypeId, String>,
195    range_inclusive: HashMap<TypeId, RangeEntry>,
196    type_functions: TypeFunctionRegistry,
197}
198
199/// Appends a typed argument read using this registration's concrete leaf type.
200///
201/// - Complexity: follows [`DynSegment::push_arg`], including segment storage growth.
202fn push_arg_impl<T: 'static + Clone>(segment: &mut DynSegment, index: usize) {
203    segment.push_arg::<T>(index);
204}
205
206/// Moves a leaf whose exact identity was validated when preparing the adapter.
207///
208/// # Safety
209/// `value` must have the complete representation `Leaf<T>`.
210unsafe fn box_owned_impl<T: 'static>(value: cel_runtime::OwnedValue) -> Box<dyn Any> {
211    Box::new(unsafe { value.into_typed_bound::<cel_runtime::Leaf<T>>() })
212}
213
214/// Calls `Sheet::add_conditional::<T>` from type-erased branch data.
215///
216/// - Precondition: each `Box<dyn Any>` in `branches` holds a value of type `T`.
217fn add_conditional_impl<T: Any + PartialEq + 'static>(
218    sheet: &mut Sheet,
219    source: MatchExpr,
220    branches: Vec<(Box<dyn Any>, Vec<RelationshipId>)>,
221    default: Vec<RelationshipId>,
222) -> Result<ConditionalId, adam_rs::Error> {
223    debug_assert!(branches.iter().all(|(value, _)| value.is::<T>()));
224    let typed_branches: Vec<(Vec<T>, Vec<RelationshipId>)> = branches
225        .into_iter()
226        .map(|(val, rel_ids)| {
227            let v = *val
228                .downcast::<T>()
229                .expect("add_conditional_impl: type matches registration");
230            (vec![v], rel_ids)
231        })
232        .collect();
233    sheet.add_conditional::<T>(source, typed_branches, default)
234}
235
236/// Adds one cell whose boxed value has the registration's exact concrete type.
237///
238/// - Precondition: `value` contains `T`.
239fn add_cell_impl<T: Any + PartialEq + 'static>(sheet: &mut Sheet, value: Box<dyn Any>) -> CellId {
240    debug_assert!(value.is::<T>());
241    let v = value
242        .downcast::<T>()
243        .expect("add_cell_impl: type matches registration");
244    sheet.add_cell(*v)
245}
246
247/// Adds `value` to `sheet` as a source-kind cell (via [`Sheet::add_source`]), for
248/// `TypeEntry::add_source_fn`.
249///
250/// - Precondition: `value` holds a `T` matching the registration that produced this fn pointer.
251fn add_source_impl<T: Any + PartialEq + 'static>(sheet: &mut Sheet, value: Box<dyn Any>) -> CellId {
252    debug_assert!(value.is::<T>());
253    let v = value
254        .downcast::<T>()
255        .expect("add_source_impl: type matches registration");
256    sheet.add_source(*v)
257}
258
259/// Compares concrete `T` values and returns false for either mismatched operand.
260///
261/// - Complexity: the concrete type's equality cost; no additional allocation.
262fn eq_dyn_impl<T: PartialEq + 'static>(a: &dyn Any, b: &dyn Any) -> bool {
263    match (a.downcast_ref::<T>(), b.downcast_ref::<T>()) {
264        (Some(a), Some(b)) => a == b,
265        _ => false,
266    }
267}
268
269/// Executes the checked host-call boundary and boxes its concrete result.
270///
271/// # Errors
272///
273/// Reports rejected argument types, result types, or evaluation failures.
274///
275/// - Complexity: the segment's execution cost plus its result's clone cost.
276fn call_dyn_impl<T: 'static + Clone>(
277    seg: &mut DynSegment,
278    inputs: &[&dyn Any],
279) -> anyhow::Result<Box<dyn Any>> {
280    Ok(Box::new(seg.call_dyn::<T>(inputs)?))
281}
282
283/// Builds complete leaf ownership and the capabilities required by Adam registration.
284fn value_type_impl<T: Clone + PartialEq + std::fmt::Debug + 'static>()
285-> cel_runtime::value_type::ValueType {
286    use cel_runtime::value_type::{Leaf, ValueType};
287    ValueType::cloneable_leaf::<T>()
288        .with_equality::<Leaf<T>>()
289        .expect("same registered leaf")
290        .with_debug::<Leaf<T>>()
291        .expect("same registered leaf")
292}
293
294/// Consumes a bound numeric range and clones the candidate or its nearest endpoint.
295///
296/// - Precondition: `result` is bound to `RangeInclusive<T>` and `value` contains `T`.
297/// - Complexity: one value clone and at most two value comparisons.
298fn range_clamp_impl<T: Clone + PartialOrd + 'static>(
299    result: cel_runtime::OwnedValue,
300    value: &dyn Any,
301) -> anyhow::Result<Box<dyn Any>> {
302    debug_assert!(value.is::<T>());
303    // SAFETY: The registered range and cell descriptors are bound during preparation.
304    let range =
305        unsafe { result.into_typed_bound::<cel_runtime::Leaf<std::ops::RangeInclusive<T>>>() };
306    let v = unsafe { &*std::ptr::from_ref(value).cast::<T>() };
307    let clamped = if v < range.start() {
308        range.start().clone()
309    } else if v > range.end() {
310        range.end().clone()
311    } else {
312        v.clone()
313    };
314    Ok(Box::new(clamped) as Box<dyn Any>)
315}
316
317/// Consumes a bound numeric range and clones both inclusive endpoints.
318///
319/// - Precondition: `result` is bound to `RangeInclusive<T>`.
320/// - Complexity: two endpoint clones.
321fn range_bounds_impl<T: Clone + 'static>(
322    result: cel_runtime::OwnedValue,
323) -> anyhow::Result<(Box<dyn Any>, Box<dyn Any>)> {
324    // SAFETY: This callback is selected only after binding the exact range descriptor.
325    let range =
326        unsafe { result.into_typed_bound::<cel_runtime::Leaf<std::ops::RangeInclusive<T>>>() };
327    Ok((
328        Box::new(range.start().clone()) as Box<dyn Any>,
329        Box::new(range.end().clone()) as Box<dyn Any>,
330    ))
331}
332
333impl TypeRegistry {
334    /// Iterates actual Adam leaf registrations without including type-function descriptors.
335    ///
336    /// - Complexity: O(n) traversal for n registered identities.
337    pub(crate) fn cell_type_ids(&self) -> impl Iterator<Item = TypeId> + '_ {
338        self.by_type_id.keys().copied()
339    }
340
341    /// Copies registered aliases and capabilities into the data-only catalog.
342    ///
343    /// # Errors
344    /// Rejects inconsistent catalog names or identities.
345    /// - Complexity: O(n²) time and O(n) auxiliary space for registration metadata
346    ///   area n, including names and retained type-function descriptors.
347    pub(crate) fn register_checking_types(
348        &self,
349        builder: &mut cel_parser::checking::CheckingBuilder,
350    ) -> Result<(), cel_parser::checking::MetadataError> {
351        let mut registrations: Vec<_> = self.by_name.iter().collect();
352        registrations.sort_unstable_by_key(|(name, _)| *name);
353        for (name, entry) in registrations {
354            let leaf = self.resolved_leaf(name, entry);
355            builder.register_type(name, &leaf, false)?;
356        }
357        for name in self.by_type_id.values() {
358            let entry = &self.by_name[name];
359            let leaf = self.resolved_leaf(name, entry);
360            builder.set_default_available(&leaf, entry.default_fn.is_some())?;
361        }
362        builder.register_type_functions(&self.type_functions)?;
363        Ok(())
364    }
365
366    /// Registers a finite nominal application independently of argument spellings.
367    ///
368    /// This does not register its result for Adam cell storage.
369    ///
370    /// # Errors
371    /// Rejects invalid names, incomplete descriptors, and conflicting results.
372    ///
373    /// - Complexity: Expected O(n + r) time and peak space for new descriptor/name
374    ///   area n and combined old/new retained descriptor area r.
375    ///
376    /// # Examples
377    /// ```
378    /// use adam_lang::TypeRegistry;
379    /// use cel_parser::ResolvedLeafType;
380    /// let mut types = TypeRegistry::new();
381    /// types.register_type_function("Bounds", &[
382    ///     ResolvedLeafType::leaf::<i32>("Integer").unwrap().into()
383    /// ], ResolvedLeafType::leaf::<std::ops::Range<i32>>("Bounds").unwrap()).unwrap();
384    /// assert!(types.type_functions().signatures().any(|signature| signature.name == "Bounds"));
385    /// ```
386    pub fn register_type_function(
387        &mut self,
388        name: &str,
389        arguments: &[ResolvedType],
390        result: ResolvedLeafType,
391    ) -> Result<(), TypeFunctionError> {
392        if arguments.is_empty()
393            && self
394                .by_name
395                .get(name)
396                .is_some_and(|alias| alias.type_id != result.type_id())
397        {
398            return Err(TypeFunctionError(
399                "conflicting type alias and zero-operand type function".into(),
400            ));
401        }
402        if cel_parser::resolve_builtin_named_type(name, arguments)
403            .is_some_and(|builtin| builtin.type_id() != result.type_id())
404        {
405            return Err(TypeFunctionError(
406                "conflicting builtin type-function result".into(),
407            ));
408        }
409        self.type_functions.register(name, arguments, result)
410    }
411
412    /// Borrows builtin and application overloads with their effective nominal descriptors.
413    ///
414    /// # Examples
415    /// See [`Self::register_type_function`].
416    pub fn type_functions(&self) -> &TypeFunctionRegistry {
417        &self.type_functions
418    }
419
420    /// Builds a CEL-facing resolver snapshot from this registry's registered leaf types.
421    ///
422    /// The returned resolver owns leaf aliases and finite type-function descriptors,
423    /// keeping sheet construction and other Adam-specific function pointers out of
424    /// `cel-parser`.
425    ///
426    /// - Complexity: O(n + a · d) time and O(n) result space for registration
427    ///   metadata area n, a aliases, and largest effective diagnostic name size d.
428    ///
429    /// # Examples
430    ///
431    /// ```
432    /// use cel_parser::TypeResolver;
433    /// let registry = adam_lang::TypeRegistry::new();
434    /// let snapshot = registry.cel_type_resolver();
435    /// drop(registry);
436    /// assert!(snapshot.resolve_named_type("i32", &[]).is_some());
437    /// ```
438    #[must_use]
439    pub fn cel_type_resolver(&self) -> RegistryTypeResolver {
440        let by_name = self
441            .by_name
442            .iter()
443            .map(|(name, entry)| (name.clone(), self.resolved_leaf(name, entry)))
444            .collect();
445        RegistryTypeResolver {
446            by_name,
447            type_functions: self.type_functions.clone(),
448        }
449    }
450
451    /// Creates a registry pre-populated with all built-in CEL/Rust primitive types.
452    ///
453    /// Registered types: `i8`, `i16`, `i32`, `i64`, `i128`, `isize`,
454    /// `u8`, `u16`, `u32`, `u64`, `u128`, `usize`, `f32`, `f64`, `bool`, `String`.
455    ///
456    /// # Examples
457    ///
458    /// ```
459    /// let registry = adam_lang::TypeRegistry::new();
460    /// assert_eq!(registry.get("i32").unwrap().type_id, std::any::TypeId::of::<i32>());
461    /// ```
462    #[must_use]
463    pub fn new() -> Self {
464        let mut r = TypeRegistry {
465            by_name: HashMap::new(),
466            by_type_id: HashMap::new(),
467            range_inclusive: HashMap::new(),
468            type_functions: TypeFunctionRegistry::with_builtins(),
469        };
470        r.register::<i8>("i8").expect("builtin type registration");
471        r.register::<i16>("i16").expect("builtin type registration");
472        r.register::<i32>("i32").expect("builtin type registration");
473        r.register::<i64>("i64").expect("builtin type registration");
474        r.register::<i128>("i128")
475            .expect("builtin type registration");
476        r.register::<isize>("isize")
477            .expect("builtin type registration");
478        r.register::<u8>("u8").expect("builtin type registration");
479        r.register::<u16>("u16").expect("builtin type registration");
480        r.register::<u32>("u32").expect("builtin type registration");
481        r.register::<u64>("u64").expect("builtin type registration");
482        r.register::<u128>("u128")
483            .expect("builtin type registration");
484        r.register::<usize>("usize")
485            .expect("builtin type registration");
486        r.register::<f32>("f32").expect("builtin type registration");
487        r.register::<f64>("f64").expect("builtin type registration");
488        r.register::<bool>("bool")
489            .expect("builtin type registration");
490        r.register::<String>("String")
491            .expect("builtin type registration");
492        r.register_range_inclusive::<i8>();
493        r.register_range_inclusive::<i16>();
494        r.register_range_inclusive::<i32>();
495        r.register_range_inclusive::<i64>();
496        r.register_range_inclusive::<i128>();
497        r.register_range_inclusive::<isize>();
498        r.register_range_inclusive::<u8>();
499        r.register_range_inclusive::<u16>();
500        r.register_range_inclusive::<u32>();
501        r.register_range_inclusive::<u64>();
502        r.register_range_inclusive::<u128>();
503        r.register_range_inclusive::<usize>();
504        r.register_range_inclusive::<f32>();
505        r.register_range_inclusive::<f64>();
506        r
507    }
508
509    /// Registers `T` under `name` with default initialization support.
510    ///
511    /// - Postcondition: `self.get(name)` returns `Some(entry)` with `entry.default_fn.is_some()`.
512    ///   Surviving aliases remain reachable by name and concrete type identity.
513    /// # Errors
514    /// Rejects a conflicting zero-operand type function or incompatible descriptor facts.
515    ///
516    /// - Complexity: O(n + r + k) time and peak auxiliary space for n aliases,
517    ///   combined old/new retained descriptor area r, and copied or compared name bytes k.
518    ///
519    /// # Examples
520    ///
521    /// ```rust
522    /// use adam_lang::TypeRegistry;
523    /// let mut reg = TypeRegistry::new();
524    /// reg.register::<u64>("my_u64").unwrap();
525    /// assert!(reg.get("my_u64").is_some());
526    /// ```
527    pub fn register<T: Any + PartialEq + Default + Clone + std::fmt::Debug + 'static>(
528        &mut self,
529        name: &str,
530    ) -> Result<(), TypeFunctionError> {
531        let type_id = TypeId::of::<T>();
532        self.register_leaf_descriptor::<T>(name)?;
533        self.remove_registration_name(name);
534        self.by_name.insert(
535            name.to_owned(),
536            TypeEntry {
537                template: crate::composition::LeafAdapters::of::<T>(),
538                box_owned: box_owned_impl::<T>,
539                type_id,
540                type_name: std::any::type_name::<T>(),
541                push_arg_fn: push_arg_impl::<T>,
542                add_cell_fn: add_cell_impl::<T>,
543                add_source_fn: add_source_impl::<T>,
544                call_dyn_fn: call_dyn_impl::<T>,
545                eq_dyn_fn: eq_dyn_impl::<T>,
546                default_fn: Some(|| Box::new(T::default()) as Box<dyn Any>),
547                add_conditional_fn: add_conditional_impl::<T>,
548                value_type_fn: value_type_impl::<T>,
549            },
550        );
551        self.by_type_id.insert(type_id, name.to_owned());
552        Ok(())
553    }
554
555    /// Registers `T` under `name` without default initialization support.
556    ///
557    /// A cell declared as `cell x: T;` (no initializer) is a parse error for this type.
558    ///
559    /// - Postcondition: `self.get(name)` returns `Some(entry)` with `entry.default_fn.is_none()`.
560    ///   Surviving aliases remain reachable by name and concrete type identity.
561    /// # Errors
562    /// Rejects a conflicting zero-operand type function or incompatible descriptor facts.
563    ///
564    /// - Complexity: O(n + r + k) time and peak auxiliary space for n aliases,
565    ///   combined old/new retained descriptor area r, and copied or compared name bytes k.
566    ///
567    /// # Examples
568    ///
569    /// ```rust
570    /// use adam_lang::TypeRegistry;
571    /// #[derive(PartialEq, Clone, Debug)]
572    /// struct MyType(i32);
573    /// let mut reg = TypeRegistry::new();
574    /// reg.register_no_default::<MyType>("MyType").unwrap();
575    /// let entry = reg.get("MyType").unwrap();
576    /// assert!(entry.default_fn.is_none());
577    /// ```
578    pub fn register_no_default<T: Any + PartialEq + Clone + std::fmt::Debug + 'static>(
579        &mut self,
580        name: &str,
581    ) -> Result<(), TypeFunctionError> {
582        let type_id = TypeId::of::<T>();
583        self.register_leaf_descriptor::<T>(name)?;
584        self.remove_registration_name(name);
585        self.by_name.insert(
586            name.to_owned(),
587            TypeEntry {
588                template: crate::composition::LeafAdapters::of::<T>(),
589                box_owned: box_owned_impl::<T>,
590                type_id,
591                type_name: std::any::type_name::<T>(),
592                push_arg_fn: push_arg_impl::<T>,
593                add_cell_fn: add_cell_impl::<T>,
594                add_source_fn: add_source_impl::<T>,
595                call_dyn_fn: call_dyn_impl::<T>,
596                eq_dyn_fn: eq_dyn_impl::<T>,
597                default_fn: None,
598                add_conditional_fn: add_conditional_impl::<T>,
599                value_type_fn: value_type_impl::<T>,
600            },
601        );
602        self.by_type_id.insert(type_id, name.to_owned());
603        Ok(())
604    }
605
606    /// Validates source-key compatibility and retains this leaf's executable descriptor.
607    ///
608    /// # Errors
609    /// Rejects conflicting zero-operand results or incompatible descriptor facts.
610    ///
611    /// - Complexity: O(r + k) time and peak space for combined old/new retained
612    ///   descriptor area r and name bytes k.
613    fn register_leaf_descriptor<T: PartialEq + Clone + std::fmt::Debug + 'static>(
614        &mut self,
615        name: &str,
616    ) -> Result<(), TypeFunctionError> {
617        if self
618            .type_functions
619            .resolve(name, &[])
620            .is_some_and(|result| result.type_id() != TypeId::of::<T>())
621        {
622            return Err(TypeFunctionError(
623                "conflicting type alias and zero-operand type function".into(),
624            ));
625        }
626        self.type_functions
627            .register_descriptor(ResolvedLeafType::new(
628                name.to_owned(),
629                value_type_impl::<T>(),
630            ))
631    }
632
633    /// Binds a registered alias to its effective nominal capabilities.
634    ///
635    /// - Complexity: O(k) time and result space for alias and retained diagnostic name bytes k.
636    fn resolved_leaf(&self, name: &str, entry: &TypeEntry) -> ResolvedLeafType {
637        ResolvedLeafType::new(
638            name.to_owned(),
639            self.type_functions
640                .descriptor(entry.type_id)
641                .expect("registered alias descriptor")
642                .element_type()
643                .clone(),
644        )
645    }
646
647    /// Removes `name`, retaining reverse lookup through a surviving alias before replacement.
648    ///
649    /// - Complexity: O(n + k) time over n registrations and k inspected or copied
650    ///   name bytes; O(k) space for a surviving name.
651    fn remove_registration_name(&mut self, name: &str) {
652        let Some(old) = self.by_name.remove(name) else {
653            return;
654        };
655        let old_id = old.type_id;
656        if self
657            .by_type_id
658            .get(&old_id)
659            .is_none_or(|canonical| canonical != name)
660        {
661            return;
662        }
663        let remaining = self
664            .by_name
665            .iter()
666            .find(|(_, entry)| entry.type_id == old_id)
667            .map(|(alias, _)| alias.clone());
668        if let Some(alias) = remaining {
669            self.by_type_id.insert(old_id, alias);
670        } else {
671            self.by_type_id.remove(&old_id);
672        }
673    }
674
675    /// Looks up a type entry by its DSL name.
676    ///
677    /// Returns `None` if `name` has not been registered.
678    ///
679    /// - Complexity: expected O(k) time in k name bytes and O(1) space.
680    ///
681    /// # Examples
682    ///
683    /// ```rust
684    /// use adam_lang::TypeRegistry;
685    /// let reg = TypeRegistry::new();
686    /// assert!(reg.get("f64").is_some());
687    /// assert!(reg.get("nonexistent").is_none());
688    /// ```
689    #[must_use]
690    pub fn get(&self, name: &str) -> Option<&TypeEntry> {
691        self.by_name.get(name)
692    }
693
694    /// Looks up a type entry by its `TypeId`.
695    ///
696    /// Returns `None` if no type with this `TypeId` has been registered.
697    ///
698    /// - Complexity: expected O(k) time in the selected registered name's k bytes and O(1) space.
699    ///
700    /// # Examples
701    ///
702    /// ```rust
703    /// use adam_lang::TypeRegistry;
704    /// use std::any::TypeId;
705    /// let reg = TypeRegistry::new();
706    /// assert!(reg.entry_by_type_id(TypeId::of::<f64>()).is_some());
707    /// assert!(reg.entry_by_type_id(TypeId::of::<Vec<u8>>()).is_none());
708    /// ```
709    #[must_use]
710    pub fn entry_by_type_id(&self, type_id: TypeId) -> Option<&TypeEntry> {
711        let name = self.by_type_id.get(&type_id)?;
712        self.by_name.get(name)
713    }
714
715    /// Registers `RangeInclusive<T>` support for `T`, keyed by `RangeInclusive<T>`'s own
716    /// `TypeId`. Private — only called from [`TypeRegistry::new`] for the fixed set of numeric
717    /// primitives `cel-parser`'s `..=` operator supports; unlike [`TypeRegistry::register`], this
718    /// is not part of the public API a host binary extends for its own custom types, since
719    /// `RangeInclusive<T>` recognition is not extensible per-type in this codebase's current
720    /// design.
721    fn register_range_inclusive<T: Clone + PartialOrd + 'static>(&mut self) {
722        self.range_inclusive.insert(
723            TypeId::of::<std::ops::RangeInclusive<T>>(),
724            RangeEntry {
725                element_type_id: TypeId::of::<T>(),
726                clamp_fn: range_clamp_impl::<T>,
727                bounds_fn: range_bounds_impl::<T>,
728            },
729        );
730    }
731
732    /// Looks up `RangeInclusive<T>` support by the range's own `TypeId`.
733    ///
734    /// Returns `None` if `range_type_id` is not `RangeInclusive<T>` for any `T` this registry
735    /// recognizes range support for (see [`TypeRegistry::new`]).
736    #[allow(dead_code)] // Used by Task 4 (parser.rs)
737    pub(crate) fn range_entry(&self, range_type_id: TypeId) -> Option<&RangeEntry> {
738        self.range_inclusive.get(&range_type_id)
739    }
740
741    /// Resolves a parsed `type_expr` against this registry, recursively.
742    ///
743    /// # Errors
744    /// Returns an unknown leaf name, malformed callable signature, or unrepresentable layout.
745    /// Registered type functions select complete argument identities.
746    ///
747    /// - Complexity: O(n) in type nodes and registered-name bytes.
748    ///
749    /// # Examples
750    /// ```
751    /// let registry = adam_lang::TypeRegistry::new();
752    /// let ty = cel_parser::CELParser::new(cel_parser::OpLookup::new())
753    ///     .parse_type_expr_str("[(i32, [f64])]").unwrap();
754    /// assert_eq!(registry.display_name(&registry.resolve(&ty).unwrap()), "[(i32, [f64])]");
755    /// ```
756    pub fn resolve(
757        &self,
758        expr: &cel_parser::TypeExpr,
759    ) -> std::result::Result<TypeShape, (String, proc_macro2::Span)> {
760        let resolved = expr
761            .resolve(self)
762            .map_err(|error| (error.message().to_string(), error.span()))?;
763        self.shape_of(
764            &resolved
765                .into_value_type()
766                .map_err(|error| (error.to_string(), expr.span().start))?,
767        )
768        .map_err(|error| (error, expr.span().start))
769    }
770
771    /// Returns the DSL name `type_id` was registered under, or `None` if it is unregistered.
772    ///
773    /// This is the name every diagnostic should use for a live value's type: a `TypeEntry`'s own
774    /// `type_name` is the Rust type path (`alloc::string::String`), not the registered name.
775    ///
776    /// # Examples
777    ///
778    /// ```rust
779    /// use adam_lang::TypeRegistry;
780    /// let reg = TypeRegistry::new();
781    /// assert_eq!(reg.registered_name(std::any::TypeId::of::<String>()), Some("String"));
782    /// assert_eq!(reg.registered_name(std::any::TypeId::of::<Vec<u8>>()), None);
783    /// ```
784    #[must_use]
785    pub fn registered_name(&self, type_id: TypeId) -> Option<&str> {
786        self.by_type_id.get(&type_id).map(String::as_str)
787    }
788
789    /// Formats `shape` recursively using registered leaf names, or `?` for unknown leaves.
790    ///
791    /// - Complexity: O(n + b) time for n shape nodes and b result bytes; O(b + d)
792    ///   space including the result and recursion depth d.
793    ///
794    /// # Examples
795    ///
796    /// ```
797    /// use adam_lang::{TypeRegistry, type_registry::TypeShape};
798    /// let shape = TypeShape::Tuple(vec![TypeShape::Named(std::any::TypeId::of::<i32>())]);
799    /// assert_eq!(TypeRegistry::new().display_name(&shape), "(i32,)");
800    /// ```
801    #[must_use]
802    pub fn display_name(&self, shape: &TypeShape) -> String {
803        let mut output = String::new();
804        self.write_shape_name(&mut output, shape);
805        output
806    }
807
808    /// Appends a shape name without cloning shapes or allocating intermediate names.
809    ///
810    /// - Complexity: O(n + b) amortized time and O(b + d) space for n nodes,
811    ///   b appended bytes, and recursion depth d, including output growth.
812    fn write_shape_name(&self, output: &mut String, shape: &TypeShape) {
813        match shape {
814            TypeShape::Named(type_id) => {
815                output.push_str(self.registered_name(*type_id).unwrap_or("?"));
816            }
817            TypeShape::Tuple(elements) => self.write_tuple_name(output, elements),
818            TypeShape::Array(element) => {
819                output.push('[');
820                self.write_shape_name(output, element);
821                output.push(']');
822            }
823            TypeShape::Callable(parameters, result) => {
824                output.push_str("Fn(");
825                self.write_tuple_name(output, parameters);
826                output.push_str(", ");
827                self.write_shape_name(output, result);
828                output.push(')');
829            }
830        }
831    }
832
833    /// Appends a tuple name, including the required terminal comma for one element.
834    ///
835    /// - Complexity: O(n + b) amortized time and O(b + d) space over n reachable
836    ///   shape nodes, b appended bytes, and recursion depth d, including output growth.
837    fn write_tuple_name(&self, output: &mut String, elements: &[TypeShape]) {
838        output.push('(');
839        // Emit each borrowed element directly into the shared output.
840        for (index, element) in elements.iter().enumerate() {
841            if index != 0 {
842                output.push_str(", ");
843            }
844            self.write_shape_name(output, element);
845        }
846        if elements.len() == 1 {
847            output.push(',');
848        }
849        output.push(')');
850    }
851
852    /// Builds one `AssociatedType` entry describing `shape`: a leaf's own registered layout for
853    /// `TypeShape::Named`, or a nested tuple's own recursively-laid-out elements (via
854    /// `cel_runtime::ValueType::tuple`) for `TypeShape::Tuple`.
855    ///
856    /// - Precondition: every leaf `TypeId` reachable from `shape` is registered.
857    ///
858    /// - Postcondition: the returned entry's `offset` is always 0; the caller
859    ///   (`ValueType::tuple`) computes canonical tail-first sibling offsets.
860    /// - Complexity: O(n) descriptor nodes and space, including recursive traversal.
861    fn one_associated(&self, shape: &TypeShape) -> cel_runtime::AssociatedType {
862        let value_type = match shape {
863            TypeShape::Named(type_id) => {
864                let entry = self
865                    .entry_by_type_id(*type_id)
866                    .expect("one_associated: type registered");
867                (entry.value_type_fn)()
868            }
869            TypeShape::Tuple(elements) => cel_runtime::ValueType::tuple(
870                elements.iter().map(|e| self.one_associated(e)).collect(),
871            )
872            .expect("registered tuple layout"),
873            TypeShape::Array(element) => cel_runtime::ValueType::array(self.value_type(element)),
874            TypeShape::Callable(parameters, result) => cel_runtime::ValueType::callable(
875                parameters.iter().map(|p| self.value_type(p)).collect(),
876                self.value_type(result),
877            ),
878        };
879        cel_runtime::AssociatedType {
880            offset: 0,
881            value_type,
882        }
883    }
884
885    /// Returns the canonical descriptor of a resolved shape.
886    ///
887    /// - Precondition: Every named leaf is registered.
888    /// - Complexity: O(n) in shape nodes.
889    pub(crate) fn value_type(&self, shape: &TypeShape) -> cel_runtime::ValueType {
890        self.one_associated(shape).value_type
891    }
892
893    /// Checks every registered leaf and representable compound layout without evaluation.
894    ///
895    /// Callable signatures and empty arrays still require registered element leaves.
896    /// # Errors
897    /// Rejects unregistered leaves or unrepresentable tuple layouts.
898    /// - Complexity: O(n) descriptor nodes and space.
899    ///
900    /// # Examples
901    /// ```
902    /// use adam_lang::{TypeRegistry, type_registry::TypeShape};
903    /// let types = TypeRegistry::new();
904    /// assert!(types.validate_shape(&TypeShape::Array(Box::new(
905    ///     TypeShape::Named(std::any::TypeId::of::<i32>())
906    /// ))).is_ok());
907    /// ```
908    pub fn validate_shape(&self, shape: &TypeShape) -> anyhow::Result<()> {
909        self.checked_value_type(shape).map(|_| ())
910    }
911
912    /// Resolves a full descriptor while rejecting unknown leaves and invalid layouts.
913    ///
914    /// # Errors
915    /// Rejects unregistered leaves and unrepresentable tuple layouts.
916    /// - Complexity: O(n) descriptor nodes and space.
917    pub(crate) fn checked_value_type(
918        &self,
919        shape: &TypeShape,
920    ) -> anyhow::Result<cel_runtime::ValueType> {
921        use cel_runtime::{AssociatedType, ValueType};
922        Ok(match shape {
923            TypeShape::Named(id) => {
924                let entry = self
925                    .entry_by_type_id(*id)
926                    .ok_or_else(|| anyhow::anyhow!("unregistered shape leaf {id:?}"))?;
927                (entry.value_type_fn)()
928            }
929            TypeShape::Tuple(fields) => ValueType::tuple(
930                fields
931                    .iter()
932                    .map(|field| {
933                        Ok(AssociatedType {
934                            offset: 0,
935                            value_type: self.checked_value_type(field)?,
936                        })
937                    })
938                    .collect::<anyhow::Result<_>>()?,
939            )?,
940            TypeShape::Array(element) => ValueType::array(self.checked_value_type(element)?),
941            TypeShape::Callable(parameters, result) => ValueType::callable(
942                parameters
943                    .iter()
944                    .map(|p| self.checked_value_type(p))
945                    .collect::<anyhow::Result<_>>()?,
946                self.checked_value_type(result)?,
947            ),
948        })
949    }
950
951    /// Recovers structural identity without synthesizing aggregate Rust identities.
952    ///
953    /// # Errors
954    /// Names an unregistered leaf, including leaves nested in a signature.
955    /// - Complexity: O(n) in descriptor nodes.
956    pub(crate) fn shape_of(&self, ty: &cel_runtime::ValueType) -> Result<TypeShape, String> {
957        use cel_runtime::ValueKind;
958        Ok(match ty.kind() {
959            ValueKind::Leaf(id) => {
960                if self.entry_by_type_id(*id).is_none() {
961                    return Err(format!(
962                        "cannot infer a type: unregistered type `{}`",
963                        ty.type_name()
964                    ));
965                }
966                TypeShape::Named(*id)
967            }
968            ValueKind::Array(element) => TypeShape::Array(Box::new(self.shape_of(element)?)),
969            ValueKind::Tuple(fields) => TypeShape::Tuple(
970                fields
971                    .iter()
972                    .map(|field| self.shape_of(&field.value_type))
973                    .collect::<Result<_, _>>()?,
974            ),
975            ValueKind::Callable { parameters, result } => TypeShape::Callable(
976                parameters
977                    .iter()
978                    .map(|p| self.shape_of(p))
979                    .collect::<Result<_, _>>()?,
980                Box::new(self.shape_of(result)?),
981            ),
982        })
983    }
984
985    /// Checks default availability without constructing any values.
986    ///
987    /// Arrays need no element defaults; tuple fields are checked in source order.
988    /// # Errors
989    /// Names the first missing leaf default or callable requiring an initializer.
990    /// - Complexity: O(n) in constructed shape nodes.
991    pub(crate) fn validate_default(&self, shape: &TypeShape) -> anyhow::Result<()> {
992        match shape {
993            TypeShape::Named(id) => {
994                anyhow::ensure!(
995                    self.entry_by_type_id(*id)
996                        .expect("resolved leaf")
997                        .default_fn
998                        .is_some(),
999                    "type `{}` has no default; provide `= ...`",
1000                    self.display_name(shape)
1001                );
1002            }
1003            TypeShape::Tuple(fields) => {
1004                for field in fields {
1005                    self.validate_default(field)?;
1006                }
1007            }
1008            TypeShape::Array(_) => {}
1009            TypeShape::Callable(_, _) => {
1010                anyhow::bail!("callable has no default; provide an initializer `= ...`")
1011            }
1012        }
1013        Ok(())
1014    }
1015
1016    /// Emits recursive defaults, leaving arrays empty without constructing their elements.
1017    ///
1018    /// Cell builders preflight default availability and cell capabilities for the entire
1019    /// descriptor before calling this effectful emitter.
1020    ///
1021    /// # Errors
1022    /// Names the precise missing default leaf; callables require an initializer.
1023    /// - Complexity: O(n) in constructed shape nodes.
1024    pub(crate) fn emit_default(
1025        &self,
1026        shape: &TypeShape,
1027        body: &mut DynSegment,
1028    ) -> anyhow::Result<()> {
1029        let origin = body.current_stack_offset();
1030        match shape {
1031            TypeShape::Named(id) => {
1032                let entry = self.entry_by_type_id(*id).expect("resolved leaf");
1033                let default = entry.default_fn.ok_or_else(|| {
1034                    anyhow::anyhow!(
1035                        "type `{}` has no default; provide `= ...`",
1036                        self.display_name(shape)
1037                    )
1038                })?;
1039                body.just_external(self.value_type(shape), default())?;
1040            }
1041            TypeShape::Tuple(fields) => {
1042                for field in fields {
1043                    self.emit_default(field, body)?;
1044                }
1045                body.make_tuple(fields.len(), origin)?;
1046            }
1047            TypeShape::Array(element) => {
1048                body.make_typed_array(0, origin, self.value_type(element))?
1049            }
1050            TypeShape::Callable(_, _) => {
1051                anyhow::bail!("callable has no default; provide an initializer `= ...`")
1052            }
1053        }
1054        Ok(())
1055    }
1056}
1057
1058/// A CEL-facing snapshot of leaf aliases and finite type-function overloads.
1059///
1060/// The metadata remains valid independently of later registry mutation or destruction.
1061///
1062/// # Examples
1063///
1064/// See [`TypeRegistry::cel_type_resolver`] for a snapshot used after registry destruction.
1065#[derive(Clone, Default)]
1066pub struct RegistryTypeResolver {
1067    by_name: HashMap<String, ResolvedLeafType>,
1068    type_functions: TypeFunctionRegistry,
1069}
1070
1071impl TypeResolver for RegistryTypeResolver {
1072    /// Resolves registered plain or generic leaves, then CEL built-ins.
1073    ///
1074    /// - Complexity: Expected O(n + r) time and peak space for argument/name area n
1075    ///   and retained/result diagnostic name bytes r.
1076    fn resolve_named_type(&self, name: &str, args: &[ResolvedType]) -> Option<ResolvedLeafType> {
1077        if args.is_empty()
1078            && let Some(leaf) = self.by_name.get(name)
1079        {
1080            return Some(leaf.clone());
1081        }
1082        self.type_functions
1083            .resolve(
1084                name,
1085                &args.iter().map(ResolvedType::identity).collect::<Vec<_>>(),
1086            )
1087            .or_else(|| cel_parser::resolve_builtin_named_type(name, args))
1088    }
1089}
1090
1091impl TypeResolver for TypeRegistry {
1092    /// Resolves a leaf without allocating a complete registry snapshot.
1093    ///
1094    /// - Complexity: Expected O(n + r) time and peak space for argument/name area n
1095    ///   and retained/result diagnostic name bytes r.
1096    fn resolve_named_type(&self, name: &str, args: &[ResolvedType]) -> Option<ResolvedLeafType> {
1097        if args.is_empty()
1098            && let Some(entry) = self.get(name)
1099        {
1100            return Some(self.resolved_leaf(name, entry));
1101        }
1102        self.type_functions
1103            .resolve(
1104                name,
1105                &args.iter().map(ResolvedType::identity).collect::<Vec<_>>(),
1106            )
1107            .or_else(|| cel_parser::resolve_builtin_named_type(name, args))
1108    }
1109}
1110
1111impl Default for TypeRegistry {
1112    /// Returns `TypeRegistry::new()`.
1113    fn default() -> Self {
1114        Self::new()
1115    }
1116}
1117
1118#[cfg(test)]
1119mod tests {
1120    use super::*;
1121    use proc_macro2::Span;
1122    use std::any::TypeId;
1123
1124    /// Rejects differing alias/zero-operand results in both orders without discarding valid bindings.
1125    #[test]
1126    fn zero_operand_alias_registration_conflicts() {
1127        for alias_first in [false, true] {
1128            for default in [false, true] {
1129                let mut types = TypeRegistry::new();
1130                if alias_first {
1131                    if default {
1132                        types.register::<i32>("Maker").unwrap();
1133                    } else {
1134                        types.register_no_default::<i32>("Maker").unwrap();
1135                    }
1136                    assert!(
1137                        types
1138                            .register_type_function(
1139                                "Maker",
1140                                &[],
1141                                ResolvedLeafType::leaf::<bool>("bool").unwrap()
1142                            )
1143                            .is_err()
1144                    );
1145                    types
1146                        .register_type_function(
1147                            "Maker",
1148                            &[],
1149                            ResolvedLeafType::leaf::<i32>("Alias").unwrap(),
1150                        )
1151                        .unwrap();
1152                } else {
1153                    types
1154                        .register_type_function(
1155                            "Maker",
1156                            &[],
1157                            ResolvedLeafType::leaf::<i32>("Alias").unwrap(),
1158                        )
1159                        .unwrap();
1160                    if default {
1161                        assert!(types.register::<bool>("Maker").is_err());
1162                        types.register::<i32>("Maker").unwrap();
1163                    } else {
1164                        assert!(types.register_no_default::<bool>("Maker").is_err());
1165                        types.register_no_default::<i32>("Maker").unwrap();
1166                    }
1167                }
1168                for resolver in [&types as &dyn TypeResolver, &types.cel_type_resolver()] {
1169                    assert_eq!(
1170                        resolver.resolve_named_type("Maker", &[]).unwrap().type_id(),
1171                        TypeId::of::<i32>()
1172                    );
1173                }
1174                assert_eq!(
1175                    types
1176                        .type_functions()
1177                        .resolve("Maker", &[])
1178                        .unwrap()
1179                        .type_id(),
1180                    TypeId::of::<i32>()
1181                );
1182            }
1183        }
1184    }
1185
1186    /// Rejects builtin conflicts and preserves finite overloads in independent snapshots.
1187    #[test]
1188    fn type_function_registration_and_snapshot_contract() {
1189        let mut registry = TypeRegistry::new();
1190        let integer = ResolvedType::from(ResolvedLeafType::leaf::<i32>("Integer").unwrap());
1191        let bounds = ResolvedLeafType::leaf::<std::ops::RangeInclusive<i32>>("Bounds").unwrap();
1192        assert!(
1193            registry
1194                .register_type_function(
1195                    "RangeInclusive",
1196                    std::slice::from_ref(&integer),
1197                    ResolvedLeafType::leaf::<bool>("bool").unwrap()
1198                )
1199                .is_err()
1200        );
1201        assert!(
1202            registry
1203                .register_type_function("Fn", &[], bounds.clone())
1204                .is_err()
1205        );
1206        registry
1207            .register_type_function("Bounds", std::slice::from_ref(&integer), bounds.clone())
1208            .unwrap();
1209        registry
1210            .register_type_function("Bounds", std::slice::from_ref(&integer), bounds.clone())
1211            .unwrap();
1212        assert!(
1213            registry
1214                .register_type_function(
1215                    "Bounds",
1216                    std::slice::from_ref(&integer),
1217                    ResolvedLeafType::leaf::<bool>("bool").unwrap()
1218                )
1219                .is_err()
1220        );
1221        let snapshot = registry.cel_type_resolver();
1222        let copied = registry.clone();
1223        registry
1224            .register_type_function("Empty", &[], bounds.clone())
1225            .unwrap();
1226        assert!(snapshot.resolve_named_type("Empty", &[]).is_none());
1227        assert!(copied.resolve_named_type("Empty", &[]).is_none());
1228        let alias: ResolvedType = ResolvedLeafType::leaf::<i32>("Alias").unwrap().into();
1229        for resolver in [&registry as &dyn TypeResolver, &copied, &snapshot] {
1230            assert_eq!(
1231                resolver.resolve_named_type("Bounds", std::slice::from_ref(&alias)),
1232                Some(bounds.clone())
1233            );
1234            assert!(resolver.resolve_named_type("Bounds", &[]).is_none());
1235            assert!(
1236                resolver
1237                    .resolve_named_type("Bounds", &[integer.clone(), integer.clone()])
1238                    .is_none()
1239            );
1240        }
1241    }
1242
1243    /// Renders empty, singleton, array, callable, and unknown shapes with strict tuple syntax.
1244    #[test]
1245    fn display_name_covers_recursive_shape_variants() {
1246        let integer = TypeShape::Named(TypeId::of::<i32>());
1247        let cases = [
1248            (TypeShape::Tuple(vec![]), "()"),
1249            (TypeShape::Tuple(vec![integer.clone()]), "(i32,)"),
1250            (
1251                TypeShape::Array(Box::new(TypeShape::Tuple(vec![integer.clone()]))),
1252                "[(i32,)]",
1253            ),
1254            (
1255                TypeShape::Callable(vec![integer], Box::new(TypeShape::Tuple(vec![]))),
1256                "Fn((i32,), ())",
1257            ),
1258            (TypeShape::Named(TypeId::of::<Vec<i32>>()), "?"),
1259        ];
1260        let registry = TypeRegistry::new();
1261        for (shape, expected) in cases {
1262            assert_eq!(registry.display_name(&shape), expected);
1263        }
1264    }
1265
1266    /// Constructs a zero-width expression range at the supplied span.
1267    fn point(span: Span) -> crate::ast::ExprSpan {
1268        crate::ast::ExprSpan {
1269            start: span,
1270            end: span,
1271        }
1272    }
1273
1274    /// Registers the built-in integer under its concrete runtime type.
1275    #[test]
1276    fn new_registers_builtin_i32() {
1277        let reg = TypeRegistry::new();
1278        let entry = reg.get("i32").expect("i32 registered");
1279        assert_eq!(entry.type_id, TypeId::of::<i32>());
1280    }
1281
1282    /// Installs complete factories while foreign concrete types are still known.
1283    #[test]
1284    fn complete_factory_registered_foreign_leaf_retains_capabilities() {
1285        use cel_runtime::{owned_value::OwnedValue, value_type::Leaf};
1286        let mut registry = TypeRegistry::new();
1287        registry.register::<std::path::PathBuf>("Path").unwrap();
1288        registry
1289            .register_no_default::<std::ops::RangeInclusive<i32>>("Bounds")
1290            .unwrap();
1291        let entry = registry.get("Path").unwrap();
1292        let descriptor = (entry.value_type_fn)();
1293        let owner = OwnedValue::new::<Leaf<std::path::PathBuf>>("example".into())
1294            .with_value_type(descriptor)
1295            .unwrap();
1296        assert!(owner.try_eq(&owner.try_clone().unwrap()).unwrap());
1297        assert_eq!(owner.try_debug().unwrap(), "\"example\"");
1298        for name in ["Path", "Bounds"] {
1299            let resolved = registry
1300                .cel_type_resolver()
1301                .resolve_named_type(name, &[])
1302                .unwrap();
1303            assert_eq!(resolved.type_name(), name);
1304            assert!(
1305                resolved
1306                    .complete_value_type()
1307                    .unwrap()
1308                    .same_shape(&(registry.get(name).unwrap().value_type_fn)())
1309            );
1310        }
1311    }
1312
1313    /// Registers floating-point values with default construction.
1314    #[test]
1315    fn new_registers_builtin_f64_with_default() {
1316        let reg = TypeRegistry::new();
1317        let entry = reg.get("f64").expect("f64 registered");
1318        assert_eq!(entry.type_id, TypeId::of::<f64>());
1319        assert!(entry.default_fn.is_some(), "f64 must have a default");
1320    }
1321
1322    /// Registers the built-in owned string type.
1323    #[test]
1324    fn new_registers_builtin_string() {
1325        let reg = TypeRegistry::new();
1326        let entry = reg.get("String").expect("String registered");
1327        assert_eq!(entry.type_id, TypeId::of::<String>());
1328    }
1329
1330    /// Registers a custom name with its concrete type and default factory.
1331    #[test]
1332    fn register_custom_type_with_default() {
1333        let mut reg = TypeRegistry::new();
1334        reg.register::<u64>("my_u64").unwrap();
1335        let entry = reg.get("my_u64").expect("custom type registered");
1336        assert_eq!(entry.type_id, TypeId::of::<u64>());
1337        assert!(entry.default_fn.is_some());
1338    }
1339
1340    /// Omits default construction when registering a non-defaultable leaf.
1341    #[test]
1342    fn register_no_default_has_no_default_fn() {
1343        /// Supplies a test leaf without a `Default` implementation.
1344        #[derive(PartialEq, Clone, Debug)]
1345        struct NoDefault(i32);
1346
1347        let mut reg = TypeRegistry::new();
1348        reg.register_no_default::<NoDefault>("no_default").unwrap();
1349        let entry = reg.get("no_default").expect("registered");
1350        assert!(entry.default_fn.is_none());
1351    }
1352
1353    /// Preserves a registered custom leaf's requested CEL name and type.
1354    #[test]
1355    fn cel_type_resolver_uses_registered_leaf_names() {
1356        /// Supplies a non-built-in leaf for name resolution.
1357        #[derive(PartialEq, Clone, Debug)]
1358        struct Custom(i32);
1359
1360        let mut reg = TypeRegistry::new();
1361        reg.register_no_default::<Custom>("Custom").unwrap();
1362
1363        let resolver = reg.cel_type_resolver();
1364        let leaf = resolver
1365            .resolve_named_type("Custom", &[])
1366            .expect("custom leaf registered");
1367
1368        assert_eq!(leaf.type_id(), TypeId::of::<Custom>());
1369        assert_eq!(leaf.type_name(), "Custom");
1370    }
1371
1372    /// Forwards a registered argument through dynamic segment invocation.
1373    #[test]
1374    fn push_arg_fn_drives_call_dyn() {
1375        use cel_runtime::DynSegment;
1376        use std::any::Any;
1377
1378        let reg = TypeRegistry::new();
1379        let entry = reg.get("i32").unwrap();
1380        let mut seg = DynSegment::new::<()>();
1381        (entry.push_arg_fn)(&mut seg, 0);
1382        let x: i32 = 7;
1383        let result: i32 = seg.call_dyn(&[&x as &dyn Any]).unwrap();
1384        assert_eq!(result, 7);
1385    }
1386
1387    /// Adds exactly one cell storing the supplied concrete value.
1388    #[test]
1389    fn add_cell_fn_creates_cell() {
1390        use adam_rs::Sheet;
1391        use std::any::Any;
1392
1393        let reg = TypeRegistry::new();
1394        let entry = reg.get("f64").unwrap();
1395        let mut sheet = Sheet::new();
1396        let val: Box<dyn Any> = Box::new(42.14_f64);
1397        let cell_id = (entry.add_cell_fn)(&mut sheet, val);
1398        assert_eq!(sheet.cells().count(), 1);
1399        assert_eq!(*sheet.read::<f64>(cell_id).unwrap(), 42.14);
1400    }
1401
1402    /// Boxes a dynamic call's concrete result without changing its value.
1403    #[test]
1404    fn call_dyn_fn_returns_boxed_result() {
1405        use cel_runtime::DynSegment;
1406        use std::any::Any;
1407
1408        let reg = TypeRegistry::new();
1409        let entry = reg.get("i32").unwrap();
1410        let mut seg = DynSegment::new::<()>();
1411        (entry.push_arg_fn)(&mut seg, 0);
1412        let x: i32 = 99;
1413        let boxed = (entry.call_dyn_fn)(&mut seg, &[&x as &dyn Any]).unwrap();
1414        let result = boxed.downcast::<i32>().expect("i32");
1415        assert_eq!(*result, 99);
1416    }
1417
1418    /// Resolves a registered leaf through its concrete `TypeId`.
1419    #[test]
1420    fn entry_by_type_id_roundtrip() {
1421        let reg = TypeRegistry::new();
1422        let entry = reg
1423            .entry_by_type_id(std::any::TypeId::of::<f64>())
1424            .expect("f64 registered");
1425        assert_eq!(entry.type_id, std::any::TypeId::of::<f64>());
1426    }
1427
1428    /// Returns no entry for an unknown registered name.
1429    #[test]
1430    fn get_nonexistent_returns_none() {
1431        let reg = TypeRegistry::new();
1432        assert!(reg.get("nonexistent").is_none());
1433    }
1434
1435    /// Returns no entry for an unregistered concrete type.
1436    #[test]
1437    fn entry_by_type_id_nonexistent_returns_none() {
1438        let reg = TypeRegistry::new();
1439        // Vec<u8> is not a registered built-in type.
1440        assert!(
1441            reg.entry_by_type_id(std::any::TypeId::of::<Vec<u8>>())
1442                .is_none()
1443        );
1444    }
1445
1446    /// Removes reverse lookup when the replaced leaf has no surviving name.
1447    #[test]
1448    fn register_overwrite_removes_stale_type_id() {
1449        /// Identifies the defaultable leaf whose last name is replaced.
1450        #[derive(PartialEq, Clone, Default, Debug)]
1451        struct TypeA;
1452        /// Identifies the replacement defaultable leaf.
1453        #[derive(PartialEq, Clone, Default, Debug)]
1454        struct TypeB;
1455
1456        let mut reg = TypeRegistry::new();
1457        reg.register::<TypeA>("alias").unwrap();
1458        reg.register::<TypeB>("alias").unwrap();
1459
1460        // After overwriting, TypeA's TypeId must no longer be found.
1461        assert!(
1462            reg.entry_by_type_id(TypeId::of::<TypeA>()).is_none(),
1463            "stale TypeA mapping should have been removed"
1464        );
1465        // TypeB must be reachable by both name and TypeId.
1466        assert!(reg.entry_by_type_id(TypeId::of::<TypeB>()).is_some());
1467        assert_eq!(reg.get("alias").unwrap().type_id, TypeId::of::<TypeB>());
1468    }
1469
1470    /// Removes obsolete reverse lookup when replacing a non-defaultable leaf.
1471    #[test]
1472    fn register_no_default_overwrite_removes_stale_type_id() {
1473        /// Identifies the leaf whose last name is replaced.
1474        #[derive(PartialEq, Clone, Debug)]
1475        struct TypeA;
1476        /// Identifies the replacement leaf.
1477        #[derive(PartialEq, Clone, Debug)]
1478        struct TypeB;
1479
1480        let mut reg = TypeRegistry::new();
1481        reg.register_no_default::<TypeA>("alias").unwrap();
1482        reg.register_no_default::<TypeB>("alias").unwrap();
1483
1484        assert!(
1485            reg.entry_by_type_id(TypeId::of::<TypeA>()).is_none(),
1486            "stale TypeA mapping should have been removed"
1487        );
1488        assert!(reg.entry_by_type_id(TypeId::of::<TypeB>()).is_some());
1489    }
1490
1491    /// Registered leaves retain independent canonical clone, equality, and debug plans.
1492    #[test]
1493    fn registered_leaf_capabilities_operate_on_canonical_owners() {
1494        let reg = TypeRegistry::new();
1495        let entry = reg.get("i32").unwrap();
1496        let value = cel_runtime::OwnedValue::new::<cel_runtime::Leaf<i32>>(7)
1497            .with_value_type((entry.value_type_fn)())
1498            .unwrap();
1499        let cloned = value.try_clone().unwrap();
1500        assert!(value.try_eq(&cloned).unwrap());
1501        assert_eq!(cloned.try_debug().unwrap(), "7");
1502    }
1503
1504    /// Resolves a named annotation to its registered concrete shape.
1505    #[test]
1506    fn resolve_named_type_expr_returns_the_matching_type_shape() {
1507        let reg = TypeRegistry::new();
1508        let expr = cel_parser::TypeExpr::Named {
1509            name: "i32".to_string(),
1510            args: Vec::new(),
1511            span: point(Span::call_site()),
1512        };
1513        let shape = reg.resolve(&expr).unwrap();
1514        assert_eq!(shape, TypeShape::Named(TypeId::of::<i32>()));
1515    }
1516
1517    /// Reports an unknown named annotation.
1518    #[test]
1519    fn resolve_unknown_named_type_expr_is_an_error() {
1520        let reg = TypeRegistry::new();
1521        let expr = cel_parser::TypeExpr::Named {
1522            name: "bogus".to_string(),
1523            args: Vec::new(),
1524            span: point(Span::call_site()),
1525        };
1526        assert!(reg.resolve(&expr).is_err());
1527    }
1528
1529    /// Resolves recursively nested tuple annotations.
1530    #[test]
1531    fn resolve_tuple_type_expr_returns_a_nested_type_shape() {
1532        let reg = TypeRegistry::new();
1533        let span = point(Span::call_site());
1534        let expr = cel_parser::TypeExpr::Tuple {
1535            elements: vec![
1536                cel_parser::TypeExpr::Named {
1537                    name: "i32".to_string(),
1538                    args: Vec::new(),
1539                    span,
1540                },
1541                cel_parser::TypeExpr::Tuple {
1542                    elements: vec![
1543                        cel_parser::TypeExpr::Named {
1544                            name: "f64".to_string(),
1545                            args: Vec::new(),
1546                            span,
1547                        },
1548                        cel_parser::TypeExpr::Named {
1549                            name: "String".to_string(),
1550                            args: Vec::new(),
1551                            span,
1552                        },
1553                    ],
1554                    span,
1555                },
1556            ],
1557            span,
1558        };
1559        let shape = reg.resolve(&expr).unwrap();
1560        assert_eq!(
1561            shape,
1562            TypeShape::Tuple(vec![
1563                TypeShape::Named(TypeId::of::<i32>()),
1564                TypeShape::Tuple(vec![
1565                    TypeShape::Named(TypeId::of::<f64>()),
1566                    TypeShape::Named(TypeId::of::<String>()),
1567                ]),
1568            ])
1569        );
1570    }
1571
1572    /// Resolves structural arrays without registering their carrier.
1573    #[test]
1574    fn resolve_accepts_structural_array_cell_type() {
1575        let registry = TypeRegistry::new();
1576        let span = point(Span::call_site());
1577        let expr = cel_parser::TypeExpr::Array {
1578            element: Box::new(cel_parser::TypeExpr::Named {
1579                name: "i32".to_string(),
1580                args: Vec::new(),
1581                span,
1582            }),
1583            span,
1584        };
1585        assert_eq!(
1586            registry.resolve(&expr).unwrap(),
1587            TypeShape::Array(Box::new(TypeShape::Named(TypeId::of::<i32>())))
1588        );
1589    }
1590
1591    /// Resolves a registered generic leaf annotation.
1592    #[test]
1593    fn resolve_accepts_registered_generic_leaf() {
1594        let mut registry = TypeRegistry::new();
1595        registry
1596            .register_no_default::<std::ops::RangeInclusive<f64>>("RangeInclusive(f64)")
1597            .unwrap();
1598        let span = point(Span::call_site());
1599        let expr = cel_parser::TypeExpr::Named {
1600            name: "RangeInclusive".to_string(),
1601            args: vec![cel_parser::TypeExpr::Named {
1602                name: "f64".to_string(),
1603                args: Vec::new(),
1604                span,
1605            }],
1606            span,
1607        };
1608        assert_eq!(
1609            registry.resolve(&expr).unwrap(),
1610            TypeShape::Named(TypeId::of::<std::ops::RangeInclusive<f64>>())
1611        );
1612    }
1613
1614    /// Both resolvers retain requested names and concrete identities across alias orders.
1615    #[test]
1616    fn registered_aliases_preserve_requested_leaf_names() {
1617        for names in [["Integer", "i32"], ["i32", "Integer"]] {
1618            let mut registry = TypeRegistry::new();
1619            for name in names {
1620                registry.register::<i32>(name).unwrap();
1621            }
1622            let snapshot = registry.cel_type_resolver();
1623            for name in names {
1624                let direct = registry.resolve_named_type(name, &[]).unwrap();
1625                let copied = snapshot.resolve_named_type(name, &[]).unwrap();
1626                assert_eq!(direct.type_name(), name);
1627                assert_eq!(copied.type_name(), name);
1628                assert!(
1629                    direct
1630                        .complete_value_type()
1631                        .unwrap()
1632                        .same_shape(&cel_runtime::ValueType::leaf::<i32>())
1633                );
1634                assert!(
1635                    direct
1636                        .complete_value_type()
1637                        .unwrap()
1638                        .same_shape(copied.complete_value_type().unwrap())
1639                );
1640            }
1641        }
1642    }
1643
1644    /// Alias spelling preserves explicit signatures inside recursive arguments.
1645    #[test]
1646    fn registered_aliases_preserve_recursive_generic_keys() {
1647        use std::ops::RangeInclusive;
1648
1649        for alias_first in [false, true] {
1650            let mut registry = TypeRegistry::new();
1651            if alias_first {
1652                registry.register::<i32>("Integer").unwrap();
1653            }
1654            let names = [
1655                "Bounds(i32)",
1656                "Bounds(Integer)",
1657                "Bounds(Bounds(i32))",
1658                "Bounds([i32])",
1659                "Bounds((i32, [Integer]))",
1660                "Bounds((i32,))",
1661                "Bounds(Fn((), Integer))",
1662                "Bounds(Fn((Integer,), [i32]))",
1663                "Bounds(Fn((Integer, [i32]), ()))",
1664            ];
1665            for name in names {
1666                registry
1667                    .register_no_default::<RangeInclusive<i32>>(name)
1668                    .unwrap();
1669            }
1670            if !alias_first {
1671                registry.register::<i32>("Integer").unwrap();
1672            }
1673            let integer = ResolvedType::from(ResolvedLeafType::leaf::<i32>("i32").unwrap());
1674            let array = ResolvedType::Array {
1675                element: Box::new(integer.clone()),
1676            };
1677            let result = ResolvedLeafType::leaf::<RangeInclusive<i32>>("Bounds(i32)").unwrap();
1678            for argument in [
1679                integer.clone(),
1680                result.clone().into(),
1681                array.clone(),
1682                ResolvedType::Tuple {
1683                    elements: vec![integer.clone(), array.clone()],
1684                },
1685                ResolvedType::Tuple {
1686                    elements: vec![integer.clone()],
1687                },
1688                ResolvedType::Callable {
1689                    parameters: vec![],
1690                    result: Box::new(integer.clone()),
1691                },
1692                ResolvedType::Callable {
1693                    parameters: vec![integer.clone()],
1694                    result: Box::new(array.clone()),
1695                },
1696                ResolvedType::Callable {
1697                    parameters: vec![integer, array],
1698                    result: Box::new(ResolvedType::Tuple { elements: vec![] }),
1699                },
1700            ] {
1701                registry
1702                    .register_type_function("Bounds", &[argument], result.clone())
1703                    .unwrap();
1704            }
1705            let snapshot = registry.cel_type_resolver();
1706            for name in names {
1707                for source in [name.to_owned(), format!("[({name}, [Integer])]")] {
1708                    let expr = cel_parser::CELParser::new(cel_parser::OpLookup::new())
1709                        .parse_type_expr_str(&source)
1710                        .unwrap();
1711                    let copied = expr.resolve(&snapshot).unwrap().into_value_type().unwrap();
1712                    let direct = expr.resolve(&registry).unwrap();
1713                    let direct = direct.into_value_type().unwrap();
1714                    assert!(direct.same_shape(&copied), "{source}");
1715                    assert_eq!(
1716                        registry.resolve(&expr).unwrap(),
1717                        registry.shape_of(&copied).unwrap(),
1718                        "{source}"
1719                    );
1720                }
1721            }
1722            let missing = cel_parser::CELParser::new(cel_parser::OpLookup::new())
1723                .parse_type_expr_str("Bounds([bool])")
1724                .unwrap();
1725            let direct = missing.resolve(&registry).unwrap_err();
1726            let copied = missing.resolve(&snapshot).unwrap_err();
1727            assert_eq!(direct.message(), copied.message());
1728            assert!(direct.message().contains("unknown type `Bounds`"));
1729        }
1730    }
1731
1732    /// Resolves built-in generic types through the CEL fallback.
1733    #[test]
1734    fn cel_type_resolver_falls_back_to_builtin_generics() {
1735        let registry = TypeRegistry::new();
1736        let resolver = registry.cel_type_resolver();
1737        let f64_leaf = resolver.resolve_named_type("f64", &[]).expect("f64");
1738        let resolved = resolver
1739            .resolve_named_type("RangeInclusive", &[ResolvedType::Scalar(f64_leaf)])
1740            .expect("RangeInclusive(f64) should resolve via the builtin fallback");
1741        assert_eq!(resolved.type_name(), "RangeInclusive(f64)");
1742    }
1743
1744    /// Renders a recursive tuple shape with registered leaf names.
1745    #[test]
1746    fn display_name_formats_a_nested_tuple_shape() {
1747        let reg = TypeRegistry::new();
1748        let shape = TypeShape::Tuple(vec![
1749            TypeShape::Named(TypeId::of::<i32>()),
1750            TypeShape::Tuple(vec![
1751                TypeShape::Named(TypeId::of::<f64>()),
1752                TypeShape::Named(TypeId::of::<String>()),
1753            ]),
1754        ]);
1755        assert_eq!(reg.display_name(&shape), "(i32, (f64, String))");
1756    }
1757
1758    /// Describes a flat tuple using its canonical runtime layout.
1759    #[test]
1760    fn canonical_descriptor_describes_a_flat_tuple() {
1761        let reg = TypeRegistry::new();
1762        let shape = TypeShape::Tuple(vec![
1763            TypeShape::Named(TypeId::of::<i32>()),
1764            TypeShape::Named(TypeId::of::<f64>()),
1765        ]);
1766        let descriptor = reg.value_type(&shape);
1767        let prototype = descriptor.tuple_elements().unwrap();
1768        assert_eq!(prototype.len(), 2);
1769        assert_eq!(prototype[0].value_type.type_id(), TypeId::of::<i32>());
1770        assert_eq!(prototype[1].value_type.type_id(), TypeId::of::<f64>());
1771        assert_eq!(prototype[0].offset, 8);
1772        assert_eq!(prototype[1].offset, 0);
1773    }
1774
1775    /// Retains recursive element descriptors for a nested tuple.
1776    #[test]
1777    fn canonical_descriptor_describes_a_nested_tuple() {
1778        let reg = TypeRegistry::new();
1779        let shape = TypeShape::Tuple(vec![
1780            TypeShape::Named(TypeId::of::<i32>()),
1781            TypeShape::Tuple(vec![
1782                TypeShape::Named(TypeId::of::<i32>()),
1783                TypeShape::Named(TypeId::of::<i32>()),
1784            ]),
1785        ]);
1786        let descriptor = reg.value_type(&shape);
1787        let prototype = descriptor.tuple_elements().unwrap();
1788        assert_eq!(prototype.len(), 2);
1789        assert_eq!(
1790            prototype[1].value_type.type_id(),
1791            TypeId::of::<cel_runtime::CNil<()>>()
1792        );
1793        assert_eq!(
1794            prototype[1]
1795                .value_type
1796                .tuple_elements()
1797                .expect("nested tuple")
1798                .len(),
1799            2
1800        );
1801    }
1802
1803    /// Compound defaults compose arrays and tuples, and reject leaves lacking defaults.
1804    #[test]
1805    fn canonical_defaults_compose_and_report_missing_leaf_defaults() {
1806        use cel_runtime::{ArrayOf, Cons, IntoRustTuple, Leaf, Nil};
1807        let parsed = crate::AdamParser::new(TypeRegistry::new(), cel_parser::OpLookup::new())
1808            .parse_str("sheet s { cell x: (i32, ([f64],)); }")
1809            .unwrap();
1810        /// Represents the recursive tuple and array default requested by the fixture.
1811        type Shape = Cons<Leaf<i32>, Cons<Cons<ArrayOf<Leaf<f64>>, Nil>, Nil>>;
1812        let (number, nested) = parsed
1813            .read_compound::<Shape>(parsed.cell_names["x"].0)
1814            .unwrap()
1815            .into_rust_tuple();
1816        assert_eq!(number, 0);
1817        assert!(nested.into_rust_tuple().0.is_empty());
1818        /// Supplies a leaf whose missing default must be diagnosed.
1819        #[derive(Clone, PartialEq, Debug)]
1820        struct NoDefault;
1821        let mut registry = TypeRegistry::new();
1822        registry
1823            .register_no_default::<NoDefault>("NoDefault")
1824            .unwrap();
1825        let error = crate::AdamParser::new(registry, cel_parser::OpLookup::new())
1826            .parse_str("sheet s { cell x: (NoDefault,); }")
1827            .err()
1828            .unwrap();
1829        assert!(error.to_string().contains("NoDefault"));
1830    }
1831
1832    /// Compares equal concrete integers as equal through the erased adapter.
1833    #[test]
1834    fn eq_dyn_fn_compares_equal_i32_values_as_equal() {
1835        let reg = TypeRegistry::new();
1836        let entry = reg.get("i32").unwrap();
1837        let a: i32 = 7;
1838        let b: i32 = 7;
1839        assert!((entry.eq_dyn_fn)(&a, &b));
1840    }
1841
1842    /// Compares unequal concrete integers as unequal through the erased adapter.
1843    #[test]
1844    fn eq_dyn_fn_compares_unequal_i32_values_as_unequal() {
1845        let reg = TypeRegistry::new();
1846        let entry = reg.get("i32").unwrap();
1847        let a: i32 = 7;
1848        let b: i32 = 8;
1849        assert!(!(entry.eq_dyn_fn)(&a, &b));
1850    }
1851
1852    /// Supplies value equality for non-defaultable registered leaves.
1853    #[test]
1854    fn register_no_default_also_populates_eq_dyn_fn() {
1855        /// Supplies a non-defaultable leaf with value equality.
1856        #[derive(PartialEq, Clone, Debug)]
1857        struct NoDefault(i32);
1858
1859        let mut reg = TypeRegistry::new();
1860        reg.register_no_default::<NoDefault>("NoDefault").unwrap();
1861        let entry = reg.get("NoDefault").unwrap();
1862        let a = NoDefault(1);
1863        let b = NoDefault(1);
1864        let c = NoDefault(2);
1865        assert!((entry.eq_dyn_fn)(&a, &b));
1866        assert!(!(entry.eq_dyn_fn)(&a, &c));
1867    }
1868
1869    /// Associates a registered numeric range with its element type.
1870    #[test]
1871    fn range_entry_recognizes_a_registered_numeric_range_inclusive_type() {
1872        let reg = TypeRegistry::new();
1873        let entry = reg
1874            .range_entry(TypeId::of::<std::ops::RangeInclusive<i32>>())
1875            .expect("i32 range recognized");
1876        assert_eq!(entry.element_type_id, TypeId::of::<i32>());
1877    }
1878
1879    /// Returns no range adapter for an ordinary scalar type.
1880    #[test]
1881    fn range_entry_returns_none_for_a_non_range_type() {
1882        let reg = TypeRegistry::new();
1883        assert!(reg.range_entry(TypeId::of::<i32>()).is_none());
1884    }
1885
1886    /// Clamps an erased candidate to evaluated inclusive bounds.
1887    #[test]
1888    fn range_entry_clamp_fn_clamps_a_value_into_the_evaluated_bounds() {
1889        let reg = TypeRegistry::new();
1890        let entry = reg
1891            .range_entry(TypeId::of::<std::ops::RangeInclusive<i32>>())
1892            .unwrap();
1893        let mut segment = DynSegment::new::<()>();
1894        segment.push_arg::<i32>(1);
1895        segment.push_arg::<i32>(2);
1896        segment.op2(|a: i32, b: i32| a..=b).unwrap();
1897        let value = 500i32;
1898        let lo = 0i32;
1899        let hi = 100i32;
1900        let evaluated = segment.call_dyn_value(&[&value, &lo, &hi]).unwrap();
1901        let result = (entry.clamp_fn)(evaluated, &value).unwrap();
1902        assert_eq!(*result.downcast_ref::<i32>().unwrap(), 100);
1903    }
1904
1905    /// Returns both evaluated inclusive bounds with their concrete values.
1906    #[test]
1907    fn range_entry_bounds_fn_returns_the_evaluated_bounds() {
1908        let reg = TypeRegistry::new();
1909        let entry = reg
1910            .range_entry(TypeId::of::<std::ops::RangeInclusive<i32>>())
1911            .unwrap();
1912        let mut segment = DynSegment::new::<()>();
1913        segment.push_arg::<i32>(1);
1914        segment.push_arg::<i32>(2);
1915        segment.op2(|a: i32, b: i32| a..=b).unwrap();
1916        let placeholder = 0i32;
1917        let lo = 0i32;
1918        let hi = 100i32;
1919        let evaluated = segment.call_dyn_value(&[&placeholder, &lo, &hi]).unwrap();
1920        let (lo_out, hi_out) = (entry.bounds_fn)(evaluated).unwrap();
1921        assert_eq!(*lo_out.downcast_ref::<i32>().unwrap(), 0);
1922        assert_eq!(*hi_out.downcast_ref::<i32>().unwrap(), 100);
1923    }
1924}