Skip to content

Commit

Permalink
runtime.Fetch: add string type assertion check before trying to check…
Browse files Browse the repository at this point in the history
… if the value is a method (#349)
  • Loading branch information
blotus authored Mar 9, 2023
1 parent 742c438 commit 5613693
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
26 changes: 26 additions & 0 deletions expr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1613,6 +1613,32 @@ func TestIssue271(t *testing.T) {
require.Equal(t, 1.0, output)
}

type Issue346Array []Issue346Type

type Issue346Type struct {
Bar string
}

func (i Issue346Array) Len() int {
return len(i)
}

func TestIssue346(t *testing.T) {
code := `Foo[0].Bar`

env := map[string]interface{}{
"Foo": Issue346Array{
{Bar: "bar"},
},
}
program, err := expr.Compile(code, expr.Env(env))
require.NoError(t, err)

output, err := expr.Run(program, env)
require.NoError(t, err)
require.Equal(t, "bar", output)
}

func TestCompile_allow_to_use_interface_to_get_an_element_from_map(t *testing.T) {
code := `{"value": "ok"}[vars.key]`
env := map[string]interface{}{
Expand Down
8 changes: 5 additions & 3 deletions vm/runtime/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ func Fetch(from, i interface{}) interface{} {

// Methods can be defined on any type.
if v.NumMethod() > 0 {
method := v.MethodByName(i.(string))
if method.IsValid() {
return method.Interface()
if methodName, ok := i.(string); ok {
method := v.MethodByName(methodName)
if method.IsValid() {
return method.Interface()
}
}
}

Expand Down

0 comments on commit 5613693

Please sign in to comment.