I am extending a Listener in ANTLR4 and I want to get all of the tokens which are associated with a particular rule in the parser, is there a method in doing that?
i.e.
myConfiguration: CONFIG EQUALS parameters ;
parameters: ALPHANUMERIC+
CONFIG: 'config' ;
ALPHANUMERIC: [a-zA-Z0-9] ;
How can I tell my listener to lookup the value of CONFIG
and EQUALS
when entering the myConfiguration
parsing rule?
Is there a for loop of some sort I could use?
for( all tokens in this rule) {
System.out.println(token.getText());
}
I can see that there is a list of tokens through the parser class but I cant find a list of tokens which are associated with the current rule.
The reason why I am asking this is so that I can avoid re-typing the token names which I require in the Listener AND in the grammar. By doing that I can check whether or not each token type in that particular rule has been found without having to type in the name manually.
This might be what you're looking for.
List<TerminalNode> terminalNodes = new ArrayList<TerminalNode>();
for (int i = 0; i < context.getChildCount(); i++) {
if (context.getChild(i) instanceof TerminalNode) {
terminalNodes.add((TerminalNode)context.getChild(i));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With