Sub topic 12
LR(0) Item Sets and SLR(1) Tables
Assume you know context-free grammars, derivations, sets, and stack-based parsing. This chapter develops the working method for constructing LR(0) item sets and an SLR(1) parsing table.
LR(0) items
An LR(0) item records how much of a production the parser has recognized. A dot marks the current position:
C → c · CThis item means that c has been recognized, and the parser expects a C.
For a grammar, first add an augmented start production:
S' → SThe initial item set contains S' → · S. Then repeatedly apply two operations:
closure(I): if an item contains a dot before a nonterminal, add that nonterminal's productions with the dot at the beginning.goto(I, X): move the dot over grammar symbolX, then take the closure of the resulting items.
For example, use this grammar:
S' → S
S → C C
C → c C
C → dThe first item set is:
I0:
S' → · S
S → · C C
C → · c C
C → · dFrom I0, goto(I0, S) produces the accepting state, goto(I0, C) produces items beginning with S → C · C, and the terminal transitions on c and d begin recognition of a C.
The complete collection forms a deterministic automaton:
Building the SLR(1) table
The table has two parts:
- The ACTION part handles terminals with shift, reduce, accept, or error actions.
- The GOTO part handles nonterminals after a reduction.
A completed item such as C → d · suggests reducing by C → d. SLR(1) places this reduction only under terminals in FOLLOW(C), rather than under every terminal.
For this grammar:
FOLLOW(S) = { $ }
FOLLOW(C) = { c, d, $ }Some table entries are:
| State | `c` | `d` | `$` | GOTO `S` | GOTO `C` |
|---|---|---|---|---|---|
| 0 | s3 | s4 | error | 1 | 2 |
| 1 | — | — | accept | — | — |
| 2 | s3 | s4 | error | — | 5 |
| 4 | r(C→d) | r(C→d) | r(C→d) | — | — |
| 5 | — | — | r(S→CC) | — | — |
A conflict occurs when one table cell requires multiple actions. A shift-reduce conflict offers both a shift and a reduction. A reduce-reduce conflict offers two reductions. Either conflict means the grammar is not SLR(1) using that construction.
Exercise
In the grammar above, what action belongs in state 6 under $, where state 6 contains C → c C ·?
Show answer
Reduce by C → c C, because $ belongs to FOLLOW(C).