Skip to main content

cel_parser/
checking.rs

1//! Owns callback-free checking catalogs.
2//!
3//! Project host registrations once, or import a validated description, then borrow
4//! the resulting environment for every expression:
5//!
6//! ```
7//! use cel_parser::checking::{CheckingBuilder, CheckingEnvironment};
8//! let environment = CheckingBuilder::new().finish().unwrap();
9//! let imported = CheckingEnvironment::from_description(environment.description().clone()).unwrap();
10//! assert!(imported.resolve_type("i32").is_some());
11//! ```
12
13use crate::{Expr, ExprSpan, OpLookup, ParseError, ResolvedLeafType, ResolvedType, Ty, TypeExpr};
14use serde::{Deserialize, Serialize};
15use std::{
16    any::TypeId,
17    collections::{HashMap, HashSet},
18    fmt,
19    sync::Arc,
20};
21
22/// Describes value operations without retaining their implementations.
23///
24/// # Examples
25/// See the module example for catalog construction.
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
27pub struct Capabilities {
28    /// A default value is registered.
29    pub default_available: bool,
30    /// Values support argument cloning.
31    pub cloneable: bool,
32    /// Values support comparison.
33    pub comparable: bool,
34    /// Values support diagnostic formatting.
35    pub debuggable: bool,
36}
37
38impl Capabilities {
39    /// Copies host value capabilities without declaring default availability.
40    fn from_host(leaf: &ResolvedLeafType) -> Self {
41        Self {
42            cloneable: leaf.element_type().can_clone_for_argument(),
43            comparable: leaf.element_type().can_compare(),
44            debuggable: leaf.element_type().can_debug(),
45            default_available: false,
46        }
47    }
48}
49
50/// Distinguishes transient host identities from identities owned by one catalog.
51#[derive(Clone, Debug)]
52enum Identity {
53    Host(TypeId),
54    Catalog(Arc<()>, u32),
55}
56
57/// A nominal identity, diagnostic name, and callback-free capabilities.
58///
59/// Equality ignores aliases and capabilities. Independent catalogs never share identities.
60/// Host leaves are rebound at the checking boundary; imported leaves have no runtime identity.
61///
62/// # Examples
63/// See [`CheckingEnvironment::resolve_type`].
64#[derive(Clone, Debug)]
65pub struct NominalLeaf {
66    identity: Identity,
67    name: Arc<str>,
68    /// Value capabilities retained by projection.
69    pub capabilities: Capabilities,
70}
71
72impl PartialEq for NominalLeaf {
73    /// Compares nominal identity, independently of diagnostic spelling.
74    fn eq(&self, other: &Self) -> bool {
75        match (&self.identity, &other.identity) {
76            (Identity::Host(a), Identity::Host(b)) => a == b,
77            (Identity::Catalog(a, i), Identity::Catalog(b, j)) => Arc::ptr_eq(a, b) && i == j,
78            _ => false,
79        }
80    }
81}
82impl Eq for NominalLeaf {}
83
84impl NominalLeaf {
85    /// Copies semantic facts from a host leaf without retaining executable descriptors.
86    ///
87    /// - Complexity: O(l) for diagnostic name length l.
88    pub(crate) fn from_host(leaf: &ResolvedLeafType) -> Self {
89        Self {
90            identity: Identity::Host(leaf.type_id()),
91            name: Arc::from(leaf.type_name()),
92            capabilities: Capabilities::from_host(leaf),
93        }
94    }
95
96    /// Borrows the diagnostic name.
97    ///
98    /// # Examples
99    /// See [`CheckingEnvironment::resolve_type`].
100    pub fn type_name(&self) -> &str {
101        &self.name
102    }
103
104    /// Returns a host binding identity, or `None` for catalog-owned leaves.
105    ///
106    /// # Examples
107    /// See the module example; imported identities are catalog-local.
108    pub fn type_id(&self) -> Option<TypeId> {
109        match self.identity {
110            Identity::Host(id) => Some(id),
111            Identity::Catalog(..) => None,
112        }
113    }
114}
115
116/// Describes a recursive shape using catalog-local leaf references.
117///
118/// Structural nodes form owned trees; nominal record references may be recursive.
119///
120/// # Examples
121/// See [`CheckingDescription`].
122#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
123pub enum CheckingType {
124    /// A nominal catalog reference.
125    Leaf(u32),
126    /// A homogeneous array.
127    Array(Box<CheckingType>),
128    /// A source-ordered tuple.
129    Tuple(Vec<CheckingType>),
130    /// Ordered parameters and a result.
131    Callable(Vec<CheckingType>, Box<CheckingType>),
132}
133
134/// Describes a nominal leaf and its source aliases.
135///
136/// # Examples
137/// See [`CheckingDescription`].
138#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
139pub struct TypeDescription {
140    /// The catalog-local identity.
141    pub id: u32,
142    /// The canonical diagnostic name.
143    pub name: String,
144    /// Declared source aliases and reserved builtin literal-kind names.
145    pub aliases: Vec<String>,
146    /// A language primitive name, when this is a primitive.
147    pub primitive: Option<String>,
148    /// Available value operations.
149    pub capabilities: Capabilities,
150    /// The element accepted by inclusive-range filtering.
151    pub range_element: Option<u32>,
152}
153
154/// Describes an overload; member operands begin with the receiver.
155///
156/// # Examples
157/// See [`CheckingBuilder::register_lookup`].
158#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
159pub struct OperationDescription {
160    /// The callable operation name.
161    pub name: String,
162    /// Ordered operand shapes.
163    pub operands: Vec<CheckingType>,
164    /// The result shape.
165    pub result: CheckingType,
166}
167
168/// Describes required record fields in canonical order.
169///
170/// # Examples
171/// See [`CheckingBuilder::register_lookup`].
172#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
173pub struct RecordDescription {
174    /// The constructor's source name.
175    pub name: String,
176    /// The constructed nominal identity.
177    pub ty: u32,
178    /// Required field names and complete shapes.
179    pub fields: Vec<(String, CheckingType)>,
180}
181
182/// Describes a function-value marker and its dispatch name.
183///
184/// # Examples
185/// See [`CheckingBuilder::register_lookup`].
186#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
187pub struct FunctionDescription {
188    /// The source callable name.
189    pub name: String,
190    /// The nominal function marker.
191    pub marker: u32,
192}
193
194/// An owned serializable checking catalog without Rust identities or callbacks.
195///
196/// Leaf IDs are local references, not cross-environment equality.
197///
198/// # Examples
199/// ```
200/// let environment = cel_parser::checking::CheckingBuilder::new().finish().unwrap();
201/// let description = environment.description().clone();
202/// assert!(!description.types.is_empty());
203/// ```
204#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
205pub struct CheckingDescription {
206    /// The language builtin/checker contract.
207    pub builtin_contract: u32,
208    /// Nominal identities and aliases.
209    pub types: Vec<TypeDescription>,
210    /// Persistent operation overloads.
211    pub operations: Vec<OperationDescription>,
212    /// Record field contracts.
213    pub records: Vec<RecordDescription>,
214    /// Function marker contracts.
215    pub functions: Vec<FunctionDescription>,
216    /// Explicit nominal type-function overloads.
217    pub type_functions: Vec<TypeFunctionDescription>,
218}
219
220/// A finite type-function overload using catalog-local structural identities.
221///
222/// The result is a nominal leaf; arguments preserve full recursive shapes.
223///
224/// # Examples
225/// See [`CheckingBuilder::register_type_function`].
226#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
227pub struct TypeFunctionDescription {
228    /// The source constructor identifier.
229    pub name: String,
230    /// Source-ordered complete argument shapes.
231    pub arguments: Vec<CheckingType>,
232    /// The nominal result identity.
233    pub result: CheckingType,
234}
235
236/// Rejects invalid descriptions or registrations lacking checking metadata.
237///
238/// # Examples
239/// See [`CheckingEnvironment::from_description`].
240#[derive(Clone, Debug, PartialEq, Eq)]
241pub struct MetadataError(pub String);
242impl fmt::Display for MetadataError {
243    /// Formats the failing metadata condition.
244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245        self.0.fmt(f)
246    }
247}
248impl std::error::Error for MetadataError {}
249
250/// Records whether the catalog is authoritative for application declarations.
251///
252/// # Examples
253/// See [`check_expr_with_environment`].
254#[derive(Clone, Copy, Debug, PartialEq, Eq)]
255pub enum MetadataAvailability {
256    /// Unknown declarations are errors.
257    Complete,
258    /// Missing host facts produce incomplete-check diagnostics.
259    Unavailable,
260}
261
262/// Retains an inferred value, definite errors, and unavailable-metadata diagnostics.
263///
264/// # Examples
265/// See [`check_expr_with_environment`].
266pub struct CheckingReport<T> {
267    /// The best-effort checking result.
268    pub value: T,
269    /// Definite source errors.
270    pub diagnostics: Vec<ParseError>,
271    /// Checks requiring unavailable host metadata.
272    pub incomplete: Vec<ParseError>,
273}
274
275/// Owns validated nominal identities and indexed semantic contracts.
276///
277/// No environment contains executable descriptors or callbacks.
278///
279/// # Examples
280/// See the module example.
281pub struct CheckingEnvironment {
282    owner: Arc<()>,
283    description: CheckingDescription,
284    types: HashMap<u32, Ty>,
285    type_indices: HashMap<u32, usize>,
286    names: HashMap<String, u32>,
287    type_functions: HashMap<String, HashMap<Vec<CheckingType>, u32>>,
288    operations: HashMap<String, Vec<SemanticOperation>>,
289    records: HashMap<String, SemanticRecord>,
290    functions: HashMap<String, Ty>,
291    function_names: HashMap<u32, String>,
292}
293
294/// Stores a lowered operation shape for repeated checking.
295pub(crate) struct SemanticOperation {
296    pub(crate) operands: Vec<Ty>,
297    pub(crate) result: Ty,
298}
299/// Stores a lowered required-field schema.
300pub(crate) struct SemanticRecord {
301    pub(crate) ty: Ty,
302    pub(crate) fields: Vec<(String, Ty)>,
303}
304
305impl CheckingEnvironment {
306    /// Validates and owns a description with fresh catalog-local nominal identities.
307    ///
308    /// - Complexity: Expected O(n) time and space for description size n,
309    ///   including alias syntax and recursive argument shapes.
310    ///
311    /// # Errors
312    /// Rejects incompatible builtin contracts, duplicate identities/names/signatures,
313    /// unresolved references, invalid primitives, and shapes deeper than 128 nodes.
314    ///
315    /// # Examples
316    /// See the module example.
317    pub fn from_description(description: CheckingDescription) -> Result<Self, MetadataError> {
318        validate(&description)?;
319        Self::from_validated_description(description)
320    }
321
322    /// Lowers validated facts into indexed, freshly owned semantic identities.
323    ///
324    /// - Complexity: Expected O(n) time and space for description size n.
325    fn from_validated_description(description: CheckingDescription) -> Result<Self, MetadataError> {
326        let owner = Arc::new(());
327        let types: HashMap<_, _> = description
328            .types
329            .iter()
330            .map(|leaf| {
331                let ty = leaf
332                    .primitive
333                    .as_deref()
334                    .and_then(Ty::from_name)
335                    .unwrap_or_else(|| {
336                        Ty::Registered(NominalLeaf {
337                            identity: Identity::Catalog(owner.clone(), leaf.id),
338                            name: Arc::from(leaf.name.as_str()),
339                            capabilities: leaf.capabilities,
340                        })
341                    });
342                (leaf.id, ty)
343            })
344            .collect();
345        let names = description
346            .types
347            .iter()
348            .flat_map(|leaf| {
349                leaf.aliases
350                    .iter()
351                    .map(move |alias| (alias.clone(), leaf.id))
352            })
353            .collect();
354        let mut operations: HashMap<String, Vec<SemanticOperation>> = HashMap::new();
355        for operation in &description.operations {
356            operations
357                .entry(operation.name.clone())
358                .or_default()
359                .push(SemanticOperation {
360                    operands: operation
361                        .operands
362                        .iter()
363                        .map(|ty| lower(ty, &types))
364                        .collect(),
365                    result: lower(&operation.result, &types),
366                });
367        }
368        let mut records = HashMap::new();
369        for record in &description.records {
370            records.insert(
371                record.name.clone(),
372                SemanticRecord {
373                    ty: types[&record.ty].clone(),
374                    fields: record
375                        .fields
376                        .iter()
377                        .map(|(name, ty)| (name.clone(), lower(ty, &types)))
378                        .collect(),
379                },
380            );
381        }
382        let functions = description
383            .functions
384            .iter()
385            .map(|function| (function.name.clone(), types[&function.marker].clone()))
386            .collect();
387        let function_names = description
388            .functions
389            .iter()
390            .map(|function| (function.marker, function.name.clone()))
391            .collect();
392        let type_indices = description
393            .types
394            .iter()
395            .enumerate()
396            .map(|(index, ty)| (ty.id, index))
397            .collect();
398        let mut environment = Self {
399            owner,
400            description,
401            types,
402            type_indices,
403            names,
404            type_functions: HashMap::new(),
405            operations,
406            records,
407            functions,
408            function_names,
409        };
410        for signature in &environment.description.type_functions {
411            let CheckingType::Leaf(result) = signature.result else {
412                return Err(MetadataError("type-function result must be nominal".into()));
413            };
414            environment
415                .type_functions
416                .entry(signature.name.clone())
417                .or_default()
418                .insert(signature.arguments.clone(), result);
419        }
420        Ok(environment)
421    }
422
423    /// Borrows the validated wire description.
424    ///
425    /// # Examples
426    /// See [`CheckingDescription`].
427    pub fn description(&self) -> &CheckingDescription {
428        &self.description
429    }
430
431    /// Resolves a registered source name, preserving aliases and catalog ownership.
432    ///
433    /// - Complexity: Expected O(l + t) for name bytes l and returned shape size t.
434    ///
435    /// # Examples
436    /// ```
437    /// let env = cel_parser::checking::CheckingBuilder::new().finish().unwrap();
438    /// assert_eq!(env.resolve_type("i32"), Some(cel_parser::Ty::I32));
439    /// ```
440    pub fn resolve_type(&self, name: &str) -> Option<Ty> {
441        self.names.get(name).map(|id| self.types[id].clone())
442    }
443
444    /// Returns value capabilities for a nominal or primitive type in this catalog.
445    ///
446    /// Structural and foreign-catalog types have no nominal capability entry.
447    ///
448    /// # Examples
449    /// ```
450    /// let env = cel_parser::checking::CheckingBuilder::new().finish().unwrap();
451    /// assert!(env.capabilities(&cel_parser::Ty::I32).unwrap().cloneable);
452    /// ```
453    pub fn capabilities(&self, ty: &Ty) -> Option<Capabilities> {
454        let id = self.nominal_id(ty)?;
455        Some(self.description.types[self.type_indices[&id]].capabilities)
456    }
457
458    /// Returns the element accepted by a registered inclusive range.
459    ///
460    /// Types without range capability and foreign-catalog identities return `None`.
461    ///
462    /// # Examples
463    /// ```
464    /// let env = cel_parser::checking::CheckingBuilder::new().finish().unwrap();
465    /// let range = env.resolve_type("RangeInclusive(i32)").unwrap();
466    /// assert_eq!(env.range_element(&range), Some(cel_parser::Ty::I32));
467    /// ```
468    pub fn range_element(&self, ty: &Ty) -> Option<Ty> {
469        let id = self.nominal_id(ty)?;
470        self.description.types[self.type_indices[&id]]
471            .range_element
472            .map(|id| self.types[&id].clone())
473    }
474
475    /// Checks an annotation without constructing runtime descriptors.
476    ///
477    /// Missing host types follow `availability`; invalid language type syntax
478    /// remains a definite diagnostic. Unresolved leaves become `Any` without
479    /// erasing tuple, array, or callable siblings. Every independent finding is retained.
480    /// - Complexity: O(n * (r + t)) for n annotation nodes, worst-case strict
481    ///   resolution cost r and returned type area t.
482    ///
483    /// # Examples
484    /// ```
485    /// use cel_parser::checking::*;
486    /// let environment = CheckingBuilder::new().finish().unwrap();
487    /// let ty = cel_parser::CELParser::new(cel_parser::OpLookup::new())
488    ///     .parse_type_expr_str("i32").unwrap();
489    /// assert_eq!(environment.check_annotation(&ty, MetadataAvailability::Complete).value,
490    ///     cel_parser::Ty::I32);
491    /// let ty = cel_parser::CELParser::new(cel_parser::OpLookup::new())
492    ///     .parse_type_expr_str("(Missing, bool)").unwrap();
493    /// let report = environment.check_annotation(&ty, MetadataAvailability::Unavailable);
494    /// assert_eq!(report.value,
495    ///     cel_parser::Ty::Tuple(vec![cel_parser::Ty::Any, cel_parser::Ty::Bool]));
496    /// assert!(report.diagnostics.is_empty());
497    /// assert_eq!(report.incomplete.len(), 1);
498    /// ```
499    pub fn check_annotation(
500        &self,
501        expr: &TypeExpr,
502        availability: MetadataAvailability,
503    ) -> CheckingReport<Ty> {
504        let (value, errors) = resolve_partial_annotation(expr, &|ty| self.resolve_annotation(ty));
505        let (incomplete, diagnostics) = errors.into_iter().partition(|error| {
506            availability == MetadataAvailability::Unavailable && is_missing(error)
507        });
508        CheckingReport {
509            value,
510            diagnostics,
511            incomplete,
512        }
513    }
514
515    /// Borrows all overloads for one name.
516    pub(crate) fn operation_signatures(
517        &self,
518        name: &str,
519    ) -> impl Iterator<Item = &SemanticOperation> {
520        self.operations.get(name).into_iter().flatten()
521    }
522    /// Borrows the required-field contract for one record alias.
523    pub(crate) fn record_schema(&self, name: &str) -> Option<&SemanticRecord> {
524        self.records.get(name)
525    }
526    /// Copies the marker for a registered callable.
527    pub(crate) fn registered_function_type(&self, name: &str) -> Option<Ty> {
528        self.functions.get(name).cloned()
529    }
530    /// Borrows the dispatch name for a registered function marker.
531    pub(crate) fn registered_function_name(&self, marker: &Ty) -> Option<&str> {
532        self.function_names
533            .get(&self.nominal_id(marker)?)
534            .map(String::as_str)
535    }
536
537    /// Resolves complete structural annotations without constructing runtime descriptors.
538    ///
539    /// # Errors
540    /// Returns the first unresolved or invalid type; never substitutes `Any`.
541    ///
542    /// - Complexity: O(n + b) for annotation nodes n and formatted name bytes b.
543    pub(crate) fn resolve_annotation(&self, expr: &TypeExpr) -> Result<Ty, ParseError> {
544        match expr {
545            TypeExpr::Array { element, .. } => {
546                Ok(Ty::Array(Box::new(self.resolve_annotation(element)?)))
547            }
548            TypeExpr::Tuple { elements, .. } => Ok(Ty::Tuple(
549                elements
550                    .iter()
551                    .map(|ty| self.resolve_annotation(ty))
552                    .collect::<Result<_, _>>()?,
553            )),
554            TypeExpr::Named { name, args, span } if name == "Fn" => {
555                if let [parameters, result] = args.as_slice()
556                    && let Ty::Tuple(parameters) = self.resolve_annotation(parameters)?
557                {
558                    return Ok(Ty::Callable(
559                        parameters,
560                        Box::new(self.resolve_annotation(result)?),
561                    ));
562                }
563                Err(ParseError::new_range(
564                    "Fn requires a parameter tuple and result type",
565                    span.start,
566                    span.end,
567                ))
568            }
569            TypeExpr::Named { name, args, span } => {
570                if args.is_empty()
571                    && let Some(ty) = self.resolve_type(name)
572                {
573                    return Ok(ty);
574                }
575                let arguments = args
576                    .iter()
577                    .map(|arg| self.resolve_annotation(arg))
578                    .collect::<Result<Vec<_>, _>>()?;
579                let keys = arguments
580                    .iter()
581                    .map(|ty| self.type_reference(ty))
582                    .collect::<Option<Vec<_>>>();
583                keys.and_then(|keys| self.type_functions.get(name)?.get(keys.as_slice()))
584                    .map(|id| self.types[id].clone())
585                    .ok_or_else(|| {
586                        missing(
587                            if args.is_empty() {
588                                format!("unknown type `{name}`")
589                            } else {
590                                format!(
591                                    "unknown concrete type `{name}({})`",
592                                    arguments
593                                        .iter()
594                                        .map(Ty::name)
595                                        .collect::<Vec<_>>()
596                                        .join(", ")
597                                )
598                            },
599                            *span,
600                        )
601                    })
602            }
603        }
604    }
605
606    /// Returns a local structural reference, or `None` for unknown or foreign types.
607    ///
608    /// - Complexity: O(n) time and result space for n shape nodes.
609    ///
610    /// # Examples
611    /// ```
612    /// use cel_parser::{Ty, checking::{CheckingBuilder, CheckingType}};
613    /// let environment = CheckingBuilder::new().finish().unwrap();
614    /// assert!(matches!(environment.type_reference(&Ty::I32), Some(CheckingType::Leaf(_))));
615    /// ```
616    pub fn type_reference(&self, ty: &Ty) -> Option<CheckingType> {
617        Some(match ty {
618            Ty::Array(element) => CheckingType::Array(Box::new(self.type_reference(element)?)),
619            Ty::Tuple(elements) => CheckingType::Tuple(
620                elements
621                    .iter()
622                    .map(|ty| self.type_reference(ty))
623                    .collect::<Option<_>>()?,
624            ),
625            Ty::Callable(parameters, result) => CheckingType::Callable(
626                parameters
627                    .iter()
628                    .map(|ty| self.type_reference(ty))
629                    .collect::<Option<_>>()?,
630                Box::new(self.type_reference(result)?),
631            ),
632            Ty::Any => return None,
633            nominal => CheckingType::Leaf(self.nominal_id(nominal)?),
634        })
635    }
636
637    /// Returns the local identity of a primitive or an owned nominal leaf.
638    fn nominal_id(&self, ty: &Ty) -> Option<u32> {
639        match ty {
640            Ty::Registered(leaf) => {
641                let Identity::Catalog(_, id) = leaf.identity else {
642                    return None;
643                };
644                (self.types.get(&id) == Some(ty)).then_some(id)
645            }
646            Ty::Array(_) | Ty::Tuple(_) | Ty::Callable(..) | Ty::Any => None,
647            primitive => self.names.get(primitive.name().as_ref()).copied(),
648        }
649    }
650}
651
652/// Builds an offline catalog by reading retained host registration facts.
653///
654/// Runtime descriptors remain in the caller's registrations, never in the finished environment.
655///
656/// # Examples
657/// See the module example.
658pub struct CheckingBuilder {
659    description: CheckingDescription,
660    bindings: HashMap<TypeId, u32>,
661}
662
663/// Binds host nominal identities explicitly to one checking catalog.
664///
665/// This object contains no executable descriptors and is never serialized.
666/// A separately imported catalog requires a new binding, even with identical bytes.
667///
668/// # Examples
669/// ```
670/// use cel_parser::{Ty, checking::*};
671/// let environment = CheckingBuilder::new().finish().unwrap();
672/// let mut binding = HostTypeBinding::new(&environment);
673/// binding.bind::<i32>(&environment, Ty::I32).unwrap();
674/// assert_eq!(binding.resolve(&environment, std::any::TypeId::of::<i32>()), Some(Ty::I32));
675/// ```
676#[derive(Clone)]
677pub struct HostTypeBinding {
678    owner: Arc<()>,
679    types: HashMap<TypeId, Ty>,
680}
681
682impl HostTypeBinding {
683    /// Creates an empty binding owned by `environment`.
684    ///
685    /// # Examples
686    /// See the [type example](Self).
687    pub fn new(environment: &CheckingEnvironment) -> Self {
688        Self {
689            owner: environment.owner.clone(),
690            types: HashMap::new(),
691        }
692    }
693
694    /// Binds `T` to the explicitly selected nominal type.
695    ///
696    /// # Errors
697    /// Rejects foreign catalogs, structural/unknown types, and conflicting bindings.
698    /// - Complexity: Expected O(t) type comparison and retained type size t.
699    ///
700    /// # Examples
701    /// See the [type example](Self).
702    pub fn bind<T: 'static>(
703        &mut self,
704        environment: &CheckingEnvironment,
705        ty: Ty,
706    ) -> Result<(), MetadataError> {
707        if !Arc::ptr_eq(&self.owner, &environment.owner) || environment.nominal_id(&ty).is_none() {
708            return Err(MetadataError(
709                "native binding requires a nominal type from its owning catalog".into(),
710            ));
711        }
712        let id = TypeId::of::<T>();
713        if self.types.get(&id).is_some_and(|prior| *prior != ty) {
714            return Err(MetadataError("conflicting native type binding".into()));
715        }
716        self.types.insert(id, ty);
717        Ok(())
718    }
719
720    /// Resolves a host identity only in this binding's owning catalog.
721    ///
722    /// - Complexity: Expected O(t) for returned type size t.
723    ///
724    /// # Examples
725    /// See the [type example](Self).
726    pub fn resolve(&self, environment: &CheckingEnvironment, id: TypeId) -> Option<Ty> {
727        Arc::ptr_eq(&self.owner, &environment.owner)
728            .then(|| self.types.get(&id).cloned())
729            .flatten()
730    }
731}
732
733impl Default for CheckingBuilder {
734    /// Creates a builtin-seeded builder.
735    fn default() -> Self {
736        Self::new()
737    }
738}
739
740impl CheckingBuilder {
741    /// Projects one nominal overload without executing a host resolver or emitter.
742    ///
743    /// Repeated keys and result identities merge nominal descriptor facts.
744    /// Exact repeats are idempotent.
745    ///
746    /// # Errors
747    /// Rejects invalid constructor names, incomplete descriptors, conflicting results,
748    /// and zero-operand names bound to a different source alias identity.
749    ///
750    /// - Complexity: O(n ยท m + k ยท s) time and O(n) retained space for incoming
751    ///   descriptor area n, retained nominal metadata area m, k existing signatures,
752    ///   and largest compared argument/name area s.
753    ///
754    /// # Examples
755    /// ```
756    /// use cel_parser::{ResolvedLeafType, checking::CheckingBuilder};
757    /// let mut builder = CheckingBuilder::new();
758    /// let argument = ResolvedLeafType::leaf::<i32>("Integer").unwrap().into();
759    /// let result = ResolvedLeafType::leaf::<std::ops::Range<i32>>("Bounds").unwrap();
760    /// builder.register_type_function("Bounds", &[argument], &result).unwrap();
761    /// assert!(builder.finish().is_ok());
762    /// ```
763    pub fn register_type_function(
764        &mut self,
765        name: &str,
766        arguments: &[ResolvedType],
767        result: &ResolvedLeafType,
768    ) -> Result<(), MetadataError> {
769        if !crate::type_functions::valid_type_function_name(name) {
770            return Err(MetadataError("invalid type-function name".into()));
771        }
772        for argument in arguments {
773            argument
774                .complete_value_type()
775                .map_err(|error| MetadataError(error.to_string()))?;
776        }
777        result
778            .complete_value_type()
779            .map_err(|error| MetadataError(error.to_string()))?;
780        let arguments = arguments
781            .iter()
782            .map(|argument| self.shape(argument))
783            .collect::<Result<Vec<_>, _>>()?;
784        let result = CheckingType::Leaf(self.intern(result)?);
785        if arguments.is_empty()
786            && self.description.types.iter().any(|ty| {
787                ty.aliases.iter().any(|alias| alias == name) && result != CheckingType::Leaf(ty.id)
788            })
789        {
790            return Err(MetadataError(
791                "conflicting type alias and zero-operand type function".into(),
792            ));
793        }
794        if let Some(previous) = self
795            .description
796            .type_functions
797            .iter()
798            .find(|signature| signature.name == name && signature.arguments == arguments)
799        {
800            return if previous.result == result {
801                Ok(())
802            } else {
803                Err(MetadataError("conflicting type-function result".into()))
804            };
805        }
806        self.description
807            .type_functions
808            .push(TypeFunctionDescription {
809                name: name.into(),
810                arguments,
811                result,
812            });
813        Ok(())
814    }
815
816    /// Projects retained argument and result descriptors without invoking callbacks.
817    ///
818    /// # Errors
819    /// Reports invalid or conflicting registrations as [`Self::register_type_function`].
820    ///
821    /// - Complexity: O(n ยท m + kยฒ ยท s) time and O(n) retained space for incoming
822    ///   descriptor area n, combined nominal metadata area m, combined signature
823    ///   count k, and largest compared argument/name area s.
824    ///
825    /// # Examples
826    /// ```
827    /// let functions = cel_parser::type_functions::TypeFunctionRegistry::new();
828    /// let mut builder = cel_parser::checking::CheckingBuilder::new();
829    /// builder.register_type_functions(&functions).unwrap();
830    /// ```
831    pub fn register_type_functions(
832        &mut self,
833        functions: &crate::type_functions::TypeFunctionRegistry,
834    ) -> Result<(), MetadataError> {
835        for (name, arguments, result) in functions.descriptors() {
836            self.register_type_function(name, arguments, result)?;
837        }
838        Ok(())
839    }
840
841    /// Creates a builder seeded with language primitive and range contracts.
842    ///
843    /// # Examples
844    /// See the module example.
845    pub fn new() -> Self {
846        let mut builder = Self {
847            description: CheckingDescription {
848                builtin_contract: 1,
849                types: vec![],
850                operations: vec![],
851                records: vec![],
852                functions: vec![],
853                type_functions: vec![],
854            },
855            bindings: HashMap::new(),
856        };
857        for name in crate::op_table::BUILTIN_SCALAR_NAMES {
858            let scalar = crate::op_table::builtin_scalar_type(name).expect("builtin scalar");
859            builder
860                .register_type(
861                    name,
862                    &ResolvedLeafType::new(*name, (scalar.value_type)()),
863                    true,
864                )
865                .expect("builtin metadata");
866        }
867        let functions = crate::type_functions::builtin_type_functions();
868        builder
869            .register_type_functions(functions)
870            .expect("builtin type functions");
871        for (name, arguments, result) in functions.descriptors() {
872            builder
873                .register_type(result.type_name(), result, false)
874                .expect("builtin alias");
875            if name == "RangeInclusive"
876                && let [ResolvedType::Scalar(element)] = arguments
877            {
878                builder
879                    .register_range(result, element)
880                    .expect("builtin range element");
881            }
882        }
883        builder
884            .register_type(
885                "char",
886                &ResolvedLeafType::leaf::<char>("char").expect("char leaf"),
887                false,
888            )
889            .expect("char metadata");
890        let bytes = builder
891            .intern(&ResolvedLeafType::leaf::<Vec<u8>>("byte string").expect("bytes leaf"))
892            .expect("bytes metadata");
893        builder.description.types[bytes as usize]
894            .aliases
895            .push("byte string".into());
896        let cstring = builder
897            .intern(
898                &ResolvedLeafType::leaf::<std::ffi::CString>("C string").expect("C string leaf"),
899            )
900            .expect("C string metadata");
901        builder.description.types[cstring as usize]
902            .aliases
903            .push("C string".into());
904        builder
905    }
906
907    /// Registers a source alias and default availability for a concrete host leaf.
908    ///
909    /// - Complexity: Expected O(m + l) time for retained type and signature metadata
910    ///   area m (including alias entries and name bytes) and incoming names' bytes l;
911    ///   O(l) additional name storage.
912    ///
913    /// # Errors
914    /// Rejects names exceeding metadata limits and conflicting source aliases or
915    /// zero-operand type functions.
916    /// [`Self::finish`] additionally validates source alias grammar.
917    ///
918    /// # Examples
919    /// ```
920    /// let mut builder = cel_parser::checking::CheckingBuilder::new();
921    /// let leaf = cel_parser::ResolvedLeafType::leaf::<std::path::PathBuf>("Path").unwrap();
922    /// builder.register_type("Path", &leaf, false).unwrap();
923    /// ```
924    pub fn register_type(
925        &mut self,
926        name: &str,
927        leaf: &ResolvedLeafType,
928        default_available: bool,
929    ) -> Result<(), MetadataError> {
930        if !valid_metadata_name(name) {
931            return Err(MetadataError("invalid type alias".into()));
932        }
933        let id = self.intern(leaf)?;
934        if self.description.type_functions.iter().any(|signature| {
935            signature.name == name
936                && signature.arguments.is_empty()
937                && signature.result != CheckingType::Leaf(id)
938        }) {
939            return Err(MetadataError(
940                "conflicting type alias and zero-operand type function".into(),
941            ));
942        }
943        if self
944            .description
945            .types
946            .iter()
947            .any(|ty| ty.id != id && ty.aliases.iter().any(|alias| alias == name))
948        {
949            return Err(MetadataError(format!("duplicate type alias `{name}`")));
950        }
951        let ty = &mut self.description.types[id as usize];
952        if !ty.aliases.iter().any(|alias| alias == name) {
953            ty.aliases.push(name.into());
954        }
955        ty.capabilities.default_available |= default_available;
956        Ok(())
957    }
958
959    /// Selects the effective host default availability for an already registered leaf.
960    ///
961    /// Unlike adding an alias, this replaces prior availability, including builtin
962    /// defaults. It does not construct a value.
963    ///
964    /// # Errors
965    /// Rejects leaves not registered in this builder.
966    ///
967    /// # Examples
968    /// ```
969    /// use cel_parser::{checking::*, ResolvedLeafType};
970    /// let mut builder = CheckingBuilder::new();
971    /// builder.set_default_available(&ResolvedLeafType::leaf::<i32>("i32").unwrap(), false).unwrap();
972    /// let environment = builder.finish().unwrap();
973    /// assert!(!environment.capabilities(&cel_parser::Ty::I32).unwrap().default_available);
974    /// ```
975    pub fn set_default_available(
976        &mut self,
977        leaf: &ResolvedLeafType,
978        available: bool,
979    ) -> Result<(), MetadataError> {
980        let id = self.bindings.get(&leaf.type_id()).ok_or_else(|| {
981            MetadataError("default availability requires a registered leaf".into())
982        })?;
983        self.description.types[*id as usize]
984            .capabilities
985            .default_available = available;
986        Ok(())
987    }
988
989    /// Registers an inclusive range's accepted element identity and both source names.
990    ///
991    /// - Complexity: Expected O(m + l) time for retained type metadata size m
992    ///   (including alias entries and name bytes) and incoming names' bytes l;
993    ///   O(l) additional name storage.
994    ///
995    /// # Errors
996    /// Rejects conflicting range element identities.
997    ///
998    /// # Examples
999    /// See [`Self::register_type`] for creating host leaves.
1000    pub fn register_range(
1001        &mut self,
1002        range: &ResolvedLeafType,
1003        element: &ResolvedLeafType,
1004    ) -> Result<(), MetadataError> {
1005        self.register_type(range.type_name(), range, false)?;
1006        self.register_type(element.type_name(), element, false)?;
1007        let range = self.intern(range)?;
1008        let element = self.intern(element)?;
1009        let slot = &mut self.description.types[range as usize].range_element;
1010        if slot.is_some_and(|previous| previous != element) {
1011            return Err(MetadataError("conflicting range element".into()));
1012        }
1013        *slot = Some(element);
1014        Ok(())
1015    }
1016
1017    /// Projects persistent operation, function, and record metadata without invoking callbacks.
1018    ///
1019    /// - Complexity: O(n ยท (r + n)) time and O(r + n) peak space for new
1020    ///   registration metadata area n and previously accumulated description area r,
1021    ///   including names, aliases, and recursive shapes.
1022    ///
1023    /// # Errors
1024    /// Rejects callback-only scopes, legacy tuple registrations, and conflicting metadata.
1025    ///
1026    /// # Examples
1027    /// ```
1028    /// let mut builder = cel_parser::checking::CheckingBuilder::new();
1029    /// builder.register_lookup(&cel_parser::OpLookup::new()).unwrap();
1030    /// ```
1031    pub fn register_lookup(&mut self, lookup: &OpLookup) -> Result<(), MetadataError> {
1032        if let Some(category) = lookup.unsupported_checking_metadata() {
1033            return Err(MetadataError(format!(
1034                "{category} lacks complete checking metadata"
1035            )));
1036        }
1037        self.project_lookup(lookup)
1038    }
1039
1040    /// Projects retained metadata while allowing executing legacy callers to retain opaque scopes.
1041    ///
1042    /// - Complexity: O(n ยท (r + n)) time and O(r + n) peak space for new
1043    ///   registration metadata area n and previously accumulated description area r,
1044    ///   including names, aliases, and recursive shapes.
1045    pub(crate) fn project_lookup(&mut self, lookup: &OpLookup) -> Result<(), MetadataError> {
1046        for operation in &lookup.registered.operations {
1047            let operands = operation
1048                .operands
1049                .iter()
1050                .map(|ty| self.shape(ty))
1051                .collect::<Result<_, _>>()?;
1052            let result = self.shape(&operation.result)?;
1053            if self
1054                .description
1055                .operations
1056                .iter()
1057                .any(|previous| previous.name == operation.name && previous.operands == operands)
1058            {
1059                return Err(MetadataError(format!(
1060                    "duplicate operation signature `{}`",
1061                    operation.name
1062                )));
1063            }
1064            self.description.operations.push(OperationDescription {
1065                name: operation.name.into(),
1066                operands,
1067                result,
1068            });
1069        }
1070        for record in &lookup.registered.records {
1071            if self
1072                .description
1073                .records
1074                .iter()
1075                .any(|previous| previous.name == record.ty.type_name())
1076            {
1077                return Err(MetadataError(format!(
1078                    "duplicate record constructor `{}`",
1079                    record.ty.type_name()
1080                )));
1081            }
1082            let ty = self.intern(&record.ty)?;
1083            let fields = record
1084                .fields
1085                .iter()
1086                .map(|field| Ok((field.name.into(), self.shape(&field.ty)?)))
1087                .collect::<Result<_, MetadataError>>()?;
1088            let name = record.ty.type_name();
1089            if !self.description.types[ty as usize]
1090                .aliases
1091                .iter()
1092                .any(|alias| alias == name)
1093            {
1094                self.description.types[ty as usize]
1095                    .aliases
1096                    .push(name.into());
1097            }
1098            self.description.records.push(RecordDescription {
1099                name: name.into(),
1100                ty,
1101                fields,
1102            });
1103        }
1104        for function in &lookup.registered.functions {
1105            if self
1106                .description
1107                .functions
1108                .iter()
1109                .any(|previous| previous.name == function.name)
1110            {
1111                return Err(MetadataError(format!(
1112                    "duplicate function name `{}`",
1113                    function.name
1114                )));
1115            }
1116            let marker = self.intern(&function.marker)?;
1117            self.description.functions.push(FunctionDescription {
1118                name: function.name.into(),
1119                marker,
1120            });
1121        }
1122        Ok(())
1123    }
1124
1125    /// Validates and transfers the accumulated description into a fresh environment.
1126    ///
1127    /// Ordering ignores registration and hash iteration order for unchanged runtime
1128    /// identities. Host-only `TypeId` ordering breaks ties between identical
1129    /// diagnostic names and alias lists; no raw `TypeId` is serialized.
1130    /// Catalog-local nominal IDs are not stable application identifiers across
1131    /// builds. A rebuild may reorder IDs and change description bytes without
1132    /// changing checking semantics.
1133    ///
1134    /// - Complexity: O(n log n ยท m) time and O(n) space for description size n
1135    ///   and largest compared name or shape size m.
1136    ///
1137    /// # Errors
1138    /// Returns the description-validation errors documented by that method.
1139    ///
1140    /// # Examples
1141    /// See the module example.
1142    pub fn finish(self) -> Result<CheckingEnvironment, MetadataError> {
1143        self.finish_with_bindings()
1144            .map(|(environment, _)| environment)
1145    }
1146
1147    /// Finalizes a catalog and its explicit, nonserializable host identity binding.
1148    ///
1149    /// # Errors
1150    /// Reports the same invalid-registration conditions as [`Self::finish`].
1151    /// - Complexity: Catalog finalization plus expected O(n) host bindings.
1152    ///
1153    /// # Examples
1154    /// ```
1155    /// let (environment, binding) = cel_parser::checking::CheckingBuilder::new()
1156    ///     .finish_with_host_binding().unwrap();
1157    /// assert_eq!(binding.resolve(&environment, std::any::TypeId::of::<i32>()),
1158    ///     Some(cel_parser::Ty::I32));
1159    /// ```
1160    pub fn finish_with_host_binding(
1161        self,
1162    ) -> Result<(CheckingEnvironment, HostTypeBinding), MetadataError> {
1163        let (environment, ids) = self.finish_with_bindings()?;
1164        let mut binding = HostTypeBinding::new(&environment);
1165        binding.types.extend(
1166            ids.into_iter()
1167                .map(|(host, local)| (host, environment.types[&local].clone())),
1168        );
1169        Ok((environment, binding))
1170    }
1171
1172    /// Finalizes one deterministic projection together with its host-side identity binding.
1173    ///
1174    /// - Complexity: O(n log n ยท m) for description size n and largest compared name or shape m.
1175    pub(crate) fn finish_with_bindings(
1176        mut self,
1177    ) -> Result<(CheckingEnvironment, HashMap<TypeId, u32>), MetadataError> {
1178        validate(&self.description)?;
1179        self.canonicalize();
1180        let environment = CheckingEnvironment::from_validated_description(self.description)?;
1181        Ok((environment, self.bindings))
1182    }
1183
1184    /// Orders validated records and reassigns all local references consistently.
1185    ///
1186    /// - Complexity: O(n log n ยท m) for description size n and largest compared name or shape m.
1187    fn canonicalize(&mut self) {
1188        let mut host_ids = vec![None; self.description.types.len()];
1189        for (&host, &local) in &self.bindings {
1190            host_ids[local as usize] = Some(host);
1191        }
1192        debug_assert!(host_ids.iter().all(Option::is_some));
1193        for ty in &mut self.description.types {
1194            ty.aliases.sort();
1195        }
1196        self.description.types.sort_by(|left, right| {
1197            (&left.name, &left.aliases)
1198                .cmp(&(&right.name, &right.aliases))
1199                .then_with(|| host_ids[left.id as usize].cmp(&host_ids[right.id as usize]))
1200        });
1201        let identities: HashMap<_, _> = self
1202            .description
1203            .types
1204            .iter()
1205            .enumerate()
1206            .map(|(index, ty)| (ty.id, u32::try_from(index).expect("validated catalog size")))
1207            .collect();
1208        for ty in &mut self.description.types {
1209            ty.id = identities[&ty.id];
1210            ty.range_element = ty.range_element.map(|id| identities[&id]);
1211        }
1212        for id in self.bindings.values_mut() {
1213            *id = identities[id];
1214        }
1215        for operation in &mut self.description.operations {
1216            for operand in &mut operation.operands {
1217                remap_shape(operand, &identities);
1218            }
1219            remap_shape(&mut operation.result, &identities);
1220        }
1221        for signature in &mut self.description.type_functions {
1222            for argument in &mut signature.arguments {
1223                remap_shape(argument, &identities);
1224            }
1225            remap_shape(&mut signature.result, &identities);
1226        }
1227        self.description.type_functions.sort_by(|left, right| {
1228            (&left.name, &left.arguments).cmp(&(&right.name, &right.arguments))
1229        });
1230        self.description.operations.sort_by(|left, right| {
1231            (&left.name, &left.operands).cmp(&(&right.name, &right.operands))
1232        });
1233        for record in &mut self.description.records {
1234            record.ty = identities[&record.ty];
1235            for (_, field) in &mut record.fields {
1236                remap_shape(field, &identities);
1237            }
1238        }
1239        self.description
1240            .records
1241            .sort_by(|left, right| left.name.cmp(&right.name));
1242        for function in &mut self.description.functions {
1243            function.marker = identities[&function.marker];
1244        }
1245        self.description
1246            .functions
1247            .sort_by(|left, right| left.name.cmp(&right.name));
1248    }
1249
1250    /// Interns concrete identity and capabilities without declaring source aliases.
1251    ///
1252    /// Selects the lexicographically least retained descriptor name for diagnostics.
1253    ///
1254    /// - Complexity: O(t + l) for types t and name bytes l.
1255    fn intern(&mut self, leaf: &ResolvedLeafType) -> Result<u32, MetadataError> {
1256        if !valid_metadata_name(leaf.type_name()) {
1257            return Err(MetadataError("invalid nominal diagnostic name".into()));
1258        }
1259        let capabilities = Capabilities::from_host(leaf);
1260        if let Some(&id) = self.bindings.get(&leaf.type_id()) {
1261            let ty = &mut self.description.types[id as usize];
1262            if leaf.type_name() < ty.name.as_str() {
1263                ty.name = leaf.type_name().into();
1264            }
1265            // Metadata can add capabilities through a complete descriptor.
1266            ty.capabilities.cloneable |= capabilities.cloneable;
1267            ty.capabilities.comparable |= capabilities.comparable;
1268            ty.capabilities.debuggable |= capabilities.debuggable;
1269            return Ok(id);
1270        }
1271        let id = u32::try_from(self.description.types.len())
1272            .map_err(|_| MetadataError("too many nominal types".into()))?;
1273        let primitive = Ty::from_type_id(leaf.type_id());
1274        self.description.types.push(TypeDescription {
1275            id,
1276            name: leaf.type_name().into(),
1277            aliases: vec![],
1278            primitive: (primitive != Ty::Any).then(|| primitive.name().into_owned()),
1279            capabilities,
1280            range_element: None,
1281        });
1282        self.bindings.insert(leaf.type_id(), id);
1283        Ok(id)
1284    }
1285
1286    /// Projects a complete runtime shape into catalog-local references.
1287    ///
1288    /// - Complexity: O(n ยท t) for shape nodes n and catalog types t.
1289    fn shape(&mut self, ty: &ResolvedType) -> Result<CheckingType, MetadataError> {
1290        Ok(match ty {
1291            ResolvedType::Scalar(leaf) => CheckingType::Leaf(self.intern(leaf)?),
1292            ResolvedType::Array { element } => CheckingType::Array(Box::new(self.shape(element)?)),
1293            ResolvedType::Tuple { elements } => CheckingType::Tuple(
1294                elements
1295                    .iter()
1296                    .map(|ty| self.shape(ty))
1297                    .collect::<Result<_, _>>()?,
1298            ),
1299            ResolvedType::Callable { parameters, result } => CheckingType::Callable(
1300                parameters
1301                    .iter()
1302                    .map(|ty| self.shape(ty))
1303                    .collect::<Result<_, _>>()?,
1304                Box::new(self.shape(result)?),
1305            ),
1306        })
1307    }
1308}
1309
1310/// Reassigns leaf references in one validated structural shape.
1311///
1312/// - Complexity: O(n) time and O(d) stack space for nodes n at depth d.
1313fn remap_shape(shape: &mut CheckingType, identities: &HashMap<u32, u32>) {
1314    match shape {
1315        CheckingType::Leaf(id) => *id = identities[id],
1316        CheckingType::Array(element) => remap_shape(element, identities),
1317        CheckingType::Tuple(elements) => {
1318            for element in elements {
1319                remap_shape(element, identities);
1320            }
1321        }
1322        CheckingType::Callable(parameters, result) => {
1323            for parameter in parameters {
1324                remap_shape(parameter, identities);
1325            }
1326            remap_shape(result, identities);
1327        }
1328    }
1329}
1330
1331/// Lowers one validated shape, preserving nominal references without record expansion.
1332///
1333/// - Complexity: O(n) time and result space for shape nodes n.
1334fn lower(shape: &CheckingType, types: &HashMap<u32, Ty>) -> Ty {
1335    match shape {
1336        CheckingType::Leaf(id) => types[id].clone(),
1337        CheckingType::Array(element) => Ty::Array(Box::new(lower(element, types))),
1338        CheckingType::Tuple(elements) => {
1339            Ty::Tuple(elements.iter().map(|ty| lower(ty, types)).collect())
1340        }
1341        CheckingType::Callable(parameters, result) => Ty::Callable(
1342            parameters.iter().map(|ty| lower(ty, types)).collect(),
1343            Box::new(lower(result, types)),
1344        ),
1345    }
1346}
1347
1348/// Validates external nominal references and structural depth before lowering.
1349///
1350/// - Complexity: Expected O(n) time and space for description size n, including shapes.
1351fn validate(description: &CheckingDescription) -> Result<(), MetadataError> {
1352    let fail = |message: &str| MetadataError(message.into());
1353    if description.builtin_contract != 1 {
1354        return Err(fail("unsupported builtin checking contract"));
1355    }
1356    let mut ids = HashSet::new();
1357    let mut names = HashMap::new();
1358    let mut primitives = HashSet::new();
1359    let mut alias_parser = crate::CELParser::new(OpLookup::new());
1360    for leaf in &description.types {
1361        if !ids.insert(leaf.id) {
1362            return Err(fail("duplicate nominal identity"));
1363        }
1364        if !valid_metadata_name(&leaf.name) {
1365            return Err(fail("invalid canonical type name"));
1366        }
1367        for alias in &leaf.aliases {
1368            if !valid_metadata_name(alias) || names.insert(alias.as_str(), leaf).is_some() {
1369                return Err(fail("duplicate or invalid type alias"));
1370            }
1371            if !matches!(alias.as_str(), "byte string" | "C string") {
1372                let syntax = alias_parser.parse_type_expr_str(alias).map_err(|error| {
1373                    MetadataError(format!("invalid type alias `{alias}`: {error}"))
1374                })?;
1375                if !matches!(syntax, TypeExpr::Named { name, .. } if name != "Fn") {
1376                    return Err(fail("type alias must name a nominal type"));
1377                }
1378            }
1379        }
1380        if let Some(primitive) = &leaf.primitive
1381            && (Ty::from_name(primitive).is_none()
1382                || !primitives.insert(primitive)
1383                || !leaf.aliases.contains(primitive))
1384        {
1385            return Err(fail("invalid or duplicate primitive identity"));
1386        }
1387    }
1388    validate_builtins(&names)?;
1389    for leaf in &description.types {
1390        if leaf.range_element.is_some_and(|id| !ids.contains(&id)) {
1391            return Err(fail("unresolved range element"));
1392        }
1393    }
1394    let mut shapes = Vec::new();
1395    for signature in &description.type_functions {
1396        if !crate::type_functions::valid_type_function_name(&signature.name)
1397            || !matches!(signature.result, CheckingType::Leaf(_))
1398        {
1399            return Err(fail("invalid or duplicate type-function signature"));
1400        }
1401        shapes.extend(signature.arguments.iter().map(|ty| (ty, 0usize)));
1402        shapes.push((&signature.result, 0));
1403    }
1404    for operation in &description.operations {
1405        if !valid_metadata_name(&operation.name) {
1406            return Err(fail("invalid operation name"));
1407        }
1408        shapes.extend(operation.operands.iter().map(|ty| (ty, 0usize)));
1409        shapes.push((&operation.result, 0));
1410    }
1411    let mut records = HashSet::new();
1412    for record in &description.records {
1413        if !ids.contains(&record.ty)
1414            || !records.insert(&record.name)
1415            || names
1416                .get(record.name.as_str())
1417                .is_none_or(|ty| ty.id != record.ty)
1418        {
1419            return Err(fail(
1420                "unresolved record identity or duplicate constructor name",
1421            ));
1422        }
1423        let mut fields = HashSet::new();
1424        for (name, ty) in &record.fields {
1425            if !valid_metadata_name(name) || !fields.insert(name) {
1426                return Err(fail("duplicate or invalid field name"));
1427            }
1428            shapes.push((ty, 0));
1429        }
1430    }
1431    let mut functions = HashSet::new();
1432    let mut markers = HashSet::new();
1433    for function in &description.functions {
1434        if !valid_metadata_name(&function.name)
1435            || !functions.insert(&function.name)
1436            || !markers.insert(function.marker)
1437            || !ids.contains(&function.marker)
1438        {
1439            return Err(fail("invalid function identity or name"));
1440        }
1441    }
1442    while let Some((shape, depth)) = shapes.pop() {
1443        if depth > 128 {
1444            return Err(fail("checking shape exceeds maximum depth 128"));
1445        }
1446        match shape {
1447            CheckingType::Leaf(id) if !ids.contains(id) => {
1448                return Err(fail("unresolved shape leaf"));
1449            }
1450            CheckingType::Leaf(_) => {}
1451            CheckingType::Array(element) => shapes.push((element, depth + 1)),
1452            CheckingType::Tuple(elements) => {
1453                shapes.extend(elements.iter().map(|ty| (ty, depth + 1)))
1454            }
1455            CheckingType::Callable(parameters, result) => {
1456                shapes.extend(parameters.iter().map(|ty| (ty, depth + 1)));
1457                shapes.push((result, depth + 1));
1458            }
1459        }
1460    }
1461    let mut signatures = HashSet::new();
1462    let mut type_functions = HashSet::new();
1463    for signature in &description.type_functions {
1464        if !type_functions.insert((signature.name.as_str(), signature.arguments.as_slice())) {
1465            return Err(fail("duplicate type-function signature"));
1466        }
1467        if signature.arguments.is_empty()
1468            && names
1469                .get(signature.name.as_str())
1470                .is_some_and(|alias| signature.result != CheckingType::Leaf(alias.id))
1471        {
1472            return Err(fail(
1473                "conflicting type alias and zero-operand type function",
1474            ));
1475        }
1476    }
1477    for operation in &description.operations {
1478        if !signatures.insert((operation.name.as_str(), operation.operands.as_slice())) {
1479            return Err(fail("duplicate operation signature"));
1480        }
1481    }
1482    validate_builtin_type_functions(description, &names)?;
1483    Ok(())
1484}
1485
1486/// Verifies explicit builtin signatures against their declared catalog roles.
1487///
1488/// - Complexity: O(n) time for signature metadata area n and the fixed builtin vocabulary.
1489fn validate_builtin_type_functions(
1490    description: &CheckingDescription,
1491    names: &HashMap<&str, &TypeDescription>,
1492) -> Result<(), MetadataError> {
1493    let fail = || MetadataError("missing or inconsistent builtin type-function signature".into());
1494    for (name, arguments, result) in crate::type_functions::builtin_type_functions().descriptors() {
1495        let argument = match arguments {
1496            [] => None,
1497            [ResolvedType::Scalar(argument)] => Some(CheckingType::Leaf(
1498                names.get(argument.type_name()).ok_or_else(fail)?.id,
1499            )),
1500            _ => return Err(fail()),
1501        };
1502        let result = CheckingType::Leaf(names.get(result.type_name()).ok_or_else(fail)?.id);
1503        if !description.type_functions.iter().any(|signature| {
1504            signature.name == name
1505                && signature.arguments == argument.as_slice()
1506                && signature.result == result
1507        }) {
1508            return Err(fail());
1509        }
1510    }
1511    Ok(())
1512}
1513
1514/// Verifies that serialized builtin facts agree with the supported language contract.
1515///
1516/// - Complexity: Expected O(1), since the builtin vocabulary is fixed.
1517fn validate_builtins(names: &HashMap<&str, &TypeDescription>) -> Result<(), MetadataError> {
1518    let fail = |message: &str| MetadataError(message.into());
1519    let mut identities = HashSet::new();
1520    let mut role = |name: &str| {
1521        let leaf = names
1522            .get(name)
1523            .copied()
1524            .ok_or_else(|| fail("missing builtin identity"))?;
1525        if !identities.insert(leaf.id) {
1526            return Err(fail("distinct builtin roles share one nominal identity"));
1527        }
1528        Ok(leaf)
1529    };
1530    for name in crate::op_table::BUILTIN_SCALAR_NAMES {
1531        let leaf = role(name)?;
1532        if leaf.primitive.as_deref() != Some(*name)
1533            || !leaf.capabilities.cloneable
1534            || !leaf.capabilities.comparable
1535            || !leaf.capabilities.debuggable
1536            || leaf.range_element.is_some()
1537        {
1538            return Err(fail(
1539                "inconsistent builtin primitive capabilities or identity",
1540            ));
1541        }
1542    }
1543    for name in ["char", "byte string", "C string", "RangeFull"] {
1544        if role(name)?.primitive.is_some() {
1545            return Err(fail("missing or inconsistent builtin nominal identity"));
1546        }
1547    }
1548    for range in [
1549        "Range",
1550        "RangeInclusive",
1551        "RangeFrom",
1552        "RangeTo",
1553        "RangeToInclusive",
1554    ] {
1555        for element in crate::op_table::BUILTIN_SCALAR_NAMES
1556            .iter()
1557            .filter(|name| !matches!(**name, "bool" | "String"))
1558        {
1559            let name = format!("{range}({element})");
1560            let leaf = role(&name)?;
1561            let expected = (range == "RangeInclusive").then_some(names[element].id);
1562            if leaf.primitive.is_some() || leaf.range_element != expected {
1563                return Err(fail("inconsistent builtin range capability"));
1564            }
1565        }
1566    }
1567    Ok(())
1568}
1569
1570/// Bounds metadata name storage and syntax nesting before invoking the type parser.
1571///
1572/// - Complexity: O(l) for name bytes l.
1573fn valid_metadata_name(name: &str) -> bool {
1574    if name.trim().is_empty() || name.len() > 4096 {
1575        return false;
1576    }
1577    let mut depth = 0usize;
1578    for byte in name.bytes() {
1579        if matches!(byte, b'(' | b'[') {
1580            depth += 1;
1581            if depth > 64 {
1582                return false;
1583            }
1584        } else if matches!(byte, b')' | b']') {
1585            depth = depth.saturating_sub(1);
1586        }
1587    }
1588    true
1589}
1590
1591/// Identifies a missing semantic fact without classifying unrelated errors as incomplete.
1592#[derive(Debug)]
1593struct MissingMetadata {
1594    legacy_ignored: bool,
1595}
1596impl fmt::Display for MissingMetadata {
1597    /// Formats the missing-fact category.
1598    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1599        f.write_str("missing checking metadata")
1600    }
1601}
1602impl std::error::Error for MissingMetadata {}
1603
1604/// Creates a source diagnostic carrying the unavailable-metadata category.
1605pub(crate) fn missing(message: String, span: ExprSpan) -> ParseError {
1606    ParseError::new_range(message, span.start, span.end).with_cause(MissingMetadata {
1607        legacy_ignored: false,
1608    })
1609}
1610
1611/// Marks an unknown name accepted by the older best-effort checking entry points.
1612pub(crate) fn optional_missing(message: String, span: ExprSpan) -> ParseError {
1613    ParseError::new_range(message, span.start, span.end).with_cause(MissingMetadata {
1614        legacy_ignored: true,
1615    })
1616}
1617
1618/// Checks an expression using only catalog facts and lexical declarations.
1619///
1620/// `Some(Ty::Any)` declares an unresolved value; `None` permits function-name lookup.
1621/// Closure bodies remain noncapturing. Unavailable host facts do not erase definite
1622/// errors in children. No host emitter, constructor, or value operation is invoked.
1623/// The returned type retains independently known result shapes even when diagnostics
1624/// are present: logical results are Boolean and resolved casts retain their target.
1625/// Invalid operations whose results cannot be inferred return [`Ty::Any`], including
1626/// within compound shapes. A known result type does not imply a valid expression
1627/// or complete checking; callers must retain both diagnostic collections.
1628///
1629/// - Complexity: Matches [`crate::ty::check_expr_with_type_resolver`], excluding projection.
1630///
1631/// # Examples
1632/// ```
1633/// use cel_parser::{AstContext, OpLookup, Parser, Ty};
1634/// use cel_parser::checking::*;
1635/// let expr = Parser::<AstContext>::new(OpLookup::new()).parse_str_ast("1i32 + 2i32").unwrap();
1636/// let env = CheckingBuilder::new().finish().unwrap();
1637/// let report = check_expr_with_environment(&expr, &|_| None, &env, MetadataAvailability::Complete);
1638/// assert_eq!(report.value, Ty::I32);
1639/// assert!(report.diagnostics.is_empty());
1640/// let expr = Parser::<AstContext>::new(OpLookup::new())
1641///     .parse_str_ast("missing && true").unwrap();
1642/// let report = check_expr_with_environment(&expr, &|_| None, &env, MetadataAvailability::Complete);
1643/// assert_eq!(report.value, Ty::Bool);
1644/// assert_eq!(report.diagnostics.len(), 1);
1645/// ```
1646pub fn check_expr_with_environment(
1647    expr: &Expr,
1648    resolve_ident: &dyn Fn(&str) -> Option<Ty>,
1649    environment: &CheckingEnvironment,
1650    availability: MetadataAvailability,
1651) -> CheckingReport<Ty> {
1652    let (value, errors) = crate::ty::check_semantic_expr(
1653        expr,
1654        resolve_ident,
1655        &|ty| resolve_partial_annotation(ty, &|ty| environment.resolve_annotation(ty)),
1656        environment,
1657    );
1658    let (incomplete, diagnostics) = errors
1659        .into_iter()
1660        .partition(|error| availability == MetadataAvailability::Unavailable && is_missing(error));
1661    CheckingReport {
1662        value,
1663        diagnostics,
1664        incomplete,
1665    }
1666}
1667
1668/// Resolves annotation shapes, replacing only unresolved subtrees with `Any`.
1669///
1670/// Accumulates independent leaf and malformed-callable findings. Nominal generic
1671/// applications remain unresolved if an argument is unresolved; they never become
1672/// complete nominal types containing `Any`. `resolve` requires complete types.
1673///
1674/// - Complexity: O(n * (r + t)) time and result storage for n annotation nodes,
1675///   worst-case strict resolver cost r and returned type area t; O(n) traversal stack.
1676pub(crate) fn resolve_partial_annotation(
1677    expr: &TypeExpr,
1678    resolve: &dyn Fn(&TypeExpr) -> crate::Result<Ty>,
1679) -> (Ty, Vec<ParseError>) {
1680    let mut errors = Vec::new();
1681    let value = partial_annotation_type(expr, resolve, &mut errors);
1682    (value, errors)
1683}
1684
1685/// Retains annotation shape and appends each independent finding once.
1686///
1687/// - Complexity: Matches [`resolve_partial_annotation`], excluding its result tuple.
1688fn partial_annotation_type(
1689    expr: &TypeExpr,
1690    resolve: &dyn Fn(&TypeExpr) -> crate::Result<Ty>,
1691    errors: &mut Vec<ParseError>,
1692) -> Ty {
1693    let mut child = |expr: &TypeExpr| partial_annotation_type(expr, resolve, errors);
1694    match expr {
1695        TypeExpr::Array { element, .. } => Ty::Array(Box::new(child(element))),
1696        TypeExpr::Tuple { elements, .. } => Ty::Tuple(elements.iter().map(&mut child).collect()),
1697        TypeExpr::Named { name, args, span } if name == "Fn" => {
1698            if let [parameters, result] = args.as_slice() {
1699                let parameters = child(parameters);
1700                let result = child(result);
1701                if let Ty::Tuple(parameters) = parameters {
1702                    return Ty::Callable(parameters, Box::new(result));
1703                }
1704            } else {
1705                args.iter().for_each(|arg| {
1706                    child(arg);
1707                });
1708            }
1709            errors.push(ParseError::new_range(
1710                "Fn requires a parameter tuple and result type",
1711                span.start,
1712                span.end,
1713            ));
1714            Ty::Any
1715        }
1716        TypeExpr::Named { args, .. } => {
1717            let mut complete = true;
1718            // Visit every argument to retain independent annotation findings.
1719            for arg in args {
1720                complete &= !child(arg).contains_any();
1721            }
1722            if !complete {
1723                Ty::Any
1724            } else {
1725                match resolve(expr) {
1726                    Ok(ty) => ty,
1727                    Err(error) => {
1728                        errors.push(error);
1729                        Ty::Any
1730                    }
1731                }
1732            }
1733        }
1734    }
1735}
1736
1737/// Reports whether an error specifically requires absent host metadata.
1738pub(crate) fn is_missing(error: &ParseError) -> bool {
1739    use std::error::Error;
1740    error
1741        .source()
1742        .is_some_and(|cause| cause.is::<MissingMetadata>())
1743}
1744
1745/// Reports an unresolved value or operation tolerated by legacy checker contracts.
1746pub(crate) fn legacy_ignored(error: &ParseError) -> bool {
1747    use std::error::Error;
1748    error
1749        .source()
1750        .and_then(|cause| cause.downcast_ref::<MissingMetadata>())
1751        .is_some_and(|missing| missing.legacy_ignored)
1752}
1753
1754/// Restores transient host identities for legacy runtime-oriented checker callers.
1755///
1756/// - Complexity: Expected O(n) for result nodes n.
1757pub(crate) fn unbind(
1758    ty: Ty,
1759    bindings: &HashMap<u32, TypeId>,
1760    environment: &CheckingEnvironment,
1761) -> Ty {
1762    let local_id = environment.nominal_id(&ty);
1763    match ty {
1764        Ty::Registered(mut leaf) => {
1765            if let Some(id) = local_id
1766                && let Some(host) = bindings.get(&id)
1767            {
1768                leaf.identity = Identity::Host(*host);
1769            }
1770            Ty::Registered(leaf)
1771        }
1772        Ty::Array(element) => Ty::Array(Box::new(unbind(*element, bindings, environment))),
1773        Ty::Tuple(elements) => Ty::Tuple(
1774            elements
1775                .into_iter()
1776                .map(|ty| unbind(ty, bindings, environment))
1777                .collect(),
1778        ),
1779        Ty::Callable(parameters, result) => Ty::Callable(
1780            parameters
1781                .into_iter()
1782                .map(|ty| unbind(ty, bindings, environment))
1783                .collect(),
1784            Box::new(unbind(*result, bindings, environment)),
1785        ),
1786        ty => ty,
1787    }
1788}
1789
1790/// Rebinds transient host leaf identities into the projected catalog recursively.
1791///
1792/// - Complexity: O(n) for shape nodes n.
1793pub(crate) fn bind(
1794    ty: Ty,
1795    bindings: &HashMap<TypeId, u32>,
1796    environment: &CheckingEnvironment,
1797) -> Ty {
1798    match ty {
1799        Ty::Registered(ref leaf) => {
1800            if let Some(id) = leaf.type_id().and_then(|id| bindings.get(&id)) {
1801                environment.types[id].clone()
1802            } else {
1803                ty
1804            }
1805        }
1806        Ty::Array(element) => Ty::Array(Box::new(bind(*element, bindings, environment))),
1807        Ty::Tuple(elements) => Ty::Tuple(
1808            elements
1809                .into_iter()
1810                .map(|ty| bind(ty, bindings, environment))
1811                .collect(),
1812        ),
1813        Ty::Callable(parameters, result) => Ty::Callable(
1814            parameters
1815                .into_iter()
1816                .map(|ty| bind(ty, bindings, environment))
1817                .collect(),
1818            Box::new(bind(*result, bindings, environment)),
1819        ),
1820        ty => ty,
1821    }
1822}
1823
1824#[cfg(test)]
1825mod host_binding_tests {
1826    use super::*;
1827
1828    /// Retains explicit default removal through data-only import and rejects unknown leaves.
1829    #[test]
1830    fn default_selection_replaces_seeded_facts() {
1831        let mut builder = CheckingBuilder::new();
1832        let unregistered = ResolvedLeafType::leaf::<std::path::PathBuf>("Path").unwrap();
1833        assert!(builder.set_default_available(&unregistered, true).is_err());
1834        builder
1835            .set_default_available(&ResolvedLeafType::leaf::<i32>("i32").unwrap(), false)
1836            .unwrap();
1837        let environment = builder.finish().unwrap();
1838        let imported =
1839            CheckingEnvironment::from_description(environment.description().clone()).unwrap();
1840        assert!(!imported.capabilities(&Ty::I32).unwrap().default_available);
1841    }
1842
1843    /// Rejects foreign owners, nonnominal shapes, and conflicting explicit selections.
1844    #[test]
1845    fn binding_checks_ownership_shape_and_conflicts() {
1846        let environment = CheckingBuilder::new().finish().unwrap();
1847        let imported =
1848            CheckingEnvironment::from_description(environment.description().clone()).unwrap();
1849        let mut binding = HostTypeBinding::new(&environment);
1850        assert!(binding.bind::<i32>(&imported, Ty::I32).is_err());
1851        assert!(binding.bind::<i32>(&environment, Ty::Any).is_err());
1852        assert!(
1853            binding
1854                .bind::<i32>(&environment, Ty::Array(Box::new(Ty::I32)))
1855                .is_err()
1856        );
1857        let foreign = imported.resolve_type("char").unwrap();
1858        assert!(binding.bind::<char>(&environment, foreign).is_err());
1859        binding.bind::<i32>(&environment, Ty::I32).unwrap();
1860        binding.bind::<i32>(&environment, Ty::I32).unwrap();
1861        assert!(binding.bind::<i32>(&environment, Ty::F64).is_err());
1862        assert_eq!(
1863            binding.resolve(&environment, TypeId::of::<i32>()),
1864            Some(Ty::I32)
1865        );
1866        assert_eq!(binding.resolve(&imported, TypeId::of::<i32>()), None);
1867        assert_eq!(binding.resolve(&environment, TypeId::of::<bool>()), None);
1868    }
1869}