0

Calculator math operator precedence is often remembered pneumonic PMDAS.

The grammar on the ANTLR home page (using the same abbreviations) has order MDASP. This isn't PMDAS or reverse PMDAS like I would expect. E.g. this stackoverflow answer contains a grammar that looks like PMDAS.

But no matter what expressions I put into the command line; the parse tree looks correct!

grammar Expr;       
prog:   (expr NEWLINE)* ;
expr:   expr ('*'|'/') expr
    |   expr ('+'|'-') expr
    |   INT
    |   '(' expr ')'
    ;
NEWLINE : [\r\n]+ ;
INT     : [0-9]+ ;

How does this work?

Community
  • 1
  • 1
libliflin
  • 1
  • 1

1 Answers1

0

The question is a little tricky to answer as im not entirely sure what you were trying to parse but pseudo code for what this grammar expects may help you understand it:

An int is one or more numbers from 0 to 9
A new line is one or more \r\n

an (expr)ession is made up of any of these:
an expression with a '*' or '/' and another expression
an expression with a '+' or '-' and another expression
an int
a curly brace containing an expression followed by a curly brace

the (prog)ram is made up of zero or more expressions followed by new lines.

Also remember that ANTLR:

goes for the longest sequence first. if two rules or more match the longest possible sequence then it chooses the lexical rule specified first

This link may be very useful to you. Anyway if you post the tree you are struggling to understand we could try and help you further. Good luck with your project.

D3181
  • 2,037
  • 5
  • 19
  • 44