Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Prefix notation in ANTLR4

I am working with Antlr4 at the moment, and I have a confusion with one example. I have to calculate value of expressions in prefix notation which implies following notation:

  • ADD expr expr OR
  • SUB expr expr OR
  • MUL expr expr OR
  • DIV expr expr OR
  • Integer OR
  • Double

(also every expression needs to have ‘;’ at the end of it).

I have written grammar and regular expression for this, but I have a test example of a professor which says ADD 1 2 SUB 1;, which shouldn’t even belong to this grammar right? Because for SUB operation I don’t have two expressions from the right side? Would be grateful if someone could confirm this for me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

PS. I didn’t post the code because for other examples it works, just this one reports error "mismatched input on SUB ';'"

>Solution :

If your expr rule is

expr : 'ADD' expr expr
     | 'SUB' expr expr
     | 'MUL' expr expr
     | 'DIV' expr expr
     | Integer
     | Double
     ;

then yes, ADD 1 2 SUB 1 would not match it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading