Modifying a Grammar in ANTLR to manage expressions correctly -
I am working with ANTLR on a simple expression evaluator
This is the grammar I created:
Expression: relationExpr (cond_op expression)? ; RelationExpr: addExpr (rel_op relationExpr)? ; AddExpr: multExpr (add_op addExpr)? ; MultExpr: unaryExpr (mult_op multExpr)? ; UnaryExpr: '-' Value | '!' Price | value; Price: verb | '(' Expression ')'; Mult_op: '*' | '/' | '%'; Add_op: '+' | '-'; Rel_op: '& lt;' | '& Gt;' | '& Lt; = '| '& Gt; = '| Eq_op; Eq_op: '==' | '! = '; Cond_op: '& amp; Amp; | '||' ; Verb: int_literal | Char_literal | Bull_Litral; Int_literal: NUM; Char_literal: CHAR; Bool_literal: Correct | false ; The problem is that the association of Operand is not left, for example, if I evaluate: 10 + 20 * 2/10
I get this tree:
As You are seeing that the / operand is being evaluated first and should be correctly placed on the left side.
Can you give me if you do not really need your parse tree nodes then will you help in modifying grammar?
For binary operations, grammar below produces a single multExpr node that you can move from left to right Which I believe is your goal.
NUM: [0-9] +; Expression: relationExpr (cond_op relationExpr) *; RelationExpr: addExpr (rel_op addExpr) *; AddExpr: multExpr (add_op multExpr) *; MultExpr: mult_op unaryExpr * *; UnaryExpr: '-' Value | '!' Price | value; Price: verb | '(' Expression ')'; Mult_op: '*' | '/' | '%'; Add_op: '+' | '-'; Rel_op: '& lt;' | '& Gt;' | '& Lt; = '| '& Gt; = '| Eq_op; Eq_op: '==' | '! = '; Cond_op: '& amp; Amp; | '||' ; Literally: int_literal; Int_literal: NUM; Example expression parsing 10 + 20 * 2/10 < 8 produces the Perce Tree below.
Comments
Post a Comment