Skip to content

Commit

Permalink
Fix checker: allow to use any as key in maps
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Jan 20, 2023
1 parent 6382f82 commit 5366e57
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
2 changes: 1 addition & 1 deletion checker/checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ func (v *visitor) MemberNode(node *ast.MemberNode) (reflect.Type, info) {
return anyType, info{}

case reflect.Map:
if !prop.AssignableTo(base.Key()) {
if !prop.AssignableTo(base.Key()) && !isAny(prop) {
return v.error(node.Property, "cannot use %v to get an element from %v", prop, base)
}
t, c := deref(base.Elem())
Expand Down
31 changes: 31 additions & 0 deletions expr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1599,6 +1599,37 @@ func TestIssue271(t *testing.T) {
require.Equal(t, 1.0, 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{}{
"vars": map[string]interface{}{
"key": "value",
},
}

program, err := expr.Compile(code, expr.Env(env))
assert.NoError(t, err)

out, err := expr.Run(program, env)
assert.NoError(t, err)
assert.Equal(t, "ok", out)

t.Run("with allow undefined variables", func(t *testing.T) {
code := `{'key': 'value'}[Key]`
env := mockMapStringStringEnv{}
options := []expr.Option{
expr.AllowUndefinedVariables(),
}

program, err := expr.Compile(code, options...)
assert.NoError(t, err)

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

// Mock types
type mockEnv struct {
Any interface{}
Expand Down

0 comments on commit 5366e57

Please sign in to comment.