Back to the 2023 paper

Module 2: Syntax Analysis (Parser)

20235m

Write the algorithm to compute FIRST and FOLLOW for a given grammar.

Worked SolutionAI Assisted

Algorithm to compute FIRST and FOLLOW

Notation: XX = nonterminal/terminal; α,β\alpha,\beta = strings of grammar symbols; ϵ\epsilon = empty string; $ = end marker.

FIRST

Compute FIRST(X1…Xn))FIRST(X_1\dots X_n)) = set of terminals that can start any string derivable from X1X2…XnX_1X_2\dots X_n (plus ϵ\epsilon if the whole can derive ϵ\epsilon).

Rules (for individual symbol):

  1. If XX is a terminal, then FIRST(X)={X}\mathrm{FIRST}(X) = \{X\}.
  2. If XX is ϵ\epsilon production i.e. X→ϵX\to\epsilon, add ϵ\epsilon to FIRST(X)\mathrm{FIRST}(X).
  3. If XX is a nonterminal and X→Y1Y2…YkX\to Y_1Y_2\dots Y_k, then:
    • Put FIRST(Y1)\mathrm{FIRST}(Y_1) \textbackslash}{\epsilon} into FIRST(X)\mathrm{FIRST}(X).
    • If Y1Y_1 derives ϵ\epsilon, also put FIRST(Y2)∖{ϵ}\mathrm{FIRST}(Y_2)\setminus\{\epsilon\}, and so on.
    • If Y1..YkY_1..Y_k all can derive ϵ\epsilon, then put ϵ\epsilon into FIRST(X)\mathrm{FIRST}(X).
    • Order: For each production, apply until no more additions; repeat the whole loop until no change.

For a string α=X1X2…Xn\alpha = X_1X_2\dots X_n :
FIRST(α)=FIRST(X1)∖{ϵ}\mathrm{FIRST}(\alpha) = \mathrm{FIRST}(X_1) \setminus \{\epsilon\}; if ϵ∈FIRST(X1)\epsilon\in \mathrm{FIRST}(X_1), add FIRST(X2)∖{ϵ}\mathrm{FIRST}(X_2)\setminus\{\epsilon\}, etc.; if all XiX_i derive ϵ\epsilon, add ϵ\epsilon to FIRST(α)\mathrm{FIRST}(\alpha).

2. Compute FOLLOW(X) for every nonterminal X

Rule to find the set of terminals that can appear immediately to the right of XX in some sentential form.

  1. If XX is the start symbol, place `‘in` in \mathrm{FOLLOW}(X)$.
  2. For a production A→αBβA\to\alpha B\beta: everything in FIRST(β)\mathrm{FIRST}(\beta) except ϵ\epsilon goes into FOLLOW(B)\mathrm{FOLLOW}(B).
  3. If there is a production A→αBA\to\alpha B or A→αBβA\to\alpha B\beta where β⇝ϵ\beta \rightsquigarrow \epsilon (i.e. β\beta is nullable), then everything in FOLLOW(A)\mathrm{FOLLOW}(A) gets added to FOLLOW(B)\mathrm{FOLLOW}(B).
  4. Repeat these steps until no further additions occur.

(Terminals/symbol ) that are not nonterminals have no FOLLOW.)

These First/Follow results are then used to build the predictive (LL(1)) parsing table: for A→αA\to\alpha, put the production into M[A][a] for each a in FIRST(α)\mathrm{FIRST}(\alpha); if α\alpha nullable, put it into M[A][b] for each b in FOLLOW(A)\mathrm{FOLLOW}(A).

Similar questions

AI LearningWeb Platform

Coursify — Personal AI Course Generator

Struggling with a difficult subject or concept? Turn any engineering topic into a structured course with interactive lessons, quizzes, and research-backed explanations.