[antlr-interest] How does AST construction work?

Paul Johnson gt54-antlr at cyconix.com
Mon May 16 08:56:01 PDT 2005


I'm working my way through the ref manual, and I'm having a problem 
understanding how an AST is created from a parser grammar. The 'example 
tree walker' grammar in the manual looks like this:

expr:   mexpr (PLUS^ mexpr)* SEMI!
     ;

mexpr
     :   atom (STAR^ atom)*
     ;

This is much the same as the 'calc' example in the distribution, and if 
I make and run this (the C++ version), and enter

 > Main
 > 2+4*5;

Then I get the following output from parser.getAST().toStringTree():

  ( + 2 ( * 4 5 ) )

As expected. But how does this happen? Only PLUS and STAR have AST 
annotations - how does ANTLR decide where to put 'mexpr' and 'atom' in 
the tree? And if I just enter a single digit as an 'expr' then the tree 
(of course) only has one entry - but is it a root and, if so, how?

Thanks -

Paul



More information about the antlr-interest mailing list