Skip to content

Commit ac585a2

Browse files
adds EvaluationException when accessing an out-of-bounds array index (#490)
1 parent 7931797 commit ac585a2

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

src/main/java/com/ezylang/evalex/Expression.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,14 @@ private EvaluationValue evaluateArrayIndex(ASTNode startNode) throws EvaluationE
196196
EvaluationValue index = evaluateSubtree(startNode.getParameters().get(1));
197197

198198
if (array.isArrayValue() && index.isNumberValue()) {
199+
if (index.getNumberValue().intValue() < 0
200+
|| index.getNumberValue().intValue() >= array.getArrayValue().size()) {
201+
throw new EvaluationException(
202+
startNode.getToken(),
203+
String.format(
204+
"Index %d out of bounds for array of length %d",
205+
index.getNumberValue().intValue(), array.getArrayValue().size()));
206+
}
199207
return array.getArrayValue().get(index.getNumberValue().intValue());
200208
} else {
201209
throw EvaluationException.ofUnsupportedDataTypeInOperation(startNode.getToken());

src/main/java/com/ezylang/evalex/parser/Tokenizer.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,7 @@ private boolean prefixOperatorAllowed() {
312312
case INFIX_OPERATOR:
313313
case COMMA:
314314
case PREFIX_OPERATOR:
315+
case ARRAY_OPEN:
315316
return true;
316317
default:
317318
return false;

src/test/java/com/ezylang/evalex/ExpressionEvaluatorArrayTest.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,4 +151,26 @@ void testThrowsUnsupportedDataTypeForIndex() {
151151
.isInstanceOf(EvaluationException.class)
152152
.hasMessage("Unsupported data types in operation");
153153
}
154+
155+
@Test
156+
void testArrayIndexOutOfBounds() {
157+
assertThatThrownBy(
158+
() -> {
159+
List<?> array = List.of("Hello");
160+
createExpression("a[1]").with("a", array).evaluate();
161+
})
162+
.isInstanceOf(EvaluationException.class)
163+
.hasMessage("Index 1 out of bounds for array of length 1");
164+
}
165+
166+
@Test
167+
void testArrayNegativeIndex() {
168+
assertThatThrownBy(
169+
() -> {
170+
List<?> array = List.of("Hello");
171+
createExpression("a[-1]").with("a", array).evaluate();
172+
})
173+
.isInstanceOf(EvaluationException.class)
174+
.hasMessage("Index -1 out of bounds for array of length 1");
175+
}
154176
}

0 commit comments

Comments
 (0)