Left Recursion Lecture 7 Fri Feb 4 2005
Left Recursion Lecture 7 Fri, Feb 4, 2005
A Problem with Recursive Descent Parsers l l Suppose the grammar were S AB|CD A BA|CA B CA|AD C BA|AD|a D AC|BD|b How could a top-down parser decide which production for S to use?
Another Problem with Recursive Descent Parsers l l Suppose the grammar were S SS|a How could the parser decide how many times to use the production S S S before using the production S a?
Futile Attempt #1 void S() { if (token == a) match(a); else { S(); } }
Futile Attempt #2 void S() { if (token != EOF) { S(); } }
Left Recursion l l l The method of recursive descent does not work if the grammar is left recursive. A grammar is left recursive if there is a derivation A + A for some nonterminal A and string . In particular, a production is left recursive if it is of the form A A.
Left Recursion l Applying the method of recursive descent would lead to the function void A() { A(); // Process } which leads to infinite recursion.
Left Recursion l l l Recall that in the earlier example, we added the production S' S S' | , not the production S' S | Why? Are they equivalent as far as the language of the grammar is concerned?
Eliminating Left Recursion l l Left recursion in a production may be removed by transforming the grammar in the following way. Replace A A | with A A' A' | .
Eliminating Left Recursion l l Under the original productions, a derivation of is A A A A . Under the new productions, a derivation of is A A' A' A' .
Example: Eliminating Left Recursion l l Consider the left recursive grammar E E+T|T T T*F|F F (E) | id Apply the transformation to E: E T E' E' + T E' | .
Example: Eliminating Left Recursion l Then apply the transformation to T: T F T' T' * F T' | .
Example: Eliminating Left Recursion l Now the grammar is E T E' E' + T E' | . T F T' T' * F T' | . F (E) | id
Example: Eliminating Left Recursion l The function for E' would be void Eprime() { if (token == PLUS) { match(PLUS); T(); Eprime(); } return; }
Advantages of Left Recursion l l A left recursive grammar is often more intuitive than the transformed grammar. A left recursive grammar will match expressions earlier, leading to shallow recursion. l l Consider parsing a + b + c + d + e. Bottom-up parsing takes advantage of the benefits of left recursion.
Example l l l Consider the simple grammar E E + E | num Convert it to E num E' E' + E E' | Example: Simple. Parser
Exercise l l l The grammar R R R | R* | (R) | a | b generates all regular expressions on the alphabet {a, b}. Rewrite the grammar to reflect the precedence rules. Eliminate left recursion.
- Slides: 17