14. LR & LALR Parsing
Bottom-up parsing with a state machine
Top-down vs. bottom-up
Every parser we've seen so far — recursive descent, parser combinators, PEG — works top-down. It starts from the start symbol and tries to figure out which rules expand into the input. You predict which production to use, then verify.
LR parsing flips this around. It works bottom-up: read tokens from the input, accumulate them on a stack, and when the top of the stack matches the right-hand side of a production, reduce it to the left-hand side. You're building the parse tree from the leaves up to the root.
Bottom-up parsing can handle a strictly larger class of grammars than top-down LL parsing. That power comes with more machinery — but the machinery is generated automatically from the grammar, which is the whole point.
Shift and reduce
The LR parser has two fundamental operations:
- Shift: read the next input token and push it onto the stack.
- Reduce: pop symbols from the top of the stack that match a production's right-hand side, and push the left-hand side nonterminal.
Let's trace through a tiny example. Grammar:
1. E → E + T
2. E → T
3. T → number
Input: 3 + 5
| Step | Stack | Input | Action |
|---|---|---|---|
| 1 | (empty) | 3 + 5 |
Shift 3 |
| 2 | 3 |
+ 5 |
Reduce by rule 3: T → number |
| 3 | T |
+ 5 |
Reduce by rule 2: E → T |
| 4 | E |
+ 5 |
Shift + |
| 5 | E + |
5 |
Shift 5 |
| 6 | E + 5 |
(empty) | Reduce by rule 3: T → number |
| 7 | E + T |
(empty) | Reduce by rule 1: E → E + T |
| 8 | E |
(empty) | Accept! |
At step 7, the stack has E + T, which matches the right-hand side of rule 1. We pop those three symbols and push E. Done.
But how does the parser know when to shift and when to reduce? That's where the state machine comes in.
LR items and the automaton
An LR(0) item is a production with a dot showing how much of the right-hand side we've matched so far:
E → . E + T // Haven't matched anything yet
E → E . + T // Matched E, expecting +
E → E + . T // Matched E +, expecting T
E → E + T . // Matched everything — ready to reduce
The dot is like a cursor. When it's at the end (like E + T .), we can reduce.
We build a state machine (technically a DFA) where each state is a set of items. The parser's current state tells it what it has seen so far and what it expects next.
Building item sets
Start with the initial item and compute the closure: if the dot is before a nonterminal, add all productions for that nonterminal (with the dot at the start).
State 0 (initial):
E' → . E (augmented start rule)
E → . E + T
E → . T
T → . number
From state 0, if we see number, we shift and move to a new state where the dot has advanced:
State 1 (after shifting number):
T → number .
The dot is at the end — this state means "reduce by T → number."
If from state 0 we see T (after reducing), we go to:
State 2 (after seeing T):
E → T .
Reduce by E → T.
And so on for every possible transition. The full automaton for even a small grammar has a handful of states. For a real programming language grammar, it might have hundreds or thousands — but it's all generated automatically.
The parse table
The state machine is encoded as two tables:
ACTION table: indexed by (state, terminal). Each entry says:
- Shift : push the token and go to state
- Reduce : reduce by production
- Accept: parsing succeeded
- (empty): syntax error
GOTO table: indexed by (state, nonterminal). After a reduction replaces stack symbols with a nonterminal, the GOTO table says which state to go to.
Here's what the tables look like for our tiny grammar:
ACTION:
| State | number |
+ |
$ |
|---|---|---|---|
| 0 | shift 1 | ||
| 1 | reduce 3 | reduce 3 | |
| 2 | reduce 2 | reduce 2 | |
| 3 | shift 4 | accept | |
| 4 | shift 1 | ||
| 5 | reduce 1 | reduce 1 |
GOTO:
| State | E | T |
|---|---|---|
| 0 | 3 | 2 |
| 4 | 5 |
The parsing algorithm
function lrParse(actionTable, gotoTable, tokens) {
const stack = [0]; // Stack of states
const symbols = []; // Stack of symbols (for the AST)
let pos = 0;
while (true) {
const state = stack[stack.length - 1];
const token = tokens[pos] || { type: '$' };
const action = actionTable[state][token.type];
if (!action) {
throw new Error(`Syntax error at ${token.type}`);
}
if (action.type === 'shift') {
symbols.push(token);
stack.push(action.state);
pos++;
}
else if (action.type === 'reduce') {
const rule = action.rule;
// Pop |rhs| symbols and states
for (let i = 0; i < rule.rhs.length; i++) {
stack.pop();
symbols.pop();
}
// Push the LHS nonterminal
const node = { type: rule.lhs, children: /* popped symbols */ };
symbols.push(node);
// Look up the GOTO for the state now on top
const newState = gotoTable[stack[stack.length - 1]][rule.lhs];
stack.push(newState);
}
else if (action.type === 'accept') {
return symbols[0]; // The AST root
}
}
}
The elegance is that all the decision-making is in the tables. The algorithm itself is a simple loop.
Conflicts
Sometimes the table construction hits a problem: two different actions want to occupy the same cell.
Shift/reduce conflict: the parser could either shift the next token or reduce what's already on the stack. The classic example is the dangling else:
if a then if b then s1 else s2
Should the parser shift else (attaching it to the inner if) or reduce the inner if statement (attaching else to the outer if)? Most tools resolve this in favor of shift (matching the nearest if), which happens to be what most languages want.
Reduce/reduce conflict: two different productions could apply. This usually indicates a genuinely ambiguous grammar and requires restructuring the rules.
SLR, LALR, and canonical LR
Not all LR parsers are created equal. They differ in how much lookahead information they use to build the tables:
LR(0): no lookahead at all. Very few practical grammars are LR(0).
SLR (Simple LR): uses the FOLLOW sets from the grammar to decide when to reduce. Better than LR(0), but still has limitations.
Canonical LR(1): each item carries a lookahead token. The most powerful, but the tables can be enormous — the number of states can explode because items that differ only in lookahead create separate states.
LALR(1): merges LR(1) states that differ only in their lookahead sets. This gives you nearly the power of canonical LR(1) with the compact table size of SLR. It's the sweet spot and what most parser generators use.
| Variant | Table size | Power | Used by |
|---|---|---|---|
| LR(0) | Small | Weak | Rarely |
| SLR | Small | Moderate | Academic |
| LALR(1) | Small | Strong | yacc, bison |
| LR(1) | Large | Strongest | Some modern tools |
LALR(1) occasionally has conflicts that canonical LR(1) doesn't, but in practice this is rare. When it happens, the grammar can usually be tweaked.
Worked example: 1 + 2 * 3
Let's parse 1 + 2 * 3 with a grammar that handles precedence:
1. E → E + T
2. E → T
3. T → T * F
4. T → F
5. F → number
| Step | Stack (states) | Symbols | Input | Action |
|---|---|---|---|---|
| 1 | 0 | 1 + 2 * 3 $ |
shift | |
| 2 | 0,1 | 1 |
+ 2 * 3 $ |
reduce F → number |
| 3 | 0,2 | F |
+ 2 * 3 $ |
reduce T → F |
| 4 | 0,3 | T |
+ 2 * 3 $ |
reduce E → T |
| 5 | 0,4 | E |
+ 2 * 3 $ |
shift + |
| 6 | 0,4,5 | E + |
2 * 3 $ |
shift |
| 7 | 0,4,5,1 | E + 2 |
* 3 $ |
reduce F → number |
| 8 | 0,4,5,2 | E + F |
* 3 $ |
reduce T → F |
| 9 | 0,4,5,6 | E + T |
* 3 $ |
shift * |
| 10 | 0,4,5,6,7 | E + T * |
3 $ |
shift |
| 11 | 0,4,5,6,7,1 | E + T * 3 |
$ |
reduce F → number |
| 12 | 0,4,5,6,7,8 | E + T * F |
$ |
reduce T → T * F |
| 13 | 0,4,5,6 | E + T |
$ |
reduce E → E + T |
| 14 | 0,4 | E |
$ |
accept |
Notice step 9: the stack has E + T and the next token is *. The parser could reduce E + T to E, but instead it shifts *. This is correct because * has higher precedence than + — and the grammar encodes this (multiplication is nested deeper in the grammar hierarchy).
Parser generators
Nobody builds LR tables by hand for real grammars. You use a parser generator:
- yacc / bison — the classic LALR generators for C. You write a grammar file (
.y), and they output C code with the parse tables baked in. - ANTLR — primarily LL-based, but can use LR techniques. Generates parsers in Java, Python, C#, and more.
- Menhir (OCaml) — an LR(1) generator with excellent error messages.
- tree-sitter — uses a GLR approach (generalized LR) that can handle ambiguous grammars by maintaining multiple parse stacks.
When to use LR vs. recursive descent
| Factor | Recursive descent | LR (parser generator) |
|---|---|---|
| Grammar class | LL | LR (strictly larger) |
| Error messages | Easy to customize | Harder, but improving |
| Hand-written | Yes | No — use a generator |
| Left recursion | Must rewrite | Handles natively |
| Operator precedence | Needs encoding in grammar | Needs encoding in grammar |
| Maintenance | Edit code directly | Edit grammar file |
| Debugging | Step through code | Inspect tables (harder) |
Many modern compilers (GCC, Clang, Rust, Go, V8) use hand-written recursive descent despite LR being theoretically more powerful. The reasons: better error messages, easier to maintain, and the grammars of most programming languages fit comfortably in LL with a bit of manual tweaking.
LR shines when you need to parse a complex grammar with many ambiguities that are resolved by precedence/associativity declarations — languages like SQL, where writing a recursive descent parser would be painful.
Summary
LR parsing builds the parse tree from the bottom up using a stack and a state machine encoded in ACTION/GOTO tables. LALR(1) is the practical sweet spot — compact tables, strong parsing power, and mature tool support. The concepts are more abstract than recursive descent, but the generated parsers are fast and handle grammars that top-down parsers struggle with.
Try It Yourself — LR Parsing
Enter an arithmetic expression below. The visualizer will show the LR parser's stack, the current state, and each shift/reduce action as it builds the parse tree bottom-up.