Sub topic 8
Leftmost and rightmost derivations and parse trees
Prerequisites and scope
This chapter assumes you can read a context-free grammar (CFG): a set of productions, a start symbol, nonterminals, and terminals. It also assumes you know what a stack and a tree are. Here you learn how a string is generated from the start symbol, how the choices made during generation are recorded, and how a parse tree captures the structure of a derivation. Ambiguity is the next chapter's topic. It is only touched on here.
Derivations
A derivation is a sequence of steps. Each step replaces one nonterminal in the current string with the right-hand side of one of its productions. We write α ⇒ β for one step and α ⇒* β for zero or more steps. Every string in the sequence, including the start symbol, is called a sentential form. A sentential form made only of terminals is a sentence of the language.
Consider this grammar:
E -> E + T | T
T -> T * F | F
F -> ( E ) | idA derivation of id + id * id that always expands the leftmost nonterminal:
E ⇒ E + T
⇒ T + T
⇒ F + T
⇒ id + T
⇒ id + T * F
⇒ id + F * F
⇒ id + id * F
⇒ id + id * idA derivation always has a choice at each step: which nonterminal to expand, and which production to use. The two standard disciplines fix the first choice.
Leftmost and rightmost derivations
- A leftmost derivation (written
⇒lm) expands the leftmost nonterminal at every step. - A rightmost derivation (written
⇒rm) expands the rightmost nonterminal at every step. It is also called a canonical derivation.
The rightmost derivation of the same string:
E ⇒ E + T
⇒ E + T * F
⇒ E + T * id
⇒ E + F * id
⇒ E + id * id
⇒ T + id * id
⇒ F + id * id
⇒ id + id * idBoth derivations use the same eight productions. Only the order differs. A sentential form reached in a leftmost derivation is a left-sentential form. One reached in a rightmost derivation is a right-sentential form.
Parse trees
A parse tree is a tree that records which productions were used, but not the order in which they were applied. It has these properties:
- The root is labeled with the start symbol.
- Each leaf is labeled with a terminal or with ε.
- Each interior node is labeled with a nonterminal.
- If an interior node is labeled
Aand its children are labeledX1 X2 ... Xkfrom left to right, thenA -> X1 X2 ... Xkis a production.
Reading the leaves from left to right gives the yield of the tree, which is the derived string.
The parse tree for id + id * id:
The tree shows that id * id is grouped under one T before the addition. The grammar encodes the higher precedence of *.
From derivations to trees
Both derivations above produce exactly this tree. The leftmost derivation builds it by expanding the leftmost unexpanded interior node first, which is a preorder (depth-first, left-to-right) construction. The rightmost derivation expands the rightmost unexpanded node first, which is the mirror order.
This gives a useful fact: every parse tree corresponds to exactly one leftmost derivation and exactly one rightmost derivation. The choice of expansion order is fixed by the discipline, and the tree fixes the productions. So the number of distinct parse trees for a string equals the number of distinct leftmost derivations, and also the number of distinct rightmost derivations.
Why parsers care about the two orders
The two orders correspond to the two parser families in this tutorial.
| Parser family | Derivation it traces | Direction of construction |
|---|---|---|
| Top-down (LL) | Leftmost | Builds the tree from the root downward |
| Bottom-up (LR) | Rightmost, in reverse | Builds the tree from the leaves upward |
The first L in LL means the input is scanned left to right. The second L means a leftmost derivation is produced. The R in LR means a rightmost derivation is produced, and it is produced in reverse: the parser performs the last step of the rightmost derivation first. When a shift-reduce parser reduces id to F in id + id * id, it is undoing the last-but-one step of the rightmost derivation above.
Reading the rightmost derivation from bottom to top gives the sequence of reductions:
id + id * id
F + id * id (reduce id to F)
T + id * id (reduce F to T)
E + id * id (reduce T to E)
E + F * id (reduce id to F)
E + T * id (reduce F to T)
E + T * F (reduce id to F)
E + T (reduce T * F to T)
E (reduce E + T to E)In each right-sentential form, the part that is replaced is the handle. The next chapters on shift-reduce parsing define it precisely.
A small program that prints both derivations
Given a parse tree, you can recover both derivations. The code below builds the tree for id + id * id and prints the sentential forms of each derivation.
class Node:
def __init__(self, label, children=None):
self.label = label
self.children = children or []
def leaf(t):
return Node(t)
def n(label, *kids):
return Node(label, list(kids))
def is_nonterminal(node):
return bool(node.children)
def derive(root, leftmost):
# The frontier is the current sentential form, as a list of nodes.
frontier = [root]
forms = [" ".join(x.label for x in frontier)]
while any(is_nonterminal(x) for x in frontier):
idxs = [i for i, x in enumerate(frontier) if is_nonterminal(x)]
i = idxs[0] if leftmost else idxs[-1]
frontier[i:i + 1] = frontier[i].children
forms.append(" ".join(x.label for x in frontier))
return forms
tree = n("E",
n("E", n("T", n("F", leaf("id")))),
leaf("+"),
n("T",
n("T", n("F", leaf("id"))),
leaf("*"),
n("F", leaf("id"))))
print("Leftmost:")
for form in derive(tree, True):
print(" ", form)
print("Rightmost:")
for form in derive(tree, False):
print(" ", form)In this simplified model, a nonterminal is any node with children, so a nonterminal with an ε production would need an explicit ε leaf. The grammar here has no ε productions, so the model is exact.
Common errors
- Confusing the order of expansion with the tree. A leftmost and a rightmost derivation of the same string can give the same tree. They differ only in step order.
- Forgetting that a rightmost derivation is read in reverse by an LR parser. The sequence of reductions is the reverse of the rightmost derivation.
- Mixing up "leftmost derivation" with "left-recursive grammar." The first is a property of one derivation. The second is a property of the grammar.
- Counting derivations instead of trees. A string with one parse tree can have many derivations, because a derivation that is neither leftmost nor rightmost may expand nonterminals in any order. Only the leftmost and the rightmost derivation are unique for a given tree.
- Treating the yield as the whole tree. Two different trees can have the same yield. That situation is ambiguity, covered next.
Exercises
Exercise
Using the grammar S -> a S b | a b, give the leftmost derivation of aaabbb and state how many parse trees the string has.
Show answer
S ⇒ a S b ⇒ a a S b b ⇒ a a a b b b. The string has exactly one parse tree, because at each step the next input symbols determine whether to use S -> a S b or S -> a b, and only one choice is possible.
Exercise
For the expression grammar in this chapter, write the sequence of reductions a bottom-up parser performs on id * id. Which derivation does this sequence reverse?
Show answer
id id, then F id (id to F), T id (F to T), T F (id to F), T (T F to T), E (T to E). This is the reverse of the rightmost derivation E ⇒ T ⇒ T F ⇒ T id ⇒ F id ⇒ id * id.
Exercise
A string has 5 distinct parse trees. How many distinct leftmost derivations and how many distinct rightmost derivations does it have?
Show answer
5 and 5. Each parse tree corresponds to exactly one leftmost derivation and exactly one rightmost derivation.