| 1 | // Copyright 2018 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 | "time" |
| 21 | |
| 22 | "google.golang.org/protobuf/proto" |
| 23 | "google.golang.org/protobuf/reflect/protoreflect" |
| 24 | |
| 25 | "github.com/google/cel-go/common/types/pb" |
| 26 | "github.com/google/cel-go/common/types/ref" |
| 27 | "github.com/google/cel-go/common/types/traits" |
| 28 | |
| 29 | exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" |
| 30 | anypb "google.golang.org/protobuf/types/known/anypb" |
| 31 | dpb "google.golang.org/protobuf/types/known/durationpb" |
| 32 | structpb "google.golang.org/protobuf/types/known/structpb" |
| 33 | tpb "google.golang.org/protobuf/types/known/timestamppb" |
| 34 | ) |
| 35 | |
| 36 | // Adapter converts native Go values of varying type and complexity to equivalent CEL values. |
| 37 | type Adapter = ref.TypeAdapter |
| 38 | |
| 39 | // Provider specifies functions for creating new object instances and for resolving |
| 40 | // enum values by name. |
| 41 | type Provider interface { |
| 42 | // EnumValue returns the numeric value of the given enum value name. |
| 43 | EnumValue(enumName string) ref.Val |
| 44 | |
| 45 | // FindIdent takes a qualified identifier name and returns a ref.Val if one exists. |
| 46 | FindIdent(identName string) (ref.Val, bool) |
| 47 | |
| 48 | // FindStructType returns the Type give a qualified type name. |
| 49 | // |
| 50 | // For historical reasons, only struct types are expected to be returned through this |
| 51 | // method, and the type values are expected to be wrapped in a TypeType instance using |
| 52 | // TypeTypeWithParam(<structType>). |
| 53 | // |
| 54 | // Returns false if not found. |
| 55 | FindStructType(structType string) (*Type, bool) |
| 56 | |
| 57 | // FindStructFieldNames returns thet field names associated with the type, if the type |
| 58 | // is found. |
| 59 | FindStructFieldNames(structType string) ([]string, bool) |
| 60 | |
| 61 | // FieldStructFieldType returns the field type for a checked type value. Returns |
| 62 | // false if the field could not be found. |
| 63 | FindStructFieldType(structType, fieldName string) (*FieldType, bool) |
| 64 | |
| 65 | // NewValue creates a new type value from a qualified name and map of field |
| 66 | // name to value. |
| 67 | // |
| 68 | // Note, for each value, the Val.ConvertToNative function will be invoked |
| 69 | // to convert the Val to the field's native type. If an error occurs during |
| 70 | // conversion, the NewValue will be a types.Err. |
| 71 | NewValue(structType string, fields map[string]ref.Val) ref.Val |
| 72 | } |
| 73 | |
| 74 | // FieldType represents a field's type value and whether that field supports presence detection. |
| 75 | type FieldType struct { |
| 76 | // Type of the field as a CEL native type value. |
| 77 | Type *Type |
| 78 | |
| 79 | // IsSet indicates whether the field is set on an input object. |
| 80 | IsSet ref.FieldTester |
| 81 | |
| 82 | // GetFrom retrieves the field value on the input object, if set. |
| 83 | GetFrom ref.FieldGetter |
| 84 | } |
| 85 | |
| 86 | // Registry provides type information for a set of registered types. |
| 87 | type Registry struct { |
| 88 | revTypeMap map[string]*Type |
| 89 | pbdb *pb.Db |
| 90 | } |
| 91 | |
| 92 | // NewRegistry accepts a list of proto message instances and returns a type |
| 93 | // provider which can create new instances of the provided message or any |
| 94 | // message that proto depends upon in its FileDescriptor. |
| 95 | func NewRegistry(types ...proto.Message) (*Registry, error) { |
| 96 | p := &Registry{ |
| 97 | revTypeMap: make(map[string]*Type), |
| 98 | pbdb: pb.NewDb(), |
| 99 | } |
| 100 | err := p.RegisterType( |
| 101 | BoolType, |
| 102 | BytesType, |
| 103 | DoubleType, |
| 104 | DurationType, |
| 105 | IntType, |
| 106 | ListType, |
| 107 | MapType, |
| 108 | NullType, |
| 109 | StringType, |
| 110 | TimestampType, |
| 111 | TypeType, |
| 112 | UintType) |
| 113 | if err != nil { |
| 114 | return nil, err |
| 115 | } |
| 116 | // This block ensures that the well-known protobuf types are registered by default. |
| 117 | for _, fd := range p.pbdb.FileDescriptions() { |
| 118 | err = p.registerAllTypes(fd) |
| 119 | if err != nil { |
| 120 | return nil, err |
| 121 | } |
| 122 | } |
| 123 | for _, msgType := range types { |
| 124 | err = p.RegisterMessage(msgType) |
| 125 | if err != nil { |
| 126 | return nil, err |
| 127 | } |
| 128 | } |
| 129 | return p, nil |
| 130 | } |
| 131 | |
| 132 | // NewEmptyRegistry returns a registry which is completely unconfigured. |
| 133 | func NewEmptyRegistry() *Registry { |
| 134 | return &Registry{ |
| 135 | revTypeMap: make(map[string]*Type), |
| 136 | pbdb: pb.NewDb(), |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | // Copy copies the current state of the registry into its own memory space. |
| 141 | func (p *Registry) Copy() *Registry { |
| 142 | copy := &Registry{ |
| 143 | revTypeMap: make(map[string]*Type), |
| 144 | pbdb: p.pbdb.Copy(), |
| 145 | } |
| 146 | for k, v := range p.revTypeMap { |
| 147 | copy.revTypeMap[k] = v |
| 148 | } |
| 149 | return copy |
| 150 | } |
| 151 | |
| 152 | // EnumValue returns the numeric value of the given enum value name. |
| 153 | func (p *Registry) EnumValue(enumName string) ref.Val { |
| 154 | enumVal, found := p.pbdb.DescribeEnum(enumName) |
| 155 | if !found { |
| 156 | return NewErr("unknown enum name '%s'", enumName) |
| 157 | } |
| 158 | return Int(enumVal.Value()) |
| 159 | } |
| 160 | |
| 161 | // FindFieldType returns the field type for a checked type value. Returns false if |
| 162 | // the field could not be found. |
| 163 | // |
| 164 | // Deprecated: use FindStructFieldType |
| 165 | func (p *Registry) FindFieldType(structType, fieldName string) (*ref.FieldType, bool) { |
| 166 | msgType, found := p.pbdb.DescribeType(structType) |
| 167 | if !found { |
| 168 | return nil, false |
| 169 | } |
| 170 | field, found := msgType.FieldByName(fieldName) |
| 171 | if !found { |
| 172 | return nil, false |
| 173 | } |
| 174 | return &ref.FieldType{ |
| 175 | Type: field.CheckedType(), |
| 176 | IsSet: field.IsSet, |
| 177 | GetFrom: field.GetFrom}, true |
| 178 | } |
| 179 | |
| 180 | // FindStructFieldNames returns the set of field names for the given struct type, |
| 181 | // if the type exists in the registry. |
| 182 | func (p *Registry) FindStructFieldNames(structType string) ([]string, bool) { |
| 183 | msgType, found := p.pbdb.DescribeType(structType) |
| 184 | if !found { |
| 185 | return []string{}, false |
| 186 | } |
| 187 | fieldMap := msgType.FieldMap() |
| 188 | fields := make([]string, len(fieldMap)) |
| 189 | idx := 0 |
| 190 | for f := range fieldMap { |
| 191 | fields[idx] = f |
| 192 | idx++ |
| 193 | } |
| 194 | return fields, true |
| 195 | } |
| 196 | |
| 197 | // FindStructFieldType returns the field type for a checked type value. Returns |
| 198 | // false if the field could not be found. |
| 199 | func (p *Registry) FindStructFieldType(structType, fieldName string) (*FieldType, bool) { |
| 200 | msgType, found := p.pbdb.DescribeType(structType) |
| 201 | if !found { |
| 202 | return nil, false |
| 203 | } |
| 204 | field, found := msgType.FieldByName(fieldName) |
| 205 | if !found { |
| 206 | return nil, false |
| 207 | } |
| 208 | return &FieldType{ |
| 209 | Type: fieldDescToCELType(field), |
| 210 | IsSet: field.IsSet, |
| 211 | GetFrom: field.GetFrom}, true |
| 212 | } |
| 213 | |
| 214 | // FindIdent takes a qualified identifier name and returns a ref.Val if one exists. |
| 215 | func (p *Registry) FindIdent(identName string) (ref.Val, bool) { |
| 216 | if t, found := p.revTypeMap[identName]; found { |
| 217 | return t, true |
| 218 | } |
| 219 | if enumVal, found := p.pbdb.DescribeEnum(identName); found { |
| 220 | return Int(enumVal.Value()), true |
| 221 | } |
| 222 | return nil, false |
| 223 | } |
| 224 | |
| 225 | // FindType looks up the Type given a qualified typeName. Returns false if not found. |
| 226 | // |
| 227 | // Deprecated: use FindStructType |
| 228 | func (p *Registry) FindType(structType string) (*exprpb.Type, bool) { |
| 229 | if _, found := p.pbdb.DescribeType(structType); !found { |
| 230 | return nil, false |
| 231 | } |
| 232 | if structType != "" && structType[0] == '.' { |
| 233 | structType = structType[1:] |
| 234 | } |
| 235 | return &exprpb.Type{ |
| 236 | TypeKind: &exprpb.Type_Type{ |
| 237 | Type: &exprpb.Type{ |
| 238 | TypeKind: &exprpb.Type_MessageType{ |
| 239 | MessageType: structType}}}}, true |
| 240 | } |
| 241 | |
| 242 | // FindStructType returns the Type give a qualified type name. |
| 243 | // |
| 244 | // For historical reasons, only struct types are expected to be returned through this |
| 245 | // method, and the type values are expected to be wrapped in a TypeType instance using |
| 246 | // TypeTypeWithParam(<structType>). |
| 247 | // |
| 248 | // Returns false if not found. |
| 249 | func (p *Registry) FindStructType(structType string) (*Type, bool) { |
| 250 | if _, found := p.pbdb.DescribeType(structType); !found { |
| 251 | return nil, false |
| 252 | } |
| 253 | if structType != "" && structType[0] == '.' { |
| 254 | structType = structType[1:] |
| 255 | } |
| 256 | return NewTypeTypeWithParam(NewObjectType(structType)), true |
| 257 | } |
| 258 | |
| 259 | // NewValue creates a new type value from a qualified name and map of field |
| 260 | // name to value. |
| 261 | // |
| 262 | // Note, for each value, the Val.ConvertToNative function will be invoked |
| 263 | // to convert the Val to the field's native type. If an error occurs during |
| 264 | // conversion, the NewValue will be a types.Err. |
| 265 | func (p *Registry) NewValue(structType string, fields map[string]ref.Val) ref.Val { |
| 266 | td, found := p.pbdb.DescribeType(structType) |
| 267 | if !found { |
| 268 | return NewErr("unknown type '%s'", structType) |
| 269 | } |
| 270 | msg := td.New() |
| 271 | fieldMap := td.FieldMap() |
| 272 | for name, value := range fields { |
| 273 | field, found := fieldMap[name] |
| 274 | if !found { |
| 275 | return NewErr("no such field: %s", name) |
| 276 | } |
| 277 | err := msgSetField(msg, field, value) |
| 278 | if err != nil { |
| 279 | return &Err{error: err} |
| 280 | } |
| 281 | } |
| 282 | return p.NativeToValue(msg.Interface()) |
| 283 | } |
| 284 | |
| 285 | // RegisterDescriptor registers the contents of a protocol buffer `FileDescriptor`. |
| 286 | func (p *Registry) RegisterDescriptor(fileDesc protoreflect.FileDescriptor) error { |
| 287 | fd, err := p.pbdb.RegisterDescriptor(fileDesc) |
| 288 | if err != nil { |
| 289 | return err |
| 290 | } |
| 291 | return p.registerAllTypes(fd) |
| 292 | } |
| 293 | |
| 294 | // RegisterMessage registers a protocol buffer message and its dependencies. |
| 295 | func (p *Registry) RegisterMessage(message proto.Message) error { |
| 296 | fd, err := p.pbdb.RegisterMessage(message) |
| 297 | if err != nil { |
| 298 | return err |
| 299 | } |
| 300 | return p.registerAllTypes(fd) |
| 301 | } |
| 302 | |
| 303 | // RegisterType registers a type value with the provider which ensures the provider is aware of how to |
| 304 | // map the type to an identifier. |
| 305 | // |
| 306 | // If the `ref.Type` value is a `*types.Type` it will be registered directly by its runtime type name. |
| 307 | // If the `ref.Type` value is not a `*types.Type` instance, a `*types.Type` instance which reflects the |
| 308 | // traits present on the input and the runtime type name. By default this foreign type will be treated |
| 309 | // as a types.StructKind. To avoid potential issues where the `ref.Type` values does not match the |
| 310 | // generated `*types.Type` instance, consider always using the `*types.Type` to represent type extensions |
| 311 | // to CEL, even when they're not based on protobuf types. |
| 312 | func (p *Registry) RegisterType(types ...ref.Type) error { |
| 313 | for _, t := range types { |
| 314 | celType := maybeForeignType(t) |
| 315 | existing, found := p.revTypeMap[t.TypeName()] |
| 316 | if !found { |
| 317 | p.revTypeMap[t.TypeName()] = celType |
| 318 | continue |
| 319 | } |
| 320 | if !existing.IsEquivalentType(celType) { |
| 321 | return fmt.Errorf("type registration conflict. found: %v, input: %v", existing, celType) |
| 322 | } |
| 323 | if existing.traitMask != celType.traitMask { |
| 324 | return fmt.Errorf( |
| 325 | "type registered with conflicting traits: %v with traits %v, input: %v", |
| 326 | existing.TypeName(), existing.traitMask, celType.traitMask) |
| 327 | } |
| 328 | } |
| 329 | return nil |
| 330 | } |
| 331 | |
| 332 | // NativeToValue converts various "native" types to ref.Val with this specific implementation |
| 333 | // providing support for custom proto-based types. |
| 334 | // |
| 335 | // This method should be the inverse of ref.Val.ConvertToNative. |
| 336 | func (p *Registry) NativeToValue(value any) ref.Val { |
| 337 | if val, found := nativeToValue(p, value); found { |
| 338 | return val |
| 339 | } |
| 340 | switch v := value.(type) { |
| 341 | case proto.Message: |
| 342 | typeName := string(v.ProtoReflect().Descriptor().FullName()) |
| 343 | td, found := p.pbdb.DescribeType(typeName) |
| 344 | if !found { |
| 345 | return NewErr("unknown type: '%s'", typeName) |
| 346 | } |
| 347 | unwrapped, isUnwrapped, err := td.MaybeUnwrap(v) |
| 348 | if err != nil { |
| 349 | return UnsupportedRefValConversionErr(v) |
| 350 | } |
| 351 | if isUnwrapped { |
| 352 | return p.NativeToValue(unwrapped) |
| 353 | } |
| 354 | typeVal, found := p.FindIdent(typeName) |
| 355 | if !found { |
| 356 | return NewErr("unknown type: '%s'", typeName) |
| 357 | } |
| 358 | return NewObject(p, td, typeVal, v) |
| 359 | case *pb.Map: |
| 360 | return NewProtoMap(p, v) |
| 361 | case protoreflect.List: |
| 362 | return NewProtoList(p, v) |
| 363 | case protoreflect.Message: |
| 364 | return p.NativeToValue(v.Interface()) |
| 365 | case protoreflect.Value: |
| 366 | return p.NativeToValue(v.Interface()) |
| 367 | } |
| 368 | return UnsupportedRefValConversionErr(value) |
| 369 | } |
| 370 | |
| 371 | func (p *Registry) registerAllTypes(fd *pb.FileDescription) error { |
| 372 | for _, typeName := range fd.GetTypeNames() { |
| 373 | // skip well-known type names since they're automatically sanitized |
| 374 | // during NewObjectType() calls. |
| 375 | if _, found := checkedWellKnowns[typeName]; found { |
| 376 | continue |
| 377 | } |
| 378 | err := p.RegisterType(NewObjectTypeValue(typeName)) |
| 379 | if err != nil { |
| 380 | return err |
| 381 | } |
| 382 | } |
| 383 | return nil |
| 384 | } |
| 385 | |
| 386 | func fieldDescToCELType(field *pb.FieldDescription) *Type { |
| 387 | if field.IsMap() { |
| 388 | return NewMapType( |
| 389 | singularFieldDescToCELType(field.KeyType), |
| 390 | singularFieldDescToCELType(field.ValueType)) |
| 391 | } |
| 392 | if field.IsList() { |
| 393 | return NewListType(singularFieldDescToCELType(field)) |
| 394 | } |
| 395 | return singularFieldDescToCELType(field) |
| 396 | } |
| 397 | |
| 398 | func singularFieldDescToCELType(field *pb.FieldDescription) *Type { |
| 399 | if field.IsMessage() { |
| 400 | return NewObjectType(string(field.Descriptor().Message().FullName())) |
| 401 | } |
| 402 | if field.IsEnum() { |
| 403 | return IntType |
| 404 | } |
| 405 | return ProtoCELPrimitives[field.ProtoKind()] |
| 406 | } |
| 407 | |
| 408 | // defaultTypeAdapter converts go native types to CEL values. |
| 409 | type defaultTypeAdapter struct{} |
| 410 | |
| 411 | var ( |
| 412 | // DefaultTypeAdapter adapts canonical CEL types from their equivalent Go values. |
| 413 | DefaultTypeAdapter = &defaultTypeAdapter{} |
| 414 | ) |
| 415 | |
| 416 | // NativeToValue implements the ref.TypeAdapter interface. |
| 417 | func (a *defaultTypeAdapter) NativeToValue(value any) ref.Val { |
| 418 | if val, found := nativeToValue(a, value); found { |
| 419 | return val |
| 420 | } |
| 421 | return UnsupportedRefValConversionErr(value) |
| 422 | } |
| 423 | |
| 424 | // nativeToValue returns the converted (ref.Val, true) of a conversion is found, |
| 425 | // otherwise (nil, false) |
| 426 | func nativeToValue(a Adapter, value any) (ref.Val, bool) { |
| 427 | switch v := value.(type) { |
| 428 | case nil: |
| 429 | return NullValue, true |
| 430 | case *Bool: |
| 431 | if v != nil { |
| 432 | return *v, true |
| 433 | } |
| 434 | case *Bytes: |
| 435 | if v != nil { |
| 436 | return *v, true |
| 437 | } |
| 438 | case *Double: |
| 439 | if v != nil { |
| 440 | return *v, true |
| 441 | } |
| 442 | case *Int: |
| 443 | if v != nil { |
| 444 | return *v, true |
| 445 | } |
| 446 | case *String: |
| 447 | if v != nil { |
| 448 | return *v, true |
| 449 | } |
| 450 | case *Uint: |
| 451 | if v != nil { |
| 452 | return *v, true |
| 453 | } |
| 454 | case bool: |
| 455 | return Bool(v), true |
| 456 | case int: |
| 457 | return Int(v), true |
| 458 | case int32: |
| 459 | return Int(v), true |
| 460 | case int64: |
| 461 | return Int(v), true |
| 462 | case uint: |
| 463 | return Uint(v), true |
| 464 | case uint32: |
| 465 | return Uint(v), true |
| 466 | case uint64: |
| 467 | return Uint(v), true |
| 468 | case float32: |
| 469 | return Double(v), true |
| 470 | case float64: |
| 471 | return Double(v), true |
| 472 | case string: |
| 473 | return String(v), true |
| 474 | case *dpb.Duration: |
| 475 | return Duration{Duration: v.AsDuration()}, true |
| 476 | case time.Duration: |
| 477 | return Duration{Duration: v}, true |
| 478 | case *tpb.Timestamp: |
| 479 | return Timestamp{Time: v.AsTime()}, true |
| 480 | case time.Time: |
| 481 | return Timestamp{Time: v}, true |
| 482 | case *bool: |
| 483 | if v != nil { |
| 484 | return Bool(*v), true |
| 485 | } |
| 486 | case *float32: |
| 487 | if v != nil { |
| 488 | return Double(*v), true |
| 489 | } |
| 490 | case *float64: |
| 491 | if v != nil { |
| 492 | return Double(*v), true |
| 493 | } |
| 494 | case *int: |
| 495 | if v != nil { |
| 496 | return Int(*v), true |
| 497 | } |
| 498 | case *int32: |
| 499 | if v != nil { |
| 500 | return Int(*v), true |
| 501 | } |
| 502 | case *int64: |
| 503 | if v != nil { |
| 504 | return Int(*v), true |
| 505 | } |
| 506 | case *string: |
| 507 | if v != nil { |
| 508 | return String(*v), true |
| 509 | } |
| 510 | case *uint: |
| 511 | if v != nil { |
| 512 | return Uint(*v), true |
| 513 | } |
| 514 | case *uint32: |
| 515 | if v != nil { |
| 516 | return Uint(*v), true |
| 517 | } |
| 518 | case *uint64: |
| 519 | if v != nil { |
| 520 | return Uint(*v), true |
| 521 | } |
| 522 | case []byte: |
| 523 | return Bytes(v), true |
| 524 | // specializations for common lists types. |
| 525 | case []string: |
| 526 | return NewStringList(a, v), true |
| 527 | case []ref.Val: |
| 528 | return NewRefValList(a, v), true |
| 529 | // specializations for common map types. |
| 530 | case map[string]string: |
| 531 | return NewStringStringMap(a, v), true |
| 532 | case map[string]any: |
| 533 | return NewStringInterfaceMap(a, v), true |
| 534 | case map[ref.Val]ref.Val: |
| 535 | return NewRefValMap(a, v), true |
| 536 | // additional specializations may be added upon request / need. |
| 537 | case *anypb.Any: |
| 538 | if v == nil { |
| 539 | return UnsupportedRefValConversionErr(v), true |
| 540 | } |
| 541 | unpackedAny, err := v.UnmarshalNew() |
| 542 | if err != nil { |
| 543 | return NewErr("anypb.UnmarshalNew() failed for type %q: %v", v.GetTypeUrl(), err), true |
| 544 | } |
| 545 | return a.NativeToValue(unpackedAny), true |
| 546 | case *structpb.NullValue, structpb.NullValue: |
| 547 | return NullValue, true |
| 548 | case *structpb.ListValue: |
| 549 | return NewJSONList(a, v), true |
| 550 | case *structpb.Struct: |
| 551 | return NewJSONStruct(a, v), true |
| 552 | case ref.Val: |
| 553 | return v, true |
| 554 | case protoreflect.EnumNumber: |
| 555 | return Int(v), true |
| 556 | case proto.Message: |
| 557 | if v == nil { |
| 558 | return UnsupportedRefValConversionErr(v), true |
| 559 | } |
| 560 | typeName := string(v.ProtoReflect().Descriptor().FullName()) |
| 561 | td, found := pb.DefaultDb.DescribeType(typeName) |
| 562 | if !found { |
| 563 | return nil, false |
| 564 | } |
| 565 | val, unwrapped, err := td.MaybeUnwrap(v) |
| 566 | if err != nil { |
| 567 | return UnsupportedRefValConversionErr(v), true |
| 568 | } |
| 569 | if !unwrapped { |
| 570 | return nil, false |
| 571 | } |
| 572 | return a.NativeToValue(val), true |
| 573 | // Note: dynamicpb.Message implements the proto.Message _and_ protoreflect.Message interfaces |
| 574 | // which means that this case must appear after handling a proto.Message type. |
| 575 | case protoreflect.Message: |
| 576 | return a.NativeToValue(v.Interface()), true |
| 577 | default: |
| 578 | refValue := reflect.ValueOf(v) |
| 579 | if refValue.Kind() == reflect.Ptr { |
| 580 | if refValue.IsNil() { |
| 581 | return UnsupportedRefValConversionErr(v), true |
| 582 | } |
| 583 | refValue = refValue.Elem() |
| 584 | } |
| 585 | refKind := refValue.Kind() |
| 586 | switch refKind { |
| 587 | case reflect.Array, reflect.Slice: |
| 588 | if refValue.Type().Elem() == reflect.TypeOf(byte(0)) { |
| 589 | if refValue.CanAddr() { |
| 590 | return Bytes(refValue.Bytes()), true |
| 591 | } |
| 592 | tmp := reflect.New(refValue.Type()) |
| 593 | tmp.Elem().Set(refValue) |
| 594 | return Bytes(tmp.Elem().Bytes()), true |
| 595 | } |
| 596 | return NewDynamicList(a, v), true |
| 597 | case reflect.Map: |
| 598 | return NewDynamicMap(a, v), true |
| 599 | // type aliases of primitive types cannot be asserted as that type, but rather need |
| 600 | // to be downcast to int32 before being converted to a CEL representation. |
| 601 | case reflect.Bool: |
| 602 | boolTupe := reflect.TypeOf(false) |
| 603 | return Bool(refValue.Convert(boolTupe).Interface().(bool)), true |
| 604 | case reflect.Int: |
| 605 | intType := reflect.TypeOf(int(0)) |
| 606 | return Int(refValue.Convert(intType).Interface().(int)), true |
| 607 | case reflect.Int8: |
| 608 | intType := reflect.TypeOf(int8(0)) |
| 609 | return Int(refValue.Convert(intType).Interface().(int8)), true |
| 610 | case reflect.Int16: |
| 611 | intType := reflect.TypeOf(int16(0)) |
| 612 | return Int(refValue.Convert(intType).Interface().(int16)), true |
| 613 | case reflect.Int32: |
| 614 | intType := reflect.TypeOf(int32(0)) |
| 615 | return Int(refValue.Convert(intType).Interface().(int32)), true |
| 616 | case reflect.Int64: |
| 617 | intType := reflect.TypeOf(int64(0)) |
| 618 | return Int(refValue.Convert(intType).Interface().(int64)), true |
| 619 | case reflect.Uint: |
| 620 | uintType := reflect.TypeOf(uint(0)) |
| 621 | return Uint(refValue.Convert(uintType).Interface().(uint)), true |
| 622 | case reflect.Uint8: |
| 623 | uintType := reflect.TypeOf(uint8(0)) |
| 624 | return Uint(refValue.Convert(uintType).Interface().(uint8)), true |
| 625 | case reflect.Uint16: |
| 626 | uintType := reflect.TypeOf(uint16(0)) |
| 627 | return Uint(refValue.Convert(uintType).Interface().(uint16)), true |
| 628 | case reflect.Uint32: |
| 629 | uintType := reflect.TypeOf(uint32(0)) |
| 630 | return Uint(refValue.Convert(uintType).Interface().(uint32)), true |
| 631 | case reflect.Uint64: |
| 632 | uintType := reflect.TypeOf(uint64(0)) |
| 633 | return Uint(refValue.Convert(uintType).Interface().(uint64)), true |
| 634 | case reflect.Float32: |
| 635 | doubleType := reflect.TypeOf(float32(0)) |
| 636 | return Double(refValue.Convert(doubleType).Interface().(float32)), true |
| 637 | case reflect.Float64: |
| 638 | doubleType := reflect.TypeOf(float64(0)) |
| 639 | return Double(refValue.Convert(doubleType).Interface().(float64)), true |
| 640 | case reflect.String: |
| 641 | stringType := reflect.TypeOf("") |
| 642 | return String(refValue.Convert(stringType).Interface().(string)), true |
| 643 | } |
| 644 | } |
| 645 | return nil, false |
| 646 | } |
| 647 | |
| 648 | func msgSetField(target protoreflect.Message, field *pb.FieldDescription, val ref.Val) error { |
| 649 | if field.IsList() { |
| 650 | lv := target.NewField(field.Descriptor()) |
| 651 | list, ok := val.(traits.Lister) |
| 652 | if !ok { |
| 653 | return unsupportedTypeConversionError(field, val) |
| 654 | } |
| 655 | err := msgSetListField(lv.List(), field, list) |
| 656 | if err != nil { |
| 657 | return err |
| 658 | } |
| 659 | target.Set(field.Descriptor(), lv) |
| 660 | return nil |
| 661 | } |
| 662 | if field.IsMap() { |
| 663 | mv := target.NewField(field.Descriptor()) |
| 664 | mp, ok := val.(traits.Mapper) |
| 665 | if !ok { |
| 666 | return unsupportedTypeConversionError(field, val) |
| 667 | } |
| 668 | err := msgSetMapField(mv.Map(), field, mp) |
| 669 | if err != nil { |
| 670 | return err |
| 671 | } |
| 672 | target.Set(field.Descriptor(), mv) |
| 673 | return nil |
| 674 | } |
| 675 | v, err := val.ConvertToNative(field.ReflectType()) |
| 676 | if err != nil { |
| 677 | return fieldTypeConversionError(field, err) |
| 678 | } |
| 679 | if v == nil { |
| 680 | return nil |
| 681 | } |
| 682 | switch pv := v.(type) { |
| 683 | case proto.Message: |
| 684 | v = pv.ProtoReflect() |
| 685 | } |
| 686 | target.Set(field.Descriptor(), protoreflect.ValueOf(v)) |
| 687 | return nil |
| 688 | } |
| 689 | |
| 690 | func msgSetListField(target protoreflect.List, listField *pb.FieldDescription, listVal traits.Lister) error { |
| 691 | elemReflectType := listField.ReflectType().Elem() |
| 692 | for i := Int(0); i < listVal.Size().(Int); i++ { |
| 693 | elem := listVal.Get(i) |
| 694 | elemVal, err := elem.ConvertToNative(elemReflectType) |
| 695 | if err != nil { |
| 696 | return fieldTypeConversionError(listField, err) |
| 697 | } |
| 698 | if elemVal == nil { |
| 699 | continue |
| 700 | } |
| 701 | switch ev := elemVal.(type) { |
| 702 | case proto.Message: |
| 703 | elemVal = ev.ProtoReflect() |
| 704 | } |
| 705 | target.Append(protoreflect.ValueOf(elemVal)) |
| 706 | } |
| 707 | return nil |
| 708 | } |
| 709 | |
| 710 | func msgSetMapField(target protoreflect.Map, mapField *pb.FieldDescription, mapVal traits.Mapper) error { |
| 711 | targetKeyType := mapField.KeyType.ReflectType() |
| 712 | targetValType := mapField.ValueType.ReflectType() |
| 713 | it := mapVal.Iterator() |
| 714 | for it.HasNext() == True { |
| 715 | key := it.Next() |
| 716 | val := mapVal.Get(key) |
| 717 | k, err := key.ConvertToNative(targetKeyType) |
| 718 | if err != nil { |
| 719 | return fieldTypeConversionError(mapField, err) |
| 720 | } |
| 721 | v, err := val.ConvertToNative(targetValType) |
| 722 | if err != nil { |
| 723 | return fieldTypeConversionError(mapField, err) |
| 724 | } |
| 725 | if v == nil { |
| 726 | continue |
| 727 | } |
| 728 | switch pv := v.(type) { |
| 729 | case proto.Message: |
| 730 | v = pv.ProtoReflect() |
| 731 | } |
| 732 | target.Set(protoreflect.ValueOf(k).MapKey(), protoreflect.ValueOf(v)) |
| 733 | } |
| 734 | return nil |
| 735 | } |
| 736 | |
| 737 | func unsupportedTypeConversionError(field *pb.FieldDescription, val ref.Val) error { |
| 738 | msgName := field.Descriptor().ContainingMessage().FullName() |
| 739 | return fmt.Errorf("unsupported field type for %v.%v: %v", msgName, field.Name(), val.Type()) |
| 740 | } |
| 741 | |
| 742 | func fieldTypeConversionError(field *pb.FieldDescription, err error) error { |
| 743 | msgName := field.Descriptor().ContainingMessage().FullName() |
| 744 | return fmt.Errorf("field type conversion error for %v.%v value type: %v", msgName, field.Name(), err) |
| 745 | } |
| 746 | |
| 747 | var ( |
| 748 | // ProtoCELPrimitives provides a map from the protoreflect Kind to the equivalent CEL type. |
| 749 | ProtoCELPrimitives = map[protoreflect.Kind]*Type{ |
| 750 | protoreflect.BoolKind: BoolType, |
| 751 | protoreflect.BytesKind: BytesType, |
| 752 | protoreflect.DoubleKind: DoubleType, |
| 753 | protoreflect.FloatKind: DoubleType, |
| 754 | protoreflect.Int32Kind: IntType, |
| 755 | protoreflect.Int64Kind: IntType, |
| 756 | protoreflect.Sint32Kind: IntType, |
| 757 | protoreflect.Sint64Kind: IntType, |
| 758 | protoreflect.Uint32Kind: UintType, |
| 759 | protoreflect.Uint64Kind: UintType, |
| 760 | protoreflect.Fixed32Kind: UintType, |
| 761 | protoreflect.Fixed64Kind: UintType, |
| 762 | protoreflect.Sfixed32Kind: IntType, |
| 763 | protoreflect.Sfixed64Kind: IntType, |
| 764 | protoreflect.StringKind: StringType, |
| 765 | } |
| 766 | ) |