Search code examples
antlr4left-recursion

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?


Solution

  • 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 ')'
           ;