Processing an n-ary ANTLR AST one child at a time

Posted by Chris Lieb on Stack Overflow See other posts from Stack Overflow or by Chris Lieb
Published on 2010-04-20T21:10:47Z Indexed on 2010/04/20 21:13 UTC
Read the original article Hit count: 259

Filed under:

I currently have a compiler that uses an AST where all children of a code block are on the same level (ie, block.children == {stm1, stm2, stm3, etc...}). I am trying to do liveness analysis on this tree, which means that I need to take the value returned from the processing of stm1 and then pass it to stm2, then take the value returned by stm2 and pass it to stm3, and so on. I do not see a way of executing the child rules in this fashion when the AST is structured this way.

Is there a way to allow me to chain the execution of the child grammar items with my given AST, or am I going to have to go through the painful process of refactoring the parser to generate a nested structure and updating the rest of the compiler to work with the new AST?


Example ANTLR grammar fragment:

block
    : ^(BLOCK statement*)
    ;
statement
    : // stuff
    ;

What I hope I don't have to go to:

block
    : ^(BLOCK statementList)
    ;
statementList
    : ^(StmLst statement statement+) 
    | ^(StmLst statement)
    ;
statement
    : // stuff
    ;

© Stack Overflow or respective owner

Related posts about antlr