下面的规则集是相互左递归的

The following set of rules are mutually left-recursive

我在使用 ANTLR4 时遇到以下错误:

The following sets of rules are mutually left-recursive [primary_expression, primary_no_array_creation_expression].

下面是导致该错误的语法片段:

primary_expression
    :   primary_no_array_creation_expression
    |   array_creation_expression
    ;

primary_no_array_creation_expression
    :   literal
    |   simple_name
    |   parenthesized_expression
    |   member_access
    |   primary_expression '.' identifier type_argument_list?
    |   primary_expression '(' argument_list? ')'
    |   primary_no_array_creation_expression '[' argument_list ']'
    |   this_access
    |   base_access
    |   primary_expression '++'
    |   primary_expression '--'
    |   object_creation_expression
    |   delegate_creation_expression
    |   anonymous_object_creation_expression
    |   typeof_expression
    |   checked_expression
    |   unchecked_expression
    |   default_value_expression
    |   anonymous_method_expression
    |   primary_expression '->' identifier
    |   primary_no_array_creation_expression '[' expression ']'
    |   sizeof_expression
    ;

在您的示例语法中,primary_expression 可以是 primary_no_array_creation_expression

那么,primary_no_array_creation_expression可以是primary_expression ++

因此,primary_no_array_creation_expression也可以是primary_no_array_creation_expression ++

当 "one way" 依赖于其他规则时,这是允许的,例如

term   : Digit
       | term Operator term
       ;

product : term Operator term ;

将是有效的,因为即使术语是自引用的(左递归),它也只是在其自己的定义中如此。

以下无效:

term   : Digit
       | term Operator term
       | product Operator product
       ;

product : term Operator term ;

这里,a product 引用 a term,反之亦然,因此创建了一个互左递归模式。

您应该将语法分解成不同的规则。

我遇到了同样的问题,这里有更详细的讨论: https://theantlrguy.atlassian.net/wiki/display/ANTLR3/2.+Example