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 index out of range in a struct #185

Merged
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
3 changes: 2 additions & 1 deletion compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,9 +340,10 @@ 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() {
if rv.Len()-1 < i {
err = fmt.Errorf("array index out of bounds, got index %d, while array size is %d", index, rv.Len())
} else {

if node.Callee != nil {
returnValue, err = c.evalIndexCallee(rv.Index(i), node)
} else {
Expand Down
31 changes: 31 additions & 0 deletions struct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -556,3 +556,34 @@ func Test_Render_Function_on_Invalid_Function_Struct(t *testing.T) {
_, err := plush.Render(input, ctx)
r.Error(err)
}

func Test_Render_Struct_Nested_Slice_Access_Out_Of_Range(t *testing.T) {
r := require.New(t)
type d struct {
Final string
}
type c struct {
He []d
}
type b struct {
A []c
}
type mylist struct {
Name []b
}

input := `<%= myarray[0].Name[0].A[1].He[2].Final %>`

gg := make([]mylist, 3)

var bc b

gg[0].Name = []b{bc}

ctx := plush.NewContext()
ctx.Set("myarray", gg)
res, err := plush.Render(input, ctx)
r.Error(err)
r.Empty(res)
r.Error(err, "line 1: array index out of bounds, got index 1, while array size is 0")
}
Loading