【发布时间】:2014-01-14 12:20:27
【问题描述】:
我正在编写一个语法来处理标量和向量表达式。下面的语法被简化以显示我遇到的问题,标量表达式可以从向量派生,向量可以从标量派生。例如,向量可以是文字 [1, 2, 3] 或标量与向量 2 * [1, 2, 3] 的乘积(等效于 [2, 4, 6])。标量可以是文字2 或向量[1, 2, 3][1] 的索引(相当于2)。
grammar LeftRecursion;
Integer
: [0-9]+
;
WhiteSpace
: [ \t\r\n]+ -> skip
;
input
: expression EOF;
expression
: scalar
| vector
;
scalar
: Integer
| vector '[' Integer ']'
;
vector
: '[' Integer ',' Integer ',' Integer ']'
| scalar '*' vector
;
ANTLR4 给了我错误:The following sets of rules are mutually left-recursive [scalar, vector]。这是有道理的,因为scalar 引用了vector,反之亦然,但同时它应该是确定性的。
我将如何重构此语法以避免相互(间接)左递归?我可以expand one of the terms inplace,但这会在完整的语法中引入很多重复,其中向量和标量有更多的替代方案。我也可以refactor the grammar to have a primary expression,但我不想让scalar '*' scalar 作为有效的vector 替代方案。还有其他选择吗?
【问题讨论】:
标签: antlr4 left-recursion