Debian Codegraph @

common/types/types.go

raw
1 // Copyright 2023 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package types
16
17 import (
18 "fmt"
19 "reflect"
20 "strings"
21
22 "google.golang.org/protobuf/proto"
23
24 chkdecls "github.com/google/cel-go/checker/decls"
25 "github.com/google/cel-go/common/types/ref"
26 "github.com/google/cel-go/common/types/traits"
27
28 celpb "cel.dev/expr"
29 exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
30 )
31
32 // Kind indicates a CEL type's kind which is used to differentiate quickly between simple
33 // and complex types.
34 type Kind uint
35
36 const (
37 // UnspecifiedKind is returned when the type is nil or its kind is not specified.
38 UnspecifiedKind Kind = iota
39
40 // DynKind represents a dynamic type. This kind only exists at type-check time.
41 DynKind
42
43 // AnyKind represents a google.protobuf.Any type. This kind only exists at type-check time.
44 // Prefer DynKind to AnyKind as AnyKind has a specific meaning which is based on protobuf
45 // well-known types.
46 AnyKind
47
48 // BoolKind represents a boolean type.
49 BoolKind
50
51 // BytesKind represents a bytes type.
52 BytesKind
53
54 // DoubleKind represents a double type.
55 DoubleKind
56
57 // DurationKind represents a CEL duration type.
58 DurationKind
59
60 // ErrorKind represents a CEL error type.
61 ErrorKind
62
63 // IntKind represents an integer type.
64 IntKind
65
66 // ListKind represents a list type.
67 ListKind
68
69 // MapKind represents a map type.
70 MapKind
71
72 // NullTypeKind represents a null type.
73 NullTypeKind
74
75 // OpaqueKind represents an abstract type which has no accessible fields.
76 OpaqueKind
77
78 // StringKind represents a string type.
79 StringKind
80
81 // StructKind represents a structured object with typed fields.
82 StructKind
83
84 // TimestampKind represents a a CEL time type.
85 TimestampKind
86
87 // TypeKind represents the CEL type.
88 TypeKind
89
90 // TypeParamKind represents a parameterized type whose type name will be resolved at type-check time, if possible.
91 TypeParamKind
92
93 // UintKind represents a uint type.
94 UintKind
95
96 // UnknownKind represents an unknown value type.
97 UnknownKind
98 )
99
100 var (
101 // AnyType represents the google.protobuf.Any type.
102 AnyType = &Type{
103 kind: AnyKind,
104 runtimeTypeName: "google.protobuf.Any",
105 traitMask: traits.FieldTesterType |
106 traits.IndexerType,
107 }
108 // BoolType represents the bool type.
109 BoolType = &Type{
110 kind: BoolKind,
111 runtimeTypeName: "bool",
112 traitMask: traits.ComparerType |
113 traits.NegatorType,
114 }
115 // BytesType represents the bytes type.
116 BytesType = &Type{
117 kind: BytesKind,
118 runtimeTypeName: "bytes",
119 traitMask: traits.AdderType |
120 traits.ComparerType |
121 traits.SizerType,
122 }
123 // DoubleType represents the double type.
124 DoubleType = &Type{
125 kind: DoubleKind,
126 runtimeTypeName: "double",
127 traitMask: traits.AdderType |
128 traits.ComparerType |
129 traits.DividerType |
130 traits.MultiplierType |
131 traits.NegatorType |
132 traits.SubtractorType,
133 }
134 // DurationType represents the CEL duration type.
135 DurationType = &Type{
136 kind: DurationKind,
137 runtimeTypeName: "google.protobuf.Duration",
138 traitMask: traits.AdderType |
139 traits.ComparerType |
140 traits.NegatorType |
141 traits.ReceiverType |
142 traits.SubtractorType,
143 }
144 // DynType represents a dynamic CEL type whose type will be determined at runtime from context.
145 DynType = &Type{
146 kind: DynKind,
147 runtimeTypeName: "dyn",
148 }
149 // ErrorType represents a CEL error value.
150 ErrorType = &Type{
151 kind: ErrorKind,
152 runtimeTypeName: "error",
153 }
154 // IntType represents the int type.
155 IntType = &Type{
156 kind: IntKind,
157 runtimeTypeName: "int",
158 traitMask: traits.AdderType |
159 traits.ComparerType |
160 traits.DividerType |
161 traits.ModderType |
162 traits.MultiplierType |
163 traits.NegatorType |
164 traits.SubtractorType,
165 }
166 // ListType represents the runtime list type.
167 ListType = NewListType(DynType)
168 // MapType represents the runtime map type.
169 MapType = NewMapType(DynType, DynType)
170 // NullType represents the type of a null value.
171 NullType = &Type{
172 kind: NullTypeKind,
173 runtimeTypeName: "null_type",
174 }
175 // StringType represents the string type.
176 StringType = &Type{
177 kind: StringKind,
178 runtimeTypeName: "string",
179 traitMask: traits.AdderType |
180 traits.ComparerType |
181 traits.MatcherType |
182 traits.ReceiverType |
183 traits.SizerType,
184 }
185 // TimestampType represents the time type.
186 TimestampType = &Type{
187 kind: TimestampKind,
188 runtimeTypeName: "google.protobuf.Timestamp",
189 traitMask: traits.AdderType |
190 traits.ComparerType |
191 traits.ReceiverType |
192 traits.SubtractorType,
193 }
194 // TypeType represents a CEL type
195 TypeType = &Type{
196 kind: TypeKind,
197 runtimeTypeName: "type",
198 }
199 // UintType represents a uint type.
200 UintType = &Type{
201 kind: UintKind,
202 runtimeTypeName: "uint",
203 traitMask: traits.AdderType |
204 traits.ComparerType |
205 traits.DividerType |
206 traits.ModderType |
207 traits.MultiplierType |
208 traits.SubtractorType,
209 }
210 // UnknownType represents an unknown value type.
211 UnknownType = &Type{
212 kind: UnknownKind,
213 runtimeTypeName: "unknown",
214 }
215 )
216
217 var _ ref.Type = &Type{}
218 var _ ref.Val = &Type{}
219
220 // Type holds a reference to a runtime type with an optional type-checked set of type parameters.
221 type Type struct {
222 // kind indicates general category of the type.
223 kind Kind
224
225 // parameters holds the optional type-checked set of type Parameters that are used during static analysis.
226 parameters []*Type
227
228 // runtimeTypeName indicates the runtime type name of the type.
229 runtimeTypeName string
230
231 // isAssignableType function determines whether one type is assignable to this type.
232 // A nil value for the isAssignableType function falls back to equality of kind, runtimeType, and parameters.
233 isAssignableType func(other *Type) bool
234
235 // isAssignableRuntimeType function determines whether the runtime type (with erasure) is assignable to this type.
236 // A nil value for the isAssignableRuntimeType function falls back to the equality of the type or type name.
237 isAssignableRuntimeType func(other ref.Val) bool
238
239 // traitMask is a mask of flags which indicate the capabilities of the type.
240 traitMask int
241 }
242
243 // ConvertToNative implements ref.Val.ConvertToNative.
244 func (t *Type) ConvertToNative(typeDesc reflect.Type) (any, error) {
245 return nil, fmt.Errorf("type conversion not supported for 'type'")
246 }
247
248 // ConvertToType implements ref.Val.ConvertToType.
249 func (t *Type) ConvertToType(typeVal ref.Type) ref.Val {
250 switch typeVal {
251 case TypeType:
252 return TypeType
253 case StringType:
254 return String(t.TypeName())
255 }
256 return NewErr("type conversion error from '%s' to '%s'", TypeType, typeVal)
257 }
258
259 // Equal indicates whether two types have the same runtime type name.
260 //
261 // The name Equal is a bit of a misnomer, but for historical reasons, this is the
262 // runtime behavior. For a more accurate definition see IsType().
263 func (t *Type) Equal(other ref.Val) ref.Val {
264 otherType, ok := other.(ref.Type)
265 return Bool(ok && t.TypeName() == otherType.TypeName())
266 }
267
268 // HasTrait implements the ref.Type interface method.
269 func (t *Type) HasTrait(trait int) bool {
270 return trait&t.traitMask == trait
271 }
272
273 // IsExactType indicates whether the two types are exactly the same. This check also verifies type parameter type names.
274 func (t *Type) IsExactType(other *Type) bool {
275 return t.isTypeInternal(other, true)
276 }
277
278 // IsEquivalentType indicates whether two types are equivalent. This check ignores type parameter type names.
279 func (t *Type) IsEquivalentType(other *Type) bool {
280 return t.isTypeInternal(other, false)
281 }
282
283 // Kind indicates general category of the type.
284 func (t *Type) Kind() Kind {
285 if t == nil {
286 return UnspecifiedKind
287 }
288 return t.kind
289 }
290
291 // isTypeInternal checks whether the two types are equivalent or exactly the same based on the checkTypeParamName flag.
292 func (t *Type) isTypeInternal(other *Type, checkTypeParamName bool) bool {
293 if t == nil {
294 return false
295 }
296 if t == other {
297 return true
298 }
299 if t.Kind() != other.Kind() || len(t.Parameters()) != len(other.Parameters()) {
300 return false
301 }
302 if (checkTypeParamName || t.Kind() != TypeParamKind) && t.TypeName() != other.TypeName() {
303 return false
304 }
305 for i, p := range t.Parameters() {
306 if !p.isTypeInternal(other.Parameters()[i], checkTypeParamName) {
307 return false
308 }
309 }
310 return true
311 }
312
313 // IsAssignableType determines whether the current type is type-check assignable from the input fromType.
314 func (t *Type) IsAssignableType(fromType *Type) bool {
315 if t == nil {
316 return false
317 }
318 if t.isAssignableType != nil {
319 return t.isAssignableType(fromType)
320 }
321 return t.defaultIsAssignableType(fromType)
322 }
323
324 // IsAssignableRuntimeType determines whether the current type is runtime assignable from the input runtimeType.
325 //
326 // At runtime, parameterized types are erased and so a function which type-checks to support a map(string, string)
327 // will have a runtime assignable type of a map.
328 func (t *Type) IsAssignableRuntimeType(val ref.Val) bool {
329 if t == nil {
330 return false
331 }
332 if t.isAssignableRuntimeType != nil {
333 return t.isAssignableRuntimeType(val)
334 }
335 return t.defaultIsAssignableRuntimeType(val)
336 }
337
338 // Parameters returns the list of type parameters if set.
339 //
340 // For ListKind, Parameters()[0] represents the list element type
341 // For MapKind, Parameters()[0] represents the map key type, and Parameters()[1] represents the map
342 // value type.
343 func (t *Type) Parameters() []*Type {
344 if t == nil {
345 return emptyParams
346 }
347 return t.parameters
348 }
349
350 // DeclaredTypeName indicates the fully qualified and parameterized type-check type name.
351 func (t *Type) DeclaredTypeName() string {
352 // if the type itself is neither null, nor dyn, but is assignable to null, then it's a wrapper type.
353 if t.Kind() != NullTypeKind && !t.isDyn() && t.IsAssignableType(NullType) {
354 return fmt.Sprintf("wrapper(%s)", t.TypeName())
355 }
356 return t.TypeName()
357 }
358
359 // Type implements the ref.Val interface method.
360 func (t *Type) Type() ref.Type {
361 return TypeType
362 }
363
364 // Value implements the ref.Val interface method.
365 func (t *Type) Value() any {
366 return t.TypeName()
367 }
368
369 // TypeName returns the type-erased fully qualified runtime type name.
370 //
371 // TypeName implements the ref.Type interface method.
372 func (t *Type) TypeName() string {
373 if t == nil {
374 return ""
375 }
376 return t.runtimeTypeName
377 }
378
379 func (t *Type) format(sb *strings.Builder) {
380 sb.WriteString(t.TypeName())
381 }
382
383 // WithTraits creates a copy of the current Type and sets the trait mask to the traits parameter.
384 //
385 // This method should be used with Opaque types where the type acts like a container, e.g. vector.
386 func (t *Type) WithTraits(traits int) *Type {
387 if t == nil {
388 return nil
389 }
390 return &Type{
391 kind: t.kind,
392 parameters: t.parameters,
393 runtimeTypeName: t.runtimeTypeName,
394 isAssignableType: t.isAssignableType,
395 isAssignableRuntimeType: t.isAssignableRuntimeType,
396 traitMask: traits,
397 }
398 }
399
400 // String returns a human-readable definition of the type name.
401 func (t *Type) String() string {
402 if t.Kind() == TypeParamKind {
403 return fmt.Sprintf("<%s>", t.DeclaredTypeName())
404 }
405 if len(t.Parameters()) == 0 {
406 return t.DeclaredTypeName()
407 }
408 params := make([]string, len(t.Parameters()))
409 for i, p := range t.Parameters() {
410 params[i] = p.String()
411 }
412 return fmt.Sprintf("%s(%s)", t.DeclaredTypeName(), strings.Join(params, ", "))
413 }
414
415 // isDyn indicates whether the type is dynamic in any way.
416 func (t *Type) isDyn() bool {
417 k := t.Kind()
418 return k == DynKind || k == AnyKind || k == TypeParamKind
419 }
420
421 // defaultIsAssignableType provides the standard definition of what it means for one type to be assignable to another
422 // where any of the following may return a true result:
423 // - The from types are the same instance
424 // - The target type is dynamic
425 // - The fromType has the same kind and type name as the target type, and all parameters of the target type
426 //
427 // are IsAssignableType() from the parameters of the fromType.
428 func (t *Type) defaultIsAssignableType(fromType *Type) bool {
429 if t == fromType || t.isDyn() {
430 return true
431 }
432 if t.Kind() != fromType.Kind() ||
433 t.TypeName() != fromType.TypeName() ||
434 len(t.Parameters()) != len(fromType.Parameters()) {
435 return false
436 }
437 for i, tp := range t.Parameters() {
438 fp := fromType.Parameters()[i]
439 if !tp.IsAssignableType(fp) {
440 return false
441 }
442 }
443 return true
444 }
445
446 // defaultIsAssignableRuntimeType inspects the type and in the case of list and map elements, the key and element types
447 // to determine whether a ref.Val is assignable to the declared type for a function signature.
448 func (t *Type) defaultIsAssignableRuntimeType(val ref.Val) bool {
449 valType := val.Type()
450 // If the current type and value type don't agree, then return
451 if !(t.isDyn() || t.TypeName() == valType.TypeName()) {
452 return false
453 }
454 switch t.Kind() {
455 case ListKind:
456 elemType := t.Parameters()[0]
457 l := val.(traits.Lister)
458 if l.Size() == IntZero {
459 return true
460 }
461 it := l.Iterator()
462 elemVal := it.Next()
463 return elemType.IsAssignableRuntimeType(elemVal)
464 case MapKind:
465 keyType := t.Parameters()[0]
466 elemType := t.Parameters()[1]
467 m := val.(traits.Mapper)
468 if m.Size() == IntZero {
469 return true
470 }
471 it := m.Iterator()
472 keyVal := it.Next()
473 elemVal := m.Get(keyVal)
474 return keyType.IsAssignableRuntimeType(keyVal) && elemType.IsAssignableRuntimeType(elemVal)
475 }
476 return true
477 }
478
479 // NewListType creates an instances of a list type value with the provided element type.
480 func NewListType(elemType *Type) *Type {
481 return &Type{
482 kind: ListKind,
483 parameters: []*Type{elemType},
484 runtimeTypeName: "list",
485 traitMask: traits.AdderType |
486 traits.ContainerType |
487 traits.IndexerType |
488 traits.IterableType |
489 traits.SizerType,
490 }
491 }
492
493 // NewMapType creates an instance of a map type value with the provided key and value types.
494 func NewMapType(keyType, valueType *Type) *Type {
495 return &Type{
496 kind: MapKind,
497 parameters: []*Type{keyType, valueType},
498 runtimeTypeName: "map",
499 traitMask: traits.ContainerType |
500 traits.IndexerType |
501 traits.IterableType |
502 traits.SizerType,
503 }
504 }
505
506 // NewNullableType creates an instance of a nullable type with the provided wrapped type.
507 //
508 // Note: only primitive types are supported as wrapped types.
509 func NewNullableType(wrapped *Type) *Type {
510 return &Type{
511 kind: wrapped.Kind(),
512 parameters: wrapped.Parameters(),
513 runtimeTypeName: wrapped.TypeName(),
514 traitMask: wrapped.traitMask,
515 isAssignableType: func(other *Type) bool {
516 return NullType.IsAssignableType(other) || wrapped.IsAssignableType(other)
517 },
518 isAssignableRuntimeType: func(other ref.Val) bool {
519 return NullType.IsAssignableRuntimeType(other) || wrapped.IsAssignableRuntimeType(other)
520 },
521 }
522 }
523
524 // NewOptionalType creates an abstract parameterized type instance corresponding to CEL's notion of optional.
525 func NewOptionalType(param *Type) *Type {
526 return NewOpaqueType("optional_type", param)
527 }
528
529 // NewOpaqueType creates an abstract parameterized type with a given name.
530 func NewOpaqueType(name string, params ...*Type) *Type {
531 return &Type{
532 kind: OpaqueKind,
533 parameters: params,
534 runtimeTypeName: name,
535 }
536 }
537
538 // NewObjectType creates a type reference to an externally defined type, e.g. a protobuf message type.
539 //
540 // An object type is assumed to support field presence testing and field indexing. Additionally, the
541 // type may also indicate additional traits through the use of the optional traits vararg argument.
542 func NewObjectType(typeName string, traits ...int) *Type {
543 // Function sanitizes object types on the fly
544 if wkt, found := checkedWellKnowns[typeName]; found {
545 return wkt
546 }
547 traitMask := 0
548 for _, trait := range traits {
549 traitMask |= trait
550 }
551 return &Type{
552 kind: StructKind,
553 parameters: emptyParams,
554 runtimeTypeName: typeName,
555 traitMask: structTypeTraitMask | traitMask,
556 }
557 }
558
559 // NewObjectTypeValue creates a type reference to an externally defined type.
560 //
561 // Deprecated: use cel.ObjectType(typeName)
562 func NewObjectTypeValue(typeName string) *Type {
563 return NewObjectType(typeName)
564 }
565
566 // NewTypeValue creates an opaque type which has a set of optional type traits as defined in
567 // the common/types/traits package.
568 //
569 // Deprecated: use cel.ObjectType(typeName, traits)
570 func NewTypeValue(typeName string, traits ...int) *Type {
571 traitMask := 0
572 for _, trait := range traits {
573 traitMask |= trait
574 }
575 return &Type{
576 kind: StructKind,
577 parameters: emptyParams,
578 runtimeTypeName: typeName,
579 traitMask: traitMask,
580 }
581 }
582
583 // NewTypeParamType creates a parameterized type instance.
584 func NewTypeParamType(paramName string) *Type {
585 return &Type{
586 kind: TypeParamKind,
587 runtimeTypeName: paramName,
588 }
589 }
590
591 // NewTypeTypeWithParam creates a type with a type parameter.
592 // Used for type-checking purposes, but equivalent to TypeType otherwise.
593 func NewTypeTypeWithParam(param *Type) *Type {
594 return &Type{
595 kind: TypeKind,
596 runtimeTypeName: "type",
597 parameters: []*Type{param},
598 }
599 }
600
601 // TypeToExprType converts a CEL-native type representation to a protobuf CEL Type representation.
602 func TypeToExprType(t *Type) (*exprpb.Type, error) {
603 switch t.Kind() {
604 case AnyKind:
605 return chkdecls.Any, nil
606 case BoolKind:
607 return maybeWrapper(t, chkdecls.Bool), nil
608 case BytesKind:
609 return maybeWrapper(t, chkdecls.Bytes), nil
610 case DoubleKind:
611 return maybeWrapper(t, chkdecls.Double), nil
612 case DurationKind:
613 return chkdecls.Duration, nil
614 case DynKind:
615 return chkdecls.Dyn, nil
616 case ErrorKind:
617 return chkdecls.Error, nil
618 case IntKind:
619 return maybeWrapper(t, chkdecls.Int), nil
620 case ListKind:
621 if len(t.Parameters()) != 1 {
622 return nil, fmt.Errorf("invalid list, got %d parameters, wanted one", len(t.Parameters()))
623 }
624 et, err := TypeToExprType(t.Parameters()[0])
625 if err != nil {
626 return nil, err
627 }
628 return chkdecls.NewListType(et), nil
629 case MapKind:
630 if len(t.Parameters()) != 2 {
631 return nil, fmt.Errorf("invalid map, got %d parameters, wanted two", len(t.Parameters()))
632 }
633 kt, err := TypeToExprType(t.Parameters()[0])
634 if err != nil {
635 return nil, err
636 }
637 vt, err := TypeToExprType(t.Parameters()[1])
638 if err != nil {
639 return nil, err
640 }
641 return chkdecls.NewMapType(kt, vt), nil
642 case NullTypeKind:
643 return chkdecls.Null, nil
644 case OpaqueKind:
645 params := make([]*exprpb.Type, len(t.Parameters()))
646 for i, p := range t.Parameters() {
647 pt, err := TypeToExprType(p)
648 if err != nil {
649 return nil, err
650 }
651 params[i] = pt
652 }
653 return chkdecls.NewAbstractType(t.TypeName(), params...), nil
654 case StringKind:
655 return maybeWrapper(t, chkdecls.String), nil
656 case StructKind:
657 return chkdecls.NewObjectType(t.TypeName()), nil
658 case TimestampKind:
659 return chkdecls.Timestamp, nil
660 case TypeParamKind:
661 return chkdecls.NewTypeParamType(t.TypeName()), nil
662 case TypeKind:
663 if len(t.Parameters()) == 1 {
664 p, err := TypeToExprType(t.Parameters()[0])
665 if err != nil {
666 return nil, err
667 }
668 return chkdecls.NewTypeType(p), nil
669 }
670 return chkdecls.NewTypeType(nil), nil
671 case UintKind:
672 return maybeWrapper(t, chkdecls.Uint), nil
673 }
674 return nil, fmt.Errorf("missing type conversion to proto: %v", t)
675 }
676
677 // ExprTypeToType converts a protobuf CEL type representation to a CEL-native type representation.
678 func ExprTypeToType(t *exprpb.Type) (*Type, error) {
679 return AlphaProtoAsType(t)
680 }
681
682 // AlphaProtoAsType converts a CEL v1alpha1.Type protobuf type to a CEL-native type representation.
683 func AlphaProtoAsType(t *exprpb.Type) (*Type, error) {
684 canonical := &celpb.Type{}
685 if err := convertProto(t, canonical); err != nil {
686 return nil, err
687 }
688 return ProtoAsType(canonical)
689 }
690
691 // ProtoAsType converts a canonical CEL celpb.Type protobuf type to a CEL-native type representation.
692 func ProtoAsType(t *celpb.Type) (*Type, error) {
693 switch t.GetTypeKind().(type) {
694 case *celpb.Type_Dyn:
695 return DynType, nil
696 case *celpb.Type_AbstractType_:
697 paramTypes := make([]*Type, len(t.GetAbstractType().GetParameterTypes()))
698 for i, p := range t.GetAbstractType().GetParameterTypes() {
699 pt, err := ProtoAsType(p)
700 if err != nil {
701 return nil, err
702 }
703 paramTypes[i] = pt
704 }
705 return NewOpaqueType(t.GetAbstractType().GetName(), paramTypes...), nil
706 case *celpb.Type_ListType_:
707 et, err := ProtoAsType(t.GetListType().GetElemType())
708 if err != nil {
709 return nil, err
710 }
711 return NewListType(et), nil
712 case *celpb.Type_MapType_:
713 kt, err := ProtoAsType(t.GetMapType().GetKeyType())
714 if err != nil {
715 return nil, err
716 }
717 vt, err := ProtoAsType(t.GetMapType().GetValueType())
718 if err != nil {
719 return nil, err
720 }
721 return NewMapType(kt, vt), nil
722 case *celpb.Type_MessageType:
723 return NewObjectType(t.GetMessageType()), nil
724 case *celpb.Type_Null:
725 return NullType, nil
726 case *celpb.Type_Primitive:
727 switch t.GetPrimitive() {
728 case celpb.Type_BOOL:
729 return BoolType, nil
730 case celpb.Type_BYTES:
731 return BytesType, nil
732 case celpb.Type_DOUBLE:
733 return DoubleType, nil
734 case celpb.Type_INT64:
735 return IntType, nil
736 case celpb.Type_STRING:
737 return StringType, nil
738 case celpb.Type_UINT64:
739 return UintType, nil
740 default:
741 return nil, fmt.Errorf("unsupported primitive type: %v", t)
742 }
743 case *celpb.Type_TypeParam:
744 return NewTypeParamType(t.GetTypeParam()), nil
745 case *celpb.Type_Type:
746 if t.GetType().GetTypeKind() != nil {
747 p, err := ProtoAsType(t.GetType())
748 if err != nil {
749 return nil, err
750 }
751 return NewTypeTypeWithParam(p), nil
752 }
753 return TypeType, nil
754 case *celpb.Type_WellKnown:
755 switch t.GetWellKnown() {
756 case celpb.Type_ANY:
757 return AnyType, nil
758 case celpb.Type_DURATION:
759 return DurationType, nil
760 case celpb.Type_TIMESTAMP:
761 return TimestampType, nil
762 default:
763 return nil, fmt.Errorf("unsupported well-known type: %v", t)
764 }
765 case *celpb.Type_Wrapper:
766 t, err := ProtoAsType(&celpb.Type{TypeKind: &celpb.Type_Primitive{Primitive: t.GetWrapper()}})
767 if err != nil {
768 return nil, err
769 }
770 return NewNullableType(t), nil
771 case *celpb.Type_Error:
772 return ErrorType, nil
773 default:
774 return nil, fmt.Errorf("unsupported type: %v", t)
775 }
776 }
777
778 // TypeToProto converts from a CEL-native type representation to canonical CEL celpb.Type protobuf type.
779 func TypeToProto(t *Type) (*celpb.Type, error) {
780 exprType, err := TypeToExprType(t)
781 if err != nil {
782 return nil, err
783 }
784 var pbtype celpb.Type
785 if err = convertProto(exprType, &pbtype); err != nil {
786 return nil, err
787 }
788 return &pbtype, nil
789 }
790
791 func maybeWrapper(t *Type, pbType *exprpb.Type) *exprpb.Type {
792 if t.IsAssignableType(NullType) {
793 return chkdecls.NewWrapperType(pbType)
794 }
795 return pbType
796 }
797
798 func maybeForeignType(t ref.Type) *Type {
799 if celType, ok := t.(*Type); ok {
800 return celType
801 }
802 // Inspect the incoming type to determine its traits. The assumption will be that the incoming
803 // type does not have any field values; however, if the trait mask indicates that field testing
804 // and indexing are supported, the foreign type is marked as a struct.
805 traitMask := 0
806 for _, trait := range allTraits {
807 if t.HasTrait(trait) {
808 traitMask |= trait
809 }
810 }
811 // Treat the value like a struct. If it has no fields, this is harmless to denote the type
812 // as such since it basically becomes an opaque type by convention.
813 return NewObjectType(t.TypeName(), traitMask)
814 }
815
816 func convertProto(src, dst proto.Message) error {
817 pb, err := proto.Marshal(src)
818 if err != nil {
819 return err
820 }
821 err = proto.Unmarshal(pb, dst)
822 return err
823 }
824
825 func primitiveType(primitive celpb.Type_PrimitiveType) *celpb.Type {
826 return &celpb.Type{
827 TypeKind: &celpb.Type_Primitive{
828 Primitive: primitive,
829 },
830 }
831 }
832
833 var (
834 checkedWellKnowns = map[string]*Type{
835 // Wrapper types.
836 "google.protobuf.BoolValue": NewNullableType(BoolType),
837 "google.protobuf.BytesValue": NewNullableType(BytesType),
838 "google.protobuf.DoubleValue": NewNullableType(DoubleType),
839 "google.protobuf.FloatValue": NewNullableType(DoubleType),
840 "google.protobuf.Int64Value": NewNullableType(IntType),
841 "google.protobuf.Int32Value": NewNullableType(IntType),
842 "google.protobuf.UInt64Value": NewNullableType(UintType),
843 "google.protobuf.UInt32Value": NewNullableType(UintType),
844 "google.protobuf.StringValue": NewNullableType(StringType),
845 // Well-known types.
846 "google.protobuf.Any": AnyType,
847 "google.protobuf.Duration": DurationType,
848 "google.protobuf.Timestamp": TimestampType,
849 // Json types.
850 "google.protobuf.ListValue": NewListType(DynType),
851 "google.protobuf.NullValue": NullType,
852 "google.protobuf.Struct": NewMapType(StringType, DynType),
853 "google.protobuf.Value": DynType,
854 }
855
856 emptyParams = []*Type{}
857
858 allTraits = []int{
859 traits.AdderType,
860 traits.ComparerType,
861 traits.ContainerType,
862 traits.DividerType,
863 traits.FieldTesterType,
864 traits.IndexerType,
865 traits.IterableType,
866 traits.IteratorType,
867 traits.MatcherType,
868 traits.ModderType,
869 traits.MultiplierType,
870 traits.NegatorType,
871 traits.ReceiverType,
872 traits.SizerType,
873 traits.SubtractorType,
874 }
875
876 structTypeTraitMask = traits.FieldTesterType | traits.IndexerType
877
878 boolType = primitiveType(celpb.Type_BOOL)
879 bytesType = primitiveType(celpb.Type_BYTES)
880 doubleType = primitiveType(celpb.Type_DOUBLE)
881 intType = primitiveType(celpb.Type_INT64)
882 stringType = primitiveType(celpb.Type_STRING)
883 uintType = primitiveType(celpb.Type_UINT64)
884 )