---
title: "Bottom-Up Parsing"
book: "University Computer Science — Year 3"
subject: computer-science
language: en
chapter: 3
exercises: 12
source: https://one-course.com/books/computer-science/5/en/chapter/3-bottom-up-parsing
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 3 — Bottom-Up Parsing

The parser of the last chapter decides which production to use before it has read what the production covers, from one token of lookahead. That is why $E \to E + T$ had to be rewritten and why the full [LL(1) grammar](https://one-course.com/books/computer-science/5/en/chapter/2-top-down-parsing#def-b3-top-down-parsing-ll1) of Moor needed 37 nonterminals. A bottom-up parser waits: it reads tokens onto a stack and decides that a production applies only once it has seen the whole of the production’s right side, and one token after it. The grammars it accepts are a much larger class, [left recursion](https://one-course.com/books/computer-science/5/en/chapter/2-top-down-parsing#def-b3-top-down-parsing-left-recursion) is no trouble, and the decision can be taken by a finite automaton built from the grammar by a program. This chapter builds that automaton and the tables read from it, meets the two conflicts a grammar can cause, and ends with a [parser generator](#def-b3-bottom-up-parsing-generator) of our own that turns a grammar file into a working parser for Moor’s expressions.

## 3.1 Shift and reduce

**You already know.**

FIRST and FOLLOW (chapter [2](https://one-course.com/books/computer-science/5/en/chapter/2-top-down-parsing#ch-b3-top-down-parsing)); the end marker $ follows the start symbol. A deterministic finite automaton reads a word symbol by symbol and is in one state after each; a pushdown automaton adds a stack (Year 2 volume). A rightmost derivation always rewrites the rightmost nonterminal; each sentential form it passes through is a *right sentential form*.

Take the grammar of sums and products in its natural, left-recursive form ([Listing 3.1](#lst-b3-bottom-up-parsing-expr)). A bottom-up parser keeps a stack of grammar symbols and has two moves. It can *shift*: push the next input token. Or it can *reduce*: if the top of the stack is the right side of a production, replace it by the left side. It accepts when the input is used up and the stack holds the start symbol alone.

```text
# expr.grammar -- sums and products, left-recursive
E -> E + T | T
T -> T * F | F
F -> ( E ) | id
```

***Listing 3.1.** Sums and products, left-recursive: a bottom-up parser takes this grammar as it is. The rules are numbered from 1 in reading order; rule 0 will be `Start -> E`. code/bachelor-3/03-bottom-up-parsing/listings/expr.grammar*

On `id + id * id`, the parser shifts the first `id` and reduces it to $F$, then $T$, then $E$. It shifts `+` and `id`, reduces the `id` to $F$ and $T$, and now stops reducing: with `*` next, $E + T$ on the stack must not become $E$, because the $T$ is the left operand of a product. It shifts `*` and `id`, reduces `id` to $F$, $T * F$ to $T$, and only then $E + T$ to $E$. [Output 3.1](#out-b3-bottom-up-parsing-trace) prints the whole run; the first column, a state number, is explained in the next section.

```
$ rustc --edition 2021 -O -o sr_trace sr_trace.rs && ./sr_trace expr.grammar
state symbols        input            action
0                    id + id * id $   shift 5
5     id             + id * id $      reduce F -> id, goto 3
3     F              + id * id $      reduce T -> F, goto 2
2     T              + id * id $      reduce E -> T, goto 1
1     E              + id * id $      shift 6
6     E +            id * id $        shift 5
5     E + id         * id $           reduce F -> id, goto 3
3     E + F          * id $           reduce T -> F, goto 9
9     E + T          * id $           shift 7
7     E + T *        id $             shift 5
5     E + T * id     $                reduce F -> id, goto 10
10    E + T * F      $                reduce T -> T * F, goto 9
9     E + T          $                reduce E -> E + T, goto 1
1     E              $                accept
rules reduced: 6 4 2 6 4 6 3 1
```

***Output 3.1.** The shift–reduce parser on `id + id * id`: the state on top of the stack, the symbols on the stack, the input left, and the move. The last line lists the rules reduced, by number.*

**Definition 3.1 (Shift–reduce parsing, handle).**

*Shift–reduce parsing* reads the input from left to right onto a stack, shifting tokens and reducing right sides of productions at the top of the stack to their left sides. A *handle* of a right sentential form $\gamma$ is a production $A \to \beta$ together with a position of $\beta$ in $\gamma$ such that replacing that $\beta$ by $A$ gives the previous form of a rightmost derivation of $\gamma$.

In $E + T * \mathtt{id}$, the [handle](#def-b3-bottom-up-parsing-shift-reduce) is $F \to \mathtt{id}$ at the last position; $E + T$ is the right side of a production, but it is not a [handle](#def-b3-bottom-up-parsing-shift-reduce) there, because $E * \mathtt{id}$ is not a right sentential form. The whole difficulty of bottom-up parsing is to recognise [handles](#def-b3-bottom-up-parsing-shift-reduce). A correct parser reduces exactly the [handles](#def-b3-bottom-up-parsing-shift-reduce), and so traces a rightmost derivation backwards: the figure below numbers the nodes of the parse tree in the order the parser builds them.

![The parse tree of id + id * id, each interior node numbered by the reduction that built it. Reduction 8 is the first step of the rightmost derivation on the right, reduction 1 its last.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-bottom-up-parsing/fig-c5d7dac7a4d8.svg)

*The parse tree of `id + id * id`, each interior node numbered by the reduction that built it. Reduction 8 is the first step of the rightmost derivation on the right, reduction 1 its last.*

**Proposition 3.2 (Reductions are a reversed rightmost derivation).**

If a shift–reduce parse of $w$ reduces only [handles](#def-b3-bottom-up-parsing-shift-reduce), its reductions, read from last to first, are the steps of a rightmost derivation of $w$.

**Proof.** At every moment the stack $\gamma$ followed by the unread input $x$ is a right sentential form $\gamma x$: true at the start ($\gamma = \varepsilon$, $x = w$), unchanged by a shift, and a reduction of a [handle](#def-b3-bottom-up-parsing-shift-reduce) replaces $\gamma x$ by the previous form of a rightmost derivation of $\gamma x$. The last form is the start symbol, so the forms, read backwards, are a derivation of $w$; each step rewrites the nonterminal that the corresponding reduction created, and since the input to its right is all terminals, it is the rightmost nonterminal. ∎

So a bottom-up parser builds a Rightmost derivation in reverse, reading Left to right: its grammars are the LR grammars. What remains is to know, from the stack and the next token, whether the top of the stack is a [handle](#def-b3-bottom-up-parsing-shift-reduce).

## 3.2 LR(0) items and their automaton

The parser must know, at each moment, which productions it may be in the middle of, and how far in. An item records exactly that.

**Definition 3.3 (LR(0) item, item closure, goto function).**

An *LR(0) item* is a production with a dot in its right side, such as $T \to T \cdot * F$: the part before the dot has been seen, the part after it is expected. The *item closure* of a set of items adds $B \to \cdot\,\delta$ for every production of $B$ whenever some item has its dot before the nonterminal $B$, and repeats until nothing changes. The *goto function* maps a set of items $I$ and a symbol $X$ to the closure of the items $A \to \alpha X \cdot \beta$ for which $A \to \alpha \cdot X \beta$ is in $I$.

Expecting a $B$ means expecting the start of any of $B$’s productions: that is the closure. The [goto function](#def-b3-bottom-up-parsing-items) is the move of a parser that has just seen an $X$, read or reduced. The grammar is first *augmented* with a new start rule $\mathit{Start} \to E$, so that acceptance is the reduction of rule 0. [Listing 3.2](#lst-b3-bottom-up-parsing-items) is both functions; an item is a pair (rule, position of the dot).

```rust
/// Add B -> .gamma for every item with the dot before a nonterminal B,
/// until nothing changes.
pub fn closure(g: &Grammar, items: &State) -> State {
    let mut out = items.clone();
    let mut todo: Vec<Item> = items.iter().copied().collect();
    while let Some(it) = todo.pop() {
        let Some(b) = next_sym(g, it) else { continue };
        for (r, (lhs, _)) in g.rules.iter().enumerate() {
            if lhs == b && out.insert((r, 0)) {
                todo.push((r, 0));
            }
        }
    }
    out
}

/// goto(I, X): move the dot over X in every item of I that allows it.
pub fn goto(g: &Grammar, items: &State, x: &str) -> State {
    let moved: State = items.iter().filter(|&&it| next_sym(g, it).map(|s| s.as_str()) == Some(x))
        .map(|&(r, d)| (r, d + 1)).collect();
    closure(g, &moved)
}
```

***Listing 3.2.** [Item closure](#def-b3-bottom-up-parsing-items) and goto. A state is a sorted set of items, so two states are equal when they hold the same items. code/bachelor-3/03-bottom-up-parsing/listings/lr0.rs*

**Definition 3.4 (Viable prefix, LR(0) automaton).**

An item $A \to \beta \cdot \delta$ is *valid* for a string $\gamma$ of grammar symbols if $\mathit{Start} \Rightarrow^*_{\mathrm{rm}} \alpha A w \Rightarrow_{\mathrm{rm}} \alpha\beta\delta w$ with $\gamma = \alpha\beta$. A *viable prefix* is a string for which some item is valid: a prefix of a right sentential form that does not run past the end of its [handle](#def-b3-bottom-up-parsing-shift-reduce). The *LR(0) automaton* of a grammar has as start state the closure of $\{\mathit{Start} \to \cdot\,S\}$, as states every set reachable from it by the [goto function](#def-b3-bottom-up-parsing-items), and a transition labelled $X$ from $I$ to $\mathrm{goto}(I, X)$ whenever that set is not empty.

[Listing 3.3](#lst-b3-bottom-up-parsing-automaton) discovers the states in order: for each state, the symbols that follow a dot, and for each such symbol the target, new or already known. On the expression grammar it finds 12 states ([Output 3.2](#out-b3-bottom-up-parsing-states)); the figure after it draws them.

```rust
pub fn automaton(g: &Grammar) -> Lr0 {
    let mut a = Lr0 { states: vec![closure(g, &State::from([(0, 0)]))], trans: BTreeMap::new() };
    let mut k = 0;
    while k < a.states.len() {
        let mut syms: Vec<String> = Vec::new();
        for &it in &a.states[k] {
            if let Some(s) = next_sym(g, it) {
                if !syms.contains(s) {
                    syms.push(s.clone());
                }
            }
        }
        for x in syms {
            let target = goto(g, &a.states[k], &x);
            let j = match a.states.iter().position(|s| *s == target) {
                Some(j) => j,
                None => {
                    a.states.push(target);
                    a.states.len() - 1
                }
            };
            a.trans.insert((k, x), j);
        }
        k += 1;
    }
    a
}
```

***Listing 3.3.** The [LR(0) automaton](#def-b3-bottom-up-parsing-automaton): a worklist over the states found so far. code/bachelor-3/03-bottom-up-parsing/listings/lr0.rs*

```
$ rustc --edition 2021 -O -o lr0_states lr0_states.rs && ./lr0_states expr.grammar
I0  Start -> . E           (:4 E:1 F:3 T:2 id:5
    E -> . E + T
    E -> . T
    T -> . T * F
    T -> . F
    F -> . ( E )
    F -> . id
I1  Start -> E .           +:6
    E -> E . + T
I2  E -> T .               *:7
    T -> T . * F
I3  T -> F .               
I4  F -> ( . E )           (:4 E:8 F:3 T:2 id:5
I5  F -> id .              
I6  E -> E + . T           (:4 F:3 T:9 id:5
I7  T -> T * . F           (:4 F:10 id:5
I8  E -> E . + T           ):11 +:6
    F -> ( E . )
I9  E -> E + T .           *:7
    T -> T . * F
I10 T -> T * F .           
I11 F -> ( E ) .           
12 states
```

***Output 3.2.** The [LR(0) automaton](#def-b3-bottom-up-parsing-automaton) of the expression grammar: each state’s items, kernel first, and its transitions as *symbol*:*target*. The closure items of I4, I6 and I7 are left out. Some lines are left out.*

![The LR(0) automaton of the expression grammar. Each box shows the kernel items (those whose dot is not at the start, and the start rule); the closure adds the others, as in I0. The moves that would cross the picture are written in the box as “also” symbol:target. A state with an item whose dot is at the end (I1, I2, I3, I5, I9, I10, I11) may reduce.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-bottom-up-parsing/fig-e6c79cd59992.svg)

*The [LR(0) automaton](#def-b3-bottom-up-parsing-automaton) of the expression grammar. Each box shows the kernel items (those whose dot is not at the start, and the start rule); the closure adds the others, as in I0. The moves that would cross the picture are written in the box as “also” *symbol*:*target*. A state with an item whose dot is at the end (I1, I2, I3, I5, I9, I10, I11) may reduce.*

**Theorem 3.5 (The automaton recognises viable prefixes).**

Let $\gamma$ be a string of grammar symbols. There is a path from the start state labelled $\gamma$ if and only if $\gamma$ is a [viable prefix](#def-b3-bottom-up-parsing-automaton), and the state it reaches holds exactly the items valid for $\gamma$.

**Proof.** We prove that every item of the state reached by a path labelled $\gamma$ is valid for $\gamma$; since a state is never empty, $\gamma$ is then viable. The converse, that every item valid for $\gamma$ is in that state (so every [viable prefix](#def-b3-bottom-up-parsing-automaton) labels a path), is exercise [3.10](#exo-b3-bottom-up-parsing-10). Assume the grammar has no useless nonterminal: each derives some word of terminals.

*Closure keeps validity.* Let $A \to \beta \cdot B\delta$ be valid for $\gamma$: $\mathit{Start} \Rightarrow^*_{\mathrm{rm}} \alpha A w \Rightarrow_{\mathrm{rm}} \alpha\beta B\delta w$ with $\gamma = \alpha\beta$. Let $\delta \Rightarrow^* x$, a word of terminals. Rewriting $\delta$ first keeps the derivation rightmost, since $\delta$ is to the right of $B$: $\alpha\beta B\delta w \Rightarrow^*_{\mathrm{rm}} \alpha\beta B x w \Rightarrow_{\mathrm{rm}} \alpha\beta\eta x w$ for any production $B \to \eta$. So $B \to \cdot\,\eta$ is valid for $\alpha\beta = \gamma$.

*Induction on the length of $\gamma$.* For $\gamma = \varepsilon$ the state is the closure of $\mathit{Start} \to \cdot\,S$, which is valid for $\varepsilon$ by the zero-step derivation. For $\gamma X$, the state reached is $\mathrm{goto}(I, X)$ where $I$ is the state reached by $\gamma$. Its kernel items $A \to \beta X \cdot \delta$ come from items $A \to \beta \cdot X\delta$ of $I$, valid for $\gamma$ by induction, and the same derivation shows $A \to \beta X \cdot \delta$ valid for $\gamma X$. The rest of the state is closure, which keeps validity. ∎

The theorem is what makes bottom-up parsing work. The stack of the parser always holds a [viable prefix](#def-b3-bottom-up-parsing-automaton), so instead of the symbols it can hold the states of the automaton along the path: the state on top summarises the whole stack. If that state has a completed item $A \to \beta\,\cdot$, then $\beta$ is at the top of the stack and the item is valid: reducing it may be right. If it has an item $A \to \beta \cdot a \delta$ and the next token is $a$, shifting may be right. When only one of the two can apply, the automaton has found the [handle](#def-b3-bottom-up-parsing-shift-reduce).

## 3.3 SLR tables

**Definition 3.6 (SLR table, shift–reduce and reduce–reduce conflicts).**

The *SLR table* of a grammar has a row per state of its [LR(0) automaton](#def-b3-bottom-up-parsing-automaton). Its action part has a column per terminal and $: cell $[I, a]$ holds *shift* $J$ if the automaton moves from $I$ to $J$ on $a$, *reduce* $A \to \beta$ if $A \to \beta\,\cdot$ is in $I$ and $a \in \mathrm{FOLLOW}(A)$, and *accept* if $a = \$$ and $\mathit{Start} \to S\,\cdot$ is in $I$. Its goto part has a column per nonterminal, read from the automaton’s moves. A cell with a shift and a reduce is a *shift–reduce conflict*; a cell with two reduces is a *reduce–reduce conflict*. A grammar is SLR if its table has no conflict.

The S stands for Simple: FOLLOW is a crude test of whether a reduction makes sense, but on the expression grammar it is enough. In state I2, $E \to T\,\cdot$ asks for a reduction and $T \to T \cdot * F$ for a shift on `*`; $\mathrm{FOLLOW}(E) = \{+, ), \$\}$ does not contain `*`, so the cell $[2, *]$ holds the shift alone. That is precedence, found by the table and not written by hand: a product binds tighter because the grammar says that $T * F$ is a $T$. [Listing 3.4](#lst-b3-bottom-up-parsing-table) builds the table and [Output 3.3](#out-b3-bottom-up-parsing-table) prints it.

```rust
/// Shift on the automaton's terminal moves; reduce A -> alpha in the
/// columns of FOLLOW(A); accept on $ after Start -> S.
pub fn table(g: &Grammar, a: &Lr0) -> Table {
    let follow = grammar::compute(g).follow;
    let mut t = Table { action: BTreeMap::new(), goto: BTreeMap::new() };
    for ((from, x), &to) in &a.trans {
        if g.is_nt(x) {
            t.goto.insert((*from, x.clone()), to);
        } else {
            t.action.entry((*from, x.clone())).or_default().push(Action::Shift(to));
        }
    }
    for (k, state) in a.states.iter().enumerate() {
        for &(r, d) in state {
            if next_sym(g, (r, d)).is_some() {
                continue;
            }
            if r == 0 {
                t.action.entry((k, "$".into())).or_default().push(Action::Accept);
                continue;
            }
            for x in &follow[&g.rules[r].0] {
                t.action.entry((k, x.clone())).or_default().push(Action::Reduce(r));
            }
        }
    }
    t
}
```

***Listing 3.4.** The [SLR table](#def-b3-bottom-up-parsing-slr): shifts and gotos from the automaton’s moves, reduces from FOLLOW. A cell is a list, so that conflicts are kept and can be reported. code/bachelor-3/03-bottom-up-parsing/listings/slr.rs*

```
$ rustc --edition 2021 -O -o slr_table slr_table.rs && ./slr_table expr.grammar
state id  +   *   (   )   $     | E  T  F  
    0 s5          s4            | 1  2  3  
    1     s6              acc   |          
    2     r2  s7      r2  r2    |          
    3     r4  r4      r4  r4    |          
    4 s5          s4            | 8  2  3  
    5     r6  r6      r6  r6    |          
    6 s5          s4            |    9  3  
    7 s5          s4            |       10 
    8     s6          s11       |          
    9     r1  s7      r1  r1    |          
   10     r3  r3      r3  r3    |          
   11     r5  r5      r5  r5    |          
conflicts: 0
```

***Output 3.3.** The [SLR table](#def-b3-bottom-up-parsing-slr) of the expression grammar: `s5` shifts and goes to state 5, `r2` reduces by rule 2, $E \to T$. No cell has two actions.*

**Method 3.7 (The LR driver).**

Keep a stack of states, initially the start state. Repeat, with $s$ the state on top and $a$ the next token: if $[s, a]$ is shift $j$, push $j$ and advance; if it is reduce $A \to \beta$, pop $|\beta|$ states, then push $\mathrm{goto}[t, A]$ where $t$ is the state now on top; if it is accept, stop; if it is empty, report an error at $a$.

[Listing 3.5](#lst-b3-bottom-up-parsing-driver) is the driver; the symbols are kept beside the states only for the trace. It is the same for every grammar: everything the grammar says is in the table. The driver is a pushdown automaton, as the top-down one was; the difference is in what the stack means. A top-down stack holds what is still expected; a bottom-up stack holds what has been seen.

```rust
        match act {
            Some(Action::Shift(j)) => {
                if trace {
                    println!("shift {j}");
                }
                states.push(j);
                symbols.push(a.to_string());
                i += 1;
            }
            Some(Action::Reduce(r)) => {
                let (lhs, rhs) = &g.rules[r];
                for _ in rhs {
                    states.pop();
                    symbols.pop();
                }
                let top = *states.last().unwrap();
                let j = t.goto[&(top, lhs.clone())];
                if trace {
                    println!("reduce {} -> {}, goto {j}", lhs, rhs.join(" "));
                }
                states.push(j);
                symbols.push(lhs.clone());
                reduced.push(r);
            }
            Some(Action::Accept) => {
                if trace {
                    println!("accept");
                }
                return Ok(reduced);
            }
            None => {
                if trace {
                    println!("error");
                }
                return Err(format!("unexpected {a} in state {s}"));
            }
        }
```

***Listing 3.5.** The heart of the driver: one match on the action. The reduction pops one state per symbol of the right side and takes the goto from the state uncovered. code/bachelor-3/03-bottom-up-parsing/listings/slr.rs*

An LR parser detects an error as early as a left-to-right parser can: it never shifts a token that cannot continue a [viable prefix](#def-b3-bottom-up-parsing-automaton), since a shift follows a move of the automaton and every path spells a [viable prefix](#def-b3-bottom-up-parsing-automaton) ([Theorem 3.5](#thm-b3-bottom-up-parsing-viable)). It may still perform a few reductions before the error is found, because FOLLOW lets it reduce on a token that cannot, in this context, follow. Exercise [3.9](#exo-b3-bottom-up-parsing-9) watches it happen.

## 3.4 Conflicts and their resolution

### 3.4.1 The dangling else

[Listing 3.6](#lst-b3-bottom-up-parsing-ifelse) is the oldest conflict in the trade. In `if c then if c then other else other`, the `else` may belong to either `if`: the grammar is ambiguous.

```text
# ifelse.grammar -- the dangling else
S -> if c then S | if c then S else S | other
```

***Listing 3.6.** An `if` with an optional `else`, and no braces: the dangling else. code/bachelor-3/03-bottom-up-parsing/listings/ifelse.grammar*

The [SLR table](#def-b3-bottom-up-parsing-slr) has one conflict (the figure below). In state I6 the parser has read `if c then S`: it may reduce the `if` without an `else`, since $\mathrm{else} \in \mathrm{FOLLOW}(S)$, or shift the `else` and give it to this `if`. Every language with this syntax resolves it the same way: the `else` goes to the nearest `if`, which is the shift. An ambiguous grammar is never LR, so no table construction can do better; a [parser generator](#def-b3-bottom-up-parsing-generator) reports the conflict and, unless told otherwise, shifts. Our driver takes the first action of a cell, which is the shift, and so behaves the same. Moor has no such conflict: its `if` and `else` take blocks in braces, and the closing brace says where the inner statement ends.

![The SLR table of the if grammar: rule 1 is the if without else, rule 2 the one with it, rule 3 S -> other. FOLLOW(S) = \ else, \$\, so in state 6 the reduction of rule 1 lands on the else column, where the automaton also shifts.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-bottom-up-parsing/fig-e48adc8f60be.svg)

*The [SLR table](#def-b3-bottom-up-parsing-slr) of the `if` grammar: rule 1 is the `if` without `else`, rule 2 the one with it, rule 3 `S -> other`. $\mathrm{FOLLOW}(S) = \{\mathrm{else}, \$\}$, so in state 6 the reduction of rule 1 lands on the `else` column, where the automaton also shifts.*

### 3.4.2 Precedence declarations

Grammar writers use the same trick on purpose. The grammar $E \to E + E \mid E * E \mid (\,E\,) \mid \mathit{id}$ is ambiguous and its table full of conflicts, but each conflict opposes a production, say $E \to E + E\,\cdot$, to a token, say `*`. Give operators precedences and associativities: then shift if the token binds tighter than the production’s last operator, reduce if it binds less tightly, and on a tie reduce for a left-associative operator and shift for a right-associative one. The table of a short, flat grammar then parses as the layered one does. Exercise [3.6](#exo-b3-bottom-up-parsing-6) implements the rule; [parser generators](#def-b3-bottom-up-parsing-generator) take it as declarations such as `%left PLUS MINUS`, one line per level, loosest first.

### 3.4.3 A grammar SLR cannot do

[Listing 3.7](#lst-b3-bottom-up-parsing-lr) is a small model of assignments through pointers, in the style of C: a left side $L$ is a name or a dereferenced value, a right side $R$ is any left side, read.

```text
# lr.grammar -- assignments through pointers: SLR cannot
S -> L = R | R
L -> * R | id
R -> L
```

***Listing 3.7.** Assignments through pointers. The grammar is not ambiguous, yet it is not SLR. code/bachelor-3/03-bottom-up-parsing/listings/lr.grammar*

After reading an $L$ at the start, the parser is in a state with $S \to L \cdot = R$ and $R \to L\,\cdot$. The equals sign is in $\mathrm{FOLLOW}(R)$, because of $L \to * R$ and $S \to L = R$: in `*x = y`, the $R$ under the star is followed by `=`. So SLR puts a reduction in the `=` column next to the shift ([Output 3.4](#out-b3-bottom-up-parsing-conflicts)). Yet no right sentential form starts with $R =$: reducing there is never right. FOLLOW is a property of the nonterminal everywhere in the grammar; what the parser needs is the set of tokens that can follow *in this state*. Items that carry that set are the cure.

**Definition 3.8 (LR(1) item, LALR table).**

An *LR(1) item* $[A \to \beta \cdot \delta,\ a]$ is an [LR(0) item](#def-b3-bottom-up-parsing-items) with a look-ahead terminal $a$: the item is valid for $\gamma$ if $\mathit{Start} \Rightarrow^*_{\mathrm{rm}} \alpha A w \Rightarrow_{\mathrm{rm}} \alpha\beta\delta w$ with $\gamma = \alpha\beta$ and $w$ starting with $a$ (or $a = \$$ if $w$ is empty). The closure adds $[B \to \cdot\,\eta,\ b]$ for every $b \in \mathrm{FIRST}(\delta' a)$ when an item $[A \to \beta \cdot B\delta',\ a]$ is present; the canonical LR(1) automaton is built from these items as the LR(0) one is, and a reduction by $[A \to \beta\,\cdot,\ a]$ goes in column $a$ only. The *core* of a set of LR(1) items is the set of their [LR(0) items](#def-b3-bottom-up-parsing-items). The *LALR table* is built from the LR(1) automaton by merging the states with the same core, taking the union of their look-aheads.

```rust
pub fn closure1(g: &Grammar, sets: &Sets, items: &State1) -> State1 {
    let mut out = items.clone();
    let mut todo: Vec<Item1> = items.iter().cloned().collect();
    while let Some((r, d, a)) = todo.pop() {
        let Some(b) = next_sym(g, (r, d)) else { continue };
        if !g.is_nt(b) {
            continue;
        }
        let (mut look, nullable) = sets.first_seq(g, &g.rules[r].1[d + 1..]);
        if nullable {
            look.insert(a.clone());
        }
        for (r2, _) in g.rules.iter().enumerate().filter(|(_, (l, _))| l == b) {
            for x in &look {
                let it = (r2, 0, x.clone());
                if out.insert(it.clone()) {
                    todo.push(it);
                }
            }
        }
    }
    out
}
```

***Listing 3.8.** The closure of [LR(1) items](#def-b3-bottom-up-parsing-lr1): the look-ahead of a new item is FIRST of what follows $B$, and the old look-ahead too if all of that is [nullable](https://one-course.com/books/computer-science/5/en/chapter/2-top-down-parsing#def-b3-top-down-parsing-first-follow). code/bachelor-3/03-bottom-up-parsing/listings/lr1.rs*

With look-aheads, the state reached on $L$ from the start holds $[S \to L \cdot = R,\ \$]$ and $[R \to L\,\cdot,\ \$]$: reduce on $, shift on `=`, no conflict. The price is the number of states. A state of the LR(1) automaton is an LR(0) state with look-aheads, and the same LR(0) state may appear with different look-aheads: for this grammar, 14 states instead of 10 ([Output 3.4](#out-b3-bottom-up-parsing-conflicts)); for a real language, ten times more is common. LALR merges them back. It has exactly the states of the [LR(0) automaton](#def-b3-bottom-up-parsing-automaton), so its tables are as small as SLR’s, and look-aheads nearly as sharp as LR(1)’s; the figure below shows the four merges for this grammar.

```rust
/// LALR: one state per distinct core, with the union of the look-aheads.
pub fn lalr(a: &Lr1) -> Lr1 {
    let mut cores: Vec<BTreeSet<(usize, usize)>> = Vec::new();
    let mut map = Vec::new(); // LR(1) state -> LALR state
    for s in &a.states {
        let c = core(s);
        let j = cores.iter().position(|x| *x == c).unwrap_or_else(|| {
            cores.push(c);
            cores.len() - 1
        });
        map.push(j);
    }
    let mut states = vec![State1::new(); cores.len()];
    for (k, s) in a.states.iter().enumerate() {
        states[map[k]].extend(s.iter().cloned());
    }
    let trans = a.trans.iter().map(|((k, x), j)| ((map[*k], x.clone()), map[*j])).collect();
    Lr1 { states, trans }
}
```

***Listing 3.9.** LALR by merging: one state per distinct core, with the union of the items, and the transitions mapped. code/bachelor-3/03-bottom-up-parsing/listings/lr1.rs*

```
$ rustc --edition 2021 -O -o conflicts conflicts.rs && ./conflicts ifelse.grammar lr.grammar expr.grammar
== ifelse.grammar: 9 LR(0) states
  SLR conflict in state 6 on else: shift 7 / reduce by S -> if c then S
  LR(1): 16 states, conflicting cells 1; LALR: 9 states, conflicting cells 1
== lr.grammar: 10 LR(0) states
  SLR conflict in state 2 on =: shift 6 / reduce by R -> L
  LR(1): 14 states, conflicting cells 0; LALR: 10 states, conflicting cells 0
== expr.grammar: 12 LR(0) states
  LR(1): 22 states, conflicting cells 0; LALR: 12 states, conflicting cells 0
```

***Output 3.4.** Three grammars under SLR, LR(1) and LALR. The `if` grammar keeps its conflict whatever the method; the assignment grammar loses it under both LR(1) and LALR.*

![The four pairs of LR(1) states of the assignment grammar that share a core (each box shows the item that names the state; the states of L -> * . R also hold closure items). Reached through the left side, before =, the look-aheads are = and $; after =, only $. Merging takes the union and creates no conflict: 14 LR(1) states become 10.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-bottom-up-parsing/fig-0390cb5a0922.svg)

*The four pairs of LR(1) states of the assignment grammar that share a core (each box shows the item that names the state; the states of `L -> * . R` also hold closure items). Reached through the left side, before `=`, the look-aheads are `=` and $; after `=`, only $. Merging takes the union and creates no conflict: 14 LR(1) states become 10.*

The weekend problem works through both grammars by hand, and shows that merging can never create a [shift–reduce conflict](#def-b3-bottom-up-parsing-slr) that the LR(1) table did not have. It can create a [reduce–reduce conflict](#def-b3-bottom-up-parsing-slr), but such grammars are rare; the bison run of the next section shows a generator whose default tables have as many states as the [LR(0) automaton](#def-b3-bottom-up-parsing-automaton), plus one for the end marker, with no conflict on the assignment grammar.

## 3.5 Parser generators

**Definition 3.9 (Parser generator).**

A *parser generator* is a program that takes a grammar, usually with precedence declarations and with an action to run at each reduction, and writes the source of a parser for it: the tables and a fixed driver. It reports every conflict it could not resolve.

Bison is a [parser generator](#def-b3-bottom-up-parsing-generator) of the GNU project, as its version line says. [Listing 3.10](#lst-b3-bottom-up-parsing-bison) is the `if` grammar in that format, without actions; the part between the two `%%` lines is the grammar, one rule per nonterminal, alternatives after `|`. [Output 3.5](#out-b3-bottom-up-parsing-bison) runs bison on it and on the assignment grammar.

```text
%token IF C THEN ELSE OTHER
%%
s : IF C THEN s
  | IF C THEN s ELSE s
  | OTHER
  ;
%%
```

***Listing 3.10.** The `if` grammar for bison. Tokens are declared; lower-case names are nonterminals. code/bachelor-3/03-bottom-up-parsing/listings/ifelse.y*

```
$ bison --version | head -n 1
bison (GNU Bison) 3.8.2
$ bison -o ifelse.c ifelse.y
ifelse.y: warning: 1 shift/reduce conflict [-Wconflicts-sr]
ifelse.y: note: rerun with option '-Wcounterexamples' to generate conflict counterexamples
$ wc -l ifelse.c
1284 ifelse.c
$ bison --report=state -o lr.c lr.y
$ grep -c '^State' lr.output
11
$ bison -D lr.type=canonical-lr --report=state -o lr.c lr.y
$ grep -c '^State' lr.output
15
```

***Output 3.5.** Bison on the two grammars: one [shift–reduce conflict](#def-b3-bottom-up-parsing-slr) for the dangling else, none for the assignment grammar. The state counts are those of `lr.output`, bison’s report, built first with its default construction and then with canonical LR(1).*

**Facts as of 2026.**

Bison 3.8.2, run on the author’s laptop. Bison resolved the dangling else by shifting and warned once. It accepted the assignment grammar, which an SLR generator would refuse, and its report has 11 states; asked for canonical LR(1) tables it has 15. Both are one more than our counts, 10 and 14: bison’s augmented rule is $\mathit{\$accept} \to s\ \mathit{\$end}$, and shifting the end marker takes one more state.

The generated C file is over a thousand lines: tables compressed into arrays, the driver, and error recovery. Our own generator is smaller. It reads a grammar in the format of chapter [2](https://one-course.com/books/computer-science/5/en/chapter/2-top-down-parsing#ch-b3-top-down-parsing), refuses it if the [SLR table](#def-b3-bottom-up-parsing-slr) has a conflict, and otherwise prints the tables as Rust constants, with 0 for an error, $k > 0$ for a shift to state $k - 1$ and $k < 0$ for a reduction by rule $-k - 1$. [Listing 3.11](#lst-b3-bottom-up-parsing-moorgram) is the whole of Moor’s expressions, one nonterminal per level, written as the grammar of a language manual would write them, [left recursion](https://one-course.com/books/computer-science/5/en/chapter/2-top-down-parsing#def-b3-top-down-parsing-left-recursion) included.

```text
# moor_expr.grammar -- Moor's expressions, one nonterminal per level
E    -> E || A | A
A    -> A && Q | Q
Q    -> Q == C | Q != C | C
C    -> C < S | C <= S | C > S | C >= S | S
S    -> S + M | S - M | M
M    -> M * U | M / U | M % U | U
U    -> - U | ! U | P
P    -> num | true | false | name | ( E )
| name ( ) | name ( Args ) | name [ E ]
Args -> E | Args , E
```

***Listing 3.11.** Moor’s expressions for the generator: eight levels, calls with zero or more arguments, and array indexing. code/bachelor-3/03-bottom-up-parsing/listings/moor_expr.grammar*

```
$ rustc --edition 2021 -O -o lrgen lrgen.rs && ./lrgen moor_expr.grammar
// Generated by lrgen from moor_expr.grammar: 56 states. Do not edit.
pub const NONTERMS: &[&str] = &["Start", "E", "A", "Q", "C", "S", "M", "U", "P", "Args"];
pub const RULES: &[(&str, &[&str])] = &[
    ("Start", &["E"]),
    ("E", &["E", "||", "A"]),
    ("E", &["A"]),
pub const ACTION: &[[i16; 24]] = &[
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 10, 12, 13, 14, 15, 16, 0, 0, 0, 0, 0],
    [17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ACCEPT],
    [-3, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -3, 0, -3, -3, -3],
```

***Output 3.6.** The beginning of the generated file: 56 states, the rules as data, and the first rows of the action table. Some lines are left out.*

The generated file is saved as `moor_expr_tables.rs` (a test checks that it is exactly the generator’s output). [Listing 3.12](#lst-b3-bottom-up-parsing-lrmoor) is the driver of [Method 3.7](#met-b3-bottom-up-parsing-driver) on those arrays, fed by the [scanner](https://one-course.com/books/computer-science/5/en/chapter/1-lexical-analysis#def-b3-lexical-analysis-scanner) of chapter [1](https://one-course.com/books/computer-science/5/en/chapter/1-lexical-analysis#ch-b3-lexical-analysis). Beside each state it keeps a value: the text of a token when it is shifted, and when a rule is reduced, the tree that `build` makes from the values of the right side. That function is the place where a generator user writes actions; here it builds the S-expression of chapter [2](https://one-course.com/books/computer-science/5/en/chapter/2-top-down-parsing#ch-b3-top-down-parsing)’s trees.

```rust
fn parse(src: &str) -> Result<String, String> {
    let toks = lexer::lex(src).map_err(|e| e.msg)?;
    let (mut states, mut values, mut i) = (vec![0usize], Vec::<String>::new(), 0);
    loop {
        let (term, text) = terminal(&toks[i].kind);
        let col = TERMINALS.iter().position(|t| *t == term).ok_or("not an expression token")?;
        let act = ACTION[*states.last().unwrap()][col];
        if act == ACCEPT {
            return Ok(values.pop().unwrap());
        } else if act > 0 {
            states.push(act as usize - 1);
            values.push(text);
            i += 1;
        } else if act < 0 {
            let (lhs, rhs) = RULES[(-act - 1) as usize];
            let v = values.split_off(values.len() - rhs.len());
            states.truncate(states.len() - rhs.len());
            values.push(build(rhs, v));
            let nt = NONTERMS.iter().position(|n| *n == lhs).unwrap();
            states.push(GOTO[*states.last().unwrap()][nt] as usize);
        } else {
            let (kind, col) = (&toks[i].kind, toks[i].span.col);
            return Err(format!("unexpected {} at column {col}", parser::spell(kind)));
        }
    }
}
```

***Listing 3.12.** An LR parser for Moor’s expressions on the generated tables, with a value stack beside the state stack. code/bachelor-3/03-bottom-up-parsing/listings/lr_moor.rs*

```
$ rustc --edition 2021 -O -o lr_moor lr_moor.rs && ./lr_moor
1 - 2 - 3 * 4              (- (- 1 2) (* 3 4))  [same]
-x * y % 2                 (% (* (neg x) y) 2)  [same]
!p && q || r               (|| (&& (! p) q) r)  [same]
a < b == c < d             (== (< a b) (< c d))  [same]
f(x, g(y) + 1, a[i - 1])   (call f x (+ (call g y) 1) (index a (- i 1)))  [same]
(1 + 2) * 3                (* (+ 1 2) 3)  [same]
a + * b                    error: unexpected '*' at column 5  [same]
```

***Output 3.7.** The generated parser and the hand-written [precedence climbing](https://one-course.com/books/computer-science/5/en/chapter/2-top-down-parsing#def-b3-top-down-parsing-precedence) of chapter [2](https://one-course.com/books/computer-science/5/en/chapter/2-top-down-parsing#ch-b3-top-down-parsing) build the same trees, and reject the same input.*

The two parsers agree on every test expression. One was written by hand from [binding powers](https://one-course.com/books/computer-science/5/en/chapter/2-top-down-parsing#def-b3-top-down-parsing-precedence), the other generated from a grammar a reader can check line by line against the language’s definition. The generator has also proved something: the grammar has no conflict, so it is unambiguous (exercise [3.8](#exo-b3-bottom-up-parsing-8)).

**In practice — Hand-written or generated.**

Both kinds of parser are in daily use. A generated parser follows its grammar exactly and makes grammar changes cheap; a hand-written recursive-descent parser makes it easy to give good error messages and to handle the odd corner of a real language. A common compromise keeps a grammar file under test, as this chapter does, and checks with a generator that it stays conflict-free, whatever parser the compiler ships.

**History — LR parsing.**

Donald Knuth defined the LR($k$) grammars and their parsers in “On the translation of languages from left to right”, published in December 1965. Frank DeRemer’s “Simple LR($k$) grammars”, published in July 1971, gave the [SLR tables](#def-b3-bottom-up-parsing-slr) of this chapter, built on the states of the [LR(0) automaton](#def-b3-bottom-up-parsing-automaton) and so much smaller than Knuth’s.

## 3.6 Exercises

**Exercise 3.1 ★.**

Compute the [item closure](#def-b3-bottom-up-parsing-items) of $\{F \to (\,\cdot\,E\,)\}$ in the expression grammar. Which state of [Output 3.2](#out-b3-bottom-up-parsing-states) is it?

**Solution of Exercise 3.1.**

The dot is before $E$, so the closure adds $E \to \cdot\,E + T$ and $E \to \cdot\,T$; the dot is now also before $T$, which adds $T \to \cdot\,T * F$ and $T \to \cdot\,F$; then $F$ adds $F \to \cdot\,(\,E\,)$ and $F \to \cdot\,\mathtt{id}$. With the kernel, 7 items: this is state I4, the state after `(` (`exercise_1_closure` in `tests/lr_test.rs`).

**Exercise 3.2 ★.**

The parser of [Output 3.3](#out-b3-bottom-up-parsing-table) reads `( id ) * id`. Its state stack is 0 4 8 and the next token is `)`. Give its next three actions, and the rules it reduces over the whole parse.

**Solution of Exercise 3.2.**

In state 8 on `)`: shift 11. In state 11 on `*`: reduce $F \to (\,E\,)$, popping three states back to 0, and $\mathrm{goto}[0, F] = 3$. In state 3 on `*`: reduce $T \to F$, goto 2. The parse then shifts `*` and `id` and reduces $F \to \mathtt{id}$, $T \to T * F$ and $E \to T$. Over the whole parse the rules reduced are 6, 4, 2, 5, 4, 6, 3, 2, and the parser accepts (`a_rightmost_derivation_in_reverse`).

**Exercise 3.3 ★.**

Find the [handle](#def-b3-bottom-up-parsing-shift-reduce) of each right sentential form of the expression grammar: $E + T * F$; $T * F + \mathtt{id}$; $E + F * \mathtt{id}$.

**Solution of Exercise 3.3.**

In $E + T * F$, the [handle](#def-b3-bottom-up-parsing-shift-reduce) is $T \to T * F$ on $T * F$ (positions 3 to 5): the previous form is $E + T$. In $T * F + \mathtt{id}$, it is $T \to T * F$ again, on the first three symbols; the `id` on the right is reduced later, which is what “rightmost derivation in reverse” means. In $E + F * \mathtt{id}$, it is $T \to F$ on the $F$: the previous form is $E + T * \mathtt{id}$. The first and third forms are lines of [Output 3.1](#out-b3-bottom-up-parsing-trace); the test checks the order of reductions on `id * id + id`.

**Exercise 3.4 ★.**

Classify each state as having a [shift–reduce conflict](#def-b3-bottom-up-parsing-slr), a [reduce–reduce conflict](#def-b3-bottom-up-parsing-slr) or none under SLR, on the token given: (a) $\{A \to z\,\cdot,\ B \to z\,\cdot\}$ with $\mathrm{FOLLOW}(A) = \{c\}$, $\mathrm{FOLLOW}(B) = \{c, d\}$; (b) $\{S \to L \cdot = R,\ R \to L\,\cdot\}$ with $= \in \mathrm{FOLLOW}(R)$; (c) $\{\mathit{Start} \to E\,\cdot,\ E \to E \cdot + T\}$.

**Solution of Exercise 3.4.**

(a) On `c` both reductions apply: a [reduce–reduce conflict](#def-b3-bottom-up-parsing-slr); on `d` only $B \to z$, no conflict. (b) On `=` the state shifts and, since $= \in \mathrm{FOLLOW}(R)$, also reduces by $R \to L$: a [shift–reduce conflict](#def-b3-bottom-up-parsing-slr). (c) No conflict: the completed start item gives accept on $ only, and the other item shifts on `+`.

**Exercise 3.5 ★★.**

[Listing 3.13](#lst-b3-bottom-up-parsing-kernel) builds the [LR(0) automaton](#def-b3-bottom-up-parsing-automaton) with a different goto. It finds 12 states on the expression grammar, as it should, yet two of the three parses in [Output 3.8](#out-b3-bottom-up-parsing-kernel) fail. Find the bug, say which states are wrong and why the first parse still succeeds, and fix it.

```rust
fn goto(g: &grammar::Grammar, items: &State, x: &str) -> State {
    items.iter().filter(|&&it| next_sym(g, it).map(|s| s.as_str()) == Some(x))
        .map(|&(r, d)| (r, d + 1)).collect()
}
```

***Listing 3.13.** The [goto function](#def-b3-bottom-up-parsing-items) of `kernel_bug.rs`. code/bachelor-3/03-bottom-up-parsing/listings/kernel_bug.rs*

```
$ rustc --edition 2021 -O -o kernel_bug kernel_bug.rs && ./kernel_bug expr.grammar
12 states
id $           Ok([6, 4, 2])
id + id $      Err("unexpected id in state 6")
id * id $      Err("unexpected id in state 7")
```

***Output 3.8.** Its three parses; `Ok` lists the rules reduced.*

**Solution of Exercise 3.5.**

The goto moves the dot but does not take the closure. Only the start state is closed (the automaton builds it with `closure`); every other state holds only its kernel. The state after `+` is $\{E \to E + \cdot\,T\}$: it has no item with the dot before `id`, so the table has no shift there, and the parse of `id + id` fails in state 6; likewise after `*` in state 7. The 12 states are not the right 12: for instance the target of $T$ from state 6 is $\{E \to E + T\,\cdot\}$ alone, without $T \to T \cdot * F$, so even with the shift a sum followed by a product would fail. The parse of `id` succeeds because it only passes through the start state, which is closed, and through states whose single item is complete. The fix is `closure(g, &moved)` as the last line of goto, which is [Listing 3.2](#lst-b3-bottom-up-parsing-items); `exercise_5_goto_needs_the_closure` checks that the goto from state 1 on `+` is then the 5-item state 6.

**Exercise 3.6 ★★.**

Write `table(g, prec)` for the file `exercises/ex6_prec.rs`: the [SLR table](#def-b3-bottom-up-parsing-slr) in which every [shift–reduce conflict](#def-b3-bottom-up-parsing-slr) between a production and a token that both have a precedence is resolved by the rule of [Section 3.4](#sec-3-4); a production’s precedence is that of its last terminal, and a tie on a non-associative operator leaves the cell empty, an error. Check it on `exercises/ambig.grammar` with `==` non-associative, `+` and `-` left, `*` left, and `^` right, from loosest to tightest. How many conflicts does the plain [SLR table](#def-b3-bottom-up-parsing-slr) have?

**Solution of Exercise 3.6.**

`exercises/ex6_prec.rs`. For each cell holding a shift and a reduce by rule $r$, take the precedence $p_t$ of the token and $p_r$ of the rule’s last terminal; if either has none, keep the conflict. If $p_t > p_r$, or they are equal and the operator is right-associative, keep the shift; if $p_t < p_r$, or they are equal and left-associative, keep the reduce; if they are equal and non-associative, empty the cell. The plain [SLR table](#def-b3-bottom-up-parsing-slr) of `ambig.grammar` has 25 conflicting cells (every state $E \to E\,\mathit{op}\,E\,\cdot$ meets every operator token); after resolution, none. The tests check `id + id * id` $\mapsto$ `(+ id (* id id))`, `id - id - id` $\mapsto$ `(- (- id id) id)`, `id ^ id ^ id` $\mapsto$ `(^ id (^ id id))`, a parenthesised operand, and that `id == id == id` is refused at the second `==`.

**Exercise 3.7 ★★.**

Build by hand the [LR(0) automaton](#def-b3-bottom-up-parsing-automaton) of $S \to (\,S\,)\,S \mid \varepsilon$. How many states has it, and is the grammar SLR? What does a completed item $S \to \cdot$ mean?

**Solution of Exercise 3.7.**

Six states. I0 $= \{\mathit{Start} \to \cdot\,S,\ S \to \cdot\,(\,S\,)\,S,\ S \to \cdot\}$; on $S$, I1 $= \{\mathit{Start} \to S\,\cdot\}$; on `(`, I2 $= \{S \to (\,\cdot\,S\,)\,S\}$ plus the two items of $S$; on $S$ from I2, I3 $= \{S \to (\,S\,\cdot\,)\,S\}$; on `)`, I4 $= \{S \to (\,S\,)\,\cdot\,S\}$ plus the two items of $S$; on $S$ from I4, I5 $= \{S \to (\,S\,)\,S\,\cdot\}$. From I2 and I4, `(` leads back to I2. $\mathrm{FOLLOW}(S) = \{), \$\}$ and the only shift in I0, I2 and I4 is on `(`, so the grammar is SLR (`exercise_7_parentheses`). The item $S \to \cdot$ is complete without having read anything: the parser reduces an empty $S$, pushing a nonterminal that covers no input, whenever the next token is `)` or $, that is, wherever a balanced word may end.

**Exercise 3.8 ★★.**

Prove that every SLR grammar is unambiguous.

**Solution of Exercise 3.8.**

Let $G$ be SLR and $w \in L(G)$. Take any rightmost derivation of $w$; we show that the SLR parser follows it in reverse, so that it is determined by the parser’s run, which is unique since each cell holds at most one action. Suppose the parser has followed it so far: its stack holds $\gamma$, the input left is $x$, and $\gamma x$ is a form of the derivation. If the derivation’s [handle](#def-b3-bottom-up-parsing-shift-reduce) ends inside $\gamma$, it ends at its top (everything to its right is terminal and still unread), so it is $A \to \beta$ with $\gamma = \alpha\beta$, and $A \to \beta\,\cdot$ is valid for $\gamma$; by [Theorem 3.5](#thm-b3-bottom-up-parsing-viable) it is in the state on top, and the next token $a$ (or $) follows $A$ in the previous form, so $a \in \mathrm{FOLLOW}(A)$: the table says reduce by this production. Otherwise the [handle](#def-b3-bottom-up-parsing-shift-reduce) ends to the right of $\gamma$, so $\gamma a$ is still a [viable prefix](#def-b3-bottom-up-parsing-automaton); by the theorem there is a move on $a$ from the top state, and the table says shift. So two different rightmost derivations of $w$ would make the parser take two different actions in the same configuration, which cannot happen. Hence $w$ has one rightmost derivation, and one parse tree.

**Exercise 3.9 ★★.**

Trace the SLR parser of the expression grammar on `id + * id` and on `( id + id`. Where is each error found, and which reductions happen before it on the second input?

**Solution of Exercise 3.9.**

On `id + * id`: shift 5, reduce $F \to \mathtt{id}$, $T \to F$, $E \to T$, shift `+` to state 6, and in state 6 there is no action on `*`: the error is found at the `*`, the first token that cannot continue a [viable prefix](#def-b3-bottom-up-parsing-automaton). On `( id + id`: the parser shifts `(`, reduces the first `id` to $E$, shifts `+` and `id`, and on $ reduces $F \to \mathtt{id}$, $T \to F$ and $E \to E + T$, ending in state 8, where $ has no action. The three last reductions take place on $ because $ is in the [FOLLOW sets](https://one-course.com/books/computer-science/5/en/chapter/2-top-down-parsing#def-b3-top-down-parsing-first-follow) of $F$, $T$ and $E$; they are correct reductions (in any completion of the input they would also happen), so the error is still found at the first token, $, where the missing `)` could have been. The tests assert both messages.

**Exercise 3.10 ★★★.**

Prove the other half of [Theorem 3.5](#thm-b3-bottom-up-parsing-viable): if an item is valid for $\gamma$, then there is a path labelled $\gamma$ from the start state and its last state holds the item. (Induct on the length of the rightmost derivation that makes the item valid.)

**Solution of Exercise 3.10.**

Let $A \to \beta \cdot \delta$ be valid for $\gamma = \alpha\beta$ through $\mathit{Start} \Rightarrow^n_{\mathrm{rm}} \alpha A w \Rightarrow_{\mathrm{rm}} \alpha\beta\delta w$. We show by induction on $n$ that the path labelled $\alpha$ exists and ends in a state holding $A \to \cdot\,\beta\delta$. Then the moves on the symbols of $\beta$ exist, since each state on the way holds the item with the dot before the next symbol, and goto carries the item along: the path labelled $\gamma$ ends in a state holding $A \to \beta \cdot \delta$. If $n = 0$, then $A = \mathit{Start}$, $\alpha = \varepsilon$, and $\mathit{Start} \to \cdot\,S$ is in the start state. If $n > 0$, the occurrence of $A$ was created by some earlier step $\mathit{Start} \Rightarrow^m_{\mathrm{rm}} \alpha' B w' \Rightarrow_{\mathrm{rm}} \alpha'\eta A \theta w'$, with $m < n$, $\alpha = \alpha'\eta$, and $\theta \Rightarrow^* x$ with $w = x w'$ (the steps in between rewrite only what is right of $A$, since the derivation is rightmost and $A$ is still there). So $B \to \eta \cdot A\theta$ is valid for $\alpha'\eta = \alpha$ through a derivation of length $m$, and by induction the path labelled $\alpha$ ends in a state holding it, hence, by closure, holding $A \to \cdot\,\beta\delta$.

**Exercise 3.11 ★★★.**

Let $G_n$ have terminals $a_1, \dots, a_n$ and the productions $S \to X_i$, $X_i \to a_i$ and $X_i \to a_j X_i$ for every $i$ and every $j \ne i$. It has $n^2 + n$ productions. Show that its [LR(0) automaton](#def-b3-bottom-up-parsing-automaton) has $n\,2^n + n^2 - n + 2$ states. (`exercises/ex11_family.rs` writes $G_n$.)

**Solution of Exercise 3.11.**

After the start state reads a nonempty word $u$ of $a$’s, call *alive* the indices $i$ that do not occur in $u$ before its last letter: only for them is an item $X_i \to \dots$ still in progress, since reading $a_i$ ends $X_i$ (there is no $X_i \to a_i X_i$). If the last letter is $a_j$, the kernel is $\{X_i \to a_j \cdot X_i : i \text{ alive}, i \ne j\}$, plus $X_j \to a_j\,\cdot$ if $j$ is alive. Every set $A$ of alive indices occurs (read each letter outside $A$ once, then $a_j$), and for a fixed $j$ the kernel determines $A$; it is empty only for $A = \emptyset$, which gives no state. So there are $2^n - 1$ states per letter $j$, $n(2^n - 1)$ in all. Add the start state, $\{\mathit{Start} \to S\,\cdot\}$, the $n$ states $\{S \to X_i\,\cdot\}$, and the $n(n-1)$ states $\{X_i \to a_j X_i\,\cdot\}$: $n\,2^n - n + 2 + n + n^2 - n = n\,2^n + n^2 - n + 2$. The test checks the formula for $n = 1$ to 7 (4, 12, 32, 78, 182, 416, 940 states) against grammars of $n^2 + n$ productions: the automaton is exponential in the size of the grammar.

**Exercise 3.12 ★★★.**

LALR look-aheads can be computed on the [LR(0) automaton](#def-b3-bottom-up-parsing-automaton) without building the LR(1) one: start with $ on $\mathit{Start} \to \cdot\,S$ in the start state, and propagate, along each transition and into each closure, until nothing changes. Write this propagation and check that it gives, state by state, the look-aheads of [Listing 3.9](#lst-b3-bottom-up-parsing-lalr). Why is it cheaper?

**Solution of Exercise 3.12.**

`exercises/ex12_lalr_prop.rs`. Give each item of each LR(0) state an empty set, and $ to $\mathit{Start} \to \cdot\,S$ in the start state. Repeat until no set grows: for each item $A \to \beta \cdot X \delta$ with set $L$ in state $I$, add $L$ to the set of $A \to \beta X \cdot \delta$ in $\mathrm{goto}(I, X)$; and if $X$ is a nonterminal, add $\mathrm{FIRST}(\delta)$, and $L$ too if $\delta$ is [nullable](https://one-course.com/books/computer-science/5/en/chapter/2-top-down-parsing#def-b3-top-down-parsing-first-follow), to every $X \to \cdot\,\eta$ in $I$. The test compares the sets with those of the merged LR(1) states on six grammars, Moor’s expressions included: they are equal. It is cheaper because it never builds the LR(1) automaton, which has more states (22 against 12 for the expression grammar, and more for real languages), and it stores one set per item of the small automaton.

## 3.7 Weekend problem

**Problem 3.1.**

Weekend problem — Two grammars for one if

Brenmoor’s school teaches programming with a small language of its own, and its compiler is built with a [parser generator](#def-b3-bottom-up-parsing-generator). Two of the generator’s reports have puzzled the teachers: one about `if`, one about assignments through pointers. The grammars are Listings [3.6](#lst-b3-bottom-up-parsing-ifelse) and [3.7](#lst-b3-bottom-up-parsing-lr). Work each answer out by hand, then check it with the chapter’s programs; `exercises/pb_if.rs` adds what they lack.

**Part I — The dangling else.**

1. Give the two parse trees of `if c then if c then other else other` .
2. Build the [LR(0) automaton](#def-b3-bottom-up-parsing-automaton) of the `if` grammar. How many states has it?
3. Which state holds both a completed item and an item with its dot before a terminal?
4. Is the grammar LR(0), that is, can every state decide without looking at the next token?

**Part II — The SLR table.**

5. Compute $\mathrm{FOLLOW}(S)$ .
6. Fill the [SLR table](#def-b3-bottom-up-parsing-slr) and find its conflicts.
7. With the conflict resolved by shifting, parse the input of question 1. Which `if` gets the `else` ?
8. With the conflict resolved by reducing instead, what happens to the same input, and to `if c then other else other` ?
9. How many LR(1) states has the grammar, and how many conflicts? Explain the number of conflicts without building the states.
10. Write an unambiguous grammar for the same statements, with “matched” statements (every `if` has its `else` ) and “unmatched” ones. Is it SLR, and how many LR(0) states has it?
11. Give two reasons why a language designer would rather keep the short grammar and the shift.

**Part III — Assignments through pointers.**

12. Describe the language of the assignment grammar in words, and list its sentences of at most three tokens.
13. Show that the grammar is unambiguous.
14. Build its [LR(0) automaton](#def-b3-bottom-up-parsing-automaton) . How many states has it?
15. Compute $\mathrm{FOLLOW}(R)$ , and say which production puts `=` in it.
16. Find the SLR conflict: its state, its token and its two actions.
17. Show that the reduction in that cell can never be right: no right sentential form starts with $R\,=$ .

**Part IV — LR(1) and LALR.**

18. Compute the closure of $[\mathit{Start} \to \cdot\,S,\ \$]$ . How many [LR(1) items](#def-b3-bottom-up-parsing-lr1) has it?
19. Give the LR(1) state reached from it on $L$ , and its actions.
20. How many states has the LR(1) automaton?
21. Which LR(1) states share a core? How many states has the LALR automaton, and does it have a conflict?
22. Prove that merging states with the same core never creates a [shift–reduce conflict](#def-b3-bottom-up-parsing-slr) .
23. Give a reason why merging can create a [reduce–reduce conflict](#def-b3-bottom-up-parsing-slr) , although it did not here.
24. The expression grammar has 22 LR(1) states and 12 LALR states. Which construction would you use for the school’s language, and why?
25. Sum up: for each of the two grammars, what does SLR, LR(1) and LALR make of it, and what should each report tell the teachers?

**Solution of Problem 3.1.**

The numbers are asserted in `tests/pb_test.rs`.

**1.** The `else` belongs to the inner `if`: $S \to \mathrm{if}\ c\ \mathrm{then}\ S$ whose $S$ is $\mathrm{if}\ c\ \mathrm{then}\ \mathit{other}\ \mathrm{else}\ \mathit{other}$. Or to the outer one: $S \to \mathrm{if}\ c\ \mathrm{then}\ S\ \mathrm{else}\ \mathit{other}$ whose first $S$ is $\mathrm{if}\ c\ \mathrm{then}\ \mathit{other}$.

**2.** Nine states: the start state; after $S$; after `if`; after `other`; after `if c`; after `if c then`; after `if c then S`; after `else`; after `else S`.

**3.** State 6, after `if c then S`: $S \to \mathrm{if}\ c\ \mathrm{then}\ S\,\cdot$ and $S \to \mathrm{if}\ c\ \mathrm{then}\ S \cdot \mathrm{else}\ S$.

**4.** No: state 6 must look at the next token to choose between reducing and shifting.

**5.** $\mathrm{FOLLOW}(S) = \{\mathrm{else}, \$\}$: $ because $S$ is the start symbol, `else` from $S \to \mathrm{if}\ c\ \mathrm{then}\ S\ \mathrm{else}\ S$.

**6.** The table of the figure in [Section 3.4](#sec-3-4): one conflict, in state 6 on `else`, shift 7 against reduce by rule 1.

**7.** The inner one: the parser shifts the `else` while the inner `if` is on top of the stack, and reduces the outer `if` last, without `else`.

**8.** On the `else`, the inner `if` is reduced without it. The parser is back in state 6 for the outer `if`, with `else` next, and reduces again; in state 1 the `else` has no action: error. On `if c then other else other` the same happens at once. Resolving by reduction makes rule 2 unusable: no `else` is ever accepted.

**9.** 16 LR(1) states and one conflict. The grammar is ambiguous, and an ambiguous grammar is LR($k$) for no $k$: the word of question 1 has two rightmost derivations, and a deterministic parser can follow only one, so some table cell must offer both.

**10.** $S \to M \mid U$; $M \to \mathrm{if}\ c\ \mathrm{then}\ M\ \mathrm{else}\ M \mid \mathit{other}$; $U \to \mathrm{if}\ c\ \mathrm{then}\ S \mid \mathrm{if}\ c\ \mathrm{then}\ M\ \mathrm{else}\ U$. A statement between `then` and `else` must be matched, so the `else` can only go to the nearest `if`. It is SLR, with 13 LR(0) states (`exercises/ifelse_mu.grammar`).

**11.** Every statement that ends with a statement (`while`, `for`, labelled statements) needs a matched and an unmatched version, which doubles part of the grammar; and the shift gives exactly the reading programmers expect, so the one conflict is known, documented and harmless.

**12.** A statement is an assignment $L = R$ or a bare value $R$, where a left side is a name under any number of stars and a value is a left side. The sentences of at most three tokens are `id`, `* id`, `* * id` and `id = id`.

**13.** The presence of `=` decides between $S \to L = R$ and $S \to R$. The number of stars in front of the name decides the derivation of an $L$: $k$ uses of $L \to * R$, each followed by $R \to L$, then $L \to \mathtt{id}$; and $R$ has one production. So each sentence has one tree.

**14.** Ten states.

**15.** $\mathrm{FOLLOW}(R) = \{=, \$\}$. $ comes from $S \to R$ and $S \to L = R$; the `=` comes from $L \to * R$, which puts $\mathrm{FOLLOW}(L)$ into $\mathrm{FOLLOW}(R)$, and $S \to L = R$ puts `=` into $\mathrm{FOLLOW}(L)$.

**16.** State 2, $\{S \to L \cdot = R,\ R \to L\,\cdot\}$, on `=`: shift 6 against reduce by $R \to L$.

**17.** State 2 is reached from the start state on $L$ only, so the stack holds a single $L$ at the start of the statement. Reducing would make the form start with $R =$. But an $R$ at the start of a right sentential form comes only from $S \to R$, and is then followed by nothing; the other productions put $R$ after `*` or after `=`. So the reduction is never part of a rightmost derivation.

**18.** $[\mathit{Start} \to \cdot\,S, \$]$, $[S \to \cdot\,L = R, \$]$, $[S \to \cdot\,R, \$]$, $[R \to \cdot\,L, \$]$, and $[L \to \cdot * R, a]$ and $[L \to \cdot\,\mathtt{id}, a]$ for $a$ in $\{=, \$\}$ (look-ahead `=` from $S \to \cdot\,L = R$, $ from $R \to \cdot\,L$): 8 items.

**19.** $\{[S \to L \cdot = R, \$],\ [R \to L\,\cdot, \$]\}$: shift on `=`, reduce by $R \to L$ on $ only. No conflict.

**20.** 14 states.

**21.** Four pairs: the states of $L \to * \cdot R$, $L \to \mathtt{id}\,\cdot$, $R \to L\,\cdot$ and $L \to * R\,\cdot$, each reached once before the `=` (look-aheads `=` and $) and once after it ($ only). Merging leaves $14 - 4 = 10$ states, those of the [LR(0) automaton](#def-b3-bottom-up-parsing-automaton), and no conflict: the merged states hold one complete item each.

**22.** Let a merged state have a shift on $a$ and a reduction $[B \to \gamma\,\cdot, a]$. The reduction comes from one of the merged LR(1) states, $P$. A shift on $a$ comes from an item $[A \to \alpha \cdot a\beta, b]$, and whether it is present depends only on the core: all merged states have the same core, so $P$ holds $A \to \alpha \cdot a\beta$ with some look-ahead, and shifts on $a$ too. So $P$ already had the conflict.

**23.** Reductions depend on the look-aheads, and the union mixes look-aheads that came from different contexts: two states with the same core $\{A \to c\,\cdot,\ B \to c\,\cdot\}$ may reduce $A$ on $x$ and $B$ on $y$ in one, $A$ on $y$ and $B$ on $x$ in the other; merged, both reductions apply on $x$ and on $y$.

**24.** LALR: its tables have the size of the [LR(0) automaton](#def-b3-bottom-up-parsing-automaton) (12 states here against 22), it [handles](#def-b3-bottom-up-parsing-shift-reduce) grammars such as the assignment grammar that SLR refuses, and the [reduce–reduce conflicts](#def-b3-bottom-up-parsing-slr) it can add are rare; canonical LR(1) is worth its size only when LALR reports such a conflict.

**25.** The `if` grammar has its conflict under SLR, LR(1) and LALR alike, because it is ambiguous; the report is real, and the generator’s shift gives the `else` to the nearest `if`, which is what the teachers want: they can keep the grammar and document the conflict, or rewrite it as in question 10. The assignment grammar has one SLR conflict and none under LR(1) or LALR; the conflict was an artefact of FOLLOW, and an LALR generator, as bison’s run in [Output 3.5](#out-b3-bottom-up-parsing-bison) shows, reports nothing.
