From dce8b2796eceeefd3ee0307013499282c9ff75b8 Mon Sep 17 00:00:00 2001 From: mido Date: Fri, 10 Mar 2023 04:34:02 -0800 Subject: [PATCH] Fix panic when accessing a map with a key type that's not comparable with map index --- compiler.go | 8 ++++++++ hashes_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/compiler.go b/compiler.go index 34a4dd1..bec2b57 100644 --- a/compiler.go +++ b/compiler.go @@ -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 diff --git a/hashes_test.go b/hashes_test.go index 65ce16e..d71e09f 100644 --- a/hashes_test.go +++ b/hashes_test.go @@ -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)