[antlr-interest] Is my brain crooked?

Diehl, Matthew J matthew.j.diehl at intel.com
Sat Jun 16 15:41:55 PDT 2007


I think I saw something like this in the book, but what you could try
(if reordering your original grammar and using predicates doesn't work
(times_expr times_op)=>), is:  (oh yeah, page 188 of the book)

math_expr
 : (times_expr -> times_expr)
   (
    times_op me2=math_expr -> ^(BIN_EXPR times_op $math_expr $me2)
   )?
 ;

So, if there's just times_expr, then that's all that is returned (no
tree), otherwise, a tree is created, and the previous parts of
$math_expr (which is just times_expr) are added to the tree.  ...or
something like that...
If you don't already have the book, I highly recommend it.

Matt

-----Original Message-----
From: antlr-interest-bounces at antlr.org
[mailto:antlr-interest-bounces at antlr.org] On Behalf Of Tim Gleason
Sent: Saturday, June 16, 2007 12:07 PM
To: antlr-interest at antlr.org
Subject: [antlr-interest] Is my brain crooked?

I bought the ANTLR book with the idea that I would have some fun
writing a few toy languages -- and maybe even learn a thing or two.
But it seems /every/ grammar I try to write fails due to the LL(*)
restriction.  My brain just seems unable to grok a grammar that ANTLR
likes :(  I've written several recursive descent parsers in the past
and never had these kinds of problems.

Anyway, in re-writing my grammar over an over until I get it right, I
seem to have something that sorta works, but now I can't figure out
how to write the tree generator.

A fragment of my original grammar looks like this:

math_expr
 :  times_expr                               -> times_expr
 |  times_expr times_op math_expr -> ^(BIN_EXPR times_op times_expr
math_expr)
 ;

times_op
       :        ('*'|'/');

That, of course, gave me errors.  I've rewritten the rule, like:

math_expr
 : times_expr ('*' times_expr)*
 ;

What I want is a tree if there is a '*', and no tree if not.  I know
that I can add the '^' at the '*' -- but that will give me '*' at the
root of my tree.  What I really want is a tree that looks like:
(BIN_OP {operation} {left_expression} {right_expression})

Is there an easy way to do this in my case?

Thanks for your help!
tim


More information about the antlr-interest mailing list