From 6cf0edb662c172f835d09cf93f7e2977bda52a6b Mon Sep 17 00:00:00 2001 From: Anton Medvedev Date: Sun, 12 May 2024 11:55:15 +0200 Subject: [PATCH] Add better error messages for index out of bounds errors --- expr_test.go | 10 +++++++++- vm/runtime/runtime.go | 6 +++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/expr_test.go b/expr_test.go index e16d987a..234b9be6 100644 --- a/expr_test.go +++ b/expr_test.go @@ -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 @@ -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 { diff --git a/vm/runtime/runtime.go b/vm/runtime/runtime.go index 7da1320d..cd48a280 100644 --- a/vm/runtime/runtime.go +++ b/vm/runtime/runtime.go @@ -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() {