Start Lecture #5
There are different
levels of errors.
off by oneusage of < instead of <=.
The goals are clear, but difficult.
Print an error message when parsing cannot continue and then terminate parsing.
The first level improvement. The parser discards input until it encounters a synchronizing token. These tokens are chosen so that the parser can make a fresh beginning. Good examples are ; and }.
Locally replace some prefix of the remaining input by some string. Simple cases are exchanging ; with , and = with ==. Difficulties occur when the real error occurred long before an error was detected.
Include productions for
Change the input I to the
closest correct input I' and
produce the parse tree for I'.
I am not as formal as the book. In particular, I don't use italics. Nonetheless I do (try to) use some of the conventions, in particular the ones below. Please correct me if I violate them.
This is basically just notational convenience, but important nonetheless.
Assume we have a production A → α.
We would then say that A derives α and write
A ⇒ α
We generalize this.
If, in addition, β and γ are strings (each may contain
terminals and/or nonterminals), we say that
βAγ derives βαγ and write
βAγ ⇒ βαγ.
We say that βAγ derives βαγ in one step.
We generalize further.
If α derives β and β derives γ, we say α
derives γ and write
α ⇒* γ.
The notation used is ⇒ with a * over it (I don't see it in
This should be read
derives in zero or more steps.
Definition: If S is the start symbol and S ⇒* α, we say α is a sentential form of the grammar.
A sentential form may contain nonterminals and terminals. If it contains only terminals it is a sentence of the grammar and the language generated by a grammar G, written L(G), is the set of these sentences.
Definition: A language generated by a (context-free) grammar is called a context free language.
Definition: Two grammars generating the same language are called equivalent.
Examples: Recall the ambiguous grammar above
E → E + E | E * E | ( E ) | idWe see that id + id is a sentence. Indeed it can be derived in two ways from the start symbol E.
E ⇒ E + E ⇒ id + E ⇒ id + id E ⇒ E + E ⇒ E + id ⇒ id + id
In the first derivation, each step replaced the leftmost nonterminal by the body of a production having the nonterminal as head. This is called a leftmost derivation. Similarly the second derivation in which each step replaced the rightmost nonterminal is called a rightmost derivation. Sometimes the latter are called canonical derivations, but we won't do so.
When one wishes to emphasize that a (one step) derivation is leftmost they write an lm under the ⇒. To emphasize that a (general) derivation is leftmost, one writes an lm under the ⇒*. Similarly one writes rm to indicate that a derivation is rightmost. I won't do this in the notes but will on the board.
Definition: If x can be derived using a leftmost derivation, we call x a left-sentential form. Similarly for a right-sentential form.
Homework: 1(ab), 2(ab).
The leaves of a parse tree (or of any other tree), when read left to right, are called the frontier of the tree. For a parse tree we also call them the yield of the tree.
If you are given a derivation starting with a single nonterminal,
A ⇒ α1 ⇒ α2 ... ⇒ αn it is easy to write a parse tree with A as the root and αn as the leaves. Just do what (the production contained in) each step of the derivation says. The LHS of each production is a nonterminal in the frontier of the current tree so replace it with the RHS to get the next tree.
Do this for both the leftmost and rightmost derivations of id+id above.
So there can be many derivations that wind up with the same final tree.
But for any parse tree there is a unique leftmost derivation the
produces that tree (always choose the leftmost unmarked nonterminal
to be the LHS, mark it, and write the production with this LHS and
the children as the RHS).
Similarly, there is a unique rightmost derivation that produces the
There may be others as well (e.g., sometime choose the leftmost
unmarked nonterminal to expand and other times choose the rightmost;
or choose a
middle unmarked nonterminal).
Recall that an ambiguous grammar is one for which there is more than one parse tree for a single sentence. Since each parse tree corresponds to exactly one leftmost derivation, a grammar is ambiguous if and only if it permits more than one leftmost derivation of a given sentence. Similarly, a grammar is ambiguous if and only if it permits more than one rightmost of a given sentence.
We know that the grammar
E → E + E | E * E | ( E ) | idis ambiguous because we have seen (a few lectures ago) two parse trees for
E ⇒ E + E E ⇒ E * E ⇒ id + E ⇒ E + E * E ⇒ id + E * E ⇒ id + E * E ⇒ id + id * E ⇒ id + id * E ⇒ id + id * id ⇒ id + id * id
As we stated before we prefer unambiguous grammars. Failing that, we want disambiguation rules.
Alternatively context-free languages vs regular languages.
Given an RE, construct an NFA as in chapter 3.
From that NFA construct a grammar as follows.
If you trace an NFA accepting a sentence, it just corresponds to the constructed grammar deriving the same sentence. Similarly, follow a derivation and notice that at any point prior to acceptance there is only one nonterminal; this nonterminal gives the state in the NFA corresponding to this point in the derivation.
The book starts with (a|b)*abb and then uses the short NFA on the left below. Recall that the NFA generated by our construction is the longer one on the right.
The book gives the simple grammar for the short diagram.
Let's be ambitious and try the long diagram
A0 → A1 | A7 A1 → A2 | A4 A2 → a A3 A3 → A6 A4 → b A5 A5 → A6 A6 → A1 | A7 A7 → a A8 A8 → b A9 A9 → b A10 A10 → ε
Now trace a path in the NFA and see that it is just a derivation. The same is true in reverse (derivation gives path). The key is that at every stage you have only one nonterminal.
A → a A b | εgenerates all strings of the form anbn, where there are the same number of a's and b's. In a sense the grammar has counted. No RE can generate this language.
A proof is in the book. The idea is that you need a infinite number of states to represent the number of a's you have seen so that you can ensure that you see the same number of b's. But a RE is equivalent to a DFA (or NFA) and the F is for finite.
Why have a separate lexer and parser?
Recall the ambiguous grammar with the notorious
dangling else problem.
stmt → if expr then stmt | if expr then stmt else stmt | other
This has two leftmost derivations for
if E1 then S1 else if E2 then S2 else S3
Do these on the board. They differ in the beginning.
In this case we can find a non-ambiguous, equivalent grammar.
stmt → matched-stmt | open-stmt matched-stmt → if expr then matched-stmt else matched-stmt | other open-stmt → if expr then stmt | if expr then matched-stmt else open-stmt
On the board find the unique parse tree for the problem sentence and from that the unique leftmost derivation.
There are three areas relevant to the above example.
dangling elseexample with the non-ambiguous grammar. We can do this.
We did special cases in chapter 2.
do it right(tm).
Previously we did it separately for one production and for two productions with the same nonterminal on the LHS. Not surprisingly, this can be done for n such productions (together with other non-left recursive productions involving the same nonterminal).
Specifically we start with
A → A α1 | A α2 | ... A αn | β1 | β2 | ... βmwhere the α's and β's are strings, no α is ε, and no β begins with A.
The equivalent non-left recursive grammar is
A → β1 A' | ... | βm A' A' → α1 A' | ... | αn A' | ε
The idea is as follows. Look at the left recursive grammar. At some point you stop producing more As and have the A (which is always on the left) become one of the βs. So the final string starts with a β. Up to this point all the As became Aα for one of the αs. So the final string is a β followed by a bunch of αs, which is exactly what the non-left recursive definition says.
Example: Assume n=m=1, α1 is +
and β1 is *.
With the recursive grammar, we have the following lm derivation.
A ⇒ A + ⇒ A + + ⇒ * + +
With the non-recursive grammar we have
A ⇒ * A' ⇒ * + A' ⇒ * + + A' ⇒ * + +
This removes direct left recursion where a production with A on the left hand side begins with A on the right. If you also had direct left recursion with B, you would apply the procedure twice.
The harder general case is where you permit indirect left recursion, where, for example one production has A as the LHS and begins with B on the RHS, and a second production has B on the LHS and begins with A on the RHS. Thus in two steps we can turn A into something starting again with A. Naturally, this indirection can involve more than 2 nonterminals.
Theorem: All left recursion can be eliminated.
Proof: The book proves this for grammars that have
no ε-productions and
no cycles and has exercises
asking the reader to prove that cycles and ε-productions can
We will try to avoid these hard cases.
Homework: Eliminate left recursion in the
following grammar for simple postfix expressions.
S → S S + | S S * | a
If two productions with the same LHS have their RHS beginning with the same symbol (terminal or nonterminal), then the FIRST sets will not be disjoint so predictive parsing (chapter 2) will be impossible and more generally top down parsing (defined later this chapter) will be more difficult as a longer lookahead will be needed to decide which production to use.
So convert A → x y1 | x y2 into
A → x A' A' → y1 | y2In other words
factor outthe x.
Homework: Left factor your answer to the previous homework.
Although our grammars are powerful, they are not all-powerful. For example, we cannot write a grammar that checks that all variables are declared before used.
We did an example of top down parsing, namely predictive parsing, in chapter 2.
For top down parsing, we
The above has two nondeterministic choices (the nonterminal, and the production) and requires luck at the end. Indeed, the procedure will generate the entire language. So we have to be really lucky to get the input string.
Another problem is that the procedure may not terminate.
Let's reduce the nondeterminism in the above algorithm by specifying which nonterminal to expand. Specifically, we do a depth-first (left to right) expansion. This corresponds to a leftmost derivation. That is, we expand the leftmost non-terminal in the frontier.
We leave the choice of production nondeterministic.
We also process the terminals in the RHS, checking that they match the input. By doing the expansion depth-first, left to right, we ensure that we encounter the terminals in the order they will appear in the frontier of the final tree. Thus if the terminal does not match the corresponding input symbol now, it never will (since there are no nonterminals to its left) and the expansion so far will not produce the input string as desired.
Now our algorithm is
for i = 1 to n if Xi is a nonterminal process Xi // recursive else if Xi (a terminal) matches current input symbol advance input to next symbol else // trouble Xi doesn't match and never will
Note that the
trouble mentioned at the end of the algorithm
does not signify an erroneous input.
We may simply have chosen the wrong production in step 2.
In a general recursive descent (top-down) parser, we would support backtracking. That is, when we hit the trouble, we would go back and choose another production. Since this is recursive, it is possible that no productions work for this nonterminal, because the wrong choice was made earlier.
The good news is that we will work with grammars where we can control the nondeterminism much better. Recall that for predictive parsing, the use of 1 symbol of lookahead made the algorithm fully deterministic, without backtracking.
We used FIRST(RHS) when we did predictive parsing.
Now we learn the whole truth about these two sets, which proves to be quite useful for several parsing techniques (and for error recovery, but we won't make use of this).
The basic idea is that FIRST(α) tells you what the first terminal can be when you fully expand the string α and FOLLOW(A) tells what terminals can immediately follow the nonterminal A.
Definition: For any string α of grammar symbols, we define FIRST(α) to be the set of terminals that occur as the first symbol in a string derived from α. So, if α⇒*cβ for c a terminal and β a string, then c is in FIRST(α). In addition, if α⇒*ε, then ε is in FIRST(α).
Definition: For any nonterminal A, FOLLOW(A) is the set of terminals x, that can appear immediately to the right of A in a sentential form. Formally, it is the set of terminals c, such that S⇒*αAcβ. In addition, if A can be the rightmost symbol in a sentential form (i.e., if S⇒*αA), the endmarker $ is in FOLLOW(A).
Note that there might have been symbols between A and c during the derivation, providing they all derived ε and eventually c immediately follows A.
Unfortunately, the algorithms for computing FIRST and FOLLOW are not as simple to state as the definition suggests, in large part caused by ε-productions.
Do the FIRST and FOLLOW sets for
E → T E' E' → + T E' | ε T → F T' T' → * F T' | ε F → ( E ) | id