Home > Enterprise >  How would I implement operator-precedence in my grammar?
How would I implement operator-precedence in my grammar?

Time:11-07

I'm trying to make an expression parser and although it works, it does calculations chronologically rather than by BIDMAS; 1 2 * 3 4 returns 15 instead of 11. I've rewritten the parser to use recursive descent parsing and a proper grammar which I thought would work, but it makes the same mistake.

My grammar so far is:

exp     ::= term op exp | term
op      ::= "/" | "*" | " " | "-"
term    ::= number | (exp)

It also lacks other features but right now I'm not sure how to make division precede multiplication, etc.. How should I modify my grammar to implement operator-precedence?

CodePudding user response:

Try this:

exp   ::= add
add   ::= mul ((" " | "-") mul)*
mul   ::= term (("*" | "/") term)*
term  ::= number | "(" exp ")"

Here ()* means zero or more times. This grammar will produce right associative trees and it is deterministic and unambiguous. The multiplication and the division are with the same priority. The addition and subtraction also.

  • Related