Skip to content

Commit

Permalink
Fix method calls for interfaces
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Mar 20, 2023
1 parent 68aa569 commit 1a1138d
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 3 deletions.
10 changes: 7 additions & 3 deletions checker/checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -393,15 +393,19 @@ func (v *visitor) MemberNode(node *ast.MemberNode) (reflect.Type, info) {
// First, check methods defined on base type itself,
// independent of which type it is. Without dereferencing.
if m, ok := base.MethodByName(name.Value); ok {
node.Method = true
node.MethodIndex = m.Index
node.Name = name.Value
if base.Kind() == reflect.Interface {
// In case of interface type method will not have a receiver,
// and to prevent checker decreasing numbers of in arguments
// return method type as not method (second argument is false).

// Also, we can not use m.Index here, because it will be
// different indexes for different types which implement
// the same interface.
return m.Type, info{}
} else {
node.Method = true
node.MethodIndex = m.Index
node.Name = name.Value
return m.Type, info{method: true}
}
}
Expand Down
42 changes: 42 additions & 0 deletions expr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1811,6 +1811,48 @@ func TestEval_nil_in_maps(t *testing.T) {
})
}

type Bar interface {
Bar() int
}
type Foo interface {
Foo() Bar
}

type FooImpl struct{}

func (f FooImpl) Foo() Bar {
return BarImpl{}
}

type BarImpl struct{}

// Aba is a special method that is not part of the Bar interface,
// but is used to test that the correct method is called. "Aba" name
// is chosen to be before "Bar" in the alphabet.
func (b BarImpl) Aba() bool {
return true
}

func (b BarImpl) Bar() int {
return 42
}

func TestEval_interface_method(t *testing.T) {
require.True(t, BarImpl{}.Aba())
require.True(t, BarImpl{}.Bar() == 42)

env := map[string]interface{}{
"var": FooImpl{},
}
p, err := expr.Compile(`var.Foo().Bar()`, expr.Env(env))

assert.NoError(t, err)

out, err := expr.Run(p, env)
assert.NoError(t, err)
assert.Equal(t, 42, out)
}

// Mock types

type mockEnv struct {
Expand Down

0 comments on commit 1a1138d

Please sign in to comment.