Back to the 2023 paper

Module 2: Syntax Analysis (Parser)

20235m

Consider the following grammar:
S→CCS \to CC
C→cC∣dC \to cC | d
Find the LR(1) set of items.

Worked SolutionAI Assisted

LR(1) sets of items for S→CCS\to CC, C→cC∣dC\to cC\mid d

Augmented grammar: S′→SS'\to S.

Items are written [A→α⋅β, a][A\to\alpha\cdot\beta,\ a] where a is the lookahead terminal.

Closure hint: from $[S\to \cdot CC,\ $],thesymbolafterthedotis, the symbol after the dot is Candthelookaheadcontextof and the lookahead context of C\to\cdotsis is \mathrm{FIRST}(C$)={c,d},soinner, so inner C−itemsreceivelookaheads-items receive lookaheads {c,d}$.

Canonical LR(1) collection:

  • I0I_0: $[S'\to\cdot S,$],\ [S\to\cdot CC,$],\ [C\to\cdot cC,\ c/d],\ [C\to\cdot d,\ c/d]$
  • I1I_1 = goto(I0,S)(I_0,S): $[S'\to S\cdot,$]$
  • I2I_2 = goto(I0,C)(I_0,C): $[S\to C\cdot C,$],\ [C\to\cdot cC,$],\ [C\to\cdot d,$]$
  • I3I_3 = goto(I0,c)(I_0,c): [C→c⋅C, c/d], [C→⋅cC, c/d], [C→⋅d, c/d][C\to c\cdot C,\ c/d],\ [C\to\cdot cC,\ c/d],\ [C\to\cdot d,\ c/d]
  • I4I_4 = goto(I0,d)(I_0,d): [C→d⋅, c/d][C\to d\cdot,\ c/d]
  • I5I_5 = goto(I2,C)(I_2,C): $[S\to CC\cdot,$]$
  • I6I_6 = goto(I2,c)(I_2,c): $[C\to c\cdot C,$],\ [C\to\cdot cC,$],\ [C\to\cdot d,$]$
  • I7I_7 = goto(I2,d)(I_2,d): $[C\to d\cdot,$]$
  • I8I_8 = goto(I3,C)(I_3,C): [C→cC⋅, c/d][C\to cC\cdot,\ c/d]
  • I9I_9 = goto(I6,C)(I_6,C): $[C\to cC\cdot,$]$

GOTO function:

  • goto(I0,S)(I_0,S)= I1I_1; goto(I0,C)(I_0,C)=I2I_2; goto(I0,c)(I_0,c)=I3I_3; goto(I0,d)(I_0,d)=I4I_4
  • goto(I2,C)(I_2,C)=I5I_5; goto(I2,c)(I_2,c)=I6I_6; goto(I2,d)(I_2,d)=I7I_7
  • goto(I3,C)(I_3,C)=I8I_8; goto(I3,c)(I_3,c)=I3I_3; goto(I3,d)(I_3,d)=I4I_4
  • goto(I6,C)(I_6,C)=I9I_9; goto(I6,c)(I_6,c)=I6I_6; goto(I6,d)(I_6,d)=I7I_7

So the canonical LR(1) machine has 10 states (I0I_0–I9I_9).

Reduce actions: I4I_4: C→dC\to d on {c,d}\{c,d\}; I7I_7: C→dC\to d on $$;; I_8:: C\to cCon on {c,d};; I_9:: C\to cCon‘ on `; I5I_5: S→CCS\to CC on ‘;`; I_1:accepton‘: accept on ``.

Bonus — LALR(1): merging states with equal cores (I4∪I7I_4\cup I_7, I3∪I6I_3\cup I_6, I8∪I9I_8\cup I_9) gives the 7-state LALR(1) automaton, free of conflicts for this grammar.

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.