Skip to content

Commit

Permalink
Add better error messages for index out of bounds errors
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed May 12, 2024
1 parent 45c1ae7 commit 6cf0edb
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
10 changes: 9 additions & 1 deletion expr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1329,7 +1329,9 @@ func TestExpr(t *testing.T) {
}

func TestExpr_error(t *testing.T) {
env := mock.Env{}
env := mock.Env{
ArrayOfAny: []any{1, "2", 3, true},
}

tests := []struct {
code string
Expand All @@ -1341,6 +1343,12 @@ func TestExpr_error(t *testing.T) {
| filter(1..9, # > 9)[0]
| ...................^`,
},
{
`ArrayOfAny[-7]`,
`index out of range: -3 (array length is 4) (1:11)
| ArrayOfAny[-7]
| ..........^`,
},
}

for _, tt := range tests {
Expand Down
6 changes: 5 additions & 1 deletion vm/runtime/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,12 @@ func Fetch(from, i any) any {
switch v.Kind() {
case reflect.Array, reflect.Slice, reflect.String:
index := ToInt(i)
l := v.Len()
if index < 0 {
index = v.Len() + index
index = l + index
}
if index < 0 || index >= l {
panic(fmt.Sprintf("index out of range: %v (array length is %v)", index, l))
}
value := v.Index(index)
if value.IsValid() {
Expand Down

0 comments on commit 6cf0edb

Please sign in to comment.