diff --git a/compiler.go b/compiler.go index 17f570b..8a3131f 100644 --- a/compiler.go +++ b/compiler.go @@ -349,17 +349,18 @@ func (c *compiler) evalAccessIndex(left, index interface{}, node *ast.IndexExpre case reflect.Array, reflect.Slice: if i, ok := index.(int); ok { + if i < 0 || i >= rv.Len() { + err = fmt.Errorf("array index out of bounds, got index %d, while array size is %d", index, rv.Len()) - if node.Callee != nil { + } else { - returnValue, err = c.evalIndexCallee(rv.Index(i), node) + if node.Callee != nil { + + returnValue, err = c.evalIndexCallee(rv.Index(i), node) - } else { - if i >= 0 && i < rv.Len() { - returnValue = rv.Index(i).Interface() } else { - err = fmt.Errorf("array index out of bounds, got index %d, while array size is %d", index, rv.Len()) + returnValue = rv.Index(i).Interface() } } diff --git a/for_test.go b/for_test.go index 14c5029..6b87c6a 100644 --- a/for_test.go +++ b/for_test.go @@ -221,3 +221,22 @@ func Test_Render_For_Map_Nil_Value(t *testing.T) { r.NoError(err) r.Equal("", strings.TrimSpace(s)) } + +type Category struct { + Products []Product +} +type Product struct { + Name []string +} + +func Test_Render_For_Array_OutofBoundIndex(t *testing.T) { + r := require.New(t) + ctx := NewContext() + product_listing := Category{} + ctx.Set("product_listing", product_listing) + input := `<%= for (i, names) in product_listing.Products[0].Name { %> + <%= splt %> + <% } %>` + _, err := Render(input, ctx) + r.Error(err) +} diff --git a/variables_test.go b/variables_test.go index bda526b..5496dc9 100644 --- a/variables_test.go +++ b/variables_test.go @@ -156,3 +156,20 @@ func Test_Render_Access_Array_OutofBoundsIndex(t *testing.T) { _, err := Render(input, NewContext()) r.Error(err) } + +type Category1 struct { + Products []Product1 +} +type Product1 struct { + Name []string +} + +func Test_Render_Access_CalleeArray_OutofBoundIndex(t *testing.T) { + r := require.New(t) + ctx := NewContext() + product_listing := Category1{} + ctx.Set("product_listing", product_listing) + input := `<% let a = product_listing.Products[0].Name[0] %><%= a %>` + _, err := Render(input, ctx) + r.Error(err) +}