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؟

有帮助吗?

解决方案

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
     ;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top