Very new to ANTLR4 and trying to make an expression analyser for the target language Forth. As Forth uses postfix notation, I am trying to write grammar rules for postfix integer arithmetic.
Below is the grammar for both infix and postfix integer arithmetic but my postfix grammar that I wrote does not create an appropriate parse tree.
Using input 3 4 + 5 *
for testing purpose
Desired/expected parse tree:
Can anyone help me out with this? Thanks.
grammar ExpAnalyser;
//Parser : grammer
//Infix Arithmetic
/*eval : additionExp ;
additionExp : multiplyExp(PLUS multiplyExp | MINUS multiplyExp)* ;
multiplyExp : unaryExp(MULT unaryExp | DIV unaryExp)* ;
unaryExp : MINUS atomExp | atomExp ;
atomExp : NUMBER | LPAREN eval RPAREN ;*/
//Postfix Arithmetic
eval : operation ;
operation : atomExp(atomExp PLUS | atomExp MINUS | atomExp MULT | atomExp
DIV | atomExp MOD)* ;
atomExp : NUMBER | NUMBER NUMBER eval ;
//Tokenizers : Lexers
MULT : '*' ;
DIV : '/' ;
MOD : 'mod' ;
PLUS : '+' ;
MINUS : '-' ;
//gForth floating point arithmetic tokens
FMULT : 'f*' ;
FDIV : 'f/' ;
FPLUS : 'f+' ;
FMINUS : 'f-' ;
LPAREN : '(' ;
RPAREN : ')' ;
NUMBER : [0-9]+ ('e'[0-9]+)? ;
COMMENT : '//' .+? ('\n'|EOF) -> skip ;
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines