Back to the 2023 paper

Module 2: Syntax Analysis (Parser)

20237m

Consider the following grammar:
E→E+T∣TE \to E + T | T
T→T∗F∣FT \to T * F | F
F→tdF \to td
Draw a SLR state transition diagram for the above grammar. Also draw the SLR parse table.

Worked SolutionAI Assisted

SLR parse for the grammar E→E+T∣TE\to E+T\mid T, T→T∗F∣FT\to T*F\mid F, F→idF\to \mathbf{id}

(The paper spells the token td; we treat it as the identifier token id.)

Augment with E′→EE'\to E.

Productions numbering:

  1. E→E+TE\to E+T
  2. E→TE\to T
  3. T→T∗FT\to T*F
  4. T→FT\to F
  5. F→idF\to\mathbf{id}

LR(0) canonical collection (states I0I_0–I8I_8):

  • I0I_0: E′→⋅E, E→⋅E+T, E→⋅T, T→⋅T∗F, T→⋅F, F→⋅idE'\to\cdot E,\ E\to\cdot E+T,\ E\to\cdot T,\ T\to\cdot T*F,\ T\to\cdot F,\ F\to\cdot\mathbf{id}
  • I1=goto(I0,E)I_1 = goto(I_0,E): E′→E⋅E'\to E\cdot, E→E⋅+TE\to E\cdot+T
  • I2=goto(I0,T)I_2 = goto(I_0,T): E→T⋅E\to T\cdot, T→T⋅∗FT\to T\cdot*F
  • I3=goto(I0,F)I_3 = goto(I_0,F): T→F⋅T\to F\cdot
  • I4=goto(I0,id)I_4 = goto(I_0,id): F→id⋅F\to \mathbf{id}\cdot
  • I5=goto(I1,+)I_5 = goto(I_1,+): E→E+⋅TE\to E+\cdot T, T→⋅T∗FT\to\cdot T*F, T→⋅FT\to\cdot F, F→⋅idF\to\cdot\mathbf{id}
  • I6=goto(I2,∗)I_6 = goto(I_2,*): T→T∗⋅FT\to T*\cdot F, F→⋅idF\to\cdot\mathbf{id}
  • I7=goto(I5,T)I_7 = goto(I_5,T): E→E+T⋅E\to E+T\cdot, T→T⋅∗FT\to T\cdot*F
  • I8=goto(I6,F)I_8 = goto(I_6,F): T→T∗F⋅T\to T*F\cdot

GOTO transitions: 0→E1, 0→T2, 0→F3, 0→id40\xrightarrow{E}1,\ 0\xrightarrow{T}2,\ 0\xrightarrow{F}3,\ 0\xrightarrow{id}4;
1→+51\xrightarrow{+}5; 2→∗62\xrightarrow{*}6; 5→T7, 5→F3, 5→id45\xrightarrow{T}7,\ 5\xrightarrow{F}3,\ 5\xrightarrow{id}4; 6→F8, 6→id46\xrightarrow{F}8,\ 6\xrightarrow{id}4; 7→∗67\xrightarrow{*}6.

(This is the state-transition diagram; every state is a node and every label above is an edge.)

FOLLOW sets:

  • $\mathrm{FOLLOW}(E)={+, $}(start)∪‘+‘from (start) ∪ `+` from E\to E+T$.
  • $\mathrm{FOLLOW}(T)={+,,$}$ (E→E+T ⇒ FOLLOW(E), T→TF ⇒ *).
  • $\mathrm{FOLLOW}(F)={+,*,$}$.

SLR parsing table (ACTION + GOTO):

State id + * $ E T F
0 s4 1 2 3
1 s5 acc
2 r2 s6 r2
3 r4 r4 r4
4 r5 r5 r5
5 s4 7 3
6 s4 8
7 r1 s6 r1
8 r3 r3 r3
  • s n = shift and go to state n; r k = reduce by production kk (list above); acc = accept.
  • Uses FOLLOW: r4/r5 in states 3/4 for +, *, $ (in FOLLOW(T)/FOLLOW(F)) etc.

No cell has two actions → the grammar is SLR(1) (a conflict-free table), and id + id * id is accepted.

Similar questions

Free AppAndroid App

Coursify Android App

Generate AI courses, take quick quizzes between classes, and master complex engineering concepts on the go.