From 2b3969adeb42ddc3863ae3448a69be7d1f8b7bfb Mon Sep 17 00:00:00 2001 From: rameel Date: Tue, 24 Nov 2026 19:46:58 +0500 Subject: [PATCH] parser: reject an indexer without arguments An indexer was parsed with the argument list of a call, which can be empty, so "abc"[] was accepted and failed only when the expression was built: with "Ambiguous match found" for a string, a list, or a dictionary, and with "Incorrect number of indexes" for an array. As in C#, an indexer now takes at least one argument, and "abc"[] fails with "(1:7) Expected expression" at the position of ]. The argument list is labeled "expression" so that the message does not list every token that can start an expression. --- .../ExpressionParser.Parser.cs | 6 +++++- tests/Ramstack.ExpressionParser.Tests/Data/Errors.txt | 10 ++++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/Ramstack.ExpressionParser/ExpressionParser.Parser.cs b/src/Ramstack.ExpressionParser/ExpressionParser.Parser.cs index 1f32222..45995cd 100644 --- a/src/Ramstack.ExpressionParser/ExpressionParser.Parser.cs +++ b/src/Ramstack.ExpressionParser/ExpressionParser.Parser.cs @@ -141,8 +141,12 @@ private static Parser CreateParser() Seq(L(')'), S)) .Do(Func (parameters) => expr => new Expr.Call(expr, parameters)); + // Unlike a call, an indexer takes at least one argument, as in C#. var indexer = - expression_list + expression + .Separated( + Seq(L(','), S), + min: 1).As("expression") .Between( Seq(L('['), S), Seq(L(']'), S)) diff --git a/tests/Ramstack.ExpressionParser.Tests/Data/Errors.txt b/tests/Ramstack.ExpressionParser.Tests/Data/Errors.txt index ebe34d4..d1dda0a 100644 --- a/tests/Ramstack.ExpressionParser.Tests/Data/Errors.txt +++ b/tests/Ramstack.ExpressionParser.Tests/Data/Errors.txt @@ -68,7 +68,7 @@ Method name expected (expression: 3). Cannot apply indexing with [] to an expression of type 'System.Int32'. 1 + 2 * 3[ -(1:11) Expected ']' +(1:11) Expected expression 1 + 2 * 3] (1:10) Expected '(', '[', '.', ':>', [%*/], [+-], '<<', '>>', '>>>', '<', '>', '<=', '>=', '==', '!=', '&', '^', '|', '&&', '||', '??', '?', or end of input @@ -101,7 +101,13 @@ Cannot apply indexing with [] to an expression of type 'System.Int32'. (1:2) Expected '(', '[', '.', ':>', [%*/], [+-], '<<', '>>', '>>>', '<', '>', '<=', '>=', '==', '!=', '&', '^', '|', '&&', '||', '??', '?', or end of input "test"[] -Ambiguous match found:\n Char Chars [Int32] (in System.String) +(1:8) Expected expression + +"test"[ ] +(1:9) Expected expression + +"test".Split(',')[] +(1:19) Expected expression "test"["a"] Ambiguous match found:\n Char Chars [Int32] (in System.String)