ANTLR4 grammar which accepts list of optional and required arguments in any order

666 Views Asked by At

How can I write an ANTLR rule that accepts a mixture of optional and required arguments in any order?

For example, a valid query could look like function(a = 5, c = "foo", b = 21) or function(b = 4, c = 5) where a is optional but c and b are required. The only valid arguments are a, b and c.

Any help would be appreciated.

1

There are 1 best solutions below

0
On BEST ANSWER

That is not something you would define in your grammar. The grammar would just accept function(a = 5, c = "foo", b = 21) and function(a = 5, c = "foo", i = 21). After parsing the input, you would reject the latter example in a traversal of the parse tree.

For example, take the BNF specification of a Java assignment statement:

Expression: 
    Expression1 [AssignmentOperator Expression1]

where Expression1 might very well be the variable Q which is defined as follows:

final int Q = 42;

In other words: the statement Q = 123; would be illegal since it was already defined final. Such semantic checks are not defined in the grammar but handled at a later stage.