What are FIRST and FOLLOW and how they are computed?

Compiler DesignProgramming LanguagesComputer Programming

FIRST and FOLLOW are two functions associated with grammar that help us fill in the entries of an M-table.

FIRST ()− It is a function that gives the set of terminals that begin the strings derived from the production rule.

A symbol c is in FIRST (α) if and only if α ⇒ cβ for some sequence β of grammar symbols.

A terminal symbol a is in FOLLOW (N) if and only if there is a derivation from the start symbol S of the grammar such that S ⇒ αNαβ, where α and β are a (possible empty) sequence of grammar symbols. In other words, a terminal c is in FOLLOW (N) if c can follow N at some point in a derivation.

Benefit of FIRST ( ) and FOLLOW ( )

  • It can be used to prove the LL (K) characteristic of grammar.

  • It can be used to promote in the construction of predictive parsing tables.

  • It provides selection information for recursive descent parsers.

Computation of FIRST

FIRST (α) is defined as the collection of terminal symbols which are the first letters of strings derived from α.

FIRST (α) = {α |α →∗ αβ for some string β }

If X is Grammar Symbol, then First (X) will be −

  • If X is a terminal symbol, then FIRST(X) = {X}
  • If X → ε, then FIRST(X) = {ε}
  • If X is non-terminal & X → a α, then FIRST (X) = {a}
  • If X → Y1, Y2, Y3, then FIRST (X) will be

(a) If Y is terminal, then

      FIRST (X) = FIRST (Y1, Y2, Y3) = {Y1}

(b) If Y1 is Non-terminal and

      If Y1 does not derive to an empty string i.e., If FIRST (Y1) does not contain ε then, FIRST (X) = FIRST (Y1, Y2, Y3) = FIRST(Y1)

(c) If FIRST (Y1) contains ε, then.

     FIRST (X) = FIRST (Y1, Y2, Y3) = FIRST(Y1) − {ε} ∪ FIRST(Y2, Y3)

Similarly, FIRST (Y2, Y3) = {Y2}, If Y2 is terminal otherwise if Y2 is Non-terminal then

  • FIRST (Y2, Y3) = FIRST (Y2), if FIRST (Y2) does not contain ε.

  • If FIRST (Y2) contain ε, then

  • FIRST (Y2, Y3) = FIRST (Y2) − {ε} ∪ FIRST (Y3)

Similarly, this method will be repeated for further Grammar symbols, i.e., for Y4, Y5, Y6 … . YK.

Computation of FOLLOW

Follow (A) is defined as the collection of terminal symbols that occur directly to the right of A.

FOLLOW(A) = {a|S ⇒* αAaβ where α, β can be any strings}

Rules to find FOLLOW

  • If S is the start symbol, FOLLOW (S) ={$}

  • If production is of form A → α B β, β ≠ ε.

(a) If FIRST (β) does not contain ε then, FOLLOW (B) = {FIRST (β)}

Or

(b) If FIRST (β) contains ε (i. e. , β ⇒* ε), then

        FOLLOW (B) = FIRST (β) − {ε} ∪ FOLLOW (A)

∵ when β derives ε, then terminal after A will follow B.

  • If production is of form A → αB, then Follow (B) ={FOLLOW (A)}.
raja
Published on 01-Nov-2021 11:29:30

Advertisements