Sub topic 4
Leftmost and rightmost derivations and parse trees
This chapter assumes you know what a context-free grammar is: the four-tuple (V, Σ, P, S) of variables, terminals, productions and a start symbol. It also assumes you can read a production like S -> aSb | ab. Here you learn to fix the order in which a derivation expands variables, and to draw the tree that records the result.
Sentential forms and the derivation relation
A sentential form is any string of variables and terminals that can be reached from the start symbol. A sentence is a sentential form with no variables. We write α ⇒ β when β comes from α by replacing one variable using one production. We write α ⇒* β for zero or more such steps.
The language of a grammar G is L(G) = { w in Σ : S ⇒ w }.
A sentential form often has several variables, so you must choose which one to expand next. Two fixed policies give two named derivations.
- A leftmost derivation always expands the leftmost variable.
- A rightmost derivation always expands the rightmost variable.
A worked example
Use the unambiguous expression grammar from the plan:
E -> E + T | T
T -> T * F | F
F -> idThe string is id + id * id.
| Step | Leftmost derivation | Rightmost derivation |
|---|---|---|
| 0 | E | E |
| 1 | E + T | E + T |
| 2 | T + T | E + T * F |
| 3 | F + T | E + T * id |
| 4 | id + T | E + F * id |
| 5 | id + T * F | E + id * id |
| 6 | id + F * F | T + id * id |
| 7 | id + id * F | F + id * id |
| 8 | id + id * id | id + id * id |
Both derivations apply the same eight productions. Only the order differs. The derivation length equals the number of productions used, which is also the number of variable nodes in the parse tree.
Parse trees
A parse tree records which production was applied to each variable, and ignores the order of expansion. It has these properties.
- The root is labelled with the start symbol.
- Each interior node is labelled with a variable. Its children, read left to right, are the right-hand side of one production.
- Each leaf is a terminal, a variable (in a partial tree), or ε.
- The yield is the string of leaves read left to right, skipping ε leaves. For a complete tree it is the derived string.
This is the parse tree for aaabbb under S -> aSb | ab:
The tree has three S nodes, so any derivation of aaabbb takes three steps.
One tree, many derivations, exactly one of each kind
A single parse tree corresponds to many derivations, because a sentential form with several variables lets you pick any order. For one tree, however, there is exactly one leftmost derivation and exactly one rightmost derivation. This gives the following fact, which GATE questions rely on.
- The number of distinct parse trees for w equals the number of distinct leftmost derivations of w.
- It also equals the number of distinct rightmost derivations of w.
Ambiguity, covered in the next chapter, is defined this way. A grammar is ambiguous if some string has two or more parse trees. Equivalently, it has two or more leftmost derivations.
Mechanising derivations
The following program expands either the leftmost or the rightmost variable at each step. Each choice is the index of the production to use for that variable. Run it to check hand derivations.
GRAMMAR = {
"E": [["E", "+", "T"], ["T"]],
"T": [["T", "*", "F"], ["F"]],
"F": [["id"]],
}
def derive(grammar, start, choices, rightmost=False):
"""Print a derivation. choices[i] picks the production for step i."""
form = [start]
print(" ".join(form))
for idx in choices:
positions = [i for i, s in enumerate(form) if s in grammar]
pos = positions[-1] if rightmost else positions[0]
form[pos:pos + 1] = grammar[form[pos]][idx]
print("=>", " ".join(form))
derive(GRAMMAR, "E", [0, 1, 1, 0, 0, 1, 0, 0])
print()
derive(GRAMMAR, "E", [0, 0, 0, 1, 0, 1, 1, 0], rightmost=True)Both runs end at id + id * id. The second list of choices differs from the first because the variable being expanded at each step is different.
Reading the tree for meaning
In the tree for id + id * id, the root uses E -> E + T. The right operand id * id sits under T, deeper than the left operand. A parent combines its children's values after they are computed, so * is evaluated before +. The layered grammar E / T / F therefore encodes precedence in the tree shape. Left recursion (E -> E + T) makes the tree grow to the left, which gives left associativity.
Leftmost and rightmost derivations also match two parsing styles.
- A leftmost derivation corresponds to top-down parsing (LL): the parser predicts productions from the start symbol.
- A rightmost derivation read backwards corresponds to bottom-up parsing (LR): the parser reduces handles until it reaches S.
Edge cases and common errors
- ε productions. If
A -> εis used, the tree has a leaf ε under A. The yield skips it, so the tree can have fewer yield symbols than nodes. - Mixed derivations. A derivation that expands the left variable in one step and the right in the next is neither leftmost nor rightmost. Such derivations are valid, but GATE options that call them "leftmost" are wrong.
- Counting steps. The length of a derivation is the number of productions applied, not the number of symbols in the string. For
a^n b^nunderS -> aSb | ab, the length is n. - Same tree, different strings of forms. Two derivations that differ in order give the same tree. They do not show ambiguity. Ambiguity needs two different trees.
- Variables in the yield. The yield of a complete tree has terminals only. A leaf labelled with a variable means the tree is partial.
- Terminals on the left. Leftmost means leftmost variable, not leftmost symbol. In
aSbthe next variable to expand is S, even thoughais further left.
Quick checks for GATE
- Find the number of productions used. It equals the number of internal nodes of the tree.
- To count parse trees, count leftmost derivations. This is easier to enumerate.
- For a grammar in Chomsky normal form and a string of length n, every derivation has exactly 2n − 1 steps: n − 1 binary productions and n terminal productions.
- If a question gives a "sentential form", check whether it contains variables. If it does not, it is a sentence.
Exercise
For the grammar S -> aSb | ab, how many steps does the leftmost derivation of a^5 b^5 take, and does the rightmost derivation take the same number?
Show answer
Each use of S -> aSb adds one a and one b around the inner S, and the last step S -> ab ends the derivation. For a^5 b^5 that is 4 uses of S -> aSb plus 1 use of S -> ab, so 5 steps. The grammar has one variable in every sentential form, so the rightmost derivation is the same sequence and also takes 5 steps.
Exercise
Grammar G is E -> E + E | id. How many distinct leftmost derivations does id + id + id have, and what does this say about G?
Show answer
There are 2. In one, the first step is E => E + E and the left E is then expanded with E + E, which groups as (id + id) + id. In the other, the left E becomes id and the right E is expanded with E + E, which groups as id + (id + id). Two leftmost derivations mean two parse trees, so G is ambiguous.