Interpreting the Variable Number of Tree Nodes in ANTLR Tree Grammar

While creating the built-in interpreter of the ANTLR tree grammar, I ran into the problem of the multiplicity of arguments to the procedure call.

Consider the following (erroneous) definition of a grammar tree.

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 is retrieving the given arguments. If there were a known number of expressions, I would simply assign the values ​​that come out of these expressions to my own variable, for example:

 procedureCallStatement : ^(PROCEDURECALL procedureName=NAME argument1=expression argument2=expression) { ... } ; 

This, however, is not the case.

For a case like this, what is the recommendation for interpreting the variable number of tree nodes within a row in an ANTLR tree grammar?

+4
source share
1 answer

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

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

See the wood documentation on the antlr website.

The above will change the type of the argument variable from typeof(expression) to List (well, at least when you generate Java code). Note that list types are untyped, so this is just a regular list.

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

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

Source: https://habr.com/ru/post/1300330/


All Articles