Skip to main content

cel_parser/
ty.rs

1//! Checks source expressions using complete recursive array, tuple, and callable shapes.
2//!
3//! Use [`check_expr`] with a free-identifier resolver for builtin-only expressions, or
4//! [`check_expr_with_type_resolver`] with a host registry and operation metadata.
5//! [`Ty::Any`] retains incomplete editor expressions; it never authorizes executable storage.
6
7use std::any::TypeId;
8use std::borrow::Cow;
9
10use crate::checking::{CheckingBuilder, CheckingEnvironment, NominalLeaf};
11use crate::op_table::{builtin_operand_types, cast_source_types};
12use crate::type_expr::{BuiltinTypeResolver, ResolvedType, TypeExpr, TypeResolver};
13use crate::{Expr, ExprSpan, Literal, OpLookup, ParseError, ResolvedLeafType};
14
15/// A complete recursive source type, or an unresolved editor value.
16///
17/// # Examples
18/// See [`Self::unify`] for recursive compatibility and result construction.
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub enum Ty {
21    /// `i8`.
22    I8,
23    /// `i16`.
24    I16,
25    /// `i32`.
26    I32,
27    /// `i64`.
28    I64,
29    /// `i128`.
30    I128,
31    /// `isize`.
32    Isize,
33    /// `u8`.
34    U8,
35    /// `u16`.
36    U16,
37    /// `u32`.
38    U32,
39    /// `u64`.
40    U64,
41    /// `u128`.
42    U128,
43    /// `usize`.
44    Usize,
45    /// `f32`.
46    F32,
47    /// `f64`.
48    F64,
49    /// `bool`.
50    Bool,
51    /// `String`.
52    String,
53    /// A canonical homogeneous array of the boxed element type, which may
54    /// itself be an array (`[[i32]]`) or [`Ty::Any`] (an array whose element type isn't
55    /// statically known — e.g. `[f(), g()]`, whose elements are unresolved call results).
56    Array(Box<Ty>),
57    /// A source-ordered tuple, including unit and singleton tuples.
58    Tuple(Vec<Ty>),
59    /// A callable with complete parameter and result types.
60    Callable(Vec<Ty>, Box<Ty>),
61    /// A known leaf, retaining data-only nominal identity, name, and capabilities.
62    ///
63    /// Registered function markers resolve calls through their registered identity,
64    /// without falling back to ordinary call operators. Other leaves are callable
65    /// through a matching registered `()` signature with the callee as operand zero.
66    Registered(NominalLeaf),
67    /// Anything not statically known: an unannotated cell, an
68    /// unresolved identifier, or a call without available metadata.
69    /// Unifies silently with every other `Ty`, in both directions.
70    Any,
71}
72
73impl Ty {
74    /// Copies a resolved leaf's semantic facts, using primitive variants where applicable.
75    ///
76    /// Host leaves retain a data-only binding identity, not the executable descriptor.
77    /// Runtime-oriented checker entry points rebind these leaves to their projected catalog.
78    /// Offline lexical resolvers instead use [`CheckingEnvironment::resolve_type`].
79    ///
80    /// - Complexity: O(l) in leaf display-name length l.
81    ///
82    /// # Examples
83    /// ```
84    /// use cel_parser::{ResolvedLeafType, Ty};
85    /// use cel_runtime::ValueType;
86    /// let leaf = ResolvedLeafType::new("custom", ValueType::leaf::<()>());
87    /// assert_eq!(Ty::from_leaf(&leaf).name(), "custom");
88    /// ```
89    pub fn from_leaf(leaf: &ResolvedLeafType) -> Self {
90        match Self::from_type_id(leaf.type_id()) {
91            Ty::Any | Ty::Array(_) => Ty::Registered(NominalLeaf::from_host(leaf)),
92            primitive => primitive,
93        }
94    }
95
96    /// Maps a resolved [`Literal`] to its exact primitive or registered leaf identity.
97    ///
98    /// # Examples
99    ///
100    /// ```rust
101    /// use cel_parser::{Literal, Ty};
102    ///
103    /// assert_eq!(Ty::from_literal(&Literal::I32(1)), Ty::I32);
104    /// assert_eq!(Ty::from_literal(&Literal::Unit).type_id(), Some(std::any::TypeId::of::<()>()));
105    /// ```
106    pub fn from_literal(lit: &Literal) -> Ty {
107        match lit {
108            Literal::I8(_) => Ty::I8,
109            Literal::I16(_) => Ty::I16,
110            Literal::I32(_) => Ty::I32,
111            Literal::I64(_) => Ty::I64,
112            Literal::I128(_) => Ty::I128,
113            Literal::Isize(_) => Ty::Isize,
114            Literal::U8(_) => Ty::U8,
115            Literal::U16(_) => Ty::U16,
116            Literal::U32(_) => Ty::U32,
117            Literal::U64(_) => Ty::U64,
118            Literal::U128(_) => Ty::U128,
119            Literal::Usize(_) => Ty::Usize,
120            Literal::F32(_) => Ty::F32,
121            Literal::F64(_) => Ty::F64,
122            Literal::Bool(_) => Ty::Bool,
123            Literal::Str(_) => Ty::String,
124            Literal::Char(_) => Self::known_leaf::<char>("char"),
125            Literal::ByteStr(_) => Self::known_leaf::<Vec<u8>>("byte string"),
126            Literal::CStr(_) => Self::known_leaf::<std::ffi::CString>("C string"),
127            Literal::Unit => Ty::Tuple(vec![]),
128        }
129    }
130
131    /// Describes a statically known non-array leaf.
132    ///
133    /// - Precondition: T describes an opaque host leaf, not erased whole-value ownership.
134    fn known_leaf<T: 'static>(name: &'static str) -> Ty {
135        Ty::from_leaf(&ResolvedLeafType::new(
136            name,
137            cel_runtime::ValueType::leaf::<T>(),
138        ))
139    }
140
141    /// Returns whether this type contains an unresolved leaf.
142    ///
143    /// - Complexity: O(n) in recursive type nodes.
144    pub(crate) fn contains_any(&self) -> bool {
145        match self {
146            Ty::Any => true,
147            Ty::Array(element) => element.contains_any(),
148            Ty::Tuple(elements) => elements.iter().any(Self::contains_any),
149            Ty::Callable(parameters, result) => {
150                parameters.iter().any(Self::contains_any) || result.contains_any()
151            }
152            _ => false,
153        }
154    }
155
156    /// Maps a `TypeId` (e.g. from `adam_lang::TypeRegistry::TypeEntry::type_id`) to its [`Ty`].
157    /// An unrecognized `TypeId` maps to [`Ty::Any`] — not an error, matching adam-lang/CEL's
158    /// extensible type system (a host binary's custom registered types are invisible here).
159    /// A flat `TypeId` never establishes a structural array shape; structural
160    /// identities require recursive descriptors instead.
161    ///
162    /// # Examples
163    ///
164    /// ```rust
165    /// use std::any::TypeId;
166    /// use cel_parser::Ty;
167    ///
168    /// assert_eq!(Ty::from_type_id(TypeId::of::<i32>()), Ty::I32);
169    /// assert_eq!(Ty::from_type_id(TypeId::of::<Vec<u8>>()), Ty::Any);
170    /// assert_eq!(
171    ///     Ty::from_type_id(TypeId::of::<cel_runtime::OwnedValue>()),
172    ///     Ty::Any
173    /// );
174    /// ```
175    pub fn from_type_id(id: TypeId) -> Ty {
176        if id == TypeId::of::<i8>() {
177            Ty::I8
178        } else if id == TypeId::of::<i16>() {
179            Ty::I16
180        } else if id == TypeId::of::<i32>() {
181            Ty::I32
182        } else if id == TypeId::of::<i64>() {
183            Ty::I64
184        } else if id == TypeId::of::<i128>() {
185            Ty::I128
186        } else if id == TypeId::of::<isize>() {
187            Ty::Isize
188        } else if id == TypeId::of::<u8>() {
189            Ty::U8
190        } else if id == TypeId::of::<u16>() {
191            Ty::U16
192        } else if id == TypeId::of::<u32>() {
193            Ty::U32
194        } else if id == TypeId::of::<u64>() {
195            Ty::U64
196        } else if id == TypeId::of::<u128>() {
197            Ty::U128
198        } else if id == TypeId::of::<usize>() {
199            Ty::Usize
200        } else if id == TypeId::of::<f32>() {
201            Ty::F32
202        } else if id == TypeId::of::<f64>() {
203            Ty::F64
204        } else if id == TypeId::of::<bool>() {
205            Ty::Bool
206        } else if id == TypeId::of::<String>() {
207            Ty::String
208        } else {
209            Ty::Any
210        }
211    }
212
213    /// Returns a primitive or transient host `TypeId`, or `None` for catalog-owned leaves,
214    /// [`Ty::Any`], nonempty tuples, and arrays.
215    ///
216    /// # Examples
217    ///
218    /// ```rust
219    /// use std::any::TypeId;
220    /// use cel_parser::Ty;
221    ///
222    /// assert_eq!(Ty::I32.type_id(), Some(TypeId::of::<i32>()));
223    /// assert_eq!(Ty::Any.type_id(), None);
224    /// assert_eq!(
225    ///     Ty::Array(Box::new(Ty::I32)).type_id(),
226    ///     None
227    /// );
228    /// ```
229    pub fn type_id(&self) -> Option<TypeId> {
230        Some(match self {
231            Ty::I8 => TypeId::of::<i8>(),
232            Ty::I16 => TypeId::of::<i16>(),
233            Ty::I32 => TypeId::of::<i32>(),
234            Ty::I64 => TypeId::of::<i64>(),
235            Ty::I128 => TypeId::of::<i128>(),
236            Ty::Isize => TypeId::of::<isize>(),
237            Ty::U8 => TypeId::of::<u8>(),
238            Ty::U16 => TypeId::of::<u16>(),
239            Ty::U32 => TypeId::of::<u32>(),
240            Ty::U64 => TypeId::of::<u64>(),
241            Ty::U128 => TypeId::of::<u128>(),
242            Ty::Usize => TypeId::of::<usize>(),
243            Ty::F32 => TypeId::of::<f32>(),
244            Ty::F64 => TypeId::of::<f64>(),
245            Ty::Bool => TypeId::of::<bool>(),
246            Ty::String => TypeId::of::<String>(),
247            Ty::Array(_) => return None,
248            Ty::Registered(leaf) => return leaf.type_id(),
249            Ty::Tuple(elements) if elements.is_empty() => TypeId::of::<()>(),
250            Ty::Tuple(_) => return None,
251            Ty::Callable(..) => TypeId::of::<cel_runtime::DynClosure>(),
252            Ty::Any => return None,
253        })
254    }
255
256    /// Returns a human-readable name for diagnostics, borrowing primitive and leaf names.
257    ///
258    /// - Complexity: O(n + b) time and O(b + d) space for n recursive nodes, b output bytes and depth d;
259    ///   primitive and registered leaf names take O(1).
260    ///
261    /// # Examples
262    ///
263    /// ```rust
264    /// use cel_parser::Ty;
265    ///
266    /// assert_eq!(Ty::I32.name(), "i32");
267    /// assert_eq!(Ty::Any.name(), "<any>");
268    /// assert_eq!(Ty::Array(Box::new(Ty::Array(Box::new(Ty::I32)))).name(), "[[i32]]");
269    /// ```
270    pub fn name(&self) -> Cow<'_, str> {
271        Cow::Borrowed(match self {
272            Ty::I8 => "i8",
273            Ty::I16 => "i16",
274            Ty::I32 => "i32",
275            Ty::I64 => "i64",
276            Ty::I128 => "i128",
277            Ty::Isize => "isize",
278            Ty::U8 => "u8",
279            Ty::U16 => "u16",
280            Ty::U32 => "u32",
281            Ty::U64 => "u64",
282            Ty::U128 => "u128",
283            Ty::Usize => "usize",
284            Ty::F32 => "f32",
285            Ty::F64 => "f64",
286            Ty::Bool => "bool",
287            Ty::String => "String",
288            Ty::Array(_) | Ty::Tuple(_) | Ty::Callable(..) => {
289                let mut output = String::new();
290                self.write_name(&mut output);
291                return Cow::Owned(output);
292            }
293            Ty::Registered(leaf) => leaf.type_name(),
294            Ty::Any => "<any>",
295        })
296    }
297
298    /// Appends diagnostic syntax without allocating intermediate child names.
299    ///
300    /// - Complexity: O(n + b) time and O(d) stack space for n nodes, b bytes and depth d.
301    fn write_name(&self, output: &mut String) {
302        match self {
303            Ty::Array(element) => {
304                output.push('[');
305                element.write_name(output);
306                output.push(']');
307            }
308            Ty::Tuple(elements) => Self::write_tuple_name(elements, output),
309            Ty::Callable(parameters, result) => {
310                output.push_str("Fn(");
311                Self::write_tuple_name(parameters, output);
312                output.push_str(", ");
313                result.write_name(output);
314                output.push(')');
315            }
316            leaf => output.push_str(&leaf.name()),
317        }
318    }
319
320    /// Appends tuple syntax, retaining the required singleton comma.
321    ///
322    /// - Complexity: O(n + b) time and O(d) stack space for n descendant nodes, b bytes and depth d.
323    fn write_tuple_name(elements: &[Ty], output: &mut String) {
324        output.push('(');
325        // Emit child names directly into the shared output.
326        for (index, element) in elements.iter().enumerate() {
327            if index != 0 {
328                output.push_str(", ");
329            }
330            element.write_name(output);
331        }
332        if elements.len() == 1 {
333            output.push(',');
334        }
335        output.push(')');
336    }
337
338    /// Maps a type's bare name (as written in source, e.g. in a cast's target position) to its
339    /// [`Ty`], or `None` if `name` isn't a recognized primitive - the inverse of [`Ty::name`],
340    /// except it has no input that maps to [`Ty::Any`] (nothing is spelled `<any>` in source).
341    ///
342    /// # Examples
343    ///
344    /// ```rust
345    /// use cel_parser::Ty;
346    ///
347    /// assert_eq!(Ty::from_name("i32"), Some(Ty::I32));
348    /// assert_eq!(Ty::from_name("nonsense"), None);
349    /// ```
350    pub fn from_name(name: &str) -> Option<Ty> {
351        match name {
352            "i8" => Some(Ty::I8),
353            "i16" => Some(Ty::I16),
354            "i32" => Some(Ty::I32),
355            "i64" => Some(Ty::I64),
356            "i128" => Some(Ty::I128),
357            "isize" => Some(Ty::Isize),
358            "u8" => Some(Ty::U8),
359            "u16" => Some(Ty::U16),
360            "u32" => Some(Ty::U32),
361            "u64" => Some(Ty::U64),
362            "u128" => Some(Ty::U128),
363            "usize" => Some(Ty::Usize),
364            "f32" => Some(Ty::F32),
365            "f64" => Some(Ty::F64),
366            "bool" => Some(Ty::Bool),
367            "String" => Some(Ty::String),
368            _ => None,
369        }
370    }
371
372    /// Returns `true` if `self` and `other` have compatible recursive shapes.
373    /// `Ty::Any` unifying silently with everything (in both directions and at every nesting level) is the
374    /// load-bearing property that lets unresolved inputs produce zero false-positive diagnostics.
375    /// Registered leaves unify only when their owned nominal identities agree, regardless of aliases.
376    ///
377    /// - Complexity: O(n) time and O(d) stack space for n recursive nodes at depth d.
378    ///
379    /// # Examples
380    ///
381    /// ```rust
382    /// use cel_parser::Ty;
383    ///
384    /// assert!(Ty::Any.unifies_with(&Ty::I32));
385    /// assert!(!Ty::I32.unifies_with(&Ty::F64));
386    /// assert!(Ty::Array(Box::new(Ty::Any)).unifies_with(&Ty::Array(Box::new(Ty::I32))));
387    /// assert!(!Ty::Array(Box::new(Ty::I32)).unifies_with(&Ty::Array(Box::new(Ty::F64))));
388    /// ```
389    pub fn unifies_with(&self, other: &Ty) -> bool {
390        match (self, other) {
391            (Ty::Any, _) | (_, Ty::Any) => true,
392            (Ty::Array(lhs), Ty::Array(rhs)) => lhs.unifies_with(rhs),
393            (Ty::Tuple(lhs), Ty::Tuple(rhs)) => {
394                lhs.len() == rhs.len() && lhs.iter().zip(rhs).all(|(a, b)| a.unifies_with(b))
395            }
396            (Ty::Callable(lhs, lr), Ty::Callable(rhs, rr)) => {
397                lhs.len() == rhs.len()
398                    && lhs.iter().zip(rhs).all(|(a, b)| a.unifies_with(b))
399                    && lr.unifies_with(rr)
400            }
401            (Ty::Registered(lhs), Ty::Registered(rhs)) => lhs == rhs,
402            (lhs, rhs) => lhs == rhs,
403        }
404    }
405
406    /// The most specific type both `self` and `other` describe, or `None` if they're
407    /// incompatible: [`Ty::Any`] yields the other side (it constrains nothing); arrays,
408    /// tuples, and callables unify recursively with equal arity; equal leaves yield themselves.
409    ///
410    /// - Postcondition: `self.unify(other).is_some() == self.unifies_with(other)`, and the result
411    ///   (when `Some`) unifies with both `self` and `other`.
412    /// - Complexity: O(n + l) time and space for n recursive nodes and l registered name bytes.
413    ///
414    /// # Examples
415    ///
416    /// ```rust
417    /// use cel_parser::Ty;
418    ///
419    /// assert_eq!(Ty::Any.unify(&Ty::I32), Some(Ty::I32));
420    /// assert_eq!(
421    ///     Ty::Array(Box::new(Ty::Any)).unify(&Ty::Array(Box::new(Ty::I32))),
422    ///     Some(Ty::Array(Box::new(Ty::I32)))
423    /// );
424    /// assert_eq!(Ty::I32.unify(&Ty::F64), None);
425    /// ```
426    pub fn unify(&self, other: &Ty) -> Option<Ty> {
427        match (self, other) {
428            (Ty::Any, other) => Some(other.clone()),
429            (this, Ty::Any) => Some(this.clone()),
430            (Ty::Array(lhs), Ty::Array(rhs)) => Some(Ty::Array(Box::new(lhs.unify(rhs)?))),
431            (Ty::Tuple(lhs), Ty::Tuple(rhs)) if lhs.len() == rhs.len() => Some(Ty::Tuple(
432                lhs.iter()
433                    .zip(rhs)
434                    .map(|(a, b)| a.unify(b))
435                    .collect::<Option<_>>()?,
436            )),
437            (Ty::Callable(lhs, lr), Ty::Callable(rhs, rr)) if lhs.len() == rhs.len() => {
438                Some(Ty::Callable(
439                    lhs.iter()
440                        .zip(rhs)
441                        .map(|(a, b)| a.unify(b))
442                        .collect::<Option<_>>()?,
443                    Box::new(lr.unify(rr)?),
444                ))
445            }
446            (Ty::Registered(lhs), Ty::Registered(rhs)) if lhs == rhs => Some(self.clone()),
447            (this, other) if this == other => Some(this.clone()),
448            _ => None,
449        }
450    }
451}
452
453/// Infers `expr`'s type against `resolve_ident` (looks up a free identifier's declared type, or
454/// `Ty::Any` if unknown — e.g. a bare CEL builtin name, or an adam-lang cell with no `: type`
455/// annotation), returning the expression's inferred type plus every type diagnostic found.
456///
457/// Uses an empty [`OpLookup`]; metadata-aware hosts use [`check_expr_with_type_resolver`].
458/// Checks every child, including noncapturing closure bodies under parameter-local bindings.
459/// Closure bodies ignore the outer value resolver; registered library metadata remains visible.
460/// Duplicate or reserved parameter names produce diagnostics, including in hand-built syntax.
461/// Arrays require homogeneous complete shapes, tuples retain source order, and `if` joins
462/// compatible branch types. Callable applications check parameter and result types.
463/// Calls without metadata and free identifiers without declarations remain unresolved.
464/// Registered function values retain concrete marker identity through aliases, rather than
465/// using the alias's spelling to select a signature. Builtin range expressions retain their
466/// concrete range result, not their endpoint type.
467///
468/// - Complexity: Matches [`check_expr_with_type_resolver`] with no registered overloads or schemas.
469///
470/// # Examples
471///
472/// ```rust
473/// use cel_parser::{Expr, ExprSpan, Literal, Ty};
474/// use cel_parser::ty::check_expr;
475///
476/// let span = ExprSpan {
477///     start: proc_macro2::Span::call_site(),
478///     end: proc_macro2::Span::call_site(),
479/// };
480/// let expr = Expr::Literal {
481///     value: Literal::I32(1),
482///     span,
483/// };
484/// let (ty, diagnostics) = check_expr(&expr, &|_name| Ty::Any);
485/// assert_eq!(ty, Ty::I32);
486/// assert!(diagnostics.is_empty());
487/// ```
488pub fn check_expr(expr: &Expr, resolve_ident: &dyn Fn(&str) -> Ty) -> (Ty, Vec<ParseError>) {
489    check_expr_with_type_resolver(expr, resolve_ident, &BuiltinTypeResolver, &OpLookup::new())
490}
491
492/// Infers `expr`'s type using value/type resolvers and registered operation/record metadata.
493///
494/// Resolves constructors through [`OpLookup::record_schema`] and members through
495/// [`OpLookup::operation_signatures`], never through same-named values. Checks every child even
496/// when a constructor is unknown or an operand is unresolved. Known fields and operands match
497/// exactly, without numeric coercion. Invalid constructors/operations infer as [`Ty::Any`] to
498/// avoid cascading errors. Custom calls without signatures remain best-effort.
499///
500/// Projects the retained registrations once, then borrows that catalog throughout checking.
501/// Opaque runtime scopes remain executable through runtime lookup; this checker never probes
502/// them and retains its best-effort policy for undeclared values and operations.
503///
504/// - Complexity: Catalog projection plus O(n + Σ(f² + s · a · t)), for n expression nodes,
505///   f schema fields per constructor, s overloads, a operands, and compared type-shape size t,
506///   plus resolver and type-unification costs.
507///
508/// # Examples
509///
510/// ```rust
511/// use cel_parser::{AstContext, OpLookup, Parser, Ty};
512/// use cel_parser::ty::check_expr_with_type_resolver;
513///
514/// let mut parser = Parser::<AstContext>::new(OpLookup::new());
515/// let expr = parser.parse_str_ast("[]: [i32]").unwrap();
516/// let (ty, diagnostics) =
517///     check_expr_with_type_resolver(&expr, &|_name| Ty::Any, &[(
518///         "i32",
519///         cel_parser::ResolvedLeafType::new(
520///             "i32",
521///             cel_runtime::ValueType::leaf::<i32>(),
522///         ),
523///     )], &OpLookup::new());
524/// assert_eq!(ty, Ty::Array(Box::new(Ty::I32)));
525/// assert!(diagnostics.is_empty());
526/// ```
527pub fn check_expr_with_type_resolver(
528    expr: &Expr,
529    resolve_ident: &dyn Fn(&str) -> Ty,
530    resolve_type: &dyn TypeResolver,
531    lookup: &OpLookup,
532) -> (Ty, Vec<ParseError>) {
533    let mut builder = CheckingBuilder::new();
534    if let Err(error) = builder.project_lookup(lookup) {
535        return (
536            Ty::Any,
537            vec![ParseError::new(error.to_string(), expr.span().start)],
538        );
539    }
540    let (environment, bindings) = match builder.finish_with_bindings() {
541        Ok(projected) => projected,
542        Err(error) => {
543            return (
544                Ty::Any,
545                vec![ParseError::new(error.to_string(), expr.span().start)],
546            );
547        }
548    };
549    let resolve = |name: &str| {
550        let ty = resolve_ident(name);
551        Some(if ty == Ty::Any {
552            environment
553                .registered_function_type(name)
554                .or_else(|| matching_registered_type(name, &[], &environment))
555                .unwrap_or(Ty::Any)
556        } else {
557            crate::checking::bind(ty, &bindings, &environment)
558        })
559    };
560    let annotation = |ty: &TypeExpr| {
561        crate::checking::resolve_partial_annotation(ty, &|ty| {
562            ty.resolve(resolve_type).map(|resolved| {
563                crate::checking::bind(
564                    resolved_type_to_element_ty(&resolved),
565                    &bindings,
566                    &environment,
567                )
568            })
569        })
570    };
571    let (ty, diagnostics) = check_semantic_expr(expr, &resolve, &annotation, &environment);
572    let runtime_ids = bindings
573        .iter()
574        .map(|(host, local)| (*local, *host))
575        .collect();
576    (
577        crate::checking::unbind(ty, &runtime_ids, &environment),
578        diagnostics
579            .into_iter()
580            .filter(|error| !crate::checking::legacy_ignored(error))
581            .collect(),
582    )
583}
584
585/// Checks one expression recursively against borrowed semantic contracts.
586///
587/// Function markers dispatch only to their named operation. Other calls try
588/// registered `()` signatures with the callee first, then structural callable
589/// parameters. Annotation findings retain independently known shapes.
590///
591/// - Complexity: Matches [`check_expr_with_type_resolver`], excluding projection.
592pub(crate) fn check_semantic_expr(
593    expr: &Expr,
594    resolve_ident: &dyn Fn(&str) -> Option<Ty>,
595    resolve_type: &dyn Fn(&TypeExpr) -> (Ty, Vec<ParseError>),
596    lookup: &CheckingEnvironment,
597) -> (Ty, Vec<ParseError>) {
598    match expr {
599        Expr::Literal { value, .. } => {
600            let ty = match value {
601                Literal::Char(_) => lookup
602                    .resolve_type("char")
603                    .expect("validated char identity"),
604                Literal::ByteStr(_) => lookup
605                    .resolve_type("byte string")
606                    .expect("validated byte string identity"),
607                Literal::CStr(_) => lookup
608                    .resolve_type("C string")
609                    .expect("validated C string identity"),
610                _ => Ty::from_literal(value),
611            };
612            (ty, Vec::new())
613        }
614        Expr::Ident { name, span } => {
615            let ty = resolve_ident(name);
616            let ty = if ty.is_none() {
617                lookup
618                    .registered_function_type(name)
619                    .or_else(|| matching_registered_type(name, &[], lookup))
620            } else {
621                ty
622            };
623            match ty {
624                Some(ty) => (ty, Vec::new()),
625                None => (
626                    Ty::Any,
627                    vec![crate::checking::optional_missing(
628                        format!("unknown name `{name}`"),
629                        *span,
630                    )],
631                ),
632            }
633        }
634        Expr::Struct {
635            name,
636            name_span,
637            fields,
638            ..
639        } => {
640            let mut diagnostics = Vec::new();
641            let schema = lookup.record_schema(name);
642            let mut seen = std::collections::HashSet::new();
643            for field in fields {
644                let (actual, child_diags) =
645                    check_semantic_expr(&field.value, resolve_ident, resolve_type, lookup);
646                let valid = child_diags.iter().all(crate::checking::is_missing);
647                diagnostics.extend(child_diags);
648                let Some(schema) = schema else { continue };
649                let error = if !seen.insert(field.name.as_str()) {
650                    Some(format!("duplicate field `{}`", field.name))
651                } else if let Some((_, expected)) =
652                    schema.fields.iter().find(|(name, _)| *name == field.name)
653                {
654                    (valid && !expected.unifies_with(&actual)).then(|| {
655                        format!(
656                            "field `{}` expects `{}`, found `{}`",
657                            field.name,
658                            expected.name(),
659                            actual.name(),
660                        )
661                    })
662                } else {
663                    Some(format!("unknown field `{}` for `{name}`", field.name))
664                };
665                if let Some(error) = error {
666                    diagnostics.push(ParseError::new_range(
667                        error,
668                        field.name_span.start,
669                        field.value.span().end,
670                    ));
671                }
672            }
673            if let Some(schema) = schema {
674                for (field, _) in &schema.fields {
675                    if !seen.contains(field.as_str()) {
676                        diagnostics.push(ParseError::new_range(
677                            format!("missing field `{field}` for `{name}`"),
678                            name_span.start,
679                            name_span.end,
680                        ));
681                    }
682                }
683                let ty = if diagnostics.iter().all(crate::checking::is_missing) {
684                    schema.ty.clone()
685                } else {
686                    Ty::Any
687                };
688                (ty, diagnostics)
689            } else {
690                diagnostics.push(crate::checking::missing(
691                    format!("unknown record type `{name}`"),
692                    *name_span,
693                ));
694                (Ty::Any, diagnostics)
695            }
696        }
697        Expr::Op {
698            name,
699            operands,
700            span,
701        } => check_op(name, operands, *span, resolve_ident, resolve_type, lookup),
702        Expr::Logical { lhs, rhs, span, .. } => {
703            check_logical(lhs, rhs, *span, resolve_ident, resolve_type, lookup)
704        }
705        Expr::Apply { callee, args, span } => {
706            let (callee_ty, mut diagnostics) =
707                check_semantic_expr(callee, resolve_ident, resolve_type, lookup);
708            let mut types = Vec::with_capacity(args.len() + 1);
709            types.push(callee_ty);
710            for arg in args {
711                let (ty, errors) = check_semantic_expr(arg, resolve_ident, resolve_type, lookup);
712                types.push(ty);
713                diagnostics.extend(errors);
714            }
715            let callee_ty = &types[0];
716            if let Some(name) = lookup.registered_function_name(callee_ty) {
717                let ty =
718                    registered_operation_ty(name, &types[1..], *span, lookup, &mut diagnostics);
719                return (ty.unwrap_or(Ty::Any), diagnostics);
720            }
721            if let Some(ty) = matching_registered_type("()", &types, lookup) {
722                return (ty, diagnostics);
723            }
724            let callee_ty = std::mem::replace(&mut types[0], Ty::Any);
725            if let Ty::Callable(parameters, result) = callee_ty {
726                if parameters.len() == args.len()
727                    && parameters
728                        .iter()
729                        .zip(&types[1..])
730                        .all(|(a, b)| a.unifies_with(b))
731                {
732                    return (*result, diagnostics);
733                }
734                diagnostics.push(ParseError::new_range(
735                    "callable argument type mismatch",
736                    span.start,
737                    span.end,
738                ));
739            } else if callee_ty != Ty::Any {
740                diagnostics.push(ParseError::new_range(
741                    "value is not callable",
742                    span.start,
743                    span.end,
744                ));
745            }
746            (Ty::Any, diagnostics)
747        }
748        Expr::Member {
749            receiver,
750            name,
751            args,
752            span,
753            ..
754        } => {
755            let mut diagnostics = Vec::new();
756            let operands = std::iter::once(receiver.as_ref()).chain(args.iter().flatten());
757            let types: Vec<_> = operands
758                .map(|expr| {
759                    let (ty, child_diags) =
760                        check_semantic_expr(expr, resolve_ident, resolve_type, lookup);
761                    let valid = child_diags.iter().all(crate::checking::is_missing);
762                    diagnostics.extend(child_diags);
763                    if valid { ty } else { Ty::Any }
764                })
765                .collect();
766            let ty = registered_operation_ty(name, &types, *span, lookup, &mut diagnostics)
767                .unwrap_or(Ty::Any);
768            (ty, diagnostics)
769        }
770        Expr::Tuple { elements, .. } => {
771            let mut diagnostics = Vec::new();
772            let types = elements
773                .iter()
774                .map(|element| {
775                    let (ty, errors) =
776                        check_semantic_expr(element, resolve_ident, resolve_type, lookup);
777                    diagnostics.extend(errors);
778                    ty
779                })
780                .collect();
781            (Ty::Tuple(types), diagnostics)
782        }
783        // An array literal's own type is `Array` of its elements' unified type; see `check_array`.
784        Expr::Array {
785            elements,
786            type_annotation,
787            annotation_span,
788            ..
789        } => check_array(
790            elements,
791            type_annotation.as_ref(),
792            *annotation_span,
793            resolve_ident,
794            resolve_type,
795            lookup,
796        ),
797        Expr::TupleIndex { base, index, span } => {
798            let (ty, mut diagnostics) =
799                check_semantic_expr(base, resolve_ident, resolve_type, lookup);
800            if let Ty::Tuple(elements) = ty {
801                if let Some(element) = elements.get(*index) {
802                    return (element.clone(), diagnostics);
803                }
804                diagnostics.push(ParseError::new_range(
805                    "tuple index out of bounds",
806                    span.start,
807                    span.end,
808                ));
809            } else if ty != Ty::Any {
810                diagnostics.push(ParseError::new_range(
811                    "tuple index requires a tuple",
812                    span.start,
813                    span.end,
814                ));
815            }
816            (Ty::Any, diagnostics)
817        }
818        Expr::Cast {
819            expr,
820            type_name,
821            span,
822        } => check_cast(expr, type_name, *span, resolve_ident, resolve_type, lookup),
823        Expr::If {
824            cond,
825            then_branch,
826            else_branch,
827            span,
828        } => {
829            let (condition, mut diagnostics) =
830                check_semantic_expr(cond, resolve_ident, resolve_type, lookup);
831            if !condition.unifies_with(&Ty::Bool) {
832                diagnostics.push(ParseError::new_range(
833                    "if condition must be bool",
834                    cond.span().start,
835                    cond.span().end,
836                ));
837            }
838            let (then_ty, errors) =
839                check_semantic_expr(then_branch, resolve_ident, resolve_type, lookup);
840            diagnostics.extend(errors);
841            let (else_ty, errors) = else_branch
842                .as_ref()
843                .map(|branch| check_semantic_expr(branch, resolve_ident, resolve_type, lookup))
844                .unwrap_or((Ty::Tuple(vec![]), vec![]));
845            diagnostics.extend(errors);
846            let ty = then_ty.unify(&else_ty).unwrap_or_else(|| {
847                diagnostics.push(ParseError::new_range(
848                    "if branch type mismatch",
849                    span.start,
850                    span.end,
851                ));
852                Ty::Any
853            });
854            (ty, diagnostics)
855        }
856        Expr::Closure { params, body, .. } => {
857            let mut annotation_errors = crate::ast::closure_parameter_diagnostics(params);
858            let parameters: Vec<_> = params
859                .iter()
860                .map(|p| {
861                    let (resolved, errors) = resolve_type(&p.type_expr);
862                    annotation_errors.extend(errors);
863                    resolved
864                })
865                .collect();
866            let resolve_with_params = |name: &str| -> Option<Ty> {
867                params
868                    .iter()
869                    .position(|p| p.name == name)
870                    .map(|index| parameters[index].clone())
871            };
872            let (result, mut diagnostics) =
873                check_semantic_expr(body, &resolve_with_params, resolve_type, lookup);
874            diagnostics.extend(annotation_errors);
875            (Ty::Callable(parameters, Box::new(result)), diagnostics)
876        }
877    }
878}
879
880/// Checks an [`Expr::Array`] node: infers every element (retaining all of their own nested
881/// diagnostics, whatever the fold below finds), then folds the element types left to right with
882/// [`Ty::unify`] — so [`Ty::Any`] elements (an unresolved identifier, a call result) adopt the
883/// other elements' concrete type instead of defeating inference, and nested arrays unify
884/// recursively. The first element that doesn't unify with the accumulated type gets one
885/// diagnostic, reported at that element's own span, and folding stops there: a heterogeneous
886/// literal yields exactly one conflict diagnostic, naming the first conflicting element, matching
887/// the runtime's own "first conflicting index" report. Later elements are
888/// still fully checked, so their own internal diagnostics still surface.
889///
890/// A literal whose elements conflict infers as `Array(Any)` rather than `Any`: the node is
891/// certainly an array, just one whose element type isn't known, and `Any` inside keeps the
892/// mismatch from cascading into further diagnostics at enclosing nodes. An element-less
893/// `Expr::Array` (which the grammar rejects, see <https://github.com/stlab/cel-rs/issues/212>,
894/// but which can still be built directly) infers as `Array(Any)` with no diagnostic.
895///
896/// - Postcondition: the returned type is always a [`Ty::Array`].
897/// - Complexity: O(n · d) where n is the number of elements and d is their array nesting depth,
898///   plus the cost of checking each element (see [`check_expr`]'s own complexity note).
899fn check_array(
900    elements: &[Expr],
901    type_annotation: Option<&TypeExpr>,
902    annotation_span: Option<ExprSpan>,
903    resolve_ident: &dyn Fn(&str) -> Option<Ty>,
904    resolve_type: &dyn Fn(&TypeExpr) -> (Ty, Vec<ParseError>),
905    lookup: &CheckingEnvironment,
906) -> (Ty, Vec<ParseError>) {
907    let mut diagnostics = Vec::new();
908    let element_tys: Vec<Ty> = elements
909        .iter()
910        .map(|element| {
911            let (ty, element_diags) =
912                check_semantic_expr(element, resolve_ident, resolve_type, lookup);
913            diagnostics.extend(element_diags);
914            ty
915        })
916        .collect();
917    let Some(type_annotation) = type_annotation else {
918        let mut unified = Ty::Any;
919        for (element, ty) in elements.iter().zip(&element_tys) {
920            match unified.unify(ty) {
921                Some(merged) => unified = merged,
922                None => {
923                    diagnostics.push(ParseError::new_range(
924                        format!(
925                            "array elements must share one type: expected `{}`, found `{}`",
926                            unified.name(),
927                            ty.name()
928                        ),
929                        element.span().start,
930                        element.span().end,
931                    ));
932                    return (Ty::Array(Box::new(Ty::Any)), diagnostics);
933                }
934            }
935        }
936        return (Ty::Array(Box::new(unified)), diagnostics);
937    };
938
939    let (resolved_annotation, declared_ty, mut annotation_diags) =
940        check_array_annotation(type_annotation, annotation_span, resolve_type);
941    diagnostics.append(&mut annotation_diags);
942    let (Some(Ty::Array(_)), Ty::Array(declared_element_ty)) = (&resolved_annotation, &declared_ty)
943    else {
944        return (Ty::Array(Box::new(Ty::Any)), diagnostics);
945    };
946
947    for (element, actual_ty) in elements.iter().zip(&element_tys) {
948        if !declared_element_ty.unifies_with(actual_ty) {
949            diagnostics.push(ParseError::new_range(
950                format!(
951                    "array elements must match the annotation exactly: expected `{}`, found `{}`",
952                    declared_element_ty.name(),
953                    actual_ty.name()
954                ),
955                element.span().start,
956                element.span().end,
957            ));
958            break;
959        }
960    }
961    (declared_ty, diagnostics)
962}
963
964/// Resolves an array annotation, retaining partial element shapes and all findings.
965///
966/// Adds a definite diagnostic if the annotation is known not to name an array.
967///
968/// - Complexity: O(n) in the annotation tree plus resolver and descriptor-copying costs.
969fn check_array_annotation(
970    type_annotation: &TypeExpr,
971    annotation_span: Option<ExprSpan>,
972    resolve_type: &dyn Fn(&TypeExpr) -> (Ty, Vec<ParseError>),
973) -> (Option<Ty>, Ty, Vec<ParseError>) {
974    let (resolved, mut diagnostics) = resolve_type(type_annotation);
975    if resolved == Ty::Any {
976        return (None, Ty::Array(Box::new(Ty::Any)), diagnostics);
977    }
978    if matches!(resolved, Ty::Array(_)) {
979        (Some(resolved.clone()), resolved, diagnostics)
980    } else {
981        let span = annotation_span.unwrap_or_else(|| type_annotation.span());
982        let error = ParseError::new_range(
983            format!(
984                "array annotations must name a complete array type, found `{}`",
985                resolved.name()
986            ),
987            span.start,
988            span.end,
989        );
990        diagnostics.push(error);
991        (Some(resolved), Ty::Array(Box::new(Ty::Any)), diagnostics)
992    }
993}
994
995/// Preserves every complete resolved shape in the static model.
996///
997/// - Complexity: O(n + l) in recursive descriptor nodes n and total leaf-name length l.
998///
999fn resolved_type_to_element_ty(resolved: &ResolvedType) -> Ty {
1000    match resolved {
1001        ResolvedType::Scalar(leaf) => Ty::from_leaf(leaf),
1002        ResolvedType::Array { element } => {
1003            Ty::Array(Box::new(resolved_type_to_element_ty(element)))
1004        }
1005        ResolvedType::Tuple { elements } => {
1006            Ty::Tuple(elements.iter().map(resolved_type_to_element_ty).collect())
1007        }
1008        ResolvedType::Callable { parameters, result } => Ty::Callable(
1009            parameters.iter().map(resolved_type_to_element_ty).collect(),
1010            Box::new(resolved_type_to_element_ty(result)),
1011        ),
1012    }
1013}
1014
1015/// Checks an [`Expr::Op`] node by matching known operands against registered signatures
1016/// before [`builtin_operand_types`]. Both sources accept unresolved operands only when
1017/// a signature accepts all known operands; such applications retain an unresolved result.
1018/// Known matches preserve their exact result and registered signatures take precedence.
1019/// Invalid operand expressions retain their diagnostics without a cascading operator mismatch.
1020/// An operator neither metadata source recognizes can't be checked and infers as `Ty::Any`.
1021///
1022/// - Complexity: O(s · a · t) for s registered and built-in signatures, a operands and
1023///   compared type-shape size t, plus the cost of checking each operand (see [`check_expr`]).
1024fn check_op(
1025    name: &str,
1026    operands: &[Expr],
1027    span: ExprSpan,
1028    resolve_ident: &dyn Fn(&str) -> Option<Ty>,
1029    resolve_type: &dyn Fn(&TypeExpr) -> (Ty, Vec<ParseError>),
1030    lookup: &CheckingEnvironment,
1031) -> (Ty, Vec<ParseError>) {
1032    let mut diagnostics = Vec::new();
1033    let operand_tys: Vec<Ty> = operands
1034        .iter()
1035        .map(|operand| {
1036            let (ty, operand_diags) =
1037                check_semantic_expr(operand, resolve_ident, resolve_type, lookup);
1038            diagnostics.extend(operand_diags);
1039            ty
1040        })
1041        .collect();
1042    if diagnostics
1043        .iter()
1044        .any(|error| !crate::checking::is_missing(error))
1045    {
1046        return (Ty::Any, diagnostics);
1047    }
1048    if let Some(ty) = matching_registered_type(name, &operand_tys, lookup) {
1049        return (ty, diagnostics);
1050    }
1051    if name == "range_full" && operand_tys.is_empty() {
1052        return (
1053            lookup.resolve_type("RangeFull").unwrap_or(Ty::Any),
1054            diagnostics,
1055        );
1056    }
1057    let signatures = builtin_operand_types(name);
1058    let matched = signatures.iter().find(|sig| {
1059        sig.arity as usize == operand_tys.len()
1060            && (operand_tys[0] == Ty::Any || operand_tys[0].type_id() == Some(sig.lhs))
1061            && (operand_tys.len() < 2
1062                || operand_tys[1] == Ty::Any
1063                || operand_tys[1].type_id() == Some(sig.rhs))
1064    });
1065    if matched.is_some() {
1066        let ty = if operand_tys.iter().any(Ty::contains_any) {
1067            Ty::Any
1068        } else {
1069            result_ty_for_op(name, &operand_tys[0], lookup)
1070        };
1071        return (ty, diagnostics);
1072    }
1073    if (signatures.is_empty() || lookup.operation_signatures(name).next().is_some())
1074        && let Some(ty) =
1075            registered_operation_ty(name, &operand_tys, span, lookup, &mut diagnostics)
1076    {
1077        return (ty, diagnostics);
1078    }
1079    if !signatures.is_empty() {
1080        let described = operand_tys
1081            .iter()
1082            .map(Ty::name)
1083            .collect::<Vec<_>>()
1084            .join(", ");
1085        diagnostics.push(ParseError::new_range(
1086            format!("`{name}` is not defined for operand type(s) `{described}`"),
1087            span.start,
1088            span.end,
1089        ));
1090    }
1091    (Ty::Any, diagnostics)
1092}
1093
1094/// Resolves a named metadata overload without consulting same-named value bindings.
1095///
1096/// Returns `None` only when no metadata exists. Checks known operands exactly; unresolved
1097/// operands keep the result unknown. A mismatch produces one diagnostic and an unknown result.
1098///
1099/// - Complexity: O(s · a · t) for s signatures, a operands and compared type-shape size t.
1100fn registered_operation_ty(
1101    name: &str,
1102    operands: &[Ty],
1103    span: ExprSpan,
1104    lookup: &CheckingEnvironment,
1105    diagnostics: &mut Vec<ParseError>,
1106) -> Option<Ty> {
1107    if lookup.operation_signatures(name).next().is_none() {
1108        diagnostics.push(crate::checking::optional_missing(
1109            format!("unknown operation `{name}`"),
1110            span,
1111        ));
1112        return None;
1113    }
1114    if let Some(ty) = matching_registered_type(name, operands, lookup) {
1115        return Some(ty);
1116    }
1117    let described = operands.iter().map(Ty::name).collect::<Vec<_>>().join(", ");
1118    diagnostics.push(ParseError::new_range(
1119        format!("`{name}` is not defined for operand type(s) `{described}`"),
1120        span.start,
1121        span.end,
1122    ));
1123    Some(Ty::Any)
1124}
1125
1126/// Returns the first compatible registered result, or `Any` when an operand is unresolved.
1127///
1128/// Returns `None` when no signature accepts the known operand constraints.
1129///
1130/// - Complexity: O(s · a · t) for s signatures, a operands and compared type-shape size t.
1131fn matching_registered_type(
1132    name: &str,
1133    operands: &[Ty],
1134    lookup: &CheckingEnvironment,
1135) -> Option<Ty> {
1136    let signature = lookup.operation_signatures(name).find(|signature| {
1137        signature.operands.len() == operands.len()
1138            && signature
1139                .operands
1140                .iter()
1141                .zip(operands)
1142                .all(|(expected, actual)| expected.unifies_with(actual))
1143    })?;
1144    Some(if operands.iter().any(Ty::contains_any) {
1145        Ty::Any
1146    } else {
1147        signature.result.clone()
1148    })
1149}
1150
1151/// Returns the result type of a matched built-in operator application: `Ty::Bool` for the
1152/// comparison operators, the concrete range descriptor for range constructors, or the
1153/// matched LHS type for arithmetic, bitwise, shifts, unary negation and logical not.
1154fn result_ty_for_op(name: &str, operand_ty: &Ty, lookup: &CheckingEnvironment) -> Ty {
1155    let range = match name {
1156        "range" => Some("Range"),
1157        "range_inclusive" => Some("RangeInclusive"),
1158        "range_from" => Some("RangeFrom"),
1159        "range_to" => Some("RangeTo"),
1160        "range_to_inclusive" => Some("RangeToInclusive"),
1161        _ => None,
1162    };
1163    if let Some(range) = range {
1164        return lookup
1165            .resolve_type(&format!("{range}({})", operand_ty.name()))
1166            .unwrap_or(Ty::Any);
1167    }
1168    match name {
1169        "==" | "!=" | "<" | "<=" | ">" | ">=" => Ty::Bool,
1170        _ => operand_ty.clone(),
1171    }
1172}
1173
1174/// Checks an [`Expr::Cast`] node (`expr as type_name`): infers `expr`'s type, then (only if it
1175/// resolved to a concrete type) checks that a conversion to `type_name` is registered via
1176/// [`cast_source_types`]. Unlike [`check_op`], the node always infers as the target type once
1177/// `type_name` itself resolves - a cast declares its own result type - regardless of whether a
1178/// diagnostic was recorded for the source, matching [`check_logical`]'s pattern.
1179///
1180/// - Complexity: O(s) where s is the number of registered sources [`cast_source_types`] returns
1181///   for `type_name`, plus the cost of checking `expr` (see [`check_expr`]'s own complexity
1182///   note).
1183fn check_cast(
1184    expr: &Expr,
1185    type_name: &str,
1186    span: ExprSpan,
1187    resolve_ident: &dyn Fn(&str) -> Option<Ty>,
1188    resolve_type: &dyn Fn(&TypeExpr) -> (Ty, Vec<ParseError>),
1189    lookup: &CheckingEnvironment,
1190) -> (Ty, Vec<ParseError>) {
1191    let (expr_ty, mut diagnostics) = check_semantic_expr(expr, resolve_ident, resolve_type, lookup);
1192    let Some(target_ty) = lookup.resolve_type(type_name) else {
1193        diagnostics.push(crate::checking::missing(
1194            format!("unknown type `{type_name}`"),
1195            span,
1196        ));
1197        return (Ty::Any, diagnostics);
1198    };
1199    if expr_ty != Ty::Any
1200        && !expr_ty.type_id().is_some_and(|source_type_id| {
1201            cast_source_types(type_name).any(|id| id == source_type_id)
1202        })
1203    {
1204        diagnostics.push(ParseError::new_range(
1205            format!("no cast from `{}` to `{type_name}`", expr_ty.name()),
1206            span.start,
1207            span.end,
1208        ));
1209    }
1210    (target_ty, diagnostics)
1211}
1212
1213/// Checks an [`Expr::Logical`] (`&&`/`||`) node: both operands should unify with `Ty::Bool` (CEL's
1214/// fixed short-circuit semantics, not table-driven like [`Expr::Op`]); the node's own type is
1215/// always `Ty::Bool` regardless of whether a diagnostic was recorded.
1216///
1217/// - Complexity: the sum of both operands' recursive type-checking costs.
1218fn check_logical(
1219    lhs: &Expr,
1220    rhs: &Expr,
1221    span: ExprSpan,
1222    resolve_ident: &dyn Fn(&str) -> Option<Ty>,
1223    resolve_type: &dyn Fn(&TypeExpr) -> (Ty, Vec<ParseError>),
1224    lookup: &CheckingEnvironment,
1225) -> (Ty, Vec<ParseError>) {
1226    let (lhs_ty, mut diagnostics) = check_semantic_expr(lhs, resolve_ident, resolve_type, lookup);
1227    let (rhs_ty, rhs_diags) = check_semantic_expr(rhs, resolve_ident, resolve_type, lookup);
1228    diagnostics.extend(rhs_diags);
1229    for (side, ty) in [("left", lhs_ty), ("right", rhs_ty)] {
1230        if !ty.unifies_with(&Ty::Bool) {
1231            diagnostics.push(ParseError::new_range(
1232                format!(
1233                    "`&&`/`||` requires `bool`, found `{}` on the {side}",
1234                    ty.name()
1235                ),
1236                span.start,
1237                span.end,
1238            ));
1239        }
1240    }
1241    (Ty::Bool, diagnostics)
1242}
1243
1244#[cfg(test)]
1245mod tests {
1246    use super::*;
1247
1248    /// Diagnostic names borrow leaves and preserve recursive callable and singleton syntax.
1249    #[test]
1250    fn diagnostic_names_borrow_leaves_and_preserve_nested_syntax() {
1251        assert!(matches!(Ty::I32.name(), Cow::Borrowed("i32")));
1252        let alias = Ty::Registered(NominalLeaf::from_host(
1253            &crate::ResolvedLeafType::leaf::<i32>("Alias").unwrap(),
1254        ));
1255        assert!(matches!(alias.name(), Cow::Borrowed("Alias")));
1256        let callable = Ty::Callable(
1257            vec![Ty::Array(Box::new(alias))],
1258            Box::new(Ty::Tuple(vec![Ty::I32])),
1259        );
1260        assert_eq!(callable.name(), "Fn(([Alias],), (i32,))");
1261    }
1262    use crate::LogicalOp;
1263
1264    #[test]
1265    fn from_literal_maps_every_concrete_variant() {
1266        assert_eq!(Ty::from_literal(&Literal::I8(1)), Ty::I8);
1267        assert_eq!(Ty::from_literal(&Literal::I16(1)), Ty::I16);
1268        assert_eq!(Ty::from_literal(&Literal::I32(1)), Ty::I32);
1269        assert_eq!(Ty::from_literal(&Literal::I64(1)), Ty::I64);
1270        assert_eq!(Ty::from_literal(&Literal::I128(1)), Ty::I128);
1271        assert_eq!(Ty::from_literal(&Literal::Isize(1)), Ty::Isize);
1272        assert_eq!(Ty::from_literal(&Literal::U8(1)), Ty::U8);
1273        assert_eq!(Ty::from_literal(&Literal::U16(1)), Ty::U16);
1274        assert_eq!(Ty::from_literal(&Literal::U32(1)), Ty::U32);
1275        assert_eq!(Ty::from_literal(&Literal::U64(1)), Ty::U64);
1276        assert_eq!(Ty::from_literal(&Literal::U128(1)), Ty::U128);
1277        assert_eq!(Ty::from_literal(&Literal::Usize(1)), Ty::Usize);
1278        assert_eq!(Ty::from_literal(&Literal::F32(1.0)), Ty::F32);
1279        assert_eq!(Ty::from_literal(&Literal::F64(1.0)), Ty::F64);
1280        assert_eq!(Ty::from_literal(&Literal::Bool(true)), Ty::Bool);
1281        assert_eq!(Ty::from_literal(&Literal::Str("s".to_string())), Ty::String);
1282    }
1283
1284    #[test]
1285    fn from_literal_preserves_nonprimitive_leaf_identity() {
1286        for (literal, id) in [
1287            (Literal::Char('a'), TypeId::of::<char>()),
1288            (Literal::ByteStr(vec![1]), TypeId::of::<Vec<u8>>()),
1289            (
1290                Literal::CStr(std::ffi::CString::new("a").unwrap()),
1291                TypeId::of::<std::ffi::CString>(),
1292            ),
1293            (Literal::Unit, TypeId::of::<()>()),
1294        ] {
1295            assert_eq!(Ty::from_literal(&literal).type_id(), Some(id));
1296            assert!(!Ty::from_literal(&literal).unifies_with(&Ty::F64));
1297        }
1298    }
1299
1300    #[test]
1301    fn type_id_round_trips_through_from_type_id_for_every_concrete_variant() {
1302        for ty in [
1303            Ty::I8,
1304            Ty::I16,
1305            Ty::I32,
1306            Ty::I64,
1307            Ty::I128,
1308            Ty::Isize,
1309            Ty::U8,
1310            Ty::U16,
1311            Ty::U32,
1312            Ty::U64,
1313            Ty::U128,
1314            Ty::Usize,
1315            Ty::F32,
1316            Ty::F64,
1317            Ty::Bool,
1318            Ty::String,
1319        ] {
1320            let id = ty.type_id().expect("concrete Ty has a TypeId");
1321            assert_eq!(Ty::from_type_id(id), ty);
1322        }
1323    }
1324
1325    #[test]
1326    fn any_has_no_type_id() {
1327        assert_eq!(Ty::Any.type_id(), None);
1328    }
1329
1330    #[test]
1331    fn from_type_id_maps_an_unregistered_type_id_to_any() {
1332        assert_eq!(Ty::from_type_id(TypeId::of::<Vec<u8>>()), Ty::Any);
1333    }
1334
1335    #[test]
1336    fn any_unifies_with_every_concrete_type_in_both_directions() {
1337        assert!(Ty::Any.unifies_with(&Ty::I32));
1338        assert!(Ty::I32.unifies_with(&Ty::Any));
1339        assert!(Ty::Any.unifies_with(&Ty::Any));
1340    }
1341
1342    #[test]
1343    fn identical_concrete_types_unify() {
1344        assert!(Ty::F64.unifies_with(&Ty::F64));
1345    }
1346
1347    #[test]
1348    fn distinct_concrete_types_do_not_unify() {
1349        assert!(!Ty::I32.unifies_with(&Ty::F64));
1350        assert!(!Ty::I32.unifies_with(&Ty::Bool));
1351    }
1352
1353    /// Every concrete (non-[`Ty::Array`], non-[`Ty::Any`]) variant, in declaration order.
1354    fn concrete_tys() -> [Ty; 16] {
1355        [
1356            Ty::I8,
1357            Ty::I16,
1358            Ty::I32,
1359            Ty::I64,
1360            Ty::I128,
1361            Ty::Isize,
1362            Ty::U8,
1363            Ty::U16,
1364            Ty::U32,
1365            Ty::U64,
1366            Ty::U128,
1367            Ty::Usize,
1368            Ty::F32,
1369            Ty::F64,
1370            Ty::Bool,
1371            Ty::String,
1372        ]
1373    }
1374
1375    #[test]
1376    fn every_builtin_scalar_table_agrees_on_the_same_names_and_types() {
1377        use crate::op_table::{BUILTIN_SCALAR_NAMES, builtin_scalar_type};
1378        use crate::type_expr::TypeResolver;
1379
1380        for ty in concrete_tys() {
1381            let name = ty.name();
1382            let expected_id = ty.type_id().expect("a concrete Ty has a TypeId");
1383            assert!(
1384                BUILTIN_SCALAR_NAMES.contains(&&*name),
1385                "`{name}` must be one of the built-in scalar names"
1386            );
1387            assert_eq!(
1388                Ty::from_name(&name),
1389                Some(ty.clone()),
1390                "`{name}` must round-trip through Ty::from_name"
1391            );
1392            let scalar = builtin_scalar_type(&name)
1393                .unwrap_or_else(|| panic!("`{name}` must resolve as a built-in scalar"));
1394            assert_eq!((scalar.value_type)().type_id(), expected_id);
1395            assert_eq!(scalar.type_name, name);
1396            let leaf = BuiltinTypeResolver
1397                .resolve_named_type(&name, &[])
1398                .unwrap_or_else(|| panic!("`{name}` must resolve as a CEL leaf type"));
1399            assert_eq!(leaf.type_id(), expected_id);
1400            assert_eq!(leaf.type_name(), name);
1401            assert_eq!(leaf.element_type().type_id(), expected_id);
1402            assert_eq!(
1403                leaf.element_type().type_name(),
1404                name,
1405                "the runtime element descriptor must carry the source-level name"
1406            );
1407            assert_eq!(leaf.element_type().size(), (scalar.value_type)().size());
1408            assert_eq!(leaf.element_type().align(), (scalar.value_type)().align());
1409        }
1410    }
1411
1412    #[test]
1413    fn every_builtin_scalar_name_has_a_concrete_ty() {
1414        use crate::op_table::BUILTIN_SCALAR_NAMES;
1415
1416        let types = concrete_tys();
1417        let ty_names: Vec<_> = types.iter().map(Ty::name).collect();
1418        for name in BUILTIN_SCALAR_NAMES {
1419            assert!(
1420                ty_names.iter().any(|ty_name| ty_name == name),
1421                "the built-in scalar `{name}` has no concrete Ty variant"
1422            );
1423        }
1424    }
1425
1426    #[test]
1427    fn name_is_distinct_per_type() {
1428        let types = [
1429            Ty::I32,
1430            Ty::F64,
1431            Ty::Bool,
1432            Ty::String,
1433            Ty::Array(Box::new(Ty::I32)),
1434            Ty::Array(Box::new(Ty::Array(Box::new(Ty::I32)))),
1435            Ty::Any,
1436        ];
1437        let names: Vec<_> = types.iter().map(Ty::name).collect();
1438        let mut unique = names.clone();
1439        unique.sort_unstable();
1440        unique.dedup();
1441        assert_eq!(
1442            names.len(),
1443            unique.len(),
1444            "every listed Ty has a distinct name"
1445        );
1446    }
1447
1448    fn any_resolver(_name: &str) -> Ty {
1449        Ty::Any
1450    }
1451
1452    fn point(span: proc_macro2::Span) -> ExprSpan {
1453        ExprSpan {
1454            start: span,
1455            end: span,
1456        }
1457    }
1458
1459    fn lit_i32(v: i32) -> Expr {
1460        Expr::Literal {
1461            value: Literal::I32(v),
1462            span: point(proc_macro2::Span::call_site()),
1463        }
1464    }
1465
1466    fn lit_f64(v: f64) -> Expr {
1467        Expr::Literal {
1468            value: Literal::F64(v),
1469            span: point(proc_macro2::Span::call_site()),
1470        }
1471    }
1472
1473    fn lit_bool(v: bool) -> Expr {
1474        Expr::Literal {
1475            value: Literal::Bool(v),
1476            span: point(proc_macro2::Span::call_site()),
1477        }
1478    }
1479
1480    fn lit_str(v: &str) -> Expr {
1481        Expr::Literal {
1482            value: Literal::Str(v.to_string()),
1483            span: point(proc_macro2::Span::call_site()),
1484        }
1485    }
1486
1487    fn op(name: &str, operands: Vec<Expr>) -> Expr {
1488        Expr::Op {
1489            name: name.to_string(),
1490            operands,
1491            span: point(proc_macro2::Span::call_site()),
1492        }
1493    }
1494
1495    fn array(elements: Vec<Expr>) -> Expr {
1496        Expr::Array {
1497            elements,
1498            type_annotation: None,
1499            annotation_span: None,
1500            span: point(proc_macro2::Span::call_site()),
1501        }
1502    }
1503
1504    fn call(callee: &str) -> Expr {
1505        Expr::Apply {
1506            callee: Box::new(Expr::Ident {
1507                name: callee.to_string(),
1508                span: point(proc_macro2::Span::call_site()),
1509            }),
1510            args: Vec::new(),
1511            span: point(proc_macro2::Span::call_site()),
1512        }
1513    }
1514
1515    #[test]
1516    fn literal_infers_its_own_type() {
1517        let (ty, diags) = check_expr(&lit_i32(1), &any_resolver);
1518        assert_eq!(ty, Ty::I32);
1519        assert!(diags.is_empty());
1520    }
1521
1522    #[test]
1523    fn ident_resolves_via_the_supplied_resolver() {
1524        let expr = Expr::Ident {
1525            name: "width".to_string(),
1526            span: point(proc_macro2::Span::call_site()),
1527        };
1528        let (ty, diags) = check_expr(&expr, &|name| {
1529            if name == "width" { Ty::F64 } else { Ty::Any }
1530        });
1531        assert_eq!(ty, Ty::F64);
1532        assert!(diags.is_empty());
1533    }
1534
1535    #[test]
1536    fn unknown_ident_is_any_and_not_a_diagnostic() {
1537        let expr = Expr::Ident {
1538            name: "mystery".to_string(),
1539            span: point(proc_macro2::Span::call_site()),
1540        };
1541        let (ty, diags) = check_expr(&expr, &any_resolver);
1542        assert_eq!(ty, Ty::Any);
1543        assert!(diags.is_empty());
1544    }
1545
1546    #[test]
1547    fn op_with_matching_signature_infers_the_operand_type() {
1548        let expr = op("+", vec![lit_i32(1), lit_i32(2)]);
1549        let (ty, diags) = check_expr(&expr, &any_resolver);
1550        assert_eq!(ty, Ty::I32);
1551        assert!(diags.is_empty());
1552    }
1553
1554    #[test]
1555    fn comparison_op_always_infers_bool() {
1556        let expr = op("==", vec![lit_i32(1), lit_i32(2)]);
1557        let (ty, diags) = check_expr(&expr, &any_resolver);
1558        assert_eq!(ty, Ty::Bool);
1559        assert!(diags.is_empty());
1560    }
1561
1562    #[test]
1563    fn unary_negation_preserves_the_operand_type() {
1564        let expr = op("-", vec![lit_i32(1)]);
1565        let (ty, diags) = check_expr(&expr, &any_resolver);
1566        assert_eq!(ty, Ty::I32);
1567        assert!(diags.is_empty());
1568    }
1569
1570    #[test]
1571    fn op_with_mismatched_operand_types_produces_one_diagnostic_and_infers_any() {
1572        let expr = op("+", vec![lit_i32(1), lit_str("s")]);
1573        let (ty, diags) = check_expr(&expr, &any_resolver);
1574        assert_eq!(ty, Ty::Any);
1575        assert_eq!(diags.len(), 1);
1576    }
1577
1578    #[test]
1579    fn op_with_an_any_operand_produces_no_diagnostic() {
1580        let expr = op(
1581            "+",
1582            vec![
1583                Expr::Ident {
1584                    name: "mystery".to_string(),
1585                    span: point(proc_macro2::Span::call_site()),
1586                },
1587                lit_i32(1),
1588            ],
1589        );
1590        let (ty, diags) = check_expr(&expr, &any_resolver);
1591        assert_eq!(ty, Ty::Any);
1592        assert!(diags.is_empty());
1593    }
1594
1595    #[test]
1596    fn unregistered_operator_name_is_any_and_not_a_diagnostic() {
1597        // "greet" is only ever registered at runtime via OpLookup::register_tuple_op; the static
1598        // checker can't see it and must not guess.
1599        let expr = op("greet", vec![lit_i32(1)]);
1600        let (ty, diags) = check_expr(&expr, &any_resolver);
1601        assert_eq!(ty, Ty::Any);
1602        assert!(diags.is_empty());
1603    }
1604
1605    #[test]
1606    fn logical_and_with_bool_operands_infers_bool_with_no_diagnostic() {
1607        let expr = Expr::Logical {
1608            op: LogicalOp::And,
1609            lhs: Box::new(lit_bool(true)),
1610            rhs: Box::new(lit_bool(false)),
1611            span: point(proc_macro2::Span::call_site()),
1612        };
1613        let (ty, diags) = check_expr(&expr, &any_resolver);
1614        assert_eq!(ty, Ty::Bool);
1615        assert!(diags.is_empty());
1616    }
1617
1618    #[test]
1619    fn logical_or_with_a_non_bool_operand_produces_a_diagnostic_but_still_infers_bool() {
1620        let expr = Expr::Logical {
1621            op: LogicalOp::Or,
1622            lhs: Box::new(lit_i32(1)),
1623            rhs: Box::new(lit_bool(true)),
1624            span: point(proc_macro2::Span::call_site()),
1625        };
1626        let (ty, diags) = check_expr(&expr, &any_resolver);
1627        assert_eq!(ty, Ty::Bool);
1628        assert_eq!(diags.len(), 1);
1629    }
1630
1631    #[test]
1632    fn a_broken_op_nested_inside_a_tuple_still_surfaces_a_diagnostic() {
1633        let expr = Expr::Tuple {
1634            elements: vec![op("+", vec![lit_i32(1), lit_str("s")]), lit_i32(2)],
1635            span: point(proc_macro2::Span::call_site()),
1636        };
1637        let (ty, diags) = check_expr(&expr, &any_resolver);
1638        assert_eq!(ty, Ty::Tuple(vec![Ty::Any, Ty::I32]));
1639        assert_eq!(diags.len(), 1);
1640    }
1641
1642    #[test]
1643    fn a_broken_op_nested_inside_an_if_condition_still_surfaces_a_diagnostic() {
1644        let expr = Expr::If {
1645            cond: Box::new(op("+", vec![lit_i32(1), lit_str("s")])),
1646            then_branch: Box::new(lit_i32(1)),
1647            else_branch: Some(Box::new(lit_i32(2))),
1648            span: point(proc_macro2::Span::call_site()),
1649        };
1650        let (ty, diags) = check_expr(&expr, &any_resolver);
1651        assert_eq!(ty, Ty::I32);
1652        assert_eq!(diags.len(), 1);
1653    }
1654
1655    #[test]
1656    fn a_broken_op_nested_inside_a_call_argument_still_surfaces_a_diagnostic() {
1657        let expr = Expr::Apply {
1658            callee: Box::new(Expr::Ident {
1659                name: "f".to_string(),
1660                span: point(proc_macro2::Span::call_site()),
1661            }),
1662            args: vec![op("+", vec![lit_i32(1), lit_str("s")])],
1663            span: point(proc_macro2::Span::call_site()),
1664        };
1665        let (ty, diags) = check_expr(&expr, &any_resolver);
1666        assert_eq!(ty, Ty::Any, "Apply itself is not type-checked in v1");
1667        assert_eq!(diags.len(), 1);
1668    }
1669
1670    fn cast(inner: Expr, type_name: &str) -> Expr {
1671        Expr::Cast {
1672            expr: Box::new(inner),
1673            type_name: type_name.to_string(),
1674            span: point(proc_macro2::Span::call_site()),
1675        }
1676    }
1677
1678    #[test]
1679    fn cast_to_a_registered_numeric_target_infers_the_target_type_with_no_diagnostic() {
1680        let (ty, diags) = check_expr(&cast(lit_i32(1), "f64"), &any_resolver);
1681        assert_eq!(ty, Ty::F64);
1682        assert!(diags.is_empty());
1683    }
1684
1685    #[test]
1686    fn cast_from_bool_to_bool_produces_no_diagnostic() {
1687        // Regression test for the `ty.rs`/`op_table.rs` "no cast from ... to bool" vs. "unknown
1688        // type" inconsistency: bool is the one type Rust's own `as` allows as a source for `as
1689        // bool` (a no-op identity conversion), so this must not be a diagnostic.
1690        let (ty, diags) = check_expr(&cast(lit_bool(true), "bool"), &any_resolver);
1691        assert_eq!(ty, Ty::Bool);
1692        assert!(diags.is_empty());
1693    }
1694
1695    #[test]
1696    fn cast_from_a_number_to_bool_is_a_diagnostic_not_an_unknown_type_error() {
1697        // `bool` is a recognized cast target (matches [`op_table::signatures_for_cast`]), just one
1698        // with no registered `i32` source - same "no cast from `i32` to `bool`" diagnostic
1699        // `OpLookup::lookup_cast` would report at execution time, not "unknown type `bool`".
1700        let (ty, diags) = check_expr(&cast(lit_i32(1), "bool"), &any_resolver);
1701        assert_eq!(ty, Ty::Bool);
1702        assert_eq!(diags.len(), 1);
1703        assert!(diags[0].message().contains("no cast from"));
1704    }
1705
1706    #[test]
1707    fn cast_to_an_unrecognized_type_name_is_a_diagnostic_and_infers_any() {
1708        let (ty, diags) = check_expr(&cast(lit_i32(1), "nonsense"), &any_resolver);
1709        assert_eq!(ty, Ty::Any);
1710        assert_eq!(diags.len(), 1);
1711    }
1712
1713    #[test]
1714    fn cast_of_an_any_typed_operand_produces_no_diagnostic() {
1715        let expr = Expr::Ident {
1716            name: "mystery".to_string(),
1717            span: point(proc_macro2::Span::call_site()),
1718        };
1719        let (ty, diags) = check_expr(&cast(expr, "i32"), &any_resolver);
1720        assert_eq!(ty, Ty::I32);
1721        assert!(diags.is_empty());
1722    }
1723
1724    fn closure_param(name: &str, type_name: &str) -> crate::ClosureParam {
1725        crate::ClosureParam {
1726            name: name.to_string(),
1727            name_span: point(proc_macro2::Span::call_site()),
1728            type_expr: crate::TypeExpr::Named {
1729                name: type_name.to_string(),
1730                args: Vec::new(),
1731                span: point(proc_macro2::Span::call_site()),
1732            },
1733        }
1734    }
1735
1736    fn closure(params: Vec<crate::ClosureParam>, body: Expr) -> Expr {
1737        Expr::Closure {
1738            params,
1739            body: Box::new(body),
1740            span: point(proc_macro2::Span::call_site()),
1741        }
1742    }
1743
1744    #[test]
1745    fn closure_literal_preserves_its_signature() {
1746        let expr = closure(
1747            vec![closure_param("x", "i32")],
1748            Expr::Ident {
1749                name: "x".to_string(),
1750                span: point(proc_macro2::Span::call_site()),
1751            },
1752        );
1753        let (ty, diags) = check_expr(&expr, &any_resolver);
1754        assert_eq!(ty, Ty::Callable(vec![Ty::I32], Box::new(Ty::I32)));
1755        assert!(diags.is_empty());
1756    }
1757
1758    #[test]
1759    fn closure_body_type_error_surfaces_through_the_closure() {
1760        let body = op(
1761            "+",
1762            vec![
1763                Expr::Ident {
1764                    name: "x".to_string(),
1765                    span: point(proc_macro2::Span::call_site()),
1766                },
1767                lit_str("s"),
1768            ],
1769        );
1770        let expr = closure(vec![closure_param("x", "i32")], body);
1771        let (ty, diags) = check_expr(&expr, &any_resolver);
1772        assert_eq!(ty, Ty::Callable(vec![Ty::I32], Box::new(Ty::Any)));
1773        assert_eq!(diags.len(), 1, "the body's i32 + String mismatch surfaces");
1774    }
1775
1776    #[test]
1777    fn closure_param_shadows_the_outer_resolver() {
1778        // Outer resolver claims "x" is a String; the closure's own "x: i32" parameter must win
1779        // inside the body, so `x + 1i32` type-checks cleanly with no diagnostic.
1780        let outer_resolver = |_: &str| Ty::String;
1781        let body = op(
1782            "+",
1783            vec![
1784                Expr::Ident {
1785                    name: "x".to_string(),
1786                    span: point(proc_macro2::Span::call_site()),
1787                },
1788                lit_i32(1),
1789            ],
1790        );
1791        let expr = closure(vec![closure_param("x", "i32")], body);
1792        let (_, diags) = check_expr(&expr, &outer_resolver);
1793        assert!(diags.is_empty());
1794    }
1795
1796    #[test]
1797    fn array_type_id_requires_complete_shape_instead_of_a_flat_marker() {
1798        assert_eq!(Ty::Array(Box::new(Ty::I32)).type_id(), None);
1799        assert_eq!(Ty::Array(Box::new(Ty::Any)).type_id(), None);
1800    }
1801
1802    #[test]
1803    fn from_type_id_does_not_invent_structural_shape_from_an_owner() {
1804        assert_eq!(
1805            Ty::from_type_id(TypeId::of::<cel_runtime::OwnedValue>()),
1806            Ty::Any
1807        );
1808    }
1809
1810    /// Registered aliases unify by complete concrete identity, not diagnostic spelling.
1811    #[test]
1812    fn registered_leaf_aliases_unify_independently_of_names_and_capabilities() {
1813        /// A foreign leaf whose optional clone capability does not change identity.
1814        #[derive(Clone)]
1815        struct Foreign;
1816        let first = Ty::from_leaf(&ResolvedLeafType::new(
1817            "FirstAlias",
1818            cel_runtime::ValueType::leaf::<Foreign>(),
1819        ));
1820        let second = Ty::from_leaf(&ResolvedLeafType::new(
1821            "SecondAlias",
1822            cel_runtime::ValueType::cloneable_leaf::<Foreign>(),
1823        ));
1824        assert_eq!(first.unify(&second), Some(first.clone()));
1825    }
1826
1827    #[test]
1828    fn array_name_renders_bracket_syntax_recursively() {
1829        assert_eq!(Ty::Array(Box::new(Ty::I32)).name(), "[i32]");
1830        assert_eq!(
1831            Ty::Array(Box::new(Ty::Array(Box::new(Ty::I32)))).name(),
1832            "[[i32]]"
1833        );
1834        assert_eq!(Ty::Array(Box::new(Ty::Any)).name(), "[<any>]");
1835    }
1836
1837    #[test]
1838    fn arrays_unify_only_when_their_element_types_unify_recursively() {
1839        assert!(Ty::Array(Box::new(Ty::I32)).unifies_with(&Ty::Array(Box::new(Ty::I32))));
1840        assert!(Ty::Array(Box::new(Ty::Any)).unifies_with(&Ty::Array(Box::new(Ty::I32))));
1841        assert!(!Ty::Array(Box::new(Ty::I32)).unifies_with(&Ty::Array(Box::new(Ty::F64))));
1842        assert!(
1843            !Ty::Array(Box::new(Ty::Array(Box::new(Ty::I32))))
1844                .unifies_with(&Ty::Array(Box::new(Ty::I32))),
1845            "differing nesting depth does not unify"
1846        );
1847        assert!(!Ty::Array(Box::new(Ty::I32)).unifies_with(&Ty::I32));
1848        assert!(Ty::Any.unifies_with(&Ty::Array(Box::new(Ty::I32))));
1849        assert!(Ty::Array(Box::new(Ty::I32)).unifies_with(&Ty::Any));
1850    }
1851
1852    #[test]
1853    fn unify_keeps_the_more_concrete_side_at_every_nesting_level() {
1854        assert_eq!(Ty::Any.unify(&Ty::I32), Some(Ty::I32));
1855        assert_eq!(Ty::I32.unify(&Ty::Any), Some(Ty::I32));
1856        assert_eq!(
1857            Ty::Array(Box::new(Ty::Any)).unify(&Ty::Array(Box::new(Ty::Array(Box::new(Ty::I32))))),
1858            Some(Ty::Array(Box::new(Ty::Array(Box::new(Ty::I32)))))
1859        );
1860    }
1861
1862    #[test]
1863    fn unify_of_incompatible_types_is_none() {
1864        assert_eq!(Ty::I32.unify(&Ty::F64), None);
1865        assert_eq!(Ty::Array(Box::new(Ty::I32)).unify(&Ty::I32), None);
1866        assert_eq!(
1867            Ty::Array(Box::new(Ty::I32)).unify(&Ty::Array(Box::new(Ty::F64))),
1868            None
1869        );
1870    }
1871
1872    #[test]
1873    fn a_unified_type_unifies_with_both_of_its_sides() {
1874        let lhs = Ty::Array(Box::new(Ty::Any));
1875        let rhs = Ty::Array(Box::new(Ty::I32));
1876        let merged = lhs.unify(&rhs).expect("compatible types unify");
1877        assert!(merged.unifies_with(&lhs));
1878        assert!(merged.unifies_with(&rhs));
1879    }
1880
1881    #[test]
1882    fn homogeneous_array_infers_its_element_type() {
1883        let (ty, diags) = check_expr(&array(vec![lit_i32(1), lit_i32(2)]), &any_resolver);
1884        assert_eq!(ty, Ty::Array(Box::new(Ty::I32)));
1885        assert!(diags.is_empty());
1886    }
1887
1888    #[test]
1889    fn single_element_array_infers_that_element_type() {
1890        let (ty, diags) = check_expr(&array(vec![lit_str("s")]), &any_resolver);
1891        assert_eq!(ty, Ty::Array(Box::new(Ty::String)));
1892        assert!(diags.is_empty());
1893    }
1894
1895    #[test]
1896    fn nested_array_types_unify_recursively() {
1897        let expr = array(vec![array(vec![lit_i32(1)]), array(vec![lit_i32(2)])]);
1898        let (ty, diags) = check_expr(&expr, &any_resolver);
1899        assert_eq!(ty, Ty::Array(Box::new(Ty::Array(Box::new(Ty::I32)))));
1900        assert!(diags.is_empty());
1901    }
1902
1903    #[test]
1904    fn heterogeneous_array_reports_the_conflicting_element() {
1905        let (ty, diags) = check_expr(&array(vec![lit_i32(1), lit_f64(2.0)]), &any_resolver);
1906        assert_eq!(diags.len(), 1);
1907        assert!(
1908            diags[0].message().contains("expected `i32`, found `f64`"),
1909            "got: {}",
1910            diags[0].message()
1911        );
1912        assert_eq!(
1913            ty,
1914            Ty::Array(Box::new(Ty::Any)),
1915            "a conflicting literal is still an array, of an unknown element type"
1916        );
1917    }
1918
1919    #[test]
1920    fn heterogeneous_nested_array_reports_the_recursive_element_types() {
1921        let expr = array(vec![array(vec![lit_i32(1)]), array(vec![lit_f64(1.0)])]);
1922        let (ty, diags) = check_expr(&expr, &any_resolver);
1923        assert_eq!(diags.len(), 1);
1924        assert!(
1925            diags[0]
1926                .message()
1927                .contains("expected `[i32]`, found `[f64]`"),
1928            "got: {}",
1929            diags[0].message()
1930        );
1931        assert_eq!(ty, Ty::Array(Box::new(Ty::Any)));
1932    }
1933
1934    #[test]
1935    fn mismatched_nesting_depth_is_a_diagnostic() {
1936        let expr = array(vec![array(vec![lit_i32(1)]), lit_i32(2)]);
1937        let (_, diags) = check_expr(&expr, &any_resolver);
1938        assert_eq!(diags.len(), 1);
1939        assert!(
1940            diags[0].message().contains("expected `[i32]`, found `i32`"),
1941            "got: {}",
1942            diags[0].message()
1943        );
1944    }
1945
1946    #[test]
1947    fn array_of_unresolved_call_results_infers_an_array_of_any_with_no_diagnostic() {
1948        // `Apply` results are deliberately `Ty::Any` in v1, so `[f(), g()]` cannot be proven
1949        // homogeneous - and must not be reported as heterogeneous either.
1950        let expr = array(vec![call("f"), call("g")]);
1951        let (ty, diags) = check_expr(&expr, &any_resolver);
1952        assert_eq!(ty, Ty::Array(Box::new(Ty::Any)));
1953        assert!(diags.is_empty());
1954    }
1955
1956    #[test]
1957    fn an_any_element_keeps_the_concrete_element_type() {
1958        let expr = array(vec![call("f"), lit_i32(1)]);
1959        let (ty, diags) = check_expr(&expr, &any_resolver);
1960        assert_eq!(ty, Ty::Array(Box::new(Ty::I32)));
1961        assert!(diags.is_empty());
1962    }
1963
1964    #[test]
1965    fn an_any_nested_element_keeps_the_concrete_recursive_element_type() {
1966        let expr = array(vec![array(vec![call("f")]), array(vec![lit_i32(1)])]);
1967        let (ty, diags) = check_expr(&expr, &any_resolver);
1968        assert_eq!(ty, Ty::Array(Box::new(Ty::Array(Box::new(Ty::I32)))));
1969        assert!(diags.is_empty());
1970    }
1971
1972    #[test]
1973    fn every_elements_own_diagnostics_are_retained() {
1974        let expr = array(vec![
1975            op("+", vec![lit_i32(1), lit_str("s")]),
1976            op("+", vec![lit_i32(2), lit_str("t")]),
1977        ]);
1978        let (_, diags) = check_expr(&expr, &any_resolver);
1979        assert_eq!(diags.len(), 2, "both broken elements are reported");
1980    }
1981
1982    #[test]
1983    fn a_later_elements_own_diagnostic_survives_an_earlier_element_conflict() {
1984        let expr = array(vec![
1985            lit_i32(1),
1986            lit_f64(2.0),
1987            op("+", vec![lit_i32(3), lit_str("s")]),
1988        ]);
1989        let (ty, diags) = check_expr(&expr, &any_resolver);
1990        assert_eq!(
1991            diags.len(),
1992            2,
1993            "one element-conflict diagnostic plus the third element's own operator diagnostic"
1994        );
1995        assert_eq!(ty, Ty::Array(Box::new(Ty::Any)));
1996    }
1997
1998    #[test]
1999    fn only_the_first_conflicting_element_is_reported() {
2000        let expr = array(vec![lit_i32(1), lit_f64(2.0), lit_bool(true)]);
2001        let (_, diags) = check_expr(&expr, &any_resolver);
2002        assert_eq!(diags.len(), 1, "one diagnostic per array literal");
2003        assert!(diags[0].message().contains("found `f64`"), "the first one");
2004    }
2005
2006    #[test]
2007    fn a_conflicting_elements_diagnostic_is_anchored_at_that_element() {
2008        // Every other array test builds spans with `Span::call_site()`, where "this element's
2009        // span", "the whole literal's span", and "some other element's span" are all
2010        // indistinguishable. Parsing real source (proc-macro2's `span-locations` feature is on)
2011        // gives each token its own line/column, making the anchoring observable: the conflict is
2012        // reported at the element on line 4, not at the enclosing `[`...`]` starting on line 1,
2013        // and not at a fixed earlier position such as line 2 or 3.
2014        let source = "[\n    1i32,\n    2i32,\n    3.0f64,\n    4i32\n]";
2015        let mut parser = crate::Parser::<crate::AstContext>::new(crate::OpLookup::new());
2016        let expr = parser.parse_str_ast(source).expect("source parses");
2017        let (ty, diags) = check_expr(&expr, &any_resolver);
2018        assert_eq!(ty, Ty::Array(Box::new(Ty::Any)));
2019        assert_eq!(diags.len(), 1);
2020        assert!(
2021            diags[0].message().contains("expected `i32`, found `f64`"),
2022            "got: {}",
2023            diags[0].message()
2024        );
2025        let start = diags[0].span().start();
2026        let end = diags[0]
2027            .end_span()
2028            .expect("the conflict diagnostic spans a range")
2029            .end();
2030        assert_eq!(start.line, 4, "anchored at the conflicting element's line");
2031        assert_eq!(start.column, 4, "at the element, not the enclosing group");
2032        assert_eq!(end.line, 4);
2033        assert_eq!(end.column, 4 + "3.0f64".len());
2034    }
2035
2036    #[test]
2037    fn a_conflict_inside_a_nested_array_does_not_cascade_to_the_outer_literal() {
2038        // `[[1i32, 2.0f64], [3i32, 4i32]]`: the inner `[1i32, 2.0f64]` conflicts and falls back
2039        // to `Array(Any)`, which still unifies with the valid inner array's `Array(i32)` - so the
2040        // outer fold stays silent and the outer literal keeps the concrete nested element type.
2041        let expr = array(vec![
2042            array(vec![lit_i32(1), lit_f64(2.0)]),
2043            array(vec![lit_i32(3), lit_i32(4)]),
2044        ]);
2045        let (ty, diags) = check_expr(&expr, &any_resolver);
2046        assert_eq!(diags.len(), 1, "only the inner conflict is reported");
2047        assert!(
2048            diags[0].message().contains("expected `i32`, found `f64`"),
2049            "got: {}",
2050            diags[0].message()
2051        );
2052        assert_eq!(ty, Ty::Array(Box::new(Ty::Array(Box::new(Ty::I32)))));
2053    }
2054
2055    #[test]
2056    fn typed_array_annotation_returns_the_declared_array_type() {
2057        let mut parser = crate::Parser::<crate::AstContext>::new(crate::OpLookup::new());
2058        let expr = parser
2059            .parse_str_ast("[0, 1]: [i32]")
2060            .expect("source parses");
2061        let (ty, diags) = check_expr(&expr, &any_resolver);
2062        assert_eq!(ty, Ty::Array(Box::new(Ty::I32)));
2063        assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
2064    }
2065
2066    #[test]
2067    fn typed_empty_array_annotation_returns_the_declared_nested_array_type() {
2068        let mut parser = crate::Parser::<crate::AstContext>::new(crate::OpLookup::new());
2069        let expr = parser.parse_str_ast("[]: [[i32]]").expect("source parses");
2070        let (ty, diags) = check_expr(&expr, &any_resolver);
2071        assert_eq!(ty, Ty::Array(Box::new(Ty::Array(Box::new(Ty::I32)))));
2072        assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
2073    }
2074
2075    #[test]
2076    fn typed_array_annotation_reports_exact_element_type_mismatches() {
2077        let mut parser = crate::Parser::<crate::AstContext>::new(crate::OpLookup::new());
2078        let expr = parser
2079            .parse_str_ast("[0, 1]: [f64]")
2080            .expect("source parses");
2081        let (ty, diags) = check_expr(&expr, &any_resolver);
2082        assert_eq!(ty, Ty::Array(Box::new(Ty::F64)));
2083        assert_eq!(diags.len(), 1);
2084        assert!(
2085            diags[0].message().contains("expected `f64`, found `i32`"),
2086            "got: {}",
2087            diags[0].message()
2088        );
2089    }
2090
2091    #[test]
2092    fn typed_array_annotation_reports_exact_custom_element_type_mismatches() {
2093        #[derive(Clone)]
2094        struct Custom;
2095
2096        let mut parser = crate::Parser::<crate::AstContext>::new(crate::OpLookup::new());
2097        let expr = parser
2098            .parse_str_ast("[0]: [Custom]")
2099            .expect("source parses");
2100        let (ty, diags) = check_expr_with_type_resolver(
2101            &expr,
2102            &any_resolver,
2103            &[(
2104                "Custom",
2105                crate::ResolvedLeafType::new("Custom", cel_runtime::ValueType::leaf::<Custom>()),
2106            )],
2107            &OpLookup::new(),
2108        );
2109        assert_eq!(
2110            ty,
2111            Ty::Array(Box::new(Ty::from_leaf(&crate::ResolvedLeafType::new(
2112                "Custom",
2113                cel_runtime::ValueType::leaf::<Custom>()
2114            ))))
2115        );
2116        assert_eq!(diags.len(), 1);
2117        assert!(
2118            diags[0]
2119                .message()
2120                .contains("expected `Custom`, found `i32`"),
2121            "got: {}",
2122            diags[0].message()
2123        );
2124    }
2125
2126    /// A nested literal's own annotation is part of what it means: `[[]: [CustomA]]` is an array
2127    /// of `[CustomA]`, which the runtime rejects against `[[CustomB]]`.
2128    #[test]
2129    fn nested_annotated_array_reports_a_custom_element_mismatch() {
2130        let mut parser = crate::Parser::<crate::AstContext>::new(crate::OpLookup::new());
2131        let expr = parser
2132            .parse_str_ast("[[]: [CustomA]]: [[CustomB]]")
2133            .expect("source parses");
2134        let (ty, diags) = check_expr_with_type_resolver(
2135            &expr,
2136            &any_resolver,
2137            &custom_ab_resolver(),
2138            &OpLookup::new(),
2139        );
2140
2141        assert_eq!(
2142            ty,
2143            Ty::Array(Box::new(Ty::Array(Box::new(Ty::from_leaf(
2144                &custom_ab_resolver()[1].1
2145            )))))
2146        );
2147        assert_eq!(diags.len(), 1, "unexpected diagnostics: {diags:?}");
2148        assert!(
2149            diags[0]
2150                .message()
2151                .contains("expected `[CustomB]`, found `[CustomA]`"),
2152            "got: {}",
2153            diags[0].message()
2154        );
2155    }
2156
2157    /// The same nesting with agreeing annotations is accepted with no diagnostic.
2158    #[test]
2159    fn nested_annotated_array_accepts_a_matching_custom_element_annotation() {
2160        let mut parser = crate::Parser::<crate::AstContext>::new(crate::OpLookup::new());
2161        let expr = parser
2162            .parse_str_ast("[[]: [CustomA]]: [[CustomA]]")
2163            .expect("source parses");
2164        let (ty, diags) = check_expr_with_type_resolver(
2165            &expr,
2166            &any_resolver,
2167            &custom_ab_resolver(),
2168            &OpLookup::new(),
2169        );
2170
2171        assert_eq!(
2172            ty,
2173            Ty::Array(Box::new(Ty::Array(Box::new(Ty::from_leaf(
2174                &custom_ab_resolver()[0].1
2175            )))))
2176        );
2177        assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
2178    }
2179
2180    /// A resolver registering two distinct custom leaf types.
2181    fn custom_ab_resolver() -> [(&'static str, crate::ResolvedLeafType); 2] {
2182        #[derive(Clone)]
2183        struct CustomA;
2184        #[derive(Clone)]
2185        struct CustomB;
2186
2187        [
2188            (
2189                "CustomA",
2190                crate::ResolvedLeafType::new("CustomA", cel_runtime::ValueType::leaf::<CustomA>()),
2191            ),
2192            (
2193                "CustomB",
2194                crate::ResolvedLeafType::new("CustomB", cel_runtime::ValueType::leaf::<CustomB>()),
2195            ),
2196        ]
2197    }
2198
2199    #[test]
2200    fn typed_array_annotation_diagnostics_are_anchored_at_the_annotation_span() {
2201        let source = "[0]: i32";
2202        let mut parser = crate::Parser::<crate::AstContext>::new(crate::OpLookup::new());
2203        let expr = parser.parse_str_ast(source).expect("source parses");
2204        let (_, diags) = check_expr(&expr, &any_resolver);
2205        assert_eq!(diags.len(), 1);
2206        assert!(
2207            diags[0]
2208                .message()
2209                .contains("array annotations must name a complete array type"),
2210            "got: {}",
2211            diags[0].message()
2212        );
2213        let start = diags[0].span().start();
2214        let end = diags[0]
2215            .end_span()
2216            .expect("annotation diagnostics span a range")
2217            .end();
2218        assert_eq!(&source[start.column..end.column], ": i32");
2219    }
2220
2221    #[test]
2222    fn typed_array_annotation_preserves_tuple_array_element_types() {
2223        let mut parser = crate::Parser::<crate::AstContext>::new(crate::OpLookup::new());
2224        let expr = parser
2225            .parse_str_ast("[]: [(i32, f64)]")
2226            .expect("source parses");
2227        let (ty, diags) = check_expr(&expr, &any_resolver);
2228        assert_eq!(ty, Ty::Array(Box::new(Ty::Tuple(vec![Ty::I32, Ty::F64]))));
2229        assert!(diags.is_empty());
2230    }
2231
2232    #[test]
2233    fn an_empty_array_expression_infers_an_array_of_any() {
2234        // The grammar rejects `[]` outright (see #212), but an `Expr::Array` built directly still
2235        // has to infer conservatively rather than panic.
2236        let (ty, diags) = check_expr(&array(Vec::new()), &any_resolver);
2237        assert_eq!(ty, Ty::Array(Box::new(Ty::Any)));
2238        assert!(diags.is_empty());
2239    }
2240}