您好我使用ANTLR制作一个简单的计算器示例 但是操作(/,*, - ,+)优先级存在问题 我的代码给他们相同的优先级,我需要优先考虑 用于乘法和除法
grammar Calc;
start : expr EOF;
expr: expr op expr # binaryOp
| Num # num
;
op : '+'
| '-'
| '/'
| '*'
;
Num : [0-9]+;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
public class Calc{
public static void main(String args[])throws Exception{
ANTLRFileStream str = new ANTLRFileStream(args[0]);
CalcLexer lex = new CalcLexer(str);
CommonTokenStream tok = new CommonTokenStream(lex);
CalcParser parser = new CalcParser(tok);
ParseTree tree = parser.start();
System.out.println(new MyVisitor().visit(tree));
}
}
class MyVisitor extends CalcBaseVisitor<Integer>{
@Override
public Integer visitStart(CalcParser.StartContext ctx) {
return visit(ctx.expr());
}
@Override
public Integer visitBinaryOp(CalcParser.BinaryOpContext ctx) {
int lhs = visit(ctx.expr(0));
int rhs = visit(ctx.expr(1));
String op = ctx.op().getText();
int res = 0;
if (op.equals("+")){
res = lhs + rhs;
}else if (op.equals("-")){
res = lhs - rhs;
}else if (op.equals("/")){
res = lhs / rhs;
}else if (op.equals("*")){
res = lhs * rhs;
}
return res;
}
@Override
public Integer visitNum(CalcParser.NumContext ctx) {
return Integer.parseInt(ctx.Num().getText());
}
}
我希望能帮助我 感谢
答案 0 :(得分:2)
将乘法和除法运算符放在另外两个运算符之前:
expr
: expr mul_op expr # mulExpr
| expr add_op expr # addExpr
| Num # num
;
mul_op
: '/'
| '*'
;
add_op
: '+'
| '-'
;