MCPcopy Create free account
hub / github.com/cel-expr/cel-go / ConvertToNative

Method ConvertToNative

ext/native.go:490–533  ·  view source on GitHub ↗

ConvertToNative implements the ref.Val interface method. CEL does not have a notion of pointers, so whether a field is a pointer or value is handled as part of this conversion step.

(typeDesc reflect.Type)

Source from the content-addressed store, hash-verified

488// CEL does not have a notion of pointers, so whether a field is a pointer or value
489// is handled as part of this conversion step.
490func (o *nativeObj) ConvertToNative(typeDesc reflect.Type) (any, error) {
491 if o.refValue.Type() == typeDesc {
492 return o.val, nil
493 }
494 if o.refValue.Kind() == reflect.Pointer && o.refValue.Type().Elem() == typeDesc {
495 return o.refValue.Elem().Interface(), nil
496 }
497 if typeDesc.Kind() == reflect.Pointer && o.refValue.Type() == typeDesc.Elem() {
498 ptr := reflect.New(typeDesc.Elem())
499 ptr.Elem().Set(o.refValue)
500 return ptr.Interface(), nil
501 }
502 switch typeDesc {
503 case jsonValueType:
504 jsonStruct, err := o.ConvertToNative(jsonStructType)
505 if err != nil {
506 return nil, err
507 }
508 return structpb.NewStructValue(jsonStruct.(*structpb.Struct)), nil
509 case jsonStructType:
510 refVal := reflect.Indirect(o.refValue)
511 refType := refVal.Type()
512 fields := make(map[string]*structpb.Value, refVal.NumField())
513 for i := 0; i < refVal.NumField(); i++ {
514 fieldType := refType.Field(i)
515 fieldValue := refVal.Field(i)
516 if !fieldValue.IsValid() || fieldValue.IsZero() {
517 continue
518 }
519 fieldName := toFieldName(o.valType.fieldNameHandler, fieldType)
520 if isSkippedFieldName(fieldName) {
521 continue
522 }
523 fieldCELVal := o.NativeToValue(fieldValue.Interface())
524 fieldJSONVal, err := fieldCELVal.ConvertToNative(jsonValueType)
525 if err != nil {
526 return nil, err
527 }
528 fields[fieldName] = fieldJSONVal.(*structpb.Value)
529 }
530 return &structpb.Struct{Fields: fields}, nil
531 }
532 return nil, fmt.Errorf("type conversion error from '%v' to '%v'", o.Type(), typeDesc)
533}
534
535// ConvertToType implements the ref.Val interface method.
536func (o *nativeObj) ConvertToType(typeVal ref.Type) ref.Val {

Callers

nothing calls this directly

Calls 9

TypeMethod · 0.95
toFieldNameFunction · 0.85
isSkippedFieldNameFunction · 0.85
NewMethod · 0.80
TypeMethod · 0.65
KindMethod · 0.65
SetMethod · 0.65
NativeToValueMethod · 0.65
ConvertToNativeMethod · 0.65

Tested by

no test coverage detected