Skip to content

Commit

Permalink
adds EvaluationException when accessing an out-of-bounds array index
Browse files Browse the repository at this point in the history
  • Loading branch information
uklimaschewski committed Jul 7, 2024
1 parent 7931797 commit c0e8a0f
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/main/java/com/ezylang/evalex/Expression.java
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,14 @@ private EvaluationValue evaluateArrayIndex(ASTNode startNode) throws EvaluationE
EvaluationValue index = evaluateSubtree(startNode.getParameters().get(1));

if (array.isArrayValue() && index.isNumberValue()) {
if (index.getNumberValue().intValue() < 0
|| index.getNumberValue().intValue() >= array.getArrayValue().size()) {
throw new EvaluationException(
startNode.getToken(),
String.format(
"Index %d out of bounds for array of length %d",
index.getNumberValue().intValue(), array.getArrayValue().size()));
}
return array.getArrayValue().get(index.getNumberValue().intValue());
} else {
throw EvaluationException.ofUnsupportedDataTypeInOperation(startNode.getToken());
Expand Down
1 change: 1 addition & 0 deletions src/main/java/com/ezylang/evalex/parser/Tokenizer.java
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,7 @@ private boolean prefixOperatorAllowed() {
case INFIX_OPERATOR:
case COMMA:
case PREFIX_OPERATOR:
case ARRAY_OPEN:
return true;
default:
return false;
Expand Down
22 changes: 22 additions & 0 deletions src/test/java/com/ezylang/evalex/ExpressionEvaluatorArrayTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -151,4 +151,26 @@ void testThrowsUnsupportedDataTypeForIndex() {
.isInstanceOf(EvaluationException.class)
.hasMessage("Unsupported data types in operation");
}

@Test
void testArrayIndexOutOfBounds() {
assertThatThrownBy(
() -> {
List<?> array = List.of("Hello");
createExpression("a[1]").with("a", array).evaluate();
})
.isInstanceOf(EvaluationException.class)
.hasMessage("Index 1 out of bounds for array of length 1");
}

@Test
void testArrayNegativeIndex() {
assertThatThrownBy(
() -> {
List<?> array = List.of("Hello");
createExpression("a[-1]").with("a", array).evaluate();
})
.isInstanceOf(EvaluationException.class)
.hasMessage("Index -1 out of bounds for array of length 1");
}
}

0 comments on commit c0e8a0f

Please sign in to comment.