Ambiguity in order of operations

70 Views Asked by At

I am working on a toy parser for arithmetic expressions and I am having trouble getting it to parse something like 2^-2. The reason for this is because my production rules look like:

Expression -> Expression ("+" | "-") Multiply | Multiply
... leave out a few rules for brevity ...
Unary -> ("+" | "-") Unary | Exponential
Exponential -> Primary ^ Exponential | Primary
Primary -> number | constant | "(" Expression ")"

I ordered the rules this way so that unary operators have a lower precedence than exponentiation, which I chose because most people seem to think that -2^2 is -4 not 4. The problem is that this requires that a Primary follows the ^ operator and -2 is not a Primary, it is a Unary, so it fails to parse.

Edit: For an expression like -2^-2 it seems most people's way of handling it would be to evaluate it as -(2^(-2)) which violate strict precedence rules because you are performing negation both before and after exponentiation. I am also not sure how to express that as a rule in a context-free grammar.

Edit Edit: I may have found a set of rules that accomplishes this. It seems to work so far with the desired order of operations and no ambiguities that I've detected so far...

expr -> expr "," add
      | add

add -> add ("+" | "-") mult
     | mult

mult -> mult ("*" | "/") exp
      | exp

exp -> fact "^" exp
     | ("+" | "-") exp
     | fact

fact -> fact ("!" | "!!")
      | primary

Primary -> "(" Expr ")"
         | number
         | constant