[antlr-interest] BASIC if-then-else-endif

John B. Brodie jbb at acm.org
Wed Oct 20 14:13:09 PDT 2010


Greetings!

On Wed, 2010-10-20 at 15:42 -0500, Juan Fernando Herrera J. wrote:
> I'm trying to build an AST for if-then-else-endif like in BASIC. I'm trying
> 
>     prog:   ( ast {System.out.println($ast.tree.toStringTree());} )+ EOF;
> 
>     ast:   'if' condition a=thenstat b=elsestat 'endif' -> ^('if'
> condition $a $b);
> 
>     thenstat: 'then'^ stat+;
> 
>     elsestat: 'else'^ stat+;
> 
>     stat:  'print'^ INT;
> 
> This gets me
> 
>     (if true (then (print 1) (print 2) (print 3)) (else (print 4)
> (print 5) (print 6)))
> 
> However, I'd like to get
> 
>     (if true ((print 1) (print 2) (print 3)) ((print 4) (print 5) (print 6)))
> 
> How can I do it?

UNTESTED! replace the ^ after the then and else keywords with a !

e.g.

thenstat: 'then'! stat+ ;
elsestat: 'else'! stat+ ;

as an aside a ! after EOF will also keep it out of the tree....

hope this helps
   -jbb




More information about the antlr-interest mailing list