Antlr4: The following sets of rules are mutually left-recursive

北慕城南 提交于 2019-12-02 10:25:35

问题


I am trying to describle simple grammar with AND and OR, but fail with the following error

The following sets of rules are mutually left-recursive

The grammar is following:

expr:
    NAME |
    and |
    or;

and:
    expr AND expr;

or:
    expr OR expr;

NAME : 'A' .. 'B' + ;
OR: 'OR' | '|';
AND: 'AND' | '&';

Simultaneously, the following grammar

expr:
    NAME |
    expr AND expr |
    expr OR expr;

NAME : 'A' .. 'B' + ;
OR: 'OR' | '|';
AND: 'AND' | '&';

does compile.

Why?


回答1:


ANTLR4 supports only direct left recursion (which is already an improvement over previous versions). That means you can have left recursion in a single rule, but not over multiple rules (e.g. rule a uses rule b which uses a as the first rule in an alternative.




回答2:


As already mentioned: ANTLR4 only supports direct left recursion. You can label the alternatives to make a distiction in your generated visitor or listener:

expr
 : NAME           #NameExpr
 | expr AND expr  #AndExpr
 | expr OR expr   #OrExpr
 ;

NAME : 'A' .. 'B' + ;
OR   : 'OR' | '|';
AND  : 'AND' | '&';

Note that 'A'..'Z'+ is the old v3 syntax, in v4 you can do this: [A-Z]+

See: https://github.com/antlr/antlr4/blob/master/doc/parser-rules.md#alternative-labels



来源:https://stackoverflow.com/questions/41017948/antlr4-the-following-sets-of-rules-are-mutually-left-recursive

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!