Search code examples
parsingcompiler-constructioninterpreter

Correct LL(1) grammar for arithmetic expressions


This is a correct LL grammar:

E->TX

T->(E)Y |intY

X->+E | -E | e

Y->*E | /E| e

but it 'll produce the same AST tree for expressions

int-int+int and int-(int+int)

e.q

Sub(Simple(int),Add(Simple(int),Simple(int))

Of course, I can use some lookahead, but this isn't cool.


Solution

  • Try this grammer

    E  -> T E'
    E' -> + T E' | -TE' |epsilon
    T  -> F T'
    T' -> * F T' | /FT' |epsilon
    F  -> (E) | int