Skip to content

Commit

Permalink
panic with a dedicated error when an array access index is out-of-bounds
Browse files Browse the repository at this point in the history
  • Loading branch information
turbolent committed Oct 6, 2020
1 parent af4a003 commit f210c78
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 1 deletion.
16 changes: 16 additions & 0 deletions runtime/interpreter/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -292,3 +292,19 @@ func (e *CyclicLinkError) Error() string {
paths,
)
}

// ArrayIndexOutOfBoundsError

type ArrayIndexOutOfBoundsError struct {
Index int
MaxIndex int
LocationRange
}

func (e ArrayIndexOutOfBoundsError) Error() string {
return fmt.Sprintf(
"array index out of bounds: got %d, expected max %d",
e.Index,
e.MaxIndex,
)
}
13 changes: 12 additions & 1 deletion runtime/interpreter/value.go
Original file line number Diff line number Diff line change
Expand Up @@ -528,8 +528,19 @@ func (v *ArrayValue) Concat(other ConcatenatableValue) Value {
return NewArrayValueUnownedNonCopying(concatenated...)
}

func (v *ArrayValue) Get(_ *Interpreter, _ LocationRange, key Value) Value {
func (v *ArrayValue) Get(_ *Interpreter, locationRange LocationRange, key Value) Value {
integerKey := key.(NumberValue).ToInt()
count := v.Count()

// Check bounds
if integerKey < 0 || integerKey >= count {
panic(ArrayIndexOutOfBoundsError{
Index: integerKey,
MaxIndex: count - 1,
LocationRange: locationRange,
})
}

return v.Values[integerKey]
}

Expand Down
29 changes: 29 additions & 0 deletions runtime/tests/interpreter/interpreter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,35 @@ func TestInterpretArrayIndexing(t *testing.T) {
)
}

func TestInterpretInvalidArrayIndexing(t *testing.T) {

t.Parallel()

inter := parseCheckAndInterpret(t, `
fun test(): Int {
let z = [0, 3]
return z[2]
}
`)

_, err := inter.Invoke("test")

require.Equal(t,
interpreter.ArrayIndexOutOfBoundsError{
Index: 2,
MaxIndex: 1,
LocationRange: interpreter.LocationRange{
Location: TestLocation,
Range: ast.Range{
StartPos: ast.Position{Offset: 71, Line: 4, Column: 19},
EndPos: ast.Position{Offset: 73, Line: 4, Column: 21},
},
},
},
err,
)
}

func TestInterpretArrayIndexingAssignment(t *testing.T) {

t.Parallel()
Expand Down

0 comments on commit f210c78

Please sign in to comment.