Back to the 2023 paper

Module 2: Syntax Analysis (Parser)

20237m

Construct the predictive parsing table for the following grammars:
S→AaAb∣BbBaS \to AaAb | BbBa
A→ϵA \to \epsilon
B→ϵB \to \epsilon

Worked SolutionAI Assisted

Predictive (LL(1)) parsing table

Grammar:
S→AaAb∣BbBaA→ϵB→ϵ S \to AaAb \mid BbBa\\ A \to \epsilon\\ B \to \epsilon

Step 1 — FIRST and FOLLOW

FIRST(A)={ϵ}\mathrm{FIRST}(A) = \{\epsilon\}, FIRST(B)={ϵ}\mathrm{FIRST}(B) = \{\epsilon\}.

For S→AAAbS\to AAAb : because A→ϵA\to\epsilon, the first of the right-hand string is a. For S→BbBaS\to BbBa: the first is b. Hence:
FIRST(S)={a,b}\mathrm{FIRST}(S) = \{a, b\}

FOLLOW:

  • SS is start → $\mathrm{FOLLOW}(S) = {$ }$.
  • From S→AaAbS\to AaAb: the first AA is followed by a, the second AA by b.
    FOLLOW(A)={a,b}\mathrm{FOLLOW}(A) = \{a, b\}
  • From S→BbBaS\to BbBa: first BB followed by b, second BB by a.
    FOLLOW(B)={a,b}\mathrm{FOLLOW}(B) = \{a, b\}

Step 2 — build table M[X][terminal]M[X][\text{terminal}]

For each production X→αX\to\alpha, put X→αX\to\alpha into M[X][t]M[X][t] for every t∈FIRST(α)t\in \mathrm{FIRST}(\alpha); if α⇒ϵ\alpha \Rightarrow \epsilon, also put it into M[X][t]M[X][t] for every t∈FOLLOW(X)t\in\mathrm{FOLLOW}(X).

  • For S→AaAbS \to AaAb: FIRST(AaAb)={a}\mathrm{FIRST}(AaAb)=\{a\} → entry M[S][a]=S→AaAbM[S][a] = S\to AaAb.
  • For S→BbBaS \to BbBa: FIRST={b}\mathrm{FIRST}=\{b\} → M[S][b]=S→BbBaM[S][b] = S\to BbBa.
  • For A→ϵA\to\epsilon: place under FOLLOW(A)={a,b}\mathrm{FOLLOW}(A)=\{a,b\} → M[A][a]=A→ϵM[A][a]=A\to\epsilon, M[A][b]=A→ϵM[A][b]=A\to\epsilon.
  • For B→ϵB\to\epsilon: FOLLOW(B)={a,b}\mathrm{FOLLOW}(B)=\{a,b\} → M[B][a]=B→ϵM[B][a]=B\to\epsilon, M[B][b]=B→ϵM[B][b]=B\to\epsilon.

Predictive parsing table (blank cells = error, no production):

Nonterminal a b $
SS S→AaAbS\to AaAb S→BbBaS\to BbBa —
AA A→ϵA\to\epsilon A→ϵA\to\epsilon —
BB B→ϵB\to\epsilon B→ϵB\to\epsilon —

Verification: Every cell has at most one entry, so the grammar is LL(1) — no conflicts. This is the classic example of an LL(1) grammar with A→ϵ, B→ϵA\to\epsilon,\ B\to\epsilon that resolves the choice using lookahead.

Similar questions

Official AppAndroid App

PYQDeck for Android

Solve BEU previous-year exam papers anywhere, anytime. Fast search, offline paper viewing, and step-by-step solutions designed specifically for your phone.