3

I define my own grammars using antlr 4 and I want to build tree true According to Priority of Operations (+ * - /) ....

I find sample on do Priority of Operations (* +) it work fine ...

I try to edit it to add the Priority of Operations (- /) but I failed :(

the grammars for Priority of Operations (+ *) is :

 println:PRINTLN  expression SEMICOLON {System.out.println($expression.value);};
 expression returns [Object value]:
  t1=factor {$value=(int)$t1.value;}
  (PLUS t2=factor{$value=(int)$value+(int)$t2.value;})*;

  factor returns [Object value]: t1=term {$value=(int)$t1.value;}
  (MULT t2=term{$value=(int)$value*(int)$t2.value;})*;

 term returns [Object value]:
  NUMBER {$value=Integer.parseInt($NUMBER.text);}
   | ID {$value=symbolTable.get($value=$ID.text);}
   | PAR_OPEN expression {$value=$expression.value;} PAR_CLOSE
   ;
MULT :'*';
PLUS :'+';

MINUS:'-';
DIV:'/' ; 

How I can add to them the Priority of Operations (- /) ?

code
  • 177
  • 1
  • 15

2 Answers2

3

In ANTLR3 (and ANTLR4) * and / can be given a higher precedence than + and - like this:

println
 : PRINTLN  expression SEMICOLON
 ;

expression
 : factor ( PLUS factor 
          | MINUS factor
          )*
 ;

factor
 : term ( MULT term
        | DIV term
        )*
 ;

term
 : NUMBER
 | ID
 | PAR_OPEN expression PAR_CLOSE
 ;

But in ANTLR4, this will also work:

println
 : PRINTLN  expression SEMICOLON
 ;

expression
 : NUMBER
 | ID
 | PAR_OPEN expression PAR_CLOSE
 | expression ( MULT | DIV ) expression   // higher precedence
 | expression ( PLUS | MINUS ) expression // lower precedence
 ;
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
1

You normally solve this by defining expression, term, and factor production rules. Here's a grammar (specified in EBNF) that implements unary + and unary -, along with the 4 binary arithmetic operators, plus parentheses:

start ::= expression
expression ::= term (('+' term) | ('-' term))*
term ::= factor (('*' factor) | ('/' factor))*
factor :: = (number | group | '-' factor | '+' factor) 
group ::= '(' expression ')'

where number is a numeric literal.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483