Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix panic when accessing a map with a key type that's not comparable with map index #177

Merged
merged 1 commit into from
Mar 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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