[英]How to handle left associative grammar in ANTLR
I am using antlr to generate parser that produces abstract syntax tree. 我正在使用antlr生成生成抽象语法树的解析器。 I got some problem about left associative operators. 我对左联想运算符有一些疑问。 My grammar is like the following: 我的语法如下:
add_expr returns [ASTNode value]
:a=mul_expr {$value = a;}
(
o = ('+' | '-') b = add_expr
{
$value = new AddNode(a, b, $o.text);
}
)?
;
mul_expr returns [ASTNode value]
:a=term {$value = a;}
(
o = ('*' | '/') b = mul_expr
{
$value = new MultiplyNode(a, b, $o.text);
}
)?
;
The constructor of AddNode and MultiplyNode is like: AddNode和MultiplyNode的构造函数如下:
AddNote(ASTNode left, ASTNode right, String operatorr)
The problem is, for input abc, it is parsed to something like a-(bc), rather than (ab)-c. 问题是,对于输入abc,它被解析为类似a-(bc)的东西,而不是(ab)-c。 Antlr does not accept left recursive grammar. Antlr不接受左递归语法。 How to modify the grammar to make the left associative syntax work in expression like abc? 如何修改语法以使左联想语法在像abc这样的表达式中起作用?
Parse abc
not as a-(bc)
and not as (ab)-c
but as a (-b) (-c)
, that is, 将abc
解析为a-(bc)
而不解析为(ab)-c
而是解析为a (-b) (-c)
,即,
additiveExpression
: multiplicativeExpression
(
( '+'
| '-'
)
multiplicativeExpression
)*
;
The above rule is taken from Java grammar . 以上规则取自Java语法 。 Save the text and read with an editor, as browser may ignore line ends in it. 保存文本并使用编辑器阅读,因为浏览器可能会忽略其中的行尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.