Unambiguous grammar for exponentiation operation

context-free-grammar

Solution

In EBNF (Extended Backus-Naur Form), this could look as follows:

expr -> term [ ('+' | '-') term ]*
term -> factor [ ('*' | '/') factor ]*
factor -> base [ '^' exponent ]*
base -> '(' expr ')' | identifier | number
exponent -> '(' expr ')' | identifier | number

(taken from here)

Translated to your notation (no distinction between numbers and identifiers):

E -> E+T | E-T | T
T -> T*F | T/F | F
F -> F^X | B
B -> i | (E)
X -> i | (E)

One could merge "B" and "X" for the sake of clarity.

Problem

``` E -> E+T | E-T | T T -> T*F | T/F | F F -> i | (E) ``` How can I modify this grammar to allow an exponentiation operation `^` so that I can write `i+i^i*i`? Since we know that order of operations is higher for `^` then all I know is that I must make it right associative.

Original source