Search code examples
parsingantlrantlr3antlrworks

Iterating/processing a list of Tokens parsed in ANTLR


I have a rule

((cns=IDENT '->')* IDENT | (cns=IDENT '->')* 'STOP') -> ^(PREFIX ^(EVENTS $cns*) ^(ENDS $procn? STOP?)  ) 

This will work correctly if cns=IDENT is replaced by 'cns+=IDENT'. In that case how can I access cns as $cns.text.


Solution

  • To store all IDENTs and not only last one cns=IDENT has to be changed to cns+=IDENT.

    Now if you explore parser Java code generated by ANTLR cns is a generic ArrayList where all stored items are of type Token.

    Now this list can be iterated through using a loop and you can do anything with the items using code like

    $cns.get(index)
    

    This item is of Object type though and can be Casted(is this correct terminology?) to Token object for Token specific tasks.