From 1042ff41858772449f24baa4781433f3323f5bec Mon Sep 17 00:00:00 2001 From: Anton Medvedev Date: Thu, 7 Nov 2019 11:45:37 +0300 Subject: [PATCH] Fix getting default values out of maps --- expr_test.go | 19 ++++++++++++------- vm/runtime.go | 9 +++++++-- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/expr_test.go b/expr_test.go index 853ffb8a4..378c4ef0c 100644 --- a/expr_test.go +++ b/expr_test.go @@ -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) } // diff --git a/vm/runtime.go b/vm/runtime.go index 59517a548..bbc148054 100644 --- a/vm/runtime.go +++ b/vm/runtime.go @@ -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: