cel_cxx/types/
mod.rs

1//! CEL type system types and type definitions.
2//!
3//! This module provides the core type system for CEL expressions, including
4//! the [`ValueType`] enum and type conversion utilities.
5//!
6//! This module provides the complete type system for CEL (Common Expression Language).
7//! It defines all the types that can be used in CEL expressions, from primitive types
8//! like integers and strings to complex types like lists, maps, and Protocol Buffer messages.
9//!
10//! # Type Hierarchy
11//!
12//! The CEL type system is built around the [`ValueType`] enum, which represents all
13//! possible types in CEL:
14//!
15//! ## Primitive Types
16//! - **`null`**: Represents the absence of a value
17//! - **`bool`**: Boolean values (`true`/`false`)
18//! - **`int`**: 64-bit signed integers
19//! - **`uint`**: 64-bit unsigned integers  
20//! - **`double`**: Double-precision floating point numbers
21//! - **`string`**: UTF-8 encoded text
22//! - **`bytes`**: Byte arrays
23//!
24//! ## Time Types
25//! - **`duration`**: Time spans (from Protocol Buffers)
26//! - **`timestamp`**: Points in time (from Protocol Buffers)
27//!
28//! ## Collection Types
29//! - **`list<T>`**: Ordered sequences of values
30//! - **`map<K, V>`**: Key-value mappings
31//!
32//! ## Protocol Buffer Types
33//! - **`struct`**: Protocol Buffer messages
34//! - **Wrapper types**: `BoolValue`, `StringValue`, etc.
35//! - **`any`**: Can hold any Protocol Buffer message
36//! - **`enum`**: Protocol Buffer enumerations
37//!
38//! ## Advanced Types
39//! - **`type`**: Represents types themselves as values
40//! - **`function`**: Function signatures
41//! - **`optional<T>`**: Nullable values
42//! - **Opaque types**: Custom user-defined types
43//! - **Type parameters**: For generic type definitions
44//!
45//! # Examples
46//!
47//! ## Working with primitive types
48//!
49//! ```rust,no_run
50//! use cel_cxx::types::*;
51//! use cel_cxx::Kind;
52//!
53//! // Create primitive types
54//! let int_type = ValueType::Int;
55//! let string_type = ValueType::String;
56//! let bool_type = ValueType::Bool;
57//!
58//! // Check type kinds
59//! assert_eq!(int_type.kind(), Kind::Int);
60//! assert_eq!(string_type.kind(), Kind::String);
61//! assert_eq!(bool_type.kind(), Kind::Bool);
62//! ```
63//!
64//! ## Working with collection types
65//!
66//! ```rust,no_run
67//! use cel_cxx::types::*;
68//!
69//! // List of strings: list<string>
70//! let string_list = ValueType::List(ListType::new(ValueType::String));
71//!
72//! // Map from string to int: map<string, int>
73//! let string_to_int_map = ValueType::Map(MapType::new(
74//!     MapKeyType::String,
75//!     ValueType::Int
76//! ));
77//!
78//! // Nested types: list<map<string, int>>
79//! let nested_type = ValueType::List(ListType::new(string_to_int_map));
80//! ```
81//!
82//! ## Working with optional types
83//!
84//! ```rust,no_run
85//! use cel_cxx::types::*;
86//!
87//! // Optional string: optional<string>
88//! let optional_string = ValueType::Optional(OptionalType::new(ValueType::String));
89//!
90//! // Optional list: optional<list<int>>
91//! let optional_list = ValueType::Optional(OptionalType::new(
92//!     ValueType::List(ListType::new(ValueType::Int))
93//! ));
94//! ```
95//!
96//! ## Working with function types
97//!
98//! ```rust,no_run
99//! use cel_cxx::types::*;
100//!
101//! // Function type: (string, int) -> bool
102//! let func_type = ValueType::Function(FunctionType::new(
103//!     ValueType::Bool,
104//!     vec![ValueType::String, ValueType::Int]
105//! ));
106//! ```
107
108use std::fmt::Debug;
109
110mod convert;
111mod display;
112use crate::values::TypedValue;
113use crate::Kind;
114
115pub use convert::InvalidMapKeyType;
116
117/// CEL type representation.
118///
119/// This enum represents all possible types in the CEL type system. CEL supports
120/// a rich type system including primitive types, complex types, and Protocol Buffer
121/// types. Each type corresponds to values that can be used in CEL expressions.
122///
123/// # Examples
124///
125/// ## Basic Type Usage
126///
127/// ```rust,no_run
128/// use cel_cxx::*;
129///
130/// // Create different types
131/// let int_type = ValueType::Int;
132/// let string_type = ValueType::String;
133/// let list_type = ValueType::List(ListType::new(ValueType::String));
134///
135/// // Check the kind of a type
136/// assert_eq!(int_type.kind(), Kind::Int);
137/// ```
138///
139/// ## Map Types
140///
141/// ```rust,no_run
142/// use cel_cxx::*;
143///
144/// let map_type = ValueType::Map(MapType::new(
145///     MapKeyType::String,
146///     ValueType::Int
147/// ));
148///
149/// assert_eq!(map_type.kind(), Kind::Map);
150/// ```
151#[derive(Clone, Debug, Hash, PartialEq, Eq)]
152pub enum ValueType {
153    /// Null type - represents the absence of a value.
154    ///
155    /// This corresponds to CEL's `null` literal.
156    Null,
157
158    /// Boolean type - represents true/false values.
159    ///
160    /// This corresponds to CEL's `bool` type and literals like `true` and `false`.
161    Bool,
162
163    /// Signed 64-bit integer type.
164    ///
165    /// This corresponds to CEL's `int` type and integer literals like `42`.
166    Int,
167
168    /// Unsigned 64-bit integer type.
169    ///
170    /// This corresponds to CEL's `uint` type and unsigned integer literals like `42u`.
171    Uint,
172
173    /// Double-precision floating point type.
174    ///
175    /// This corresponds to CEL's `double` type and floating-point literals like `3.14`.
176    Double,
177
178    /// String type.
179    ///
180    /// This corresponds to CEL's `string` type and string literals like `"hello"`.
181    String,
182
183    /// Byte array type.
184    ///
185    /// This corresponds to CEL's `bytes` type and byte literals like `b"hello"`.
186    Bytes,
187
188    /// Struct type for Protocol Buffer messages.
189    ///
190    /// This represents structured data types, typically Protocol Buffer messages.
191    Struct(StructType),
192
193    /// Duration type from Protocol Buffers.
194    ///
195    /// This corresponds to `google.protobuf.Duration` and duration literals like `duration("1h")`.
196    Duration,
197
198    /// Timestamp type from Protocol Buffers.
199    ///
200    /// This corresponds to `google.protobuf.Timestamp` and timestamp literals like `timestamp("2023-01-01T00:00:00Z")`.
201    Timestamp,
202
203    /// List type - represents ordered collections.
204    ///
205    /// This corresponds to CEL's list type and literals like `[1, 2, 3]`.
206    List(ListType),
207
208    /// Map type - represents key-value mappings.
209    ///
210    /// This corresponds to CEL's map type and literals like `{"key": "value"}`.
211    Map(MapType),
212
213    /// Unknown type - used for values that cannot be determined at compile time.
214    ///
215    /// This is typically used in error conditions or for dynamic values.
216    Unknown,
217
218    /// Type type - represents type values themselves.
219    ///
220    /// This corresponds to CEL's type system where types can be values, such as `int` or `string`.
221    Type(TypeType),
222
223    /// Error type - represents error values.
224    ///
225    /// This is used when evaluation results in an error condition.
226    Error,
227
228    /// Any type from Protocol Buffers.
229    ///
230    /// This corresponds to `google.protobuf.Any` which can hold any Protocol Buffer message.
231    Any,
232
233    /// Dynamic type - represents values whose type is determined at runtime.
234    ///
235    /// This is used for values that can be of any type.
236    Dyn,
237
238    /// Opaque types - user-defined types that are not directly CEL types.
239    ///
240    /// This allows integration of custom Rust types into CEL expressions.
241    Opaque(OpaqueType),
242
243    /// Optional type - represents values that may or may not be present.
244    ///
245    /// This corresponds to CEL's optional types and the `optional` type constructor.
246    Optional(OptionalType),
247
248    /// Boolean wrapper type from Protocol Buffers.
249    ///
250    /// This corresponds to `google.protobuf.BoolValue`.
251    BoolWrapper,
252
253    /// Integer wrapper type from Protocol Buffers.
254    ///
255    /// This corresponds to `google.protobuf.Int32Value`.
256    IntWrapper,
257
258    /// Unsigned integer wrapper type from Protocol Buffers.
259    ///
260    /// This corresponds to `google.protobuf.UInt32Value`.
261    UintWrapper,
262
263    /// Double wrapper type from Protocol Buffers.
264    ///
265    /// This corresponds to `google.protobuf.DoubleValue`.
266    DoubleWrapper,
267
268    /// String wrapper type from Protocol Buffers.
269    ///
270    /// This corresponds to `google.protobuf.StringValue`.
271    StringWrapper,
272
273    /// Bytes wrapper type from Protocol Buffers.
274    ///
275    /// This corresponds to `google.protobuf.BytesValue`.
276    BytesWrapper,
277
278    /// Type parameter type - used in generic type definitions.
279    ///
280    /// This represents type parameters in generic contexts.
281    TypeParam(TypeParamType),
282
283    /// Function type - represents function signatures.
284    ///
285    /// This is used to represent the types of functions and their signatures.
286    Function(FunctionType),
287
288    /// Enum type - represents enumeration types.
289    ///
290    /// This corresponds to Protocol Buffer enum types.
291    Enum(EnumType),
292}
293
294impl ValueType {
295    /// Returns the kind of this type.
296    ///
297    /// The kind represents the basic category of the type, which is useful
298    /// for type checking and dispatch logic.
299    ///
300    /// # Examples
301    ///
302    /// ```rust,no_run
303    /// use cel_cxx::*;
304    ///
305    /// assert_eq!(ValueType::Int.kind(), Kind::Int);
306    /// assert_eq!(ValueType::String.kind(), Kind::String);
307    ///
308    /// let list_type = ValueType::List(ListType::new(ValueType::Int));
309    /// assert_eq!(list_type.kind(), Kind::List);
310    /// ```
311    pub fn kind(&self) -> Kind {
312        match self {
313            ValueType::Null => Kind::Null,
314
315            ValueType::Bool => Kind::Bool,
316            ValueType::Int => Kind::Int,
317            ValueType::Uint => Kind::Uint,
318            ValueType::Double => Kind::Double,
319            ValueType::String => Kind::String,
320            ValueType::Bytes => Kind::Bytes,
321
322            ValueType::Struct(_) => Kind::Struct,
323            ValueType::Duration => Kind::Duration,
324            ValueType::Timestamp => Kind::Timestamp,
325
326            ValueType::List(_) => Kind::List,
327            ValueType::Map(_) => Kind::Map,
328
329            ValueType::Unknown => Kind::Unknown,
330            ValueType::Type(_) => Kind::Type,
331            ValueType::Error => Kind::Error,
332            ValueType::Any => Kind::Any,
333
334            ValueType::Dyn => Kind::Dyn,
335            ValueType::Opaque(_) | ValueType::Optional(_) => Kind::Opaque,
336
337            ValueType::BoolWrapper => Kind::BoolWrapper,
338            ValueType::IntWrapper => Kind::IntWrapper,
339            ValueType::UintWrapper => Kind::UintWrapper,
340            ValueType::DoubleWrapper => Kind::DoubleWrapper,
341            ValueType::StringWrapper => Kind::StringWrapper,
342            ValueType::BytesWrapper => Kind::BytesWrapper,
343
344            ValueType::TypeParam(_) => Kind::TypeParam,
345            ValueType::Function(_) => Kind::Function,
346            ValueType::Enum(_) => Kind::Enum,
347        }
348    }
349
350    /// Checks if this type matches the type of a specific [`TypedValue`] implementation.
351    ///
352    /// This method provides a type-safe way to check if a [`ValueType`] corresponds
353    /// to a particular Rust type that implements [`TypedValue`]. It's particularly
354    /// useful for runtime type checking and validation.
355    ///
356    /// # Type Parameters
357    ///
358    /// * `T` - A type that implements [`TypedValue`], representing the Rust type to check against
359    ///
360    /// # Returns
361    ///
362    /// Returns `true` if this [`ValueType`] matches the CEL type representation of `T`,
363    /// `false` otherwise.
364    ///
365    /// # Examples
366    ///
367    /// ## Basic Type Checking
368    ///
369    /// ```rust,no_run
370    /// use cel_cxx::*;
371    ///
372    /// // Check primitive types
373    /// assert!(ValueType::Int.is::<i64>());
374    /// assert!(ValueType::String.is::<String>());
375    /// assert!(ValueType::Bool.is::<bool>());
376    ///
377    /// // Check against wrong types
378    /// assert!(!ValueType::Int.is::<String>());
379    /// assert!(!ValueType::String.is::<bool>());
380    /// ```
381    ///
382    /// ## Collection Type Checking
383    ///
384    /// ```rust,no_run
385    /// use cel_cxx::*;
386    /// use std::collections::HashMap;
387    ///
388    /// let list_type = ValueType::List(ListType::new(ValueType::Int));
389    /// let map_type = ValueType::Map(MapType::new(MapKeyType::String, ValueType::Int));
390    ///
391    /// // Check collection types
392    /// assert!(list_type.is::<Vec<i64>>());
393    /// assert!(map_type.is::<HashMap<String, i64>>());
394    ///
395    /// // Check against incompatible collection types
396    /// assert!(!list_type.is::<Vec<String>>());
397    /// assert!(!map_type.is::<HashMap<i64, String>>());
398    /// ```
399    ///
400    /// ## Optional Type Checking
401    ///
402    /// ```rust,no_run
403    /// use cel_cxx::*;
404    ///
405    /// let optional_string = ValueType::Optional(OptionalType::new(ValueType::String));
406    ///
407    /// // Check optional types
408    /// assert!(optional_string.is::<Option<String>>());
409    /// assert!(!optional_string.is::<Option<i64>>());
410    /// assert!(!optional_string.is::<String>()); // Not optional
411    /// ```
412    ///
413    /// ## Custom Opaque Type Checking
414    ///
415    /// ```rust,no_run
416    /// use cel_cxx::*;
417    ///
418    /// #[derive(Opaque, Debug, Clone, PartialEq)]
419    /// #[cel_cxx(type = "my.CustomType")]
420    /// #[cel_cxx(display)]
421    /// struct CustomType {
422    ///     value: i32,
423    /// }
424    ///
425    /// let opaque_type = <CustomType as TypedValue>::value_type();
426    ///
427    /// // Check custom opaque type
428    /// assert!(opaque_type.is::<CustomType>());
429    /// assert!(!opaque_type.is::<i32>());
430    /// ```
431    ///
432    /// # Use Cases
433    ///
434    /// This method is commonly used in:
435    /// - **Function implementations**: Validating argument types before processing
436    /// - **Type guards**: Ensuring type safety in generic contexts  
437    /// - **Error handling**: Providing detailed type mismatch error messages
438    /// - **Debugging**: Runtime inspection of type compatibility
439    ///
440    /// # See Also
441    ///
442    /// - [`TypedValue::value_type()`]: Get the [`ValueType`] representation of a Rust type
443    /// - [`ValueType::kind()`]: Get the basic kind category of a type
444    pub fn is<T: TypedValue>(&self) -> bool {
445        T::value_type() == *self
446    }
447
448    /// Checks if this type is a null type.
449    pub fn is_null(&self) -> bool {
450        matches!(self, ValueType::Null)
451    }
452
453    /// Checks if this type is a boolean type.
454    pub fn is_bool(&self) -> bool {
455        matches!(self, ValueType::Bool)
456    }
457
458    /// Checks if this type is a signed integer type.
459    pub fn is_int(&self) -> bool {
460        matches!(self, ValueType::Int)
461    }
462
463    /// Checks if this type is an unsigned integer type.
464    pub fn is_uint(&self) -> bool {
465        matches!(self, ValueType::Uint)
466    }
467
468    /// Checks if this type is a double type.
469    pub fn is_double(&self) -> bool {
470        matches!(self, ValueType::Double)
471    }
472
473    /// Checks if this type is a string type.
474    pub fn is_string(&self) -> bool {
475        matches!(self, ValueType::String)
476    }
477
478    /// Checks if this type is a bytes type.
479    pub fn is_bytes(&self) -> bool {
480        matches!(self, ValueType::Bytes)
481    }
482
483    /// Checks if this type is a struct type.
484    pub fn is_struct(&self) -> bool {
485        matches!(self, ValueType::Struct(_))
486    }
487
488    /// Checks if this type is a duration type.
489    pub fn is_duration(&self) -> bool {
490        matches!(self, ValueType::Duration)
491    }
492
493    /// Checks if this type is a timestamp type.
494    pub fn is_timestamp(&self) -> bool {
495        matches!(self, ValueType::Timestamp)
496    }
497
498    /// Checks if this type is a list type.
499    pub fn is_list(&self) -> bool {
500        matches!(self, ValueType::List(_))
501    }
502
503    /// Checks if this type is a map type.
504    pub fn is_map(&self) -> bool {
505        matches!(self, ValueType::Map(_))
506    }
507
508    /// Checks if this type is a unknown type.
509    pub fn is_unknown(&self) -> bool {
510        matches!(self, ValueType::Unknown)
511    }
512
513    /// Checks if this type is a type type.
514    pub fn is_type(&self) -> bool {
515        matches!(self, ValueType::Type(_))
516    }
517
518    /// Checks if this type is a error type.
519    pub fn is_error(&self) -> bool {
520        matches!(self, ValueType::Error)
521    }
522
523    /// Checks if this type is a any type.
524    pub fn is_any(&self) -> bool {
525        matches!(self, ValueType::Any)
526    }
527
528    /// Checks if this type is a dyn type.
529    pub fn is_dyn(&self) -> bool {
530        matches!(self, ValueType::Dyn)
531    }
532
533    /// Checks if this type is a opaque type.
534    pub fn is_opaque(&self) -> bool {
535        matches!(self, ValueType::Opaque(_))
536    }
537
538    /// Checks if this type is a optional type.
539    pub fn is_optional(&self) -> bool {
540        matches!(self, ValueType::Optional(_))
541    }
542
543    /// Checks if this type is a bool wrapper type.
544    pub fn is_bool_wrapper(&self) -> bool {
545        matches!(self, ValueType::BoolWrapper)
546    }
547
548    /// Checks if this type is a int wrapper type.
549    pub fn is_int_wrapper(&self) -> bool {
550        matches!(self, ValueType::IntWrapper)
551    }
552
553    /// Checks if this type is a uint wrapper type.
554    pub fn is_uint_wrapper(&self) -> bool {
555        matches!(self, ValueType::UintWrapper)
556    }
557
558    /// Checks if this type is a double wrapper type.
559    pub fn is_double_wrapper(&self) -> bool {
560        matches!(self, ValueType::DoubleWrapper)
561    }
562
563    /// Checks if this type is a string wrapper type.
564    pub fn is_string_wrapper(&self) -> bool {
565        matches!(self, ValueType::StringWrapper)
566    }
567
568    /// Checks if this type is a bytes wrapper type.
569    pub fn is_bytes_wrapper(&self) -> bool {
570        matches!(self, ValueType::BytesWrapper)
571    }
572
573    /// Checks if this type is a type param type.
574    pub fn is_type_param(&self) -> bool {
575        matches!(self, ValueType::TypeParam(_))
576    }
577
578    /// Checks if this type is a function type.
579    pub fn is_function(&self) -> bool {
580        matches!(self, ValueType::Function(_))
581    }
582
583    /// Checks if this type is a enum type.
584    pub fn is_enum(&self) -> bool {
585        matches!(self, ValueType::Enum(_))
586    }
587}
588
589/// Struct type for Protocol Buffer messages.
590///
591/// This represents a structured type, typically corresponding to a Protocol Buffer
592/// message type. Struct types are identified by their fully qualified name.
593///
594/// # Examples
595///
596/// ```rust,no_run
597/// use cel_cxx::*;
598///
599/// let struct_type = StructType::new("google.protobuf.Duration");
600/// let type_instance = ValueType::Struct(struct_type);
601/// ```
602#[derive(Clone, Debug, Hash, PartialEq, Eq)]
603pub struct StructType {
604    /// The fully qualified name of the struct type.
605    pub name: String,
606}
607
608impl StructType {
609    /// Creates a new struct type with the given name.
610    ///
611    /// # Arguments
612    ///
613    /// * `name` - The fully qualified name of the struct type
614    ///
615    /// # Examples
616    ///
617    /// ```rust,no_run
618    /// use cel_cxx::*;
619    ///
620    /// let struct_type = StructType::new("my.package.MyMessage");
621    /// ```
622    pub fn new<S: Into<String>>(name: S) -> Self {
623        Self { name: name.into() }
624    }
625}
626
627/// List type representing ordered collections.
628///
629/// List types specify the type of elements they contain. All elements in a
630/// CEL list must be of the same type (or compatible types).
631///
632/// # Examples
633///
634/// ```rust,no_run
635/// use cel_cxx::*;
636///
637/// // List of integers: list<int>
638/// let int_list = ListType::new(ValueType::Int);
639///
640/// // List of strings: list<string>
641/// let string_list = ListType::new(ValueType::String);
642///
643/// // Nested list: list<list<int>>
644/// let nested_list = ListType::new(ValueType::List(int_list));
645/// ```
646#[derive(Clone, Debug, Hash, PartialEq, Eq)]
647pub struct ListType {
648    /// The type of elements in this list.
649    pub element: Box<ValueType>,
650}
651
652impl ListType {
653    /// Creates a new list type with the given element type.
654    ///
655    /// # Arguments
656    ///
657    /// * `element` - The type of elements in the list
658    ///
659    /// # Examples
660    ///
661    /// ```rust,no_run
662    /// use cel_cxx::*;
663    ///
664    /// let list_type = ListType::new(ValueType::String);
665    /// assert_eq!(list_type.element(), &ValueType::String);
666    /// ```
667    pub fn new(element: ValueType) -> Self {
668        Self {
669            element: Box::new(element),
670        }
671    }
672
673    /// Returns the element type of this list.
674    ///
675    /// # Examples
676    ///
677    /// ```rust,no_run
678    /// use cel_cxx::*;
679    ///
680    /// let list_type = ListType::new(ValueType::Int);
681    /// assert_eq!(list_type.element(), &ValueType::Int);
682    /// ```
683    pub fn element(&self) -> &ValueType {
684        &self.element
685    }
686}
687
688/// Map type representing key-value mappings.
689///
690/// Map types specify both the type of keys and the type of values. Not all
691/// types can be used as map keys - only certain primitive types are allowed.
692///
693/// # Examples
694///
695/// ```rust,no_run
696/// use cel_cxx::*;
697///
698/// // Map from string to int: map<string, int>
699/// let string_to_int = MapType::new(MapKeyType::String, ValueType::Int);
700///
701/// // Map from int to list of strings: map<int, list<string>>
702/// let complex_map = MapType::new(
703///     MapKeyType::Int,
704///     ValueType::List(ListType::new(ValueType::String))
705/// );
706/// ```
707#[derive(Clone, Debug, Hash, PartialEq, Eq)]
708pub struct MapType {
709    /// The type of keys in this map.
710    pub key: MapKeyType,
711    /// The type of values in this map.
712    pub value: Box<ValueType>,
713}
714
715impl MapType {
716    /// Creates a new map type with the given key and value types.
717    ///
718    /// # Arguments
719    ///
720    /// * `key` - The type of keys in the map
721    /// * `value` - The type of values in the map
722    ///
723    /// # Examples
724    ///
725    /// ```rust,no_run
726    /// use cel_cxx::*;
727    ///
728    /// let map_type = MapType::new(MapKeyType::String, ValueType::Int);
729    /// assert_eq!(map_type.key(), &MapKeyType::String);
730    /// assert_eq!(map_type.value(), &ValueType::Int);
731    /// ```
732    pub fn new(key: MapKeyType, value: ValueType) -> Self {
733        Self {
734            key,
735            value: Box::new(value),
736        }
737    }
738
739    /// Returns the key type of this map.
740    ///
741    /// # Examples
742    ///
743    /// ```rust,no_run
744    /// use cel_cxx::*;
745    ///
746    /// let map_type = MapType::new(MapKeyType::Int, ValueType::String);
747    /// assert_eq!(map_type.key(), &MapKeyType::Int);
748    /// ```
749    pub fn key(&self) -> &MapKeyType {
750        &self.key
751    }
752
753    /// Returns the value type of this map.
754    ///
755    /// # Examples
756    ///
757    /// ```rust,no_run
758    /// use cel_cxx::*;
759    ///
760    /// let map_type = MapType::new(MapKeyType::String, ValueType::Double);
761    /// assert_eq!(map_type.value(), &ValueType::Double);
762    /// ```
763    pub fn value(&self) -> &ValueType {
764        &self.value
765    }
766}
767
768/// Type type representing type values.
769///
770/// This represents CEL's type system where types themselves can be values.
771/// For example, the expression `type(42)` returns a type value representing `int`.
772///
773/// # Examples
774///
775/// ```rust,no_run
776/// use cel_cxx::*;
777///
778/// // Generic type: type
779/// let generic_type = TypeType::new(None);
780///
781/// // Parameterized type: type<string>
782/// let parameterized_type = TypeType::new(Some(ValueType::String));
783/// ```
784#[derive(Clone, Debug, Hash, PartialEq, Eq)]
785pub struct TypeType {
786    /// Optional type parameter for parameterized types.
787    pub parameter: Option<Box<ValueType>>,
788}
789
790impl TypeType {
791    /// Creates a new type type with an optional parameter.
792    ///
793    /// # Arguments
794    ///
795    /// * `parameter` - Optional type parameter
796    ///
797    /// # Examples
798    ///
799    /// ```rust,no_run
800    /// use cel_cxx::*;
801    ///
802    /// // Generic type
803    /// let generic = TypeType::new(None);
804    ///
805    /// // Specific type
806    /// let specific = TypeType::new(Some(ValueType::String));
807    /// ```
808    pub fn new(parameter: Option<ValueType>) -> Self {
809        Self {
810            parameter: parameter.map(Box::new),
811        }
812    }
813
814    /// Returns the type parameter if present.
815    ///
816    /// # Examples
817    ///
818    /// ```rust,no_run
819    /// use cel_cxx::*;
820    ///
821    /// let type_type = TypeType::new(Some(ValueType::Int));
822    /// assert_eq!(type_type.parameter(), Some(&ValueType::Int));
823    /// ```
824    pub fn parameter(&self) -> Option<&ValueType> {
825        self.parameter.as_deref()
826    }
827}
828
829/// Opaque type for user-defined types.
830///
831/// Opaque types allow you to integrate custom Rust types into CEL expressions.
832/// They are identified by name and can have type parameters for generic types.
833///
834/// # Examples
835///
836/// ```rust,no_run
837/// use cel_cxx::*;
838///
839/// // Simple opaque type: MyType
840/// let simple = OpaqueType::new("MyType", vec![]);
841///
842/// // Generic opaque type: MyGeneric<string, int>
843/// let generic = OpaqueType::new("MyGeneric", vec![ValueType::String, ValueType::Int]);
844/// ```
845#[derive(Clone, Debug, Hash, PartialEq, Eq)]
846pub struct OpaqueType {
847    /// The name of the opaque type.
848    pub name: String,
849    /// Type parameters for generic opaque types.
850    pub parameters: Vec<ValueType>,
851}
852
853impl OpaqueType {
854    /// Creates a new opaque type with the given name and type parameters.
855    ///
856    /// # Arguments
857    ///
858    /// * `name` - The name of the opaque type
859    /// * `parameters` - Type parameters for generic opaque types
860    ///
861    /// # Examples
862    ///
863    /// ```rust,no_run
864    /// use cel_cxx::*;
865    ///
866    /// // Simple opaque type
867    /// let simple = OpaqueType::new("MyType", vec![]);
868    ///
869    /// // Generic opaque type
870    /// let generic = OpaqueType::new("Container", vec![ValueType::String]);
871    /// ```
872    pub fn new<S: Into<String>>(name: S, parameters: Vec<ValueType>) -> Self {
873        Self {
874            name: name.into(),
875            parameters,
876        }
877    }
878
879    /// Returns the name of this opaque type.
880    ///
881    /// # Examples
882    ///
883    /// ```rust,no_run
884    /// use cel_cxx::*;
885    ///
886    /// let opaque_type = OpaqueType::new("MyType", vec![]);
887    /// assert_eq!(opaque_type.name(), "MyType");
888    /// ```
889    pub fn name(&self) -> &str {
890        &self.name
891    }
892
893    /// Returns the type parameters of this opaque type.
894    ///
895    /// # Examples
896    ///
897    /// ```rust,no_run
898    /// use cel_cxx::*;
899    ///
900    /// let opaque_type = OpaqueType::new("Container", vec![ValueType::Int, ValueType::String]);
901    /// assert_eq!(opaque_type.parameters().len(), 2);
902    /// ```
903    pub fn parameters(&self) -> &[ValueType] {
904        &self.parameters
905    }
906}
907
908/// Optional type representing values that may or may not be present.
909///
910/// Optional types wrap another type to indicate that values of that type
911/// may be absent. This is similar to Rust's `Option<T>` type.
912///
913/// # Examples
914///
915/// ```rust,no_run
916/// use cel_cxx::*;
917///
918/// // Optional string: optional<string>
919/// let optional_string = OptionalType::new(ValueType::String);
920///
921/// // Optional list: optional<list<int>>
922/// let optional_list = OptionalType::new(
923///     ValueType::List(ListType::new(ValueType::Int))
924/// );
925/// ```
926#[derive(Clone, Debug, Hash, PartialEq, Eq)]
927pub struct OptionalType {
928    /// The type that may or may not be present.
929    pub parameter: Box<ValueType>,
930}
931
932impl OptionalType {
933    /// Creates a new optional type wrapping the given type.
934    ///
935    /// # Arguments
936    ///
937    /// * `parameter` - The type that may be optional
938    ///
939    /// # Examples
940    ///
941    /// ```rust,no_run
942    /// use cel_cxx::*;
943    ///
944    /// let optional_int = OptionalType::new(ValueType::Int);
945    /// assert_eq!(optional_int.parameter(), &ValueType::Int);
946    /// ```
947    pub fn new(parameter: ValueType) -> Self {
948        Self {
949            parameter: Box::new(parameter),
950        }
951    }
952
953    /// Returns the wrapped type.
954    ///
955    /// # Examples
956    ///
957    /// ```rust,no_run
958    /// use cel_cxx::*;
959    ///
960    /// let optional_string = OptionalType::new(ValueType::String);
961    /// assert_eq!(optional_string.parameter(), &ValueType::String);
962    /// ```
963    pub fn parameter(&self) -> &ValueType {
964        &self.parameter
965    }
966}
967
968/// Type parameter type used in generic type definitions.
969///
970/// Type parameters represent placeholders for types in generic contexts.
971/// They are typically used in function signatures and generic type definitions.
972///
973/// # Examples
974///
975/// ```rust,no_run
976/// use cel_cxx::*;
977///
978/// let type_param = TypeParamType::new("T");
979/// assert_eq!(type_param.name(), "T");
980/// ```
981#[derive(Clone, Debug, Hash, PartialEq, Eq)]
982pub struct TypeParamType {
983    /// The name of the type parameter.
984    pub name: String,
985}
986
987impl TypeParamType {
988    /// Creates a new type parameter with the given name.
989    ///
990    /// # Arguments
991    ///
992    /// * `name` - The name of the type parameter (e.g., "T", "U", "Key", "Value")
993    ///
994    /// # Examples
995    ///
996    /// ```rust,no_run
997    /// use cel_cxx::*;
998    ///
999    /// let type_param = TypeParamType::new("T");
1000    /// let another_param = TypeParamType::new("Key");
1001    /// ```
1002    pub fn new<S: Into<String>>(name: S) -> Self {
1003        Self { name: name.into() }
1004    }
1005
1006    /// Returns the name of this type parameter.
1007    ///
1008    /// # Examples
1009    ///
1010    /// ```rust,no_run
1011    /// use cel_cxx::*;
1012    ///
1013    /// let type_param = TypeParamType::new("T");
1014    /// assert_eq!(type_param.name(), "T");
1015    /// ```
1016    pub fn name(&self) -> &str {
1017        &self.name
1018    }
1019}
1020
1021/// Function type representing function signatures.
1022///
1023/// Function types describe the signature of functions, including their
1024/// parameter types and return type. This is used for type checking
1025/// function calls and declarations.
1026///
1027/// # Examples
1028///
1029/// ```rust,no_run
1030/// use cel_cxx::*;
1031///
1032/// // Function type: (string, int) -> bool
1033/// let func_type = FunctionType::new(
1034///     ValueType::Bool,
1035///     vec![ValueType::String, ValueType::Int]
1036/// );
1037///
1038/// // No-argument function: () -> string
1039/// let no_arg_func = FunctionType::new(ValueType::String, vec![]);
1040/// ```
1041#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1042pub struct FunctionType {
1043    /// The return type of the function.
1044    pub result: Box<ValueType>,
1045    /// The parameter types of the function.
1046    pub arguments: Vec<ValueType>,
1047}
1048
1049impl FunctionType {
1050    /// Creates a new function type with the given return type and parameters.
1051    ///
1052    /// # Arguments
1053    ///
1054    /// * `result` - The return type of the function
1055    /// * `arguments` - The parameter types of the function
1056    ///
1057    /// # Examples
1058    ///
1059    /// ```rust,no_run
1060    /// use cel_cxx::*;
1061    ///
1062    /// // Function that takes two ints and returns a string
1063    /// let func_type = FunctionType::new(
1064    ///     ValueType::String,
1065    ///     vec![ValueType::Int, ValueType::Int]
1066    /// );
1067    /// ```
1068    pub fn new(result: ValueType, arguments: Vec<ValueType>) -> Self {
1069        Self {
1070            result: Box::new(result),
1071            arguments,
1072        }
1073    }
1074
1075    /// Returns the return type of this function.
1076    ///
1077    /// # Examples
1078    ///
1079    /// ```rust,no_run
1080    /// use cel_cxx::*;
1081    ///
1082    /// let func_type = FunctionType::new(ValueType::Bool, vec![ValueType::String]);
1083    /// assert_eq!(func_type.result(), &ValueType::Bool);
1084    /// ```
1085    pub fn result(&self) -> &ValueType {
1086        &self.result
1087    }
1088
1089    /// Returns the parameter types of this function.
1090    ///
1091    /// # Examples
1092    ///
1093    /// ```rust,no_run
1094    /// use cel_cxx::*;
1095    ///
1096    /// let func_type = FunctionType::new(ValueType::Int, vec![ValueType::String, ValueType::Bool]);
1097    /// assert_eq!(func_type.arguments().len(), 2);
1098    /// ```
1099    pub fn arguments(&self) -> &[ValueType] {
1100        &self.arguments
1101    }
1102
1103    /// Generates a unique identifier for this function type.
1104    ///
1105    /// This creates a string representation of the function signature that
1106    /// can be used for function resolution and overload disambiguation.
1107    ///
1108    /// # Arguments
1109    ///
1110    /// * `name` - The name of the function
1111    /// * `member` - Whether this is a member function
1112    ///
1113    /// # Examples
1114    ///
1115    /// ```rust,no_run
1116    /// use cel_cxx::*;
1117    ///
1118    /// let func_type = FunctionType::new(ValueType::Int, vec![ValueType::String]);
1119    /// let id = func_type.id("myFunc", false);
1120    /// // Results in something like "myFunc(string)"
1121    /// ```
1122    pub fn id(&self, name: &str, member: bool) -> String {
1123        use itertools::Itertools;
1124        if member && !self.arguments.is_empty() {
1125            format!(
1126                "({}).{}({})",
1127                self.arguments[0],
1128                name,
1129                self.arguments[1..].iter().format(", ")
1130            )
1131        } else {
1132            format!("{}({})", name, self.arguments.iter().format(", "))
1133        }
1134    }
1135}
1136
1137/// Enum type representing enumeration types.
1138///
1139/// Enum types correspond to Protocol Buffer enum types and represent
1140/// a fixed set of named integer constants.
1141///
1142/// # Examples
1143///
1144/// ```rust,no_run
1145/// use cel_cxx::*;
1146///
1147/// let enum_type = EnumType::new("my.package.Color");
1148/// assert_eq!(enum_type.name(), "my.package.Color");
1149/// ```
1150#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1151pub struct EnumType {
1152    /// The fully qualified name of the enum type.
1153    pub name: String,
1154}
1155
1156impl EnumType {
1157    /// Creates a new enum type with the given name.
1158    ///
1159    /// # Arguments
1160    ///
1161    /// * `name` - The fully qualified name of the enum type
1162    ///
1163    /// # Examples
1164    ///
1165    /// ```rust,no_run
1166    /// use cel_cxx::*;
1167    ///
1168    /// let enum_type = EnumType::new("google.rpc.Code");
1169    /// ```
1170    pub fn new<S: Into<String>>(name: S) -> Self {
1171        Self { name: name.into() }
1172    }
1173
1174    /// Returns the name of this enum type.
1175    ///
1176    /// # Examples
1177    ///
1178    /// ```rust,no_run
1179    /// use cel_cxx::*;
1180    ///
1181    /// let enum_type = EnumType::new("my.Status");
1182    /// assert_eq!(enum_type.name(), "my.Status");
1183    /// ```
1184    pub fn name(&self) -> &str {
1185        &self.name
1186    }
1187}
1188
1189/// Types that can be used as map keys.
1190///
1191/// CEL maps can only use certain types as keys. This enum represents
1192/// the allowed key types in CEL map literals and map type definitions.
1193///
1194/// # Examples
1195///
1196/// ```rust,no_run
1197/// use cel_cxx::*;
1198///
1199/// // String keys are common
1200/// let string_key_map = MapType::new(MapKeyType::String, ValueType::Int);
1201///
1202/// // Integer keys are also supported
1203/// let int_key_map = MapType::new(MapKeyType::Int, ValueType::String);
1204///
1205/// // Check the kind of a key type
1206/// assert_eq!(MapKeyType::String.kind(), Kind::String);
1207/// ```
1208///
1209/// # Note
1210///
1211/// Not all CEL types can be used as map keys. Only primitive types that
1212/// are hashable and comparable are allowed.
1213#[derive(Clone, Debug, Hash, PartialEq, Eq)]
1214#[repr(u8)]
1215pub enum MapKeyType {
1216    /// Boolean keys - `true` and `false`.
1217    Bool,
1218
1219    /// Signed integer keys.
1220    Int,
1221
1222    /// Unsigned integer keys.
1223    Uint,
1224
1225    /// String keys (most common).
1226    String,
1227
1228    /// Dynamic key type - determined at runtime.
1229    Dyn,
1230
1231    /// Type parameter key type - used in generic contexts.
1232    TypeParam(TypeParamType),
1233}
1234
1235impl MapKeyType {
1236    /// Returns the kind of this map key type.
1237    ///
1238    /// This provides the basic category of the key type for type checking
1239    /// and dispatch purposes.
1240    ///
1241    /// # Examples
1242    ///
1243    /// ```rust,no_run
1244    /// use cel_cxx::*;
1245    ///
1246    /// assert_eq!(MapKeyType::String.kind(), Kind::String);
1247    /// assert_eq!(MapKeyType::Int.kind(), Kind::Int);
1248    /// assert_eq!(MapKeyType::Bool.kind(), Kind::Bool);
1249    /// ```
1250    pub fn kind(&self) -> Kind {
1251        match self {
1252            MapKeyType::Bool => Kind::Bool,
1253            MapKeyType::Int => Kind::Int,
1254            MapKeyType::Uint => Kind::Uint,
1255            MapKeyType::String => Kind::String,
1256            MapKeyType::Dyn => Kind::Dyn,
1257            MapKeyType::TypeParam(_) => Kind::TypeParam,
1258        }
1259    }
1260}