এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
University Computer Science — Year 3 · স্নাতক তৃতীয় বর্ষ
3Bottom-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 had to be rewritten and why the full LL(1) grammar 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 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 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); 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). 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.
# expr.grammar -- sums and products, left-recursive
E -> E + T | T
T -> T * F | F
F -> ( E ) | id
Start -> E. code/bachelor-3/03-bottom-up-parsing/listings/expr.grammarOn id + id * id, the parser shifts the first id and reduces it to , then , then . It shifts + and id, reduces the id to and , and now stops reducing: with * next, on the stack must not become , because the is the left operand of a product. It shifts * and id, reduces id to , to , and only then to . Output 3.1 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
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 is a production together with a position of in such that replacing that by gives the previous form of a rightmost derivation of .
In , the handle is at the last position; is the right side of a production, but it is not a handle there, because is not a right sentential form. The whole difficulty of bottom-up parsing is to recognise handles. A correct parser reduces exactly the handles, and so traces a rightmost derivation backwards: the figure below numbers the nodes of the parse tree in the order the parser builds them.
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 reduces only handles, its reductions, read from last to first, are the steps of a rightmost derivation of .
Proof. At every moment the stack followed by the unread input is a right sentential form : true at the start (, ), unchanged by a shift, and a reduction of a handle replaces by the previous form of a rightmost derivation of . The last form is the start symbol, so the forms, read backwards, are a derivation of ; 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.
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 : the part before the dot has been seen, the part after it is expected. The item closure of a set of items adds for every production of whenever some item has its dot before the nonterminal , and repeats until nothing changes. The goto function maps a set of items and a symbol to the closure of the items for which is in .
Expecting a means expecting the start of any of ’s productions: that is the closure. The goto function is the move of a parser that has just seen an , read or reduced. The grammar is first augmented with a new start rule , so that acceptance is the reduction of rule 0. Listing 3.2 is both functions; an item is a pair (rule, position of the dot).
/// 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)
}
Definition 3.4 (Viable prefix, LR(0) automaton)
An item is valid for a string of grammar symbols if with . 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. The LR(0) automaton of a grammar has as start state the closure of , as states every set reachable from it by the goto function, and a transition labelled from to whenever that set is not empty.
Listing 3.3 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); the figure after it draws them.
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
}
$ 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
Theorem 3.5 (The automaton recognises viable prefixes)
Let be a string of grammar symbols. There is a path from the start state labelled if and only if is a viable prefix, and the state it reaches holds exactly the items valid for .
Proof. We prove that every item of the state reached by a path labelled is valid for ; since a state is never empty, is then viable. The converse, that every item valid for is in that state (so every viable prefix labels a path), is exercise 3.10. Assume the grammar has no useless nonterminal: each derives some word of terminals.
Closure keeps validity. Let be valid for : with . Let , a word of terminals. Rewriting first keeps the derivation rightmost, since is to the right of : for any production . So is valid for .
Induction on the length of . For the state is the closure of , which is valid for by the zero-step derivation. For , the state reached is where is the state reached by . Its kernel items come from items of , valid for by induction, and the same derivation shows valid for . 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, 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 , then is at the top of the stack and the item is valid: reducing it may be right. If it has an item and the next token is , shifting may be right. When only one of the two can apply, the automaton has found the handle.
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. Its action part has a column per terminal and $: cell holds shift if the automaton moves from to on , reduce if is in and , and accept if and is in . 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, asks for a reduction and for a shift on *; does not contain *, so the cell 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 is a . Listing 3.4 builds the table and Output 3.3 prints it.
/// 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
}
$ 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
s5 shifts and goes to state 5, r2 reduces by rule 2, . No cell has two actions.Method 3.7 (The LR driver)
Keep a stack of states, initially the start state. Repeat, with the state on top and the next token: if is shift , push and advance; if it is reduce , pop states, then push where is the state now on top; if it is accept, stop; if it is empty, report an error at .
Listing 3.5 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.
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}"));
}
}
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, since a shift follows a move of the automaton and every path spells a viable prefix (Theorem 3.5). 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 watches it happen.
3.4 Conflicts and their resolution
3.4.1 The dangling else
Listing 3.6 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.
# ifelse.grammar -- the dangling else
S -> if c then S | if c then S else S | other
if with an optional else, and no braces: the dangling else. code/bachelor-3/03-bottom-up-parsing/listings/ifelse.grammarThe SLR table 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 , 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 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.
if grammar: rule 1 is the if without else, rule 2 the one with it, rule 3 S -> other. , 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 is ambiguous and its table full of conflicts, but each conflict opposes a production, say , 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 implements the rule; parser generators 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 is a small model of assignments through pointers, in the style of C: a left side is a name or a dereferenced value, a right side is any left side, read.
# lr.grammar -- assignments through pointers: SLR cannot
S -> L = R | R
L -> * R | id
R -> L
After reading an at the start, the parser is in a state with and . The equals sign is in , because of and : in *x = y, the under the star is followed by =. So SLR puts a reduction in the = column next to the shift (Output 3.4). Yet no right sentential form starts with : 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 is an LR(0) item with a look-ahead terminal : the item is valid for if with and starting with (or if is empty). The closure adds for every when an item is present; the canonical LR(1) automaton is built from these items as the LR(0) one is, and a reduction by goes in column only. The core of a set of LR(1) items is the set of their LR(0) 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.
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
}
With look-aheads, the state reached on from the start holds and : 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); for a real language, ten times more is common. LALR merges them back. It has exactly the states of the LR(0) 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.
/// 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 }
}
$ 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
if grammar keeps its conflict whatever the method; the assignment grammar loses it under both LR(1) and LALR.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 that the LR(1) table did not have. It can create a reduce–reduce conflict, 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, 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 of the GNU project, as its version line says. Listing 3.10 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 runs bison on it and on the assignment grammar.
%token IF C THEN ELSE OTHER
%%
s : IF C THEN s
| IF C THEN s ELSE s
| OTHER
;
%%
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
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 , 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, refuses it if the SLR table has a conflict, and otherwise prints the tables as Rust constants, with 0 for an error, for a shift to state and for a reduction by rule . Listing 3.11 is the whole of Moor’s expressions, one nonterminal per level, written as the grammar of a language manual would write them, left recursion included.
# 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
$ 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],
The generated file is saved as moor_expr_tables.rs (a test checks that it is exactly the generator’s output). Listing 3.12 is the driver of Method 3.7 on those arrays, fed by the scanner of chapter 1. 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’s trees.
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)));
}
}
}
$ 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]
The two parsers agree on every test expression. One was written by hand from binding powers, 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).
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() grammars and their parsers in “On the translation of languages from left to right”, published in December 1965. Frank DeRemer’s “Simple LR() grammars”, published in July 1971, gave the SLR tables of this chapter, built on the states of the LR(0) automaton and so much smaller than Knuth’s.
3.6 Exercises
Exercise 3.1 ★
Compute the item closure of in the expression grammar. Which state of Output 3.2 is it?
Solution
Solution of Exercise 3.1.
The dot is before , so the closure adds and ; the dot is now also before , which adds and ; then adds and . 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 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
Solution of Exercise 3.2.
In state 8 on ): shift 11. In state 11 on *: reduce , popping three states back to 0, and . In state 3 on *: reduce , goto 2. The parse then shifts * and id and reduces , and . 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 of each right sentential form of the expression grammar: ; ; .
Solution
Solution of Exercise 3.3.
In , the handle is on (positions 3 to 5): the previous form is . In , it is again, on the first three symbols; the id on the right is reduced later, which is what “rightmost derivation in reverse” means. In , it is on the : the previous form is . The first and third forms are lines of Output 3.1; the test checks the order of reductions on id * id + id.
Exercise 3.4 ★
Classify each state as having a shift–reduce conflict, a reduce–reduce conflict or none under SLR, on the token given: (a) with , ; (b) with ; (c) .
Solution
Solution of Exercise 3.4.
(a) On c both reductions apply: a reduce–reduce conflict; on d only , no conflict. (b) On = the state shifts and, since , also reduces by : a shift–reduce conflict. (c) No conflict: the completed start item gives accept on $ only, and the other item shifts on +.
Exercise 3.5 ★★
Listing 3.13 builds the LR(0) 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 fail. Find the bug, say which states are wrong and why the first parse still succeeds, and fix it.
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()
}
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")
Ok lists the rules reduced.Solution
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 : 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 from state 6 is alone, without , 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; 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 in which every shift–reduce conflict between a production and a token that both have a precedence is resolved by the rule of Section 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 have?
Solution
Solution of Exercise 3.6.
exercises/ex6_prec.rs. For each cell holding a shift and a reduce by rule , take the precedence of the token and of the rule’s last terminal; if either has none, keep the conflict. If , or they are equal and the operator is right-associative, keep the shift; if , or they are equal and left-associative, keep the reduce; if they are equal and non-associative, empty the cell. The plain SLR table of ambig.grammar has 25 conflicting cells (every state meets every operator token); after resolution, none. The tests check id + id * id (+ id (* id id)), id - id - id (- (- id id) id), id ^ id ^ id (^ 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 of . How many states has it, and is the grammar SLR? What does a completed item mean?
Solution
Solution of Exercise 3.7.
Six states. I0 ; on , I1 ; on (, I2 plus the two items of ; on from I2, I3 ; on ), I4 plus the two items of ; on from I4, I5 . From I2 and I4, ( leads back to I2. and the only shift in I0, I2 and I4 is on (, so the grammar is SLR (exercise_7_parentheses). The item is complete without having read anything: the parser reduces an empty , 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
Solution of Exercise 3.8.
Let be SLR and . Take any rightmost derivation of ; 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 , the input left is , and is a form of the derivation. If the derivation’s handle ends inside , it ends at its top (everything to its right is terminal and still unread), so it is with , and is valid for ; by Theorem 3.5 it is in the state on top, and the next token (or $) follows in the previous form, so : the table says reduce by this production. Otherwise the handle ends to the right of , so is still a viable prefix; by the theorem there is a move on from the top state, and the table says shift. So two different rightmost derivations of would make the parser take two different actions in the same configuration, which cannot happen. Hence 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
Solution of Exercise 3.9.
On id + * id: shift 5, reduce , , , 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. On ( id + id: the parser shifts (, reduces the first id to , shifts + and id, and on $ reduces , and , ending in state 8, where $ has no action. The three last reductions take place on $ because $ is in the FOLLOW sets of , and ; 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: if an item is valid for , then there is a path labelled 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
Solution of Exercise 3.10.
Let be valid for through . We show by induction on that the path labelled exists and ends in a state holding . Then the moves on the symbols of 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 ends in a state holding . If , then , , and is in the start state. If , the occurrence of was created by some earlier step , with , , and with (the steps in between rewrite only what is right of , since the derivation is rightmost and is still there). So is valid for through a derivation of length , and by induction the path labelled ends in a state holding it, hence, by closure, holding .
Exercise 3.11 ★★★
Let have terminals and the productions , and for every and every . It has productions. Show that its LR(0) automaton has states. (exercises/ex11_family.rs writes .)
Solution
Solution of Exercise 3.11.
After the start state reads a nonempty word of ’s, call alive the indices that do not occur in before its last letter: only for them is an item still in progress, since reading ends (there is no ). If the last letter is , the kernel is , plus if is alive. Every set of alive indices occurs (read each letter outside once, then ), and for a fixed the kernel determines ; it is empty only for , which gives no state. So there are states per letter , in all. Add the start state, , the states , and the states : . The test checks the formula for to 7 (4, 12, 32, 78, 182, 416, 940 states) against grammars of 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 without building the LR(1) one: start with $ on 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. Why is it cheaper?
Solution
Solution of Exercise 3.12.
exercises/ex12_lalr_prop.rs. Give each item of each LR(0) state an empty set, and $ to in the start state. Repeat until no set grows: for each item with set in state , add to the set of in ; and if is a nonterminal, add , and too if is nullable, to every in . 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. Two of the generator’s reports have puzzled the teachers: one about if, one about assignments through pointers. The grammars are Listings 3.6 and 3.7. 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.
- Give the two parse trees of
if c then if c then other else other. - Build the LR(0) automaton of the
ifgrammar. How many states has it? - Which state holds both a completed item and an item with its dot before a terminal?
- Is the grammar LR(0), that is, can every state decide without looking at the next token?
Part II — The SLR table.
- Compute .
- Fill the SLR table and find its conflicts.
- With the conflict resolved by shifting, parse the input of question 1. Which
ifgets theelse? - With the conflict resolved by reducing instead, what happens to the same input, and to
if c then other else other? - How many LR(1) states has the grammar, and how many conflicts? Explain the number of conflicts without building the states.
- Write an unambiguous grammar for the same statements, with “matched” statements (every
ifhas itselse) and “unmatched” ones. Is it SLR, and how many LR(0) states has it? - Give two reasons why a language designer would rather keep the short grammar and the shift.
Part III — Assignments through pointers.
- Describe the language of the assignment grammar in words, and list its sentences of at most three tokens.
- Show that the grammar is unambiguous.
- Build its LR(0) automaton. How many states has it?
- Compute , and say which production puts
=in it. - Find the SLR conflict: its state, its token and its two actions.
- Show that the reduction in that cell can never be right: no right sentential form starts with .
Part IV — LR(1) and LALR.
- Compute the closure of . How many LR(1) items has it?
- Give the LR(1) state reached from it on , and its actions.
- How many states has the LR(1) automaton?
- Which LR(1) states share a core? How many states has the LALR automaton, and does it have a conflict?
- Prove that merging states with the same core never creates a shift–reduce conflict.
- Give a reason why merging can create a reduce–reduce conflict, although it did not here.
- The expression grammar has 22 LR(1) states and 12 LALR states. Which construction would you use for the school’s language, and why?
- 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
Solution of Problem 3.1.
The numbers are asserted in tests/pb_test.rs.
1. The else belongs to the inner if: whose is . Or to the outer one: whose first is .
2. Nine states: the start state; after ; 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: and .
4. No: state 6 must look at the next token to choose between reducing and shifting.
5. : $ because is the start symbol, else from .
6. The table of the figure in Section 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() for no : 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. ; ; . 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 or a bare value , 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 and . The number of stars in front of the name decides the derivation of an : uses of , each followed by , then ; and has one production. So each sentence has one tree.
14. Ten states.
15. . $ comes from and ; the = comes from , which puts into , and puts = into .
16. State 2, , on =: shift 6 against reduce by .
17. State 2 is reached from the start state on only, so the stack holds a single at the start of the statement. Reducing would make the form start with . But an at the start of a right sentential form comes only from , and is then followed by nothing; the other productions put after * or after =. So the reduction is never part of a rightmost derivation.
18. , , , , and and for in (look-ahead = from , $ from ): 8 items.
19. : shift on =, reduce by on $ only. No conflict.
20. 14 states.
21. Four pairs: the states of , , and , each reached once before the = (look-aheads = and $) and once after it ($ only). Merging leaves states, those of the LR(0) automaton, and no conflict: the merged states hold one complete item each.
22. Let a merged state have a shift on and a reduction . The reduction comes from one of the merged LR(1) states, . A shift on comes from an item , and whether it is present depends only on the core: all merged states have the same core, so holds with some look-ahead, and shifts on too. So 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 may reduce on and on in one, on and on in the other; merged, both reductions apply on and on .
24. LALR: its tables have the size of the LR(0) automaton (12 states here against 22), it handles grammars such as the assignment grammar that SLR refuses, and the reduce–reduce conflicts 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 shows, reports nothing.