You are on page 1of 4

Finding FIRST and Follow

First and Follow sets are needed so that parser can properly apply the needed
production rule at the correct place.

FIRST Function
First(α) is a set of terminal symbol that begins in string derived from α

Example: Aabc/def/ghi/cBA

Then First(A)={a,d,g,c}

Rules for calculating First Function


Rule1: For a production rule X- ε

First(X)={ ε}

Rule2: For any terminal symbol a

First(a)={ a} Y1- aB/cd/ ε

First(Y1)={a,c, ε }

Rule3: For a production rule X-Y1Y2Y3 X- ay2y3/cY2Y3/ Y2Y3

Calculating First(X)
If ε ∉ First(Y1) then First(X)= First(Y1)

If ε ∈ First(Y1) then First(X)= {First(Y1)- ε } ∪ First(Y2 Y3)

Calculating First(Y2 Y3)


If ε ∉ First(Y2) then First(Y2 Y3)= First(Y2)

If ε ∈ First(Y2) then First(Y2 Y3)= {First(Y2)- ε } ∪ First( Y 3)


Follow Function
Follow(α) is a set of terminal symbol that appear immediately to the right of α.

Rules for calculating Follow function

Rule1: For the start symbol S, place $ in Follow(S)

Rule2: For any production rule A αB

Follow(B)=Follow(A)

Rule3: For any production rule A- αBβ

If ε ∉ First(β) then Follow(B)=First(β)

If ε ∈ First(β) then Follow(B)={First(β)- ∈ }∪ Follow(A)

Note:

 ε May appear in the first function of a non terminal


 ε Will never appear in the follow function of non terminal
 It is recommended to eliminate left recursion from grammar if present
before calculating First and Follow functions.
 We will calculate the follow function of a non terminal looking where it is
present on RHS of a production rule.
ABCD
Bb D/ ε
CcD/ ε
Dd
First(A)={FIRST(B)- ε}∪{FIRST(C)- ε}∪{FIRST(D)}

={b}∪{c}∪{d}

={bcd}

FIRST(B)={b, ε }

ABC

 bCD/CD

A-DaAb

DBb

B-c

Follow(A)={b,$}

Follow(D)={a}

Follow(B)={b}
A-Da

DB

Bc

Follow(A)={$}

Follow(D)={a}

Follow(B)=Follow(D)={a}

A-DaAb

DCBb First(B)={c} B-cBD

Cd

Follow(A)={$,b}

Follow(D)={a}

Follow(B)={b}

Follow(C)=First(B)={c}

You might also like