Consider the following grammar. I have issues with the operator priority, for instance: res=2*a+b has a similar parse tree as res=2*(a+b). I know where the problem is, but no "beautiful" solution without mutual left recursion comes to my mind. Can you please help me out a little. The grammar is used with a custom visitor.
grammar Math;
expression: expression add=('+'|'-') expression # expressionAddExpression
| expression mult='*' expression # expressionMultExpression
|'(' expression ')' # bracketExpression
| number # numberExpression
;
number: INT #int
| '(' number ')' #bracketNumber
| VARIABLE #var
;
VARIABLE: [A-Za-z][A-Za-z0-9]*;
INT: [0-9]+;
From The Definitive ANTLR 4 Reference, 5.4 Dealing with Precedence, Left Recursion, and Associativity :
So simply put multiplication before addition.
File
Question.g4
:File
input.txt
:Execution :
and