如何在我的语法中执行操作优先级 (+ * -/)? [英] How to do Priority of Operations (+ * - /) in my grammars?
问题描述
我使用 antlr 4 定义了我自己的语法,我想根据操作的优先级 (+ * -/) ....
I define my own grammars using antlr 4 and I want to build tree true According to Priority of Operations (+ * - /) ....
我在 do 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 (- /) ?
推荐答案
在 ANTLR3(和 ANTLR4)中 *
和 /
可以被赋予比 更高的优先级+
和 -
像这样:
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
;
但在 ANTLR4 中,这也适用:
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
;
这篇关于如何在我的语法中执行操作优先级 (+ * -/)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!