How to do Priority of Operations (+ * - /) in my grammars?

爷,独闯天下 提交于 2020-05-23 19:17:17

问题


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 (- /) ?


回答1:


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
 ;



回答2:


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.



来源:https://stackoverflow.com/questions/39469383/how-to-do-priority-of-operations-in-my-grammars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!