Pablo Estrada
Pablo Estrada

Reputation: 3452

Modifying a Grammar in ANTLR to manage expressions correctly

I´m working on a simple expression evaluator with ANTLR

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 | '!' value | value ;

value: literal | '('expression')' ;

mult_op :  '*' | '/' | '%' ;

add_op : '+'|'-' ;

rel_op : '<' | '>' | '<=' | '>='| eq_op ;

eq_op : '==' | '!=' ;

cond_op : '&&' | '||' ;

literal : int_literal | char_literal | bool_literal ;

int_literal : NUM ;

char_literal : CHAR  ;

bool_literal : TRUE | FALSE  ;

The problem I´m having is that association of operand is not being to the left. For example if I evaluate: 10+20*2/10

I get this tree:

enter image description here As you see the / operand is being evaluated first and the correct way should be to the left.

Can you give me help in modifying the grammar to get the asociation right?

Upvotes: 0

Views: 87

Answers (1)

Marc Q.
Marc Q.

Reputation: 551

If you do not really need your parse tree nodes to be binary operations, the grammar below yields a single multExpr node which you can walk 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: unaryExpr (mult_op unaryExpr)* ;
unaryExpr: '-' value | '!' value | value ;

value: literal | '('expression')' ;

mult_op :  '*' | '/' | '%' ;
add_op : '+'|'-' ;
rel_op : '<' | '>' | '<=' | '>='| eq_op ;
eq_op : '==' | '!=' ;
cond_op : '&&' | '||' ;

literal : int_literal ;
int_literal : NUM ;

Parsing you example expression 10+20*2/10<8 produces the parse tree below.

parse tree 'Hope this helps.

Upvotes: 1

Related Questions