Add missing check for array out of bounds

This commit is contained in:
Stanisław Barzowski 2018-01-16 23:34:02 +01:00 committed by Dave Cunningham
parent 561a986e8e
commit d135effbe4
10 changed files with 52 additions and 1 deletions

View File

@ -392,7 +392,7 @@ func (i *interpreter) evaluate(a ast.Node, tc tailCallStatus) (value, error) {
return nil, err
}
// TODO(https://github.com/google/jsonnet/issues/377): non-integer indexes should be an error
return e.evaluateTailCall(target.elements[int(indexInt.value)], tc)
return target.index(e, int(indexInt.value), tc)
case *valueString:
indexInt, err := e.getNumber(index)

10
testdata/array_out_of_bounds.golden vendored Normal file
View File

@ -0,0 +1,10 @@
RUNTIME ERROR: Index 0 out of bounds, not within [0, 0)
-------------------------------------------------
testdata/array_out_of_bounds:1:1-6 $
[][0]
-------------------------------------------------
During evaluation

1
testdata/array_out_of_bounds.jsonnet vendored Normal file
View File

@ -0,0 +1 @@
[][0]

10
testdata/array_out_of_bounds2.golden vendored Normal file
View File

@ -0,0 +1,10 @@
RUNTIME ERROR: Index 3 out of bounds, not within [0, 3)
-------------------------------------------------
testdata/array_out_of_bounds2:1:1-11 $
[1,2,3][3]
-------------------------------------------------
During evaluation

1
testdata/array_out_of_bounds2.jsonnet vendored Normal file
View File

@ -0,0 +1 @@
[1,2,3][3]

10
testdata/array_out_of_bounds3.golden vendored Normal file
View File

@ -0,0 +1,10 @@
RUNTIME ERROR: Index -1 out of bounds, not within [0, 0)
-------------------------------------------------
testdata/array_out_of_bounds3:1:1-7 $
[][-1]
-------------------------------------------------
During evaluation

1
testdata/array_out_of_bounds3.jsonnet vendored Normal file
View File

@ -0,0 +1 @@
[][-1]

10
testdata/array_out_of_bounds4.golden vendored Normal file
View File

@ -0,0 +1,10 @@
RUNTIME ERROR: Index 42 out of bounds, not within [0, 3)
-------------------------------------------------
testdata/array_out_of_bounds4:1:1-12 $
[1,2,3][42]
-------------------------------------------------
During evaluation

1
testdata/array_out_of_bounds4.jsonnet vendored Normal file
View File

@ -0,0 +1 @@
[1,2,3][42]

View File

@ -200,6 +200,13 @@ type valueArray struct {
elements []potentialValue
}
func (arr *valueArray) index(e *evaluator, index int, tc tailCallStatus) (value, error) {
if 0 <= index && index < arr.length() {
return e.evaluateTailCall(arr.elements[index], tc)
}
return nil, e.Error(fmt.Sprintf("Index %d out of bounds, not within [0, %v)", index, arr.length()))
}
func (arr *valueArray) length() int {
return len(arr.elements)
}