0
votes

Hello i'd make a simple calculator example using ANTLR but there is a problem in operations (/,*,-,+) priority my code give them the same priority ,i need to make a top priority for multiplication and division

this is the grammar:

grammar Calc;       

start : expr EOF;

expr:   expr op expr   # binaryOp
|   Num                # num
;

op : '+'
| '-'
| '/'
| '*'
;

Num : [0-9]+;

and this is the java code:

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());

  }


}

i hope to help me thanks

1

1 Answers

2
votes

Put the multiplication- and division-operator before the other two:

expr
 : expr mul_op expr   # mulExpr
 | expr add_op expr   # addExpr
 | Num                # num
 ;

mul_op
 : '/'
 | '*'
 ;

add_op
 : '+'
 | '-'
 ;