Skip to content

Commit

Permalink
Merge pull request #177 from Mido-sys/fix_invalid_key_index
Browse files Browse the repository at this point in the history
Fix panic when accessing a map with a key type that's not comparable with map index
  • Loading branch information
paganotoni authored Mar 10, 2023
2 parents a2fcc6c + dce8b27 commit 082e553
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
8 changes: 8 additions & 0 deletions compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,14 @@ func (c *compiler) evalAccessIndex(left, index interface{}, node *ast.IndexExpre
rv := reflect.ValueOf(left)
switch rv.Kind() {
case reflect.Map:
mapKeyType := reflect.TypeOf(left).Key().Kind()
keyType := reflect.TypeOf(index).Kind()
if mapKeyType != reflect.Interface &&
keyType != mapKeyType {
err = fmt.Errorf("cannot use %v (%s constant) as %s value in map index", index, keyType.String(), mapKeyType.String())
return nil, err
}

val := rv.MapIndex(reflect.ValueOf(index))
if !val.IsValid() {
return nil, nil
Expand Down
27 changes: 27 additions & 0 deletions hashes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,33 @@ import (
"github.com/stretchr/testify/require"
)

func Test_Render_Hash_Key_Interface(t *testing.T) {
r := require.New(t)

input := `<%= m["first"]%>`
s, err := Render(input, NewContextWith(map[string]interface{}{

"m": map[interface{}]bool{"first": true},
}))
r.NoError(err)
r.Equal("true", s)
}

func Test_Render_Hash_Key_Int_With_String_Index(t *testing.T) {
r := require.New(t)

input := `<%= m["first"]%>`
_, err := Render(input, NewContextWith(map[string]interface{}{

"m": map[int]bool{0: true},
}))

errStr := "line 1: cannot use first (string constant) as int value in map index"
r.Error(err)
r.Equal(errStr, err.Error())

}

func Test_Render_Hash_Array_Index(t *testing.T) {
r := require.New(t)

Expand Down

0 comments on commit 082e553

Please sign in to comment.