google / cel-go

Fast, portable, non-Turing complete expression evaluation with gradual typing (Go)
https://cel.dev
Apache License 2.0
2.27k stars 221 forks source link

Allow custom field name resolving for native types #942

Closed quantumsheep closed 5 months ago

quantumsheep commented 5 months ago

My use-case:

type CustomNativeType struct {
    reflect.Type
}

func (t *CustomNativeType) FieldByName(name string) (reflect.StructField, bool) {
    name = strcase.ToPascal(name)
    return t.Type.FieldByName(name)
}

type Foo struct {
    MyField string
}

func main() {
    fooType := &CustomNativeType{Type: reflect.TypeOf(Foo{})}

    env, err := cel.NewEnv(
        ext.NativeTypes(fooType),
        cel.Variable("foo", cel.ObjectType("package.Foo")),
    )
    if err != nil {
        panic(err)
    }

    // Evaluate "foo.my_field"
}
TristonianJones commented 5 months ago

@quantumsheep would you mind helping me understand how this change accomplishes your goal. I think the idea is to proxy to another object which implements an interface similar to what golang reflection does, but I'm not sure I understand how this PR accomplishes that.