Compiler Design
LR(0) & SLR Parsing / Solved Problem: SLR
SLR Solved Problem: E → BB, B → cB | d
Let us construct the complete SLR(1) parsing table for the following grammar and trace the verification process for the string ccdd:
(0) E' → E (1) E → BB (2) B → cB (3) B → d
- FIRST(E) = { c, d }
- FIRST(B) = { c, d }
- FOLLOW(E) = { $ }
- FOLLOW(B) = { c, d, $ }(Since E → BB, the first B is followed by FIRST(B) = {c, d}, and the second B is at the end of the production, inheriting FOLLOW(E) = {$})
State I0 (Initial State):
E' -> • E E -> • BB B -> • cB B -> • d
Goto(I0, E) = I1 | Goto(I0, B) = I2 | Goto(I0, c) = I3 | Goto(I0, d) = I4
State I1 (Accept State):
E' -> E •
State I2:
E -> B • B B -> • cB B -> • d
Goto(I2, B) = I5 | Goto(I2, c) = I3 | Goto(I2, d) = I4
State I3:
B -> c • B B -> • cB B -> • d
Goto(I3, B) = I6 | Goto(I3, c) = I3 | Goto(I3, d) = I4
State I4 (Reduce State):
B -> d • [r3]
State I5 (Reduce State):
E -> BB • [r1]
State I6 (Reduce State):
B -> cB • [r2]
Note: sN indicates Shift to state N; rN indicates Reduce using production rule N; acc means Accept.
| State | ACTION Table | GOTO Table | |||
|---|---|---|---|---|---|
| c | d | $ | E | B | |
| 0 | s3 | s4 | — | 1 | 2 |
| 1 | — | — | acc | — | — |
| 2 | s3 | s4 | — | — | 5 |
| 3 | s3 | s4 | — | — | 6 |
| 4 | r3 | r3 | r3 | — | — |
| 5 | — | — | r1 | — | — |
| 6 | r2 | r2 | r2 | — | — |
| Step | Stack | Input Buffer | Action |
|---|---|---|---|
| 1 | 0 | c c d d $ | Shift to state 3 (s3) |
| 2 | 0 c 3 | c d d $ | Shift to state 3 (s3) |
| 3 | 0 c 3 c 3 | d d $ | Shift to state 4 (s4) |
| 4 | 0 c 3 c 3 d 4 | d $ | Reduce by B → d (r3). Pop d 4, Goto(3, B) = 6. Push B 6. |
| 5 | 0 c 3 c 3 B 6 | d $ | Reduce by B → cB (r2). Pop c 3 B 6, Goto(3, B) = 6. Push B 6. |
| 6 | 0 c 3 B 6 | d $ | Reduce by B → cB (r2). Pop c 3 B 6, Goto(0, B) = 2. Push B 2. |
| 7 | 0 B 2 | d $ | Shift to state 4 (s4) |
| 8 | 0 B 2 d 4 | $ | Reduce by B → d (r3). Pop d 4, Goto(2, B) = 5. Push B 5. |
| 9 | 0 B 2 B 5 | $ | Reduce by E → BB (r1). Pop B 2 B 5, Goto(0, E) = 1. Push E 1. |
| 10 | 0 E 1 | $ | Accept (acc) |