Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ANTLR4: Obtaining list of tokens for a specific rule in Listener

Tags:

antlr4

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.

like image 574
Har Avatar asked Feb 21 '13 16:02

Har


1 Answers

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));
    }
}
like image 190
Sam Harwell Avatar answered Oct 09 '22 17:10

Sam Harwell