[antlr-interest] Print an AST in original order
Varun Bhargava
varun.bhargava at carsales.com.au
Tue Jul 29 19:24:20 PDT 2008
Thanks for pointing me in the right direction Kevin.
I'll look at the ANTLR reference.
Regards
Varun
-----Original Message-----
From: Kevin J. Cummings [mailto:cummings at kjchome.homeip.net]
Sent: Wednesday, 30 July 2008 11:45
To: Varun Bhargava
Cc: antlr-interest at antlr.org
Subject: Re: [antlr-interest] Print an AST in original order
Varun Bhargava wrote:
> Hi Kevin,
>
> Thanks for replying. I'm using ANTLR for the first time and an
absolute
> beginner to Parsing stuff, so my apologies if I ask stupid questions.
>
> Firstly, you are right. The tree does look as you mentioned.
> To print the tree I am using the ToStringTree() method of the
CommonTree
> class.
The ToStringTree() method is geared towards parenthesized lists
(LISP-like) trees. If you want to get text back out of the built trees,
you will need to do what Gavin suggested, and write a simple tree-walker
to produce what you need.
> How do I insert the root between binary children? Here is the snippet
> from my grammar file:
>
> where
> :
> | WHERE^ filter
> ;
>
> filter
> : //(key compare literal | key IS NOT? NULL | keyList IN key |
> NOT filter | LPAREN filter RPAREN) (AND^ filter | OR^ filter)*
> (compareFilter | notNullFilter | keyListFilter | NOT filter |
> LPAREN filter RPAREN) (AND^ filter | OR^ filter)*
> ;
>
> compareFilter
> :
> key compare (literal | PARAMETER)
> ;
>
> notNullFilter
> :
> key IS NOT? NULL
> ;
>
> keyListFilter
> :
> keyList IN key
> ;
>
> keyList
> : key (COMMA keyList)*
> ;
>
> compare
> : EQ | NOTEQ | LT | GT | LTE | GTE
You are looking at the parser. That's the wrong place. After you
create a tree, you want to "uncreate" it. You will need rules in a
tree-walker that understand *your* grammar. It will need to know which
operators are unary, and which are binary. Further, it will need to
know which of your unary operators are prefix and which are postfix
(WHERE looks like a prefix notation).
I have often used the ToStringTree() to look at my parsed trees because
it shows me what the parser did, and I can see whether or not they are
correct.
> Thanks
> Varun
--
Kevin J. Cummings
kjchome at rcn.com
cummings at kjchome.homeip.net
cummings at kjc386.framingham.ma.us
Registered Linux User #1232 (http://counter.li.org)
More information about the antlr-interest
mailing list