Skip to content

Commit

Permalink
Fix getting default values out of maps
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Nov 7, 2019
1 parent 211ae69 commit 1042ff4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
19 changes: 12 additions & 7 deletions expr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -828,15 +828,20 @@ func TestExpr_fetch_from_func(t *testing.T) {
assert.Contains(t, err.Error(), "cannot fetch Value from func()")
}

func TestExpr_reference_options(t *testing.T) {
options := []expr.Option{expr.Env(map[string]interface{}{})}
func TestExpr_map_default_values(t *testing.T) {
env := map[string]interface{}{
"foo": map[string]string{},
"bar": map[string]*string{},
}

e, err := expr.Compile("'hello world'", options...)
assert.NoError(t, err)
input := `foo['missing'] == '' && bar['missing'] == nil`

program, err := expr.Compile(input, expr.Env(env))
require.NoError(t, err)

output, err := expr.Run(e, "'hello world'")
assert.NoError(t, err)
assert.Equal(t, "hello world", output)
output, err := expr.Run(program, env)
require.NoError(t, err)
require.Equal(t, true, output)
}

//
Expand Down
9 changes: 7 additions & 2 deletions vm/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,13 @@ func fetch(from interface{}, i interface{}) interface{} {

case reflect.Map:
value := v.MapIndex(reflect.ValueOf(i))
if value.IsValid() && value.CanInterface() {
return value.Interface()
if value.IsValid() {
if value.CanInterface() {
return value.Interface()
}
} else {
elem := reflect.TypeOf(from).Elem()
return reflect.Zero(elem).Interface()
}

case reflect.Struct:
Expand Down

0 comments on commit 1042ff4

Please sign in to comment.