I\'m trying to use ASTs with ANTLR4, with this files:
Builder.java
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
First I'll explain what you have observed above:
First and foremost, please read the documentation for the methods you call. The Parser.addParseListener documentation includes the following note:
THIS IS ONLY FOR ADVANCED USERS. Please give your ParseTreeListener to a ParseTreeWalker instead of giving it to the parser!!!!
The implementation of toString() for the ParserRuleContext class simply prints the rule invocation stack at the time the context was created. You are printing this once when the listener enters a rule, and once when it exits. For actionexpr, cond, and condexpr you print it again, resulting in a total of 4 identical output lines for each of those contexts.
Now some notes on your goals:
enterCond and exitCond, the MEASURE text is available by calling ctx.MEASURE().getText().enterActionexpr and exitActionexpr, the ACTION text is available by calling ctx.ACTION().getText().COND token by creating a new TerminalNodeImpl and CommonToken for the updated token, and assigning it to the correct index in the field CondContext.children using either a visitor or a listener.