Sub topic 6
Leftmost and Rightmost Derivations and Parse Trees
Assume you know context-free grammars, terminals, nonterminals, and the idea of a production. This chapter shows how a grammar generates a string and how to represent that generation as a parse tree. These ideas are useful when checking ambiguity and tracing parsers.
Derivations
A sentential form is any string of terminals and nonterminals that can appear during a derivation. A derivation starts with the grammar's start symbol and repeatedly replaces a nonterminal using a production.
Consider this grammar:
| Nonterminal | Productions | Column |
|---|---|---|
| E | E → E + T \ | T |
| T | T → id |
The string id + id can be generated as follows:
E ⇒ E + T
⇒ T + T
⇒ id + T
⇒ id + idEach arrow applies one production. The final sentential form contains only terminals, so it is a sentence in the language.
In a leftmost derivation, always replace the leftmost nonterminal first. For the grammar above:
E ⇒ E + T
⇒ T + T
⇒ id + T
⇒ id + idAfter the first step, the leftmost nonterminal is the first E. After replacing it, the leftmost remaining nonterminal is the first T.
In a rightmost derivation, always replace the rightmost nonterminal first:
E ⇒ E + T
⇒ E + id
⇒ T + id
⇒ id + idBoth derivations produce the same string. They differ only in the order in which nonterminals are expanded.
Parse Trees
A parse tree is a tree that records the structure of a derivation.
- The root is the start symbol.
- Internal nodes are nonterminals.
- Children of a node are the symbols on the right side of the selected production.
- Leaves are terminals or, sometimes, the empty string.
- Reading terminal leaves from left to right gives the derived sentence.
The same parse tree can correspond to one leftmost derivation and one rightmost derivation. The derivation order is not stored in the tree. The tree stores the final hierarchical structure.
Ambiguity
A grammar is ambiguous if at least one sentence has two different parse trees. Different derivation sequences alone do not prove ambiguity. A leftmost and a rightmost derivation for the same tree are expected. To prove ambiguity, you need two distinct trees, or two distinct leftmost derivations, for the same sentence.
This distinction matters for expressions. If a grammar allows id + id * id to group as either (id + id) * id or id + (id * id), the grammar is ambiguous. A compiler cannot reliably assign meaning until the grammar or parsing rules resolve that ambiguity.
Exercise
For the grammar E → E + T | T and T → id, write a rightmost derivation of id + id.
Show answer
E ⇒ E + T ⇒ E + id ⇒ T + id ⇒ id + id