1

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

Parse tree it creates with input 3 4 + 5 *

Desired/expected parse tree:

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
Mike Lischke
  • 48,925
  • 16
  • 119
  • 181
AaySquare
  • 123
  • 10
  • Ah, I understand. I have now attached an image which shows my input and the parse tree it creates. – AaySquare Feb 12 '18 at 20:58
  • Included expected parse tree for input 3 4 + 5 * – AaySquare Feb 12 '18 at 21:48
  • I now see the language you're trying to parse is a stack oriented one. The expressions are in RPN, which can be parsed by ANTLR just fine (see github.com/antlr/grammars-v4/blob/master/rpn/rpn.g4) but you can't tell the grammar to produce the infix equivalent parse tree of it. – Bart Kiers Feb 12 '18 at 21:59

0 Answers0