Search code examples
parsingcompiler-constructiongrammarll-grammar

How to handle operator precedence in an LL(1) parser


I was writing an LL(1) parser for an expression grammar. I had the following grammar:

E -> E + E
E -> E - E
E -> E * E
E -> E / E
E -> INT

However, this is left recursive and I removed the left recursion with the following grammar:

E -> INT E'
E' -> + INT E'
E' -> - INT E'
E' -> * INT E'
E' -> / INT E'
E' -> ε

If I was to have the expression 1 + 2 * 3, how would the parser know to evaluate the multiplication before the addition?


Solution

  • Try this:

    ; an expression is an addition
    E   -> ADD          
    
    ; an addition is a multiplication that is optionally followed
    ; by +- and another addition
    ADD -> MUL T  
    T   -> PM ADD
    T   -> ε
    PM  -> +
    PM  -> -
    
    ; a multiplication is an integer that is optionally followed
    ; by */ and another multiplication
    MUL -> INT G
    G   -> MD MUL
    G   -> ε
    MD  -> *
    MD  -> /
    
    ; an integer is a digit that is optionally followed by an integer
    INT -> DIGIT J
    J   -> INT
    J   -> ε
    
    ; digits
    DIGIT -> 0
    DIGIT -> 1
    DIGIT -> 2
    DIGIT -> 3
    DIGIT -> 4
    DIGIT -> 5
    DIGIT -> 6
    DIGIT -> 7
    DIGIT -> 8
    DIGIT -> 9