[antlr-interest] Print an AST in original order

Gavin Lambert antlr at mirality.co.nz
Tue Jul 29 14:02:26 PDT 2008


At 20:46 29/07/2008, Varun Bhargava wrote:
>I cannot seem to print the AST in its original order. For EG;
>
>           WHERE
>               |
>              AND
>            /       \
>         =           =
>       /   \        /  \
>      A    5      b    10
>
>
>The above tree should be printed as WHERE A=5 AND b = 10
>
>However this is not the case in ANTLR. Has anyone done this 
>before? If yes could you please point me in the right direction 
>or give me some sample code?

Apart from the initial WHERE node, what you're describing is just 
a basic in-order traversal of the tree (print left child, print 
root, print right child).  (Although generally speaking unless you 
do something clever you'll have to insert extra parentheses in 
your output, to preserve precedence for other examples of trees.)

It's fairly trivial to write code to do this sort of thing 
directly; alternatively, you could probably use a tree-walker 
grammar and either direct code or StringTemplate to generate your 
output.



More information about the antlr-interest mailing list