Skip to content

Commit

Permalink
Fix deref interface in Fetch
Browse files Browse the repository at this point in the history
We were only de-referencing pointers, but we can have pointer of
interface or interface obfuscating pointers...
So before trying to fetch anything, just deference fully the
variable.
  • Loading branch information
a-peyrard committed Nov 14, 2023
1 parent af628d2 commit 1678baf
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
15 changes: 15 additions & 0 deletions expr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1204,6 +1204,21 @@ func TestExpr_fetch_from_func(t *testing.T) {
assert.Contains(t, err.Error(), "cannot fetch Value from func()")
}

func TestExpr_fetch_from_interface(t *testing.T) {
type FooBar struct {
Value string
}
foobar := &FooBar{"waldo"}
var foobarAny any = foobar
var foobarPtrAny any = &foobarAny

res, err := expr.Eval("foo.Value", map[string]any{
"foo": foobarPtrAny,
})
assert.NoError(t, err)
assert.Equal(t, "waldo", res)
}

func TestExpr_map_default_values(t *testing.T) {
env := map[string]any{
"foo": map[string]string{},
Expand Down
14 changes: 10 additions & 4 deletions vm/runtime/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ import (
"reflect"
)

func deref(kind reflect.Kind, value reflect.Value) (reflect.Kind, reflect.Value) {
for kind == reflect.Ptr || kind == reflect.Interface {
value = value.Elem()
kind = value.Kind()
}
return kind, value
}

func Fetch(from, i any) any {
v := reflect.ValueOf(from)
kind := v.Kind()
Expand All @@ -28,10 +36,8 @@ func Fetch(from, i any) any {
// Structs, maps, and slices can be access through a pointer or through
// a value, when they are accessed through a pointer we don't want to
// copy them to a value.
if kind == reflect.Ptr {
v = reflect.Indirect(v)
kind = v.Kind()
}
// De-reference everything if necessary (interface and pointers)
kind, v = deref(kind, v)

// TODO: We can create separate opcodes for each of the cases below to make
// the little bit faster.
Expand Down

0 comments on commit 1678baf

Please sign in to comment.