antlrantlrworks

Eliminate ambiguity of grammar in antlr


I am writing a parser. I have a production which is left-recursive a: a op a so I fix it in this way: ab : () (op ab)*; where op : + | - | / | * now I think this is ambiguous,for example for some statement like x+y*z . How can I
eliminate this ambiguity؟


Solution

  • For ANTLR 3, precedence is implicit in the multiple rule invocations done for an expression. There are plenty of examples of how to build recursive descent expression parsers on the web.

    expr : primary (op primary)* ;
    

    is not ambiguous at all, by the way.

    ANTLR 4 allows you to specify left recursive expression rules and implicitly defines a precedence by the order of the alternatives, assuming there's an ambiguity. For example here's a typical rule:

    expr : expr '*' expr
         | expr '+' expr
         | INT
         ;