I am using antlr to generate parser that produces abstract syntax tree. 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:
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. Antlr does not accept left recursive grammar. How to modify the grammar to make the left associative syntax work in expression like abc?
Parse abc
not as a-(bc)
and not as (ab)-c
but as a (-b) (-c)
, that is,
additiveExpression
: multiplicativeExpression
(
( '+'
| '-'
)
multiplicativeExpression
)*
;
The above rule is taken from Java grammar . Save the text and read with an editor, as browser may ignore line ends in it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.