3

the 'expr' rule in the ANTLR grammar below obviously mutually left-recursive. As a ANTLR newbie it's difficult to get my head around solving this. I've read "Resolving Non-LL(*) Conflicts" in the ANTLR reference book, but I still don't see the solution. Any pointers?

LPAREN : ( '(' ) ;
RPAREN : ( ')' );
AND : ( 'AND' | '&' | 'EN' ) ;
OR : ( 'OR' | '|' | 'OF' );
NOT : ('-' | 'NOT' | 'NIET' );
WS :  ( ' ' | '\t' | '\r' | '\n' ) {$channel=HIDDEN;}  ;
WORD :  (~( ' ' | '\t' | '\r' | '\n' | '(' | ')' | '"' ))*;

input : expr EOF;
expr : (andexpr | orexpr | notexpr | atom);
andexpr : expr AND expr;
orexpr :  expr OR expr;
notexpr : NOT expr;
phrase : '"' WORD* '"';
atom : (phrase | WORD); 
Ward Bekker
  • 6,316
  • 9
  • 38
  • 61

1 Answers1

5

I would suggest to have a look at the example grammers on the antlr site. The java grammar does what you want.

Basicly you can do something like this:

expr : andexpr;
andexpr : orexpr (AND andexpr)*;
orexpr : notexpr (OR orexpr)*;
notexpr : atom | NOT expr;

The key is, that every expression can end to be an atom.

Arne Deutsch
  • 14,629
  • 5
  • 53
  • 72
  • Thanks for your answer. My issue with this solution is that the parse tree looks odd: every atom has a notexpr as parent, even if that's not really a notexpr. Maybe LL(*) parsers are not the best solution for this kind of parsing? – Ward Bekker Aug 24 '10 at 12:22
  • Theres nothing wrong with LL parsers for this kind of grammer (is very common to use this kind of expression). If you generate an AST you can use rewrite rules to create an AST that does not include the "superflues" parents. – Arne Deutsch Aug 24 '10 at 13:55
  • @Arne I stumbled upon your answer while searching for a solution to the same problem the original poster had. I found a slight typo in your code: the first line should read `expr : andexpr` instead of `expr : andexp`. I cannot edit it myself, since SO for some reasons demands that I change more than 6 characters for an edit to be accepted. Can you change it yourself so that unaware copy-pasters like myself will run into the same compiliation errors? – phuibers Aug 14 '12 at 07:19