Sub topic 13
CLR(1) and LALR(1) Parsers
Assume you know LR(0) items, closure, goto, and SLR(1) parsing tables. CLR(1) and LALR(1) parsers improve LR parsing by attaching more precise lookahead information to items.
CLR(1) items
A CLR(1) item has the form:
[A → α · β, a]The dot shows how much of the production has been recognized. The symbol a is a lookahead terminal. It tells the parser when it may reduce using this production.
For example:
[C → d ·, $]means that the parser may reduce C → d only when the next input symbol is $.
The closure rule uses the symbols after the dot. If an item contains:
[A → α · B β, a]then for every production B → γ, add:
[B → · γ, b]for every b in FIRST(βa). This rule gives each item a context-sensitive lookahead instead of using the broader FOLLOW(B) set used by SLR(1).
A CLR(1) state is a set of LR(1) items. The parser computes closure for the initial item and repeatedly applies goto to build the canonical collection.
CLR(1) parsing tables
For each state:
- A transition on a terminal creates a shift action.
- An item
[A → α ·, a]creates a reduce action ona. [S' → S ·, $]creates the accept action.- A transition on a nonterminal enters the
GOTOtable.
Because reductions use item-specific lookaheads, CLR(1) avoids many conflicts that SLR(1) reports.
| Parser | Lookahead information | Typical table size | Relative power |
|---|---|---|---|
| SLR(1) | `FOLLOW` sets | Smaller | Less powerful than LALR(1) |
| CLR(1) | Lookahead on each item | Largest | Most powerful of these |
| LALR(1) | Merged CLR(1) lookaheads | Medium | Between SLR(1) and CLR(1) |
LALR(1) state merging
LALR(1) starts with the CLR(1) collection. It then merges states with the same LR(0) core, where the core is the productions and dot positions without lookaheads.
For example, these states have the same core:
[A → x ·, a]
[A → x ·, b]After merging, the state contains:
[A → x ·, a/b]The merged state is smaller, which makes LALR(1) practical for compiler tools. However, merging can combine lookaheads that belonged to different contexts. This can create a reduce-reduce conflict even when the original CLR(1) parser had no conflict.
CLR(1) recognizes at least as many grammars as LALR(1). LALR(1) usually provides the best compromise between parsing power and table size, while CLR(1) is useful when precise context is more important than memory.
Exercise
What information does a CLR(1) item add to an LR(0) item, and what can happen when CLR(1) states are merged into LALR(1) states?
Show answer
It adds a lookahead terminal that controls reductions. Merging states with the same LR(0) core can combine lookaheads and may introduce a reduce-reduce conflict.