File tree Expand file tree Collapse file tree 3 files changed +31
-0
lines changed
main/java/com/ezylang/evalex
test/java/com/ezylang/evalex Expand file tree Collapse file tree 3 files changed +31
-0
lines changed Original file line number Diff line number Diff 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 ());
Original file line number Diff line number Diff 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 ;
Original file line number Diff line number Diff 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}
You can’t perform that action at this time.
0 commit comments