cel-cxx 0.2.5

A high-performance, type-safe Rust interface for Common Expression Language (CEL), build on top of cel-cpp with zero-cost FFI bindings via cxx
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
//! CEL type system types and type definitions.
//!
//! This module provides the core type system for CEL expressions, including
//! the [`ValueType`] enum and type conversion utilities.
//!
//! This module provides the complete type system for CEL (Common Expression Language).
//! It defines all the types that can be used in CEL expressions, from primitive types
//! like integers and strings to complex types like lists, maps, and Protocol Buffer messages.
//!
//! # Type Hierarchy
//!
//! The CEL type system is built around the [`ValueType`] enum, which represents all
//! possible types in CEL:
//!
//! ## Primitive Types
//! - **`null`**: Represents the absence of a value
//! - **`bool`**: Boolean values (`true`/`false`)
//! - **`int`**: 64-bit signed integers
//! - **`uint`**: 64-bit unsigned integers  
//! - **`double`**: Double-precision floating point numbers
//! - **`string`**: UTF-8 encoded text
//! - **`bytes`**: Byte arrays
//!
//! ## Time Types
//! - **`duration`**: Time spans (from Protocol Buffers)
//! - **`timestamp`**: Points in time (from Protocol Buffers)
//!
//! ## Collection Types
//! - **`list<T>`**: Ordered sequences of values
//! - **`map<K, V>`**: Key-value mappings
//!
//! ## Protocol Buffer Types
//! - **`struct`**: Protocol Buffer messages
//! - **Wrapper types**: `BoolValue`, `StringValue`, etc.
//! - **`any`**: Can hold any Protocol Buffer message
//! - **`enum`**: Protocol Buffer enumerations
//!
//! ## Advanced Types
//! - **`type`**: Represents types themselves as values
//! - **`function`**: Function signatures
//! - **`optional<T>`**: Nullable values
//! - **Opaque types**: Custom user-defined types
//! - **Type parameters**: For generic type definitions
//!
//! # Examples
//!
//! ## Working with primitive types
//!
//! ```rust,no_run
//! use cel_cxx::types::*;
//! use cel_cxx::Kind;
//!
//! // Create primitive types
//! let int_type = ValueType::Int;
//! let string_type = ValueType::String;
//! let bool_type = ValueType::Bool;
//!
//! // Check type kinds
//! assert_eq!(int_type.kind(), Kind::Int);
//! assert_eq!(string_type.kind(), Kind::String);
//! assert_eq!(bool_type.kind(), Kind::Bool);
//! ```
//!
//! ## Working with collection types
//!
//! ```rust,no_run
//! use cel_cxx::types::*;
//!
//! // List of strings: list<string>
//! let string_list = ValueType::List(ListType::new(ValueType::String));
//!
//! // Map from string to int: map<string, int>
//! let string_to_int_map = ValueType::Map(MapType::new(
//!     MapKeyType::String,
//!     ValueType::Int
//! ));
//!
//! // Nested types: list<map<string, int>>
//! let nested_type = ValueType::List(ListType::new(string_to_int_map));
//! ```
//!
//! ## Working with optional types
//!
//! ```rust,no_run
//! use cel_cxx::types::*;
//!
//! // Optional string: optional<string>
//! let optional_string = ValueType::Optional(OptionalType::new(ValueType::String));
//!
//! // Optional list: optional<list<int>>
//! let optional_list = ValueType::Optional(OptionalType::new(
//!     ValueType::List(ListType::new(ValueType::Int))
//! ));
//! ```
//!
//! ## Working with function types
//!
//! ```rust,no_run
//! use cel_cxx::types::*;
//!
//! // Function type: (string, int) -> bool
//! let func_type = ValueType::Function(FunctionType::new(
//!     ValueType::Bool,
//!     vec![ValueType::String, ValueType::Int]
//! ));
//! ```

use std::fmt::Debug;

mod convert;
mod display;
use crate::values::TypedValue;
use crate::Kind;

pub use convert::InvalidMapKeyType;

/// CEL type representation.
///
/// This enum represents all possible types in the CEL type system. CEL supports
/// a rich type system including primitive types, complex types, and Protocol Buffer
/// types. Each type corresponds to values that can be used in CEL expressions.
///
/// # Examples
///
/// ## Basic Type Usage
///
/// ```rust,no_run
/// use cel_cxx::*;
///
/// // Create different types
/// let int_type = ValueType::Int;
/// let string_type = ValueType::String;
/// let list_type = ValueType::List(ListType::new(ValueType::String));
///
/// // Check the kind of a type
/// assert_eq!(int_type.kind(), Kind::Int);
/// ```
///
/// ## Map Types
///
/// ```rust,no_run
/// use cel_cxx::*;
///
/// let map_type = ValueType::Map(MapType::new(
///     MapKeyType::String,
///     ValueType::Int
/// ));
///
/// assert_eq!(map_type.kind(), Kind::Map);
/// ```
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub enum ValueType {
    /// Null type - represents the absence of a value.
    ///
    /// This corresponds to CEL's `null` literal.
    Null,

    /// Boolean type - represents true/false values.
    ///
    /// This corresponds to CEL's `bool` type and literals like `true` and `false`.
    Bool,

    /// Signed 64-bit integer type.
    ///
    /// This corresponds to CEL's `int` type and integer literals like `42`.
    Int,

    /// Unsigned 64-bit integer type.
    ///
    /// This corresponds to CEL's `uint` type and unsigned integer literals like `42u`.
    Uint,

    /// Double-precision floating point type.
    ///
    /// This corresponds to CEL's `double` type and floating-point literals like `3.14`.
    Double,

    /// String type.
    ///
    /// This corresponds to CEL's `string` type and string literals like `"hello"`.
    String,

    /// Byte array type.
    ///
    /// This corresponds to CEL's `bytes` type and byte literals like `b"hello"`.
    Bytes,

    /// Struct type for Protocol Buffer messages.
    ///
    /// This represents structured data types, typically Protocol Buffer messages.
    Struct(StructType),

    /// Duration type from Protocol Buffers.
    ///
    /// This corresponds to `google.protobuf.Duration` and duration literals like `duration("1h")`.
    Duration,

    /// Timestamp type from Protocol Buffers.
    ///
    /// This corresponds to `google.protobuf.Timestamp` and timestamp literals like `timestamp("2023-01-01T00:00:00Z")`.
    Timestamp,

    /// List type - represents ordered collections.
    ///
    /// This corresponds to CEL's list type and literals like `[1, 2, 3]`.
    List(ListType),

    /// Map type - represents key-value mappings.
    ///
    /// This corresponds to CEL's map type and literals like `{"key": "value"}`.
    Map(MapType),

    /// Unknown type - used for values that cannot be determined at compile time.
    ///
    /// This is typically used in error conditions or for dynamic values.
    Unknown,

    /// Type type - represents type values themselves.
    ///
    /// This corresponds to CEL's type system where types can be values, such as `int` or `string`.
    Type(TypeType),

    /// Error type - represents error values.
    ///
    /// This is used when evaluation results in an error condition.
    Error,

    /// Any type from Protocol Buffers.
    ///
    /// This corresponds to `google.protobuf.Any` which can hold any Protocol Buffer message.
    Any,

    /// Dynamic type - represents values whose type is determined at runtime.
    ///
    /// This is used for values that can be of any type.
    Dyn,

    /// Opaque types - user-defined types that are not directly CEL types.
    ///
    /// This allows integration of custom Rust types into CEL expressions.
    Opaque(OpaqueType),

    /// Optional type - represents values that may or may not be present.
    ///
    /// This corresponds to CEL's optional types and the `optional` type constructor.
    Optional(OptionalType),

    /// Boolean wrapper type from Protocol Buffers.
    ///
    /// This corresponds to `google.protobuf.BoolValue`.
    BoolWrapper,

    /// Integer wrapper type from Protocol Buffers.
    ///
    /// This corresponds to `google.protobuf.Int32Value`.
    IntWrapper,

    /// Unsigned integer wrapper type from Protocol Buffers.
    ///
    /// This corresponds to `google.protobuf.UInt32Value`.
    UintWrapper,

    /// Double wrapper type from Protocol Buffers.
    ///
    /// This corresponds to `google.protobuf.DoubleValue`.
    DoubleWrapper,

    /// String wrapper type from Protocol Buffers.
    ///
    /// This corresponds to `google.protobuf.StringValue`.
    StringWrapper,

    /// Bytes wrapper type from Protocol Buffers.
    ///
    /// This corresponds to `google.protobuf.BytesValue`.
    BytesWrapper,

    /// Type parameter type - used in generic type definitions.
    ///
    /// This represents type parameters in generic contexts.
    TypeParam(TypeParamType),

    /// Function type - represents function signatures.
    ///
    /// This is used to represent the types of functions and their signatures.
    Function(FunctionType),

    /// Enum type - represents enumeration types.
    ///
    /// This corresponds to Protocol Buffer enum types.
    Enum(EnumType),
}

impl ValueType {
    /// Returns the kind of this type.
    ///
    /// The kind represents the basic category of the type, which is useful
    /// for type checking and dispatch logic.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// assert_eq!(ValueType::Int.kind(), Kind::Int);
    /// assert_eq!(ValueType::String.kind(), Kind::String);
    ///
    /// let list_type = ValueType::List(ListType::new(ValueType::Int));
    /// assert_eq!(list_type.kind(), Kind::List);
    /// ```
    pub fn kind(&self) -> Kind {
        match self {
            ValueType::Null => Kind::Null,

            ValueType::Bool => Kind::Bool,
            ValueType::Int => Kind::Int,
            ValueType::Uint => Kind::Uint,
            ValueType::Double => Kind::Double,
            ValueType::String => Kind::String,
            ValueType::Bytes => Kind::Bytes,

            ValueType::Struct(_) => Kind::Struct,
            ValueType::Duration => Kind::Duration,
            ValueType::Timestamp => Kind::Timestamp,

            ValueType::List(_) => Kind::List,
            ValueType::Map(_) => Kind::Map,

            ValueType::Unknown => Kind::Unknown,
            ValueType::Type(_) => Kind::Type,
            ValueType::Error => Kind::Error,
            ValueType::Any => Kind::Any,

            ValueType::Dyn => Kind::Dyn,
            ValueType::Opaque(_) | ValueType::Optional(_) => Kind::Opaque,

            ValueType::BoolWrapper => Kind::BoolWrapper,
            ValueType::IntWrapper => Kind::IntWrapper,
            ValueType::UintWrapper => Kind::UintWrapper,
            ValueType::DoubleWrapper => Kind::DoubleWrapper,
            ValueType::StringWrapper => Kind::StringWrapper,
            ValueType::BytesWrapper => Kind::BytesWrapper,

            ValueType::TypeParam(_) => Kind::TypeParam,
            ValueType::Function(_) => Kind::Function,
            ValueType::Enum(_) => Kind::Enum,
        }
    }

    /// Checks if this type matches the type of a specific [`TypedValue`] implementation.
    ///
    /// This method provides a type-safe way to check if a [`ValueType`] corresponds
    /// to a particular Rust type that implements [`TypedValue`]. It's particularly
    /// useful for runtime type checking and validation.
    ///
    /// # Type Parameters
    ///
    /// * `T` - A type that implements [`TypedValue`], representing the Rust type to check against
    ///
    /// # Returns
    ///
    /// Returns `true` if this [`ValueType`] matches the CEL type representation of `T`,
    /// `false` otherwise.
    ///
    /// # Examples
    ///
    /// ## Basic Type Checking
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// // Check primitive types
    /// assert!(ValueType::Int.is::<i64>());
    /// assert!(ValueType::String.is::<String>());
    /// assert!(ValueType::Bool.is::<bool>());
    ///
    /// // Check against wrong types
    /// assert!(!ValueType::Int.is::<String>());
    /// assert!(!ValueType::String.is::<bool>());
    /// ```
    ///
    /// ## Collection Type Checking
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    /// use std::collections::HashMap;
    ///
    /// let list_type = ValueType::List(ListType::new(ValueType::Int));
    /// let map_type = ValueType::Map(MapType::new(MapKeyType::String, ValueType::Int));
    ///
    /// // Check collection types
    /// assert!(list_type.is::<Vec<i64>>());
    /// assert!(map_type.is::<HashMap<String, i64>>());
    ///
    /// // Check against incompatible collection types
    /// assert!(!list_type.is::<Vec<String>>());
    /// assert!(!map_type.is::<HashMap<i64, String>>());
    /// ```
    ///
    /// ## Optional Type Checking
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let optional_string = ValueType::Optional(OptionalType::new(ValueType::String));
    ///
    /// // Check optional types
    /// assert!(optional_string.is::<Option<String>>());
    /// assert!(!optional_string.is::<Option<i64>>());
    /// assert!(!optional_string.is::<String>()); // Not optional
    /// ```
    ///
    /// ## Custom Opaque Type Checking
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// #[derive(Opaque, Debug, Clone, PartialEq)]
    /// #[cel_cxx(type = "my.CustomType")]
    /// #[cel_cxx(display)]
    /// struct CustomType {
    ///     value: i32,
    /// }
    ///
    /// let opaque_type = <CustomType as TypedValue>::value_type();
    ///
    /// // Check custom opaque type
    /// assert!(opaque_type.is::<CustomType>());
    /// assert!(!opaque_type.is::<i32>());
    /// ```
    ///
    /// # Use Cases
    ///
    /// This method is commonly used in:
    /// - **Function implementations**: Validating argument types before processing
    /// - **Type guards**: Ensuring type safety in generic contexts  
    /// - **Error handling**: Providing detailed type mismatch error messages
    /// - **Debugging**: Runtime inspection of type compatibility
    ///
    /// # See Also
    ///
    /// - [`TypedValue::value_type()`]: Get the [`ValueType`] representation of a Rust type
    /// - [`ValueType::kind()`]: Get the basic kind category of a type
    pub fn is<T: TypedValue>(&self) -> bool {
        T::value_type() == *self
    }

    /// Checks if this type is a null type.
    pub fn is_null(&self) -> bool {
        matches!(self, ValueType::Null)
    }

    /// Checks if this type is a boolean type.
    pub fn is_bool(&self) -> bool {
        matches!(self, ValueType::Bool)
    }

    /// Checks if this type is a signed integer type.
    pub fn is_int(&self) -> bool {
        matches!(self, ValueType::Int)
    }

    /// Checks if this type is an unsigned integer type.
    pub fn is_uint(&self) -> bool {
        matches!(self, ValueType::Uint)
    }

    /// Checks if this type is a double type.
    pub fn is_double(&self) -> bool {
        matches!(self, ValueType::Double)
    }

    /// Checks if this type is a string type.
    pub fn is_string(&self) -> bool {
        matches!(self, ValueType::String)
    }

    /// Checks if this type is a bytes type.
    pub fn is_bytes(&self) -> bool {
        matches!(self, ValueType::Bytes)
    }

    /// Checks if this type is a struct type.
    pub fn is_struct(&self) -> bool {
        matches!(self, ValueType::Struct(_))
    }

    /// Checks if this type is a duration type.
    pub fn is_duration(&self) -> bool {
        matches!(self, ValueType::Duration)
    }

    /// Checks if this type is a timestamp type.
    pub fn is_timestamp(&self) -> bool {
        matches!(self, ValueType::Timestamp)
    }

    /// Checks if this type is a list type.
    pub fn is_list(&self) -> bool {
        matches!(self, ValueType::List(_))
    }

    /// Checks if this type is a map type.
    pub fn is_map(&self) -> bool {
        matches!(self, ValueType::Map(_))
    }

    /// Checks if this type is a unknown type.
    pub fn is_unknown(&self) -> bool {
        matches!(self, ValueType::Unknown)
    }

    /// Checks if this type is a type type.
    pub fn is_type(&self) -> bool {
        matches!(self, ValueType::Type(_))
    }

    /// Checks if this type is a error type.
    pub fn is_error(&self) -> bool {
        matches!(self, ValueType::Error)
    }

    /// Checks if this type is a any type.
    pub fn is_any(&self) -> bool {
        matches!(self, ValueType::Any)
    }

    /// Checks if this type is a dyn type.
    pub fn is_dyn(&self) -> bool {
        matches!(self, ValueType::Dyn)
    }

    /// Checks if this type is a opaque type.
    pub fn is_opaque(&self) -> bool {
        matches!(self, ValueType::Opaque(_))
    }

    /// Checks if this type is a optional type.
    pub fn is_optional(&self) -> bool {
        matches!(self, ValueType::Optional(_))
    }

    /// Checks if this type is a bool wrapper type.
    pub fn is_bool_wrapper(&self) -> bool {
        matches!(self, ValueType::BoolWrapper)
    }

    /// Checks if this type is a int wrapper type.
    pub fn is_int_wrapper(&self) -> bool {
        matches!(self, ValueType::IntWrapper)
    }

    /// Checks if this type is a uint wrapper type.
    pub fn is_uint_wrapper(&self) -> bool {
        matches!(self, ValueType::UintWrapper)
    }

    /// Checks if this type is a double wrapper type.
    pub fn is_double_wrapper(&self) -> bool {
        matches!(self, ValueType::DoubleWrapper)
    }

    /// Checks if this type is a string wrapper type.
    pub fn is_string_wrapper(&self) -> bool {
        matches!(self, ValueType::StringWrapper)
    }

    /// Checks if this type is a bytes wrapper type.
    pub fn is_bytes_wrapper(&self) -> bool {
        matches!(self, ValueType::BytesWrapper)
    }

    /// Checks if this type is a type param type.
    pub fn is_type_param(&self) -> bool {
        matches!(self, ValueType::TypeParam(_))
    }

    /// Checks if this type is a function type.
    pub fn is_function(&self) -> bool {
        matches!(self, ValueType::Function(_))
    }

    /// Checks if this type is a enum type.
    pub fn is_enum(&self) -> bool {
        matches!(self, ValueType::Enum(_))
    }
}

/// Struct type for Protocol Buffer messages.
///
/// This represents a structured type, typically corresponding to a Protocol Buffer
/// message type. Struct types are identified by their fully qualified name.
///
/// # Examples
///
/// ```rust,no_run
/// use cel_cxx::*;
///
/// let struct_type = StructType::new("google.protobuf.Duration");
/// let type_instance = ValueType::Struct(struct_type);
/// ```
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct StructType {
    /// The fully qualified name of the struct type.
    pub name: String,
}

impl StructType {
    /// Creates a new struct type with the given name.
    ///
    /// # Arguments
    ///
    /// * `name` - The fully qualified name of the struct type
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let struct_type = StructType::new("my.package.MyMessage");
    /// ```
    pub fn new<S: Into<String>>(name: S) -> Self {
        Self { name: name.into() }
    }
}

/// List type representing ordered collections.
///
/// List types specify the type of elements they contain. All elements in a
/// CEL list must be of the same type (or compatible types).
///
/// # Examples
///
/// ```rust,no_run
/// use cel_cxx::*;
///
/// // List of integers: list<int>
/// let int_list = ListType::new(ValueType::Int);
///
/// // List of strings: list<string>
/// let string_list = ListType::new(ValueType::String);
///
/// // Nested list: list<list<int>>
/// let nested_list = ListType::new(ValueType::List(int_list));
/// ```
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct ListType {
    /// The type of elements in this list.
    pub element: Box<ValueType>,
}

impl ListType {
    /// Creates a new list type with the given element type.
    ///
    /// # Arguments
    ///
    /// * `element` - The type of elements in the list
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let list_type = ListType::new(ValueType::String);
    /// assert_eq!(list_type.element(), &ValueType::String);
    /// ```
    pub fn new(element: ValueType) -> Self {
        Self {
            element: Box::new(element),
        }
    }

    /// Returns the element type of this list.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let list_type = ListType::new(ValueType::Int);
    /// assert_eq!(list_type.element(), &ValueType::Int);
    /// ```
    pub fn element(&self) -> &ValueType {
        &self.element
    }
}

/// Map type representing key-value mappings.
///
/// Map types specify both the type of keys and the type of values. Not all
/// types can be used as map keys - only certain primitive types are allowed.
///
/// # Examples
///
/// ```rust,no_run
/// use cel_cxx::*;
///
/// // Map from string to int: map<string, int>
/// let string_to_int = MapType::new(MapKeyType::String, ValueType::Int);
///
/// // Map from int to list of strings: map<int, list<string>>
/// let complex_map = MapType::new(
///     MapKeyType::Int,
///     ValueType::List(ListType::new(ValueType::String))
/// );
/// ```
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct MapType {
    /// The type of keys in this map.
    pub key: MapKeyType,
    /// The type of values in this map.
    pub value: Box<ValueType>,
}

impl MapType {
    /// Creates a new map type with the given key and value types.
    ///
    /// # Arguments
    ///
    /// * `key` - The type of keys in the map
    /// * `value` - The type of values in the map
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let map_type = MapType::new(MapKeyType::String, ValueType::Int);
    /// assert_eq!(map_type.key(), &MapKeyType::String);
    /// assert_eq!(map_type.value(), &ValueType::Int);
    /// ```
    pub fn new(key: MapKeyType, value: ValueType) -> Self {
        Self {
            key,
            value: Box::new(value),
        }
    }

    /// Returns the key type of this map.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let map_type = MapType::new(MapKeyType::Int, ValueType::String);
    /// assert_eq!(map_type.key(), &MapKeyType::Int);
    /// ```
    pub fn key(&self) -> &MapKeyType {
        &self.key
    }

    /// Returns the value type of this map.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let map_type = MapType::new(MapKeyType::String, ValueType::Double);
    /// assert_eq!(map_type.value(), &ValueType::Double);
    /// ```
    pub fn value(&self) -> &ValueType {
        &self.value
    }
}

/// Type type representing type values.
///
/// This represents CEL's type system where types themselves can be values.
/// For example, the expression `type(42)` returns a type value representing `int`.
///
/// # Examples
///
/// ```rust,no_run
/// use cel_cxx::*;
///
/// // Generic type: type
/// let generic_type = TypeType::new(None);
///
/// // Parameterized type: type<string>
/// let parameterized_type = TypeType::new(Some(ValueType::String));
/// ```
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct TypeType {
    /// Optional type parameter for parameterized types.
    pub parameter: Option<Box<ValueType>>,
}

impl TypeType {
    /// Creates a new type type with an optional parameter.
    ///
    /// # Arguments
    ///
    /// * `parameter` - Optional type parameter
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// // Generic type
    /// let generic = TypeType::new(None);
    ///
    /// // Specific type
    /// let specific = TypeType::new(Some(ValueType::String));
    /// ```
    pub fn new(parameter: Option<ValueType>) -> Self {
        Self {
            parameter: parameter.map(Box::new),
        }
    }

    /// Returns the type parameter if present.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let type_type = TypeType::new(Some(ValueType::Int));
    /// assert_eq!(type_type.parameter(), Some(&ValueType::Int));
    /// ```
    pub fn parameter(&self) -> Option<&ValueType> {
        self.parameter.as_deref()
    }
}

/// Opaque type for user-defined types.
///
/// Opaque types allow you to integrate custom Rust types into CEL expressions.
/// They are identified by name and can have type parameters for generic types.
///
/// # Examples
///
/// ```rust,no_run
/// use cel_cxx::*;
///
/// // Simple opaque type: MyType
/// let simple = OpaqueType::new("MyType", vec![]);
///
/// // Generic opaque type: MyGeneric<string, int>
/// let generic = OpaqueType::new("MyGeneric", vec![ValueType::String, ValueType::Int]);
/// ```
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct OpaqueType {
    /// The name of the opaque type.
    pub name: String,
    /// Type parameters for generic opaque types.
    pub parameters: Vec<ValueType>,
}

impl OpaqueType {
    /// Creates a new opaque type with the given name and type parameters.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the opaque type
    /// * `parameters` - Type parameters for generic opaque types
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// // Simple opaque type
    /// let simple = OpaqueType::new("MyType", vec![]);
    ///
    /// // Generic opaque type
    /// let generic = OpaqueType::new("Container", vec![ValueType::String]);
    /// ```
    pub fn new<S: Into<String>>(name: S, parameters: Vec<ValueType>) -> Self {
        Self {
            name: name.into(),
            parameters,
        }
    }

    /// Returns the name of this opaque type.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let opaque_type = OpaqueType::new("MyType", vec![]);
    /// assert_eq!(opaque_type.name(), "MyType");
    /// ```
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the type parameters of this opaque type.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let opaque_type = OpaqueType::new("Container", vec![ValueType::Int, ValueType::String]);
    /// assert_eq!(opaque_type.parameters().len(), 2);
    /// ```
    pub fn parameters(&self) -> &[ValueType] {
        &self.parameters
    }
}

/// Optional type representing values that may or may not be present.
///
/// Optional types wrap another type to indicate that values of that type
/// may be absent. This is similar to Rust's `Option<T>` type.
///
/// # Examples
///
/// ```rust,no_run
/// use cel_cxx::*;
///
/// // Optional string: optional<string>
/// let optional_string = OptionalType::new(ValueType::String);
///
/// // Optional list: optional<list<int>>
/// let optional_list = OptionalType::new(
///     ValueType::List(ListType::new(ValueType::Int))
/// );
/// ```
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct OptionalType {
    /// The type that may or may not be present.
    pub parameter: Box<ValueType>,
}

impl OptionalType {
    /// Creates a new optional type wrapping the given type.
    ///
    /// # Arguments
    ///
    /// * `parameter` - The type that may be optional
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let optional_int = OptionalType::new(ValueType::Int);
    /// assert_eq!(optional_int.parameter(), &ValueType::Int);
    /// ```
    pub fn new(parameter: ValueType) -> Self {
        Self {
            parameter: Box::new(parameter),
        }
    }

    /// Returns the wrapped type.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let optional_string = OptionalType::new(ValueType::String);
    /// assert_eq!(optional_string.parameter(), &ValueType::String);
    /// ```
    pub fn parameter(&self) -> &ValueType {
        &self.parameter
    }
}

/// Type parameter type used in generic type definitions.
///
/// Type parameters represent placeholders for types in generic contexts.
/// They are typically used in function signatures and generic type definitions.
///
/// # Examples
///
/// ```rust,no_run
/// use cel_cxx::*;
///
/// let type_param = TypeParamType::new("T");
/// assert_eq!(type_param.name(), "T");
/// ```
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct TypeParamType {
    /// The name of the type parameter.
    pub name: String,
}

impl TypeParamType {
    /// Creates a new type parameter with the given name.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the type parameter (e.g., "T", "U", "Key", "Value")
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let type_param = TypeParamType::new("T");
    /// let another_param = TypeParamType::new("Key");
    /// ```
    pub fn new<S: Into<String>>(name: S) -> Self {
        Self { name: name.into() }
    }

    /// Returns the name of this type parameter.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let type_param = TypeParamType::new("T");
    /// assert_eq!(type_param.name(), "T");
    /// ```
    pub fn name(&self) -> &str {
        &self.name
    }
}

/// Function type representing function signatures.
///
/// Function types describe the signature of functions, including their
/// parameter types and return type. This is used for type checking
/// function calls and declarations.
///
/// # Examples
///
/// ```rust,no_run
/// use cel_cxx::*;
///
/// // Function type: (string, int) -> bool
/// let func_type = FunctionType::new(
///     ValueType::Bool,
///     vec![ValueType::String, ValueType::Int]
/// );
///
/// // No-argument function: () -> string
/// let no_arg_func = FunctionType::new(ValueType::String, vec![]);
/// ```
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct FunctionType {
    /// The return type of the function.
    pub result: Box<ValueType>,
    /// The parameter types of the function.
    pub arguments: Vec<ValueType>,
}

impl FunctionType {
    /// Creates a new function type with the given return type and parameters.
    ///
    /// # Arguments
    ///
    /// * `result` - The return type of the function
    /// * `arguments` - The parameter types of the function
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// // Function that takes two ints and returns a string
    /// let func_type = FunctionType::new(
    ///     ValueType::String,
    ///     vec![ValueType::Int, ValueType::Int]
    /// );
    /// ```
    pub fn new(result: ValueType, arguments: Vec<ValueType>) -> Self {
        Self {
            result: Box::new(result),
            arguments,
        }
    }

    /// Returns the return type of this function.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let func_type = FunctionType::new(ValueType::Bool, vec![ValueType::String]);
    /// assert_eq!(func_type.result(), &ValueType::Bool);
    /// ```
    pub fn result(&self) -> &ValueType {
        &self.result
    }

    /// Returns the parameter types of this function.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let func_type = FunctionType::new(ValueType::Int, vec![ValueType::String, ValueType::Bool]);
    /// assert_eq!(func_type.arguments().len(), 2);
    /// ```
    pub fn arguments(&self) -> &[ValueType] {
        &self.arguments
    }

    /// Generates a unique identifier for this function type.
    ///
    /// This creates a string representation of the function signature that
    /// can be used for function resolution and overload disambiguation.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the function
    /// * `member` - Whether this is a member function
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let func_type = FunctionType::new(ValueType::Int, vec![ValueType::String]);
    /// let id = func_type.id("myFunc", false);
    /// // Results in something like "myFunc(string)"
    /// ```
    pub fn id(&self, name: &str, member: bool) -> String {
        use itertools::Itertools;
        if member && !self.arguments.is_empty() {
            format!(
                "({}).{}({})",
                self.arguments[0],
                name,
                self.arguments[1..].iter().format(", ")
            )
        } else {
            format!("{}({})", name, self.arguments.iter().format(", "))
        }
    }
}

/// Enum type representing enumeration types.
///
/// Enum types correspond to Protocol Buffer enum types and represent
/// a fixed set of named integer constants.
///
/// # Examples
///
/// ```rust,no_run
/// use cel_cxx::*;
///
/// let enum_type = EnumType::new("my.package.Color");
/// assert_eq!(enum_type.name(), "my.package.Color");
/// ```
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct EnumType {
    /// The fully qualified name of the enum type.
    pub name: String,
}

impl EnumType {
    /// Creates a new enum type with the given name.
    ///
    /// # Arguments
    ///
    /// * `name` - The fully qualified name of the enum type
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let enum_type = EnumType::new("google.rpc.Code");
    /// ```
    pub fn new<S: Into<String>>(name: S) -> Self {
        Self { name: name.into() }
    }

    /// Returns the name of this enum type.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// let enum_type = EnumType::new("my.Status");
    /// assert_eq!(enum_type.name(), "my.Status");
    /// ```
    pub fn name(&self) -> &str {
        &self.name
    }
}

/// Types that can be used as map keys.
///
/// CEL maps can only use certain types as keys. This enum represents
/// the allowed key types in CEL map literals and map type definitions.
///
/// # Examples
///
/// ```rust,no_run
/// use cel_cxx::*;
///
/// // String keys are common
/// let string_key_map = MapType::new(MapKeyType::String, ValueType::Int);
///
/// // Integer keys are also supported
/// let int_key_map = MapType::new(MapKeyType::Int, ValueType::String);
///
/// // Check the kind of a key type
/// assert_eq!(MapKeyType::String.kind(), Kind::String);
/// ```
///
/// # Note
///
/// Not all CEL types can be used as map keys. Only primitive types that
/// are hashable and comparable are allowed.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
#[repr(u8)]
pub enum MapKeyType {
    /// Boolean keys - `true` and `false`.
    Bool,

    /// Signed integer keys.
    Int,

    /// Unsigned integer keys.
    Uint,

    /// String keys (most common).
    String,

    /// Dynamic key type - determined at runtime.
    Dyn,

    /// Type parameter key type - used in generic contexts.
    TypeParam(TypeParamType),
}

impl MapKeyType {
    /// Returns the kind of this map key type.
    ///
    /// This provides the basic category of the key type for type checking
    /// and dispatch purposes.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use cel_cxx::*;
    ///
    /// assert_eq!(MapKeyType::String.kind(), Kind::String);
    /// assert_eq!(MapKeyType::Int.kind(), Kind::Int);
    /// assert_eq!(MapKeyType::Bool.kind(), Kind::Bool);
    /// ```
    pub fn kind(&self) -> Kind {
        match self {
            MapKeyType::Bool => Kind::Bool,
            MapKeyType::Int => Kind::Int,
            MapKeyType::Uint => Kind::Uint,
            MapKeyType::String => Kind::String,
            MapKeyType::Dyn => Kind::Dyn,
            MapKeyType::TypeParam(_) => Kind::TypeParam,
        }
    }
}