Search code examples
parsingcompiler-constructioncontext-free-grammar

LL(1) grammar and first & follow sets


I think the below is actually LL(1) but I am not 100% sure. are we able to prove that this iss LL(1) grammar and then also, is the first and follow sets given correct? I dont really understand for sure how to actually get the follow sets.

Grammar

expr ::= term {addop term}
term ::= factor {mulop factor}
factor ::= variable| unsigned-number| ( expr)
variable ::= identifier
addop ::= + | -
mulop ::= * | /

First Sets

First(expr) = identifier, unsigned number, (
First(Term) = identifier, unsigned number, (
First(Factor) = identifier, unsigned number, (
First(Variable) = Identifier
First(addop) = +, -
First(mulop) = *, /

Follow Sets

Follow(Expr) = First(term)
Follow(Term) = First(Factor)

Do not understand how to do the Follow sets of the below sets
Follow(Factor) = First( ")" ) = )
Follow(Variable) Follow(addop) Follow(mulop)


Solution

  • FIRST sets are correct.

    FOLLOW sets:

    FOLLOW(A) of non-terminal A is the set of terminal symbols that can follow in the derivation sequence
    

    FOLLOW(expr): check where it appeared in the right-hand side of production. It is there is factor:=(expr), when we take this production in the derivation what follows expr is ) and expr is a start symbol.

       FOLLOW(expr)={),$}
    

    similarly,

       FOLLOW(term) = FIRST(addop) U FOLLOW(expr) = {+,-,),$}
       FOLLOW(factor) = FIRST(mulop) U FOLLOW(trem) = {*,/,+,-,),$}
       FOLLOW(addop) = FIRST(term) = {identifier,unsigned number,(}
       FOLLOW(multop) = FIRST(factor) = {identifier,unsigned number,(}
       FOLLOW(Variable)= FOLLOW(factor) = {*,/,+,-,),$}
    

    where $ is the end of the input.

    Given grammar is LL(1). FIRST sets of factor are disjoint and we don't need check the FOLLOW sets as there are no epsilon productions.