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.
That is not something you would define in your grammar. The grammar would just accept
function(a = 5, c = "foo", b = 21)
andfunction(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:
where
Expression1
might very well be the variableQ
which is defined as follows:In other words: the statement
Q = 123;
would be illegal since it was already definedfinal
. Such semantic checks are not defined in the grammar but handled at a later stage.