Probably, this is a duplicated question, but I cannot find the question I want to read, so I posted here.
I'm newbie of Antlr, and I try to use Antlr4 to make abstract syntax tree with visitor pattern in Scala.
However, I cannot come up with how to put together results of multiple rules like below into one list.
foo: (rule0 | rule1)*
rule0: ...
rule1: ...
I know there is a way to get each lists (i.e. list of rule0
s and list of rule1
s).
However, that way probably breaks the order of occurrence (I want to maintain the order).
The way like rules=(rule0 | rule1)*
is not also allowed, so I cannot write like below
ctx.rules().asScala.map(...).toArray`
My question is how to put together into list of multiple rule results while maintaining order of appearance in visitor pattern.
The visitor is just a walker over the parse tree generated by your parse run. The visitor class iterates over the children of each parser context and calls the visitor functions. That means the actual information is stored in the parse tree and you can use it directly.
When you get a FooContext
iterate over its children list, which contains the found Rule0Context
and Rule1Context
instances in the order they were used in the source code. This gives you both, the positional information about sub parts as well as the info about each of the sub parts.