FIRST FOLLOW (Top-Down) Parsing

For FIRST and FOLLOW, we keep applying rules until nothing else can be added to the FIRST and FOLLOW sets.

FIRST(α)FIRST(\alpha)

The set of terminals that BEGIN strings derived from α\alpha. If α\alpha is ϵ\epsilon or generates ϵ\epsilon, then ϵ\epsilon is also in FIRST(α)FIRST(\alpha).f(x)=xe2piiξxf(x) = x * e^{2 pi i \xi x}

  1. If X is a terminal, the FIRST(X) = {X}

  2. If X aα,add a  to FIRST(X)\rightarrow a\alpha, add ~a ~~to ~FIRST(X)

  3. If X ϵ,add ϵ to FIRST(X)\rightarrow \epsilon, add ~ \epsilon ~to ~ FIRST(X)

  4. If a production has multiple Symbols like X Y1,Y2,...,Yk\rightarrow Y_1, Y_2, ..., Y_k

    1. Add every nonϵ  in  FIRST(Yi)  to  FIRST(X)non-\epsilon ~~in ~~ FIRST(Y_i) ~~to ~~FIRST(X)

    2. If Y1ϵ,add  ϵ  FIRST(Y2) to FIRST(X)Y_1 \Rightarrow^* \epsilon, add ~~\epsilon ~~FIRST(Y_2) ~to ~FIRST(X)

    3. Continue for each subsequent YiY_i, if Yiϵ add FIRST(Yi+1) to FIRST(X)Y_i \Rightarrow^*\epsilon ~add ~FIRST(Y_{i+1}) ~to ~FIRST(X)

    to FIRST(X).

  5. If all symbols Y1,Y2,...,YkY_1, Y_2, ..., Y_k can derive ϵ\epsilon, then add ϵ\epsilon

FOLLOW(α)FOLLOW(\alpha)

The set of terminals that can immediately follow A in sentential form (i.e. ).

  1. If S is the start symbol, add $ to FOLLOW(S)

  2. If AαBβ,add FIRST(β)ϵ to FOLLOW(B)A \rightarrow \alpha B \beta, add ~FIRST(\beta) - {\epsilon} ~to ~FOLLOW(B)

  3. Search for A in a production body and apply rules to that production:

    1. Add FOLLOW(A) to FOLLOW(B) if:

      1. AαBA \rightarrow \alpha B

      2. AαBβ and βϵA \rightarrow \alpha B \beta ~and ~\beta \Rightarrow^*\epsilon

Last updated