] > Algorithms for the FIRST and FOLLOW Functions

4.6 Algorithms for the FIRST and FOLLOW Functions

FIRST of a single symbol

  1. For a terminal symbol a, let FIRST(a) = {a}.
  2. For a production rule of the form A aα, add the terminal symbol a to FIRST(A).
  3. For a production rule of the form A ϵ, add the empty string ϵ to FIRST(A).
  4. For a production rule of the form A X1Xk, add to FIRST(A)

FIRST of a sequence of symbols

  1. The empty string ϵ is in FIRST(X1Xk), if ϵ is in FIRST(X1),…, FIRST(Xk)
  2. The terminal symbol a is in FIRST(X1Xk), if the empty string ϵ is in FIRST(X1Xi1) and the terminal symbol a is in FIRST(Xi).
S aA
bB
A Sa
Ca
B bS
c
C cB


S a, b


Aa, b, c


B b, c


C c


aA a


Sa a, b


S CSAc
BAD
A a
ϵ
B bS
ϵ
C c
D d
ϵ


Sa, b, c, ϵ


A a, ϵ


B b, ϵ


C c


CSAc c


BADa, b, d, ϵ


FOLLOW of a symbol

  1. For the start symbol S, add the end-of-input marker $ into FOLLOW(S)
  2. For a production rule A αB, add FOLLOW(A)-{ϵ} to FOLLOW(B)
  3. For a production rule A αBβ where βϵ, add FIRST(β)-{ϵ} to FOLLOW(B)
  4. For a production rule A αBβ where ϵ is in FIRST(β), add FOLLOW(A) to FOLLOW(B)