-
-
Notifications
You must be signed in to change notification settings - Fork 494
feat: allow field access on concrete types behind interface values #952
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
snaffi
wants to merge
1
commit into
expr-lang:master
Choose a base branch
from
snaffi:feature/get-embedded-interface-properties
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| package issue951 | ||
|
|
||
| import ( | ||
| "testing" | ||
|
|
||
| "github.com/expr-lang/expr" | ||
| "github.com/expr-lang/expr/internal/testify/require" | ||
| ) | ||
|
|
||
| type Node interface { | ||
| ID() string | ||
| } | ||
|
|
||
| type Base struct { | ||
| Name string | ||
| } | ||
|
|
||
| func (b Base) ID() string { return b.Name } | ||
|
|
||
| type Container struct { | ||
| Base | ||
| Items []*Item | ||
| } | ||
|
|
||
| type Item struct { | ||
| Kind string | ||
| Value string | ||
| } | ||
|
|
||
| type Wrapper struct { | ||
| Node // embedded interface | ||
| } | ||
|
|
||
| type Proxy struct { | ||
| *Wrapper | ||
| } | ||
|
|
||
| type Nodes []Node | ||
|
|
||
| func (ns Nodes) GetByID(id string) Node { | ||
| for _, n := range ns { | ||
| if n.ID() == id { | ||
| return n | ||
| } | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| func TestFieldAccessThroughEmbeddedInterface(t *testing.T) { | ||
| container := &Container{ | ||
| Base: Base{Name: "test"}, | ||
| Items: []*Item{ | ||
| {Kind: "card", Value: "some_value"}, | ||
| }, | ||
| } | ||
| proxy := &Proxy{ | ||
| Wrapper: &Wrapper{ | ||
| Node: container, | ||
| }, | ||
| } | ||
|
|
||
| tests := []struct { | ||
| name string | ||
| expr string | ||
| env any | ||
| expect any | ||
| }{ | ||
| { | ||
| name: "field through GetByID returning interface", | ||
| expr: `data.GetByID("test").Items[0].Value`, | ||
| env: map[string]any{"data": Nodes{proxy}}, | ||
| expect: "some_value", | ||
| }, | ||
| { | ||
| name: "optional chaining with embedded interface", | ||
| expr: `data.GetByID("test")?.Items[0].Value`, | ||
| env: map[string]any{"data": Nodes{proxy}}, | ||
| expect: "some_value", | ||
| }, | ||
| { | ||
| name: "optional chaining nil result", | ||
| expr: `data.GetByID("missing")?.Items`, | ||
| env: map[string]any{"data": Nodes{proxy}}, | ||
| expect: nil, | ||
| }, | ||
| { | ||
| name: "promoted field through interface", | ||
| expr: `data.GetByID("test").Name`, | ||
| env: map[string]any{"data": Nodes{proxy}}, | ||
| expect: "test", | ||
| }, | ||
| { | ||
| name: "method on interface still works", | ||
| expr: `data.GetByID("test").ID()`, | ||
| env: map[string]any{"data": Nodes{proxy}}, | ||
| expect: "test", | ||
| }, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| result, err := expr.Eval(tt.expr, tt.env) | ||
| require.NoError(t, err) | ||
| require.Equal(t, tt.expect, result) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestFieldAccessEmbeddedInterfaceNil(t *testing.T) { | ||
| proxy := &Proxy{ | ||
| Wrapper: &Wrapper{ | ||
| Node: nil, | ||
| }, | ||
| } | ||
|
|
||
| _, err := expr.Eval(`Items[0].Value`, proxy) | ||
| require.Error(t, err) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -79,23 +79,15 @@ func Fetch(from, i any) any { | |
| if cv, ok := fieldCache.Load(key); ok { | ||
| return v.FieldByIndex(cv.([]int)).Interface() | ||
| } | ||
| field, ok := t.FieldByNameFunc(func(name string) bool { | ||
| field, _ := t.FieldByName(name) | ||
| switch field.Tag.Get("expr") { | ||
| case "-": | ||
| return false | ||
| case fieldName: | ||
| return true | ||
| default: | ||
| return name == fieldName | ||
| } | ||
| }) | ||
| if ok && field.IsExported() { | ||
| value := v.FieldByIndex(field.Index) | ||
| if value.IsValid() { | ||
| fieldCache.Store(key, field.Index) | ||
| return value.Interface() | ||
| } | ||
| if value, field, ok := findStructField(v, fieldName); ok { | ||
| fieldCache.Store(key, field.Index) | ||
| return value.Interface() | ||
| } | ||
| // Field isn't found via standard Go promotion. Try to find it | ||
| // by traversing embedded interface values whose concrete types | ||
| // may contain the requested field. | ||
| if result, found := fetchFromEmbeddedInterfaces(v, fieldName); found { | ||
| return result | ||
| } | ||
| } | ||
| panic(fmt.Sprintf("cannot fetch %v from %T", i, from)) | ||
|
|
@@ -143,6 +135,82 @@ func fieldByIndex(v reflect.Value, field *Field) reflect.Value { | |
| return v | ||
| } | ||
|
|
||
| func findStructField(v reflect.Value, fieldName string) (reflect.Value, reflect.StructField, bool) { | ||
| t := v.Type() | ||
| field, ok := t.FieldByNameFunc(func(name string) bool { | ||
| sf, _ := t.FieldByName(name) | ||
| switch sf.Tag.Get("expr") { | ||
| case "-": | ||
| return false | ||
| case fieldName: | ||
| return true | ||
| default: | ||
| return name == fieldName | ||
| } | ||
| }) | ||
| if ok && field.IsExported() { | ||
| value := v.FieldByIndex(field.Index) | ||
| if value.IsValid() { | ||
| return value, field, true | ||
| } | ||
| } | ||
| return reflect.Value{}, reflect.StructField{}, false | ||
| } | ||
|
|
||
| func fetchFromEmbeddedInterfaces(v reflect.Value, fieldName string) (any, bool) { | ||
| t := v.Type() | ||
| for i := 0; i < t.NumField(); i++ { | ||
| f := t.Field(i) | ||
| if !f.Anonymous { | ||
| continue | ||
| } | ||
| fv := v.Field(i) | ||
| fk := f.Type.Kind() | ||
|
|
||
| // Dereference pointers to get to the underlying type. | ||
| for fk == reflect.Ptr { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Lets use our deref package. |
||
| if fv.IsNil() { | ||
| break | ||
| } | ||
| fv = fv.Elem() | ||
| fk = fv.Kind() | ||
| } | ||
|
|
||
| switch fk { | ||
| case reflect.Interface: | ||
| if fv.IsNil() { | ||
| continue | ||
| } | ||
| // Unwrap interface and dereference pointers to reach the | ||
| // concrete struct value. | ||
| concrete := fv.Elem() | ||
| for concrete.Kind() == reflect.Ptr { | ||
| if concrete.IsNil() { | ||
| break | ||
| } | ||
| concrete = concrete.Elem() | ||
| } | ||
| if concrete.Kind() != reflect.Struct { | ||
| continue | ||
| } | ||
| if value, _, ok := findStructField(concrete, fieldName); ok { | ||
| return value.Interface(), true | ||
| } | ||
| // The concrete type itself may have embedded interfaces. | ||
| if result, found := fetchFromEmbeddedInterfaces(concrete, fieldName); found { | ||
| return result, found | ||
| } | ||
|
|
||
| case reflect.Struct: | ||
| // Recurse into embedded structs to find embedded interfaces. | ||
| if result, found := fetchFromEmbeddedInterfaces(fv, fieldName); found { | ||
| return result, found | ||
| } | ||
| } | ||
| } | ||
| return nil, false | ||
| } | ||
|
|
||
| type Method struct { | ||
| Index int | ||
| Name string | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Will be nice to test this function in isolation. A better unit tests for this function, ideally with 100% coverage for this function.