views:

30

answers:

2

I have a left-recursive rule like the following:

EXPRESSION   :  EXPRESSION BINARYOP EXPRESSION | UNARYOP EXPRESSION | NUMBER;

I need to add parens to it but i'm not sure how to make a left parens depend on a matching right parens yet still optional. Can someone show me how? (or am i trying to do entirely too much in lexing, and should i leave some or all of this to the parsing?)

+1  A: 

You could add a recursive rule:

EXPRESSION      : EXPRESSION BINARYOP EXPRESSION
                | UNARYOP EXPRESSION
                | NUMBER
                | OPENPARENS EXPRESSION CLOSEPARENS
                ;
Tordek
Sorry, the rule's name is actually `EXPRESSION`, i realized that just a minute ago.
RCIX
That ought to work for now.
RCIX
@RCIX: you sure about that? AFAIK, that won't work: ANTLR cannot handle such *left-recursive* rules. See: http://www.antlr.org/wiki/display/ANTLR3/Left-Recursion+Removal
Bart Kiers
@Bart: Yeah i'm trying to weasel my way out of that one right now...
RCIX
+1  A: 

Yes, you're trying to do too much in the lexer. Here's how to get around the left-recursive rules:

http://www.antlr.org/wiki/display/ANTLR3/Expression+evaluator (see how the parser rule expr trickles down to the rule atom and then get called recursively from atom again)

HTH

Bart Kiers
Oh dear this is going to be big... Thanks for the tip though!
RCIX