Search code examples
parsingcompiler-constructionleft-recursion

Is this grammar left recursive or factor?


I am new to this topic of left recursion and left factoring, please help me in determining whether this grammar is left recursive or left factored, if it is then why ?

S-> aAd | bBd | aBe | bAe | cA | cB


Solution

  • Is it Left recursive? Answer: No.

    By definition, "A grammar is left-recursive if we can find some non-terminal A which will eventually derive a sentential form with itself as the left-symbol."

    example: Immediate left recursion occurs in rules of the form

    A -> Aa | b
    

    where a and b are sequences of nonterminals and terminals, and b doesn't start with A.

    Clearly not the case in:

    S-> aAd | bBd | aBe | bAe | cA | cB

    Is it Left factored? Answer: Yes.

    By definition, in left factoring, it is not clear which two alternative production to choose, to expand a non-terminal.

    This ambiguity occurs, when you have two alternative production that starts with same terminal/non-terminal. In your case, I can see that thrice, two alternative paths:

    S-> aAd | aBe 
    
    S-> bBd |  bAe 
    
    S-> cA | cB
    

    If I remove the left factoring then the grammar becomes:

    S-> aA'
    
    A'-> Ad | Be
    
    S-> bB'
    
    B'-> Bd | Ae
    
    S-> cC'
    
    C'-> A | B
    

    This slide explains the same in simpler words