Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ANTLR4 yet another left recursion

I'm very ashamed to ask... I wrote a grammar for the language with typecast from int to bool and vice versa.

logic_expr : expr NOT? OR | AND expr
       | expr '|' expr SMALLER | LARGER
       | NUMBER
       | NUMBER_SHORT
       | IDENT
       | LOGIC_DEFINED
       ;
math_expr : expr ADD | SUB expr
      | NUMBER
      | NUMBER_SHORT
      | IDENT
      | LOGIC_FULL
      ;
expr : logic_expr
     | math_expr
     | IDENT
     | LOGIC_DEFINED
     | '(' expr ')'
     ;

But antlr tells me "The following sets of rules are mutually left-recursive [logic_expr, expr, math_expr]" I cant understand what's wrong in my grammar?

like image 476
Diogen737 Avatar asked Feb 06 '26 15:02

Diogen737


1 Answers

As of ANTLR 4.2.2, ANTLR 4 does not currently support grammars which contain indirect left recursion. This limitation is addressed by issue #522, which I'm hopeful makes it into ANTLR 4.3.

Since ANTLR 4 already supports direct left recursion, you can solve this problem by inlining your logic_expr and math_expr rules. I also edited 3 broken alternatives by adding parentheses you omitted. I did not remove the ambiguity which was present in the original rules.

expr
       : expr NOT? (OR | AND) expr
       | expr '|' expr (SMALLER | LARGER)
       | NUMBER
       | NUMBER_SHORT
       | IDENT
       | LOGIC_DEFINED
       | expr (ADD | SUB) expr
       | NUMBER
       | NUMBER_SHORT
       | IDENT
       | LOGIC_FULL
       | IDENT
       | LOGIC_DEFINED
       | '(' expr ')'
       ;
like image 109
Sam Harwell Avatar answered Feb 12 '26 14:02

Sam Harwell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!