Find FIRST & FOLLOW for the following Grammar. S → A a A | B b B A → b B B → ε

Compiler DesignProgramming LanguagesComputer Programming

Solution

Computation of FIRST

  • A → b B

∴ FIRST(A) = {b}

  • B → ε

∴ FIRST(B) = {ε}

  • S → A a A

Applying Rule (4) of FIRST

i.e., Comparing S → A a A with X → Y1Y2Y3

∴ FIRST (S) = FIRST (A a A) = FIRST (A) = {b}

∴ FIRST(S) = {b}

  • S → B b B

∵ FIRST (B)contains ε or B derives ε ∴ Applying Rule (4c)

∴ FIRST (S) = FIRST (B to B)

∴ FIRST (S) = FIRST (B) − {ε} ∪ FIRST(bB)

∴ FIRST (S) = FIRST (B) − {ε} ∪ {b} = {ε} − {ε} ∪ {b} = {b}

∴ FIRST (A) = {b}

FIRST (B) = {ε}

FIRST (S) = {b}

Computation of FOLLOW

Applying Rule (1) FOLLOW FOLLOW (S) ={$} .....(1)

  • S → A a A

Applying Rule (2) FOLLOW

Comparing S → A a A with A → α B β

S →ΕAaA
A →ΑBβ

∵ FIRST (β) = FIRST (aA) = {a}

which does not contain ε

∴ Rule 2(a) of FOLLOW

FOLLOW(A) = {FIRST (a A)} = {a}

∴ FOLLOW(A) = {a} ……………. (2)

Applying Rule (3) of FOLLOW

Comparing S → A a A with A → α B β

S →AaA
A →Α
B

∴ FOLLOW(A) = {FOLLOW(S)} ……………………… (3)

  • S → B b B

Applying Rule (2) FOLLOW

Comparing S → B b B with A → α B β

S →EBbB
A →ΑBβ

A = S,

α = ε

B = B

β = bB

∵ FIRST (β) = FIRST (bB) = {b}

which does not contain ε

∴ Rule 2(a) of FOLLOW

FOLLOW(B) = {FIRST (b B)}

∴ FOLLOW(B) = {b} ……………. (4)

Applying Rule (3) of FOLLOW

Comparing S → B a B with A → α B

S →BaB
A →Α
B

∴ FOLLOW(B) = {FOLLOW(S)} ……………………… (5)

  • A → bB

Rule (2) cannot be applied. As we can’t match A → b B with A → α B β

If we compare α = b, B = B, β = ε.

Here, β will become ε, which is not possible

Applying Rule (3) of FOLLOW

Comparing A → b B with A → α B

A →bB
A →αB

∴ FOLLOW(B) = {FOLLOW(A)} ……………………… (6)

From statement (1) to (6)

FOLLOW(S) = {$}                                     (1)

FOLLOW(A) = {a}                                     (2)

FOLLOW(A) = {FOLLOW (S)}                  (3)

FOLLOW(B) = {b}                                     (4)

FOLLOW(B) = {FOLLOW(S)}                   (5)

FOLLOW(B) = {FOLLOW (A)}                  (6)

∴ FOLLOW(S) = {$}

From (1), (2), (3)

FOLLOW(A) = {$, a}

From (4), (5), (6)

FOLLOW(B) = {$, a, b}

raja
Updated on 01-Nov-2021 11:40:07

Advertisements