简体   繁体   English

如何从语法中删除间接左递归

[英]How to remove indirect left-recursion from grammar

I have some mutually left-recursive ANTLR code: 我有一些相互左递归的ANTLR代码:

expr: int_liter
| bool_liter
| char_liter
| str_liter
| pair_liter
| ident
| array_elem
| unary_oper expr
| expr binary_oper expr
| OPEN_PARENTHESES expr CLOSE_PARENTHESES
;

array_elem:  expr  OPEN_BRACKET expr CLOSE_BRACKET ;

Any ideas on how to fix this? 有想法该怎么解决这个吗?

ANTLR 4 can handle direct left-recursion only, but your grammar contains indirect left recursion from the rules exprarray_elemexpr . ANTLR 4只能处理直接左递归,但是您的语法包含来自规则exprarray_elemexpr间接左递归。 The easiest way to resolve this problem in your particular grammar is to inline the array_elem rule into the expr rule, and use labeled outer alternatives to assign meaningful names to each of the alternatives in expr . 解决您特定语法中此问题的最简单方法是将array_elem规则内联到expr规则中,并使用带标签的外部替代项为expr每个替代项分配有意义的名称。

expr
  : int_liter                                # someLabel
  | bool_liter                               # someLabel               
  | char_liter                               # someLabel
  | str_liter                                # someLabel
  | pair_liter                               # someLabel
  | ident                                    # someLabel
  | expr OPEN_BRACKET expr CLOSE_BRACKET     # array_elem
  | unary_oper expr                          # someLabel
  | expr binary_oper expr                    # someLabel
  | OPEN_PARENTHESES expr CLOSE_PARENTHESES  # someLabel
  ;

Note the following constraints around using labeled outer alternatives: 请注意以下有关使用标记的外部替代项的约束:

  1. No two outer alternatives can share a label, and labels cannot match any rule name; 没有两个外部替代方案可以共享标签,并且标签不能与任何规则名称匹配。 labels must be unique throughout the grammar. 标签在整个语法中必须是唯一的。
  2. If one outer alternative of a rule is labeled (eg the array_elem alternative), then all outer alternatives for that rule must be labeled. 如果标记了规则的一个外部替代项(例如, array_elem替代项),则必须标记该规则的所有外部替代项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM