Find FIRST & FOLLOW for the following Grammar E → E + T|T T → T ∗ F|F F → (E)|id

Compiler DesignProgramming LanguagesComputer Programming

Solution

Computation of FIRST

  • E → E + T|T

Since FIRST (E) does not contain ε.

∴ FIRST (E) = FIRST(E + T) = FIRST(E)

As, E → T

∴ FIRST (E) = {FIRST(T)}                                       (1)

  • T → T ∗ F|F

As FIRST (T) does not contain ε or T does not derive ε.

∴ FIRST (T) = FIRST(T ∗ F) = {FIRST(T)}

As, T → F (FIRST(T) = {FIRST(F)}                      (2)

  • F → (E)|id

∴ By Rule (3)of FIRST

FIRST (F) = {(, id}                                               (3)

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

FIRST (F) = {(, id}                                               (3)

FIRST (T) = {FIRST(F)}                                      (2)

FIRST (E) = {FIRST(T)}                                      (1)

∴ FIRST (E) = FIRST(T) = FIRST(F) = {(, id}

Computation of FOLLOW

E → E + T|T

T → T ∗ F|F

F → (E) |id

Apply Rule (1) FOLLOW (E) = {$} (1)

  • 𝐄 → 𝐄 + 𝐓|𝐓

Applying Rule (2) of FOLLOW

E →ΕE+T
A →αBΒ

𝛼 = ε, B = E, β = +T

Since FIRST (β) = FIRST (+T) = {+} does not contain ε

∴ 𝐑𝐮𝐥𝐞(𝟐𝐚) 𝐨𝐟 𝐅𝐎𝐋𝐋𝐎𝐖

∴ FOLLOW(E) = FIRST(+T) = {+}

∴ FOLLOW(E) = {+} (2)

Applying Rule (3) of FOLLOW

E →Ε +T
A →αB

FOLLOW (T) = {FOLLOW (E)}                            (3)

  • 𝐓 → 𝐓 * 𝐅

Applying Rule (2)

T →ΕT*F
A →αBβ

∴ A = T, α = ε, B = T, β =∗ F

Since FIRST (β) = {∗} does not contain ε.

∴ 𝐑𝐮𝐥𝐞 (𝟐𝐚)𝐨𝐟 𝐅𝐎𝐋𝐋𝐎𝐖 

∴ FOLLOW(T) = FIRST(∗ F)

∴ FOLLOW(T) = {∗}                                             (4)

Applying Rule (3)

T →T*F
A →αB

FOLLOW(F) = {FOLLOW(T)} (5)

  • F → (E)

Applying Rule (2)

F →(E)
A →αBβ

Since FIRST (β) = {)} does not contain ε.

∴ 𝐑𝐮𝐥𝐞 (𝟐𝐚)𝐨𝐟 𝐅𝐎𝐋𝐋𝐎𝐖

∴ FOLLOW(E) = FIRST()).

∴ FOLLOW(E) = {)}                                                    (6)

Rule (3) cannot be applied to this production

It has ) at the right end corner.

But in rule (3) we should have a non-terminal at the right end corner.

i.e., we cannot compare A → α B with F → (E).

Combining all 6 statements, we get

FOLLOW (E) = {$}                                   (1)

FOLLOW (E) = {+}                                    (2)

FOLLOW (T) = {FOLLOW (E)}                 (3)

FOLLOW (T) = {∗}                                    (4)

FOLLOW (F) = {FOLLOW (T)}                  (5)

FOLLOW (E) = {)}                                    (6)

∴ From rule (1), (2) & (6)

FOLLOW (E) = {$, +, )}

∴ From rule (3), (4) & (5)

FOLLOW (T) = FOLLOW (F) = {$, +, ),∗}

raja
Updated on 03-Nov-2021 10:58:27

Advertisements