Sub topic 4
Leftmost and Rightmost Derivations and Parse Trees
Assume you know alphabets, strings, languages, and the definition of a context-free grammar (CFG). A CFG has variables, terminals, production rules, and a start variable. This chapter focuses on how a grammar generates a string and how that generation is represented as a tree.
Sentential forms and derivations
A sentential form is any string of terminals and variables that can occur during generation. A derivation is a sequence of rule applications beginning with the start variable.
Consider this grammar:
S -> a S b | a bThe start variable is S. The grammar generates the language
L = { a^n b^n | n >= 1 }Starting with S, repeatedly replace a variable using one production:
S => aSb
=> aaSbb
=> aaabbbThe last string contains only terminals, so it is a generated word. The symbol => means “derives in one step.” The notation =>* means “derives in zero or more steps.”
Leftmost derivation
In a leftmost derivation, replace the leftmost variable in every step. For the same grammar:
S => aSb
=> aaSbb
=> aaabbbAt each step, there is only one variable, so this example does not show a choice. Use this grammar instead:
S -> A B
A -> a A | a
B -> b B | bA leftmost derivation of aabb is:
S => A B
=> a A B
=> a a B
=> a a b B
=> a a b bThe variable in the leftmost available position is expanded first.
Rightmost derivation
In a rightmost derivation, replace the rightmost variable first:
S => A B
=> A b B
=> A b b
=> a A b b
=> a a b bBoth derivations generate the same word. They differ only in the order of rule applications.
Parse trees
A parse tree is a rooted, ordered tree for a derivation. The root is the start variable. Internal nodes are variables, and the children of a variable are the symbols on the right side of its selected production. Reading the leaves from left to right gives the generated word.
The tree does not depend on whether the leftmost or rightmost derivation was used. It represents the same grammar structure.
Exercise
For the grammar S -> aSb | ab, give a derivation of aaabbb and identify whether it is leftmost or rightmost.
Show answer
S => aSb => aaSbb => aaabbb. It is both leftmost and rightmost because each sentential form has only one variable.