I wonder to know how can I write a rewrite rule to generate AST tree for this rule.
e5 : (simpleexpression) (relop simpleexpression)*
;
relop : RELOP_GT
| RELOP_LT
| RELOP_GE
| RELOP_LE
;
I wonder to know how can I write a rewrite rule to generate AST tree for this rule.
e5 : (simpleexpression) (relop simpleexpression)*
;
relop : RELOP_GT
| RELOP_LT
| RELOP_GE
| RELOP_LE
;
This seems to be a binary operation where the root of the (sub) tree is the operator, relop
, and the leaves are the simpleexpression
s. In that case, simply use the inline tree-operator ^
, which makes the token/tree before it the root:
e5 : simpleexpression (relop^ simpleexpression)?
;
relop : RELOP_GT
| RELOP_LT
| RELOP_GE
| RELOP_LE
;
Note that I changes the *
into ?
since your original rule would accept input like:
1 <= 2 < 3
In many programming languages that would evaluate to:
true < 3
which might be considered an invalid expression (your language might accept it, of course, in which case, leave the *
!).
With the inline ^
, the expression
1 <= 2
would be parsed into the following AST:
<=
/ \
1 2
Also see: How to output the AST built using ANTLR?