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

I am extending Listener in ANTLR4 and I want to get all tokens that are associated with a specific rule in the parser, is there any way to do this?

i.e.

myConfiguration: CONFIG EQUALS parameters ; parameters: ALPHANUMERIC+ CONFIG: 'config' ; ALPHANUMERIC: [a-zA-Z0-9] ; 

How can I tell my listener to find the value of CONFIG and EQUALS when I enter the myConfiguration parsing myConfiguration ?

Is there any loop I could use?

 for( all tokens in this rule) { System.out.println(token.getText()); } 

I see that there is a list of tokens through the parser class, but I can not find a list of tokens associated with the current rule.

The reason I'm asking about this is because I can avoid re-entering the token names that I need in Listener AND in the grammar. By doing this, I can check if each type of token was found in this particular rule without manually entering a name.

+4
source share
1 answer

This may be what you are 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)); } } 
+7
source

All Articles