Click here to Skip to main content
15,395,290 members
Please Sign up or sign in to vote.
0.00/5 (No 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>{

  public Integer visitStart(CalcParser.StartContext ctx) { 
   return visit(ctx.expr()); 

 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; 

 public Integer visitNum(CalcParser.NumContext ctx) { 
 return  Integer.parseInt(ctx.Num().getText());



What I have tried:

i've tried to change the code,, cause i want the same grammar

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900