Interpreting a variable number of tree nodes in ANTLR Tree Grammar

antlr, expression-trees, grammar, interpreter

Solution

Use the `+=` operator. To handle any number of arguments, including zero:

procedureCallStatement
   :    ^(PROCEDURECALL procedureName=NAME argument+=expression*)
        {
            ...
        }
   ;

See the tree construction documentation on the antlr website.

The above will change the type of the variable `argument` from `typeof(expression)` to a `List` (well, at least when you're generating Java code). Note that the list types are untyped, so it's just a plain list.

If you use multiple parameters with the same variable name, they will also create a list, for example:

twoParameterCall
   :    ^(PROCEDURECALL procedureName=NAME argument=expression argument=expression)
        {
            ...
        }
   ;

Problem

Whilst creating an inline ANTLR Tree Grammar interpreter I have come across an issue regarding the multiplicity of procedure call arguments. Consider the following (faulty) tree grammar definition. ``` procedureCallStatement : ^(PROCEDURECALL procedureName=NAME arguments=expression*) { if(procedureName.equals("foo")) { callFooMethod(arguments[0], arguments[1]); }elseif(procedureName.equals("bar")) { callBarMethod(arguments[0], arguments[1], arguments[2]); } } ; ``` My problem lies with the retrieval of the given arguments. If there would be a known quantity of expressions I would just assign the values coming out of these expressions to their own variable, e.g.: ``` procedureCallStatement : ^(PROCEDURECALL procedureName=NAME argument1=expression argument2=expression) { ... } ; ``` This however is not the case. Given a case like this, what is the recommendation on interpreting a variable number of tree nodes inline within the ANTLR Tree Grammar?

Original source