How grammars generate strings — and why the order of expansion is the fundamental difference between top-down and bottom-up parsing. The critical insight: LR = Rightmost Derivation in Reverse.
A parse tree is a visual representation of a derivation. It captures the grammatical structure of an input string, showing which rules were applied to derive it from the start symbol.
Each internal node is a non-terminal. Its children represent the right-hand side of the production rule that was applied.
Each leaf node is a terminal or ε. Reading leaves left-to-right gives you the original input string.
The root is always the start symbol S (or E in our grammar). Every derivation begins here.
An unambiguous grammar produces exactly one parse tree per input string. Ambiguous grammars are problematic for parsers.
id + id * id
In a leftmost derivation, at each step we always expand the leftmost non-terminal. This is the strategy used by top-down parsers (LL(1), recursive descent).
id + id * id
In a rightmost derivation, at each step we always expand the rightmost non-terminal. Crucially, this is what LR parsers simulate — but in reverse!
id + id * id
This is the most important connection in all of parsing theory. Understanding it unlocks the intuition behind every LR parser you'll ever encounter.
Reading the derivation steps bottom-to-top is exactly what an LR parser does. Each reduce action corresponds to one derivation step — reversed.
Click to highlight corresponding rows between the derivation and LR trace
id + id * id
| Step | Stack | Input | Action | Why (Derivation Link) |
|---|
These three facts are the foundation of everything that follows in LR parsing theory.
| Property | Leftmost Derivation | Rightmost Derivation |
|---|---|---|
| Which NT is expanded? | Leftmost non-terminal in string | Rightmost non-terminal in string |
| Associated parser type | LL (top-down): LL(1), recursive descent | LR (bottom-up): LR(0), SLR, CLR, LALR |
| Direction of construction | Root → leaves (expansion) | Leaves → root (reduction, when reversed) |
| Handles left recursion? | ❌ Causes infinite loop | ✅ Handles naturally |
| Grammar power | LL(k) grammars (strict subset) | LR(k) grammars (much larger set) |
| Parse tree result | ✅ Identical for unambiguous grammars | |