


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



A top-down parser starts with the root of the parse tree. The root node is labeled with the goal (start) symbol of the grammar. The top-down parsing algorithm proceeds as follows:
The key is picking right production in step a. That choice should be guided by the input string. Let’s try parsing using this algorithm using the expression grammar.
x – 2 (^) * y
P Sentential Form input
This worked well except that “–” does not match “+”. The parser made the wrong choice of production to use at step 2. The parser must backtrack and use a different production.
This time the “–” and “–” matched. We can advance past “ – ” to look at “ 2 ”. Now, we need to expand “ term ”
P Sentential Form input
The 2’s match but the expansion terminated too soon because there is still unconsumed input and there are no non-terminals to expand in the sentential form ⇒ Need to backtrack.
P Sentential Form input
This time the parser met with success. All of the input matched.
Left Recursion
Consider another possible parse:
Parser is using productions but no input is being consumed.
9 <id,x> – <num,2> x – ↑ (^2) * y
7 <id,x> – factor x – ↑ (^2) * y
P Sentential Form input
2 expr + term + term + term +....^ ↑ x^ –^2 * y
2 expr + term + term + term^ ↑ x^ –^2 * y
2 expr + term + term^ ↑ x^ –^2 * y
expr + term
expr
Goal
Sentential Form
2^ ↑ x^ –^2 * y
1^ ↑ x^ –^2 * y
P input
Predictive Parsing
If a top down parser picks the wrong production, it may need to backtrack. Alternative is to look-ahead in input and use context to pick the production to use correctly. How much look-ahead is needed? In general, an arbitrarily large amount of look-ahead symbols are required.. Fortunately, large classes of CFGs can be parsed with limited lookahead. Most programming languages constructs fall in those subclasses
The basic idea in predictive parsing is: given A? α | β , the parser should be able to choose between α and β. To accomplish this, the parser needs FIRST and FOLLOW sets.
Definition: FIRST sets: for some rhs α ∈ G , define FIRST( α ) as the set of tokens that appear as the first symbol in some string that derives from α. That is, x ∈ FIRST( α ) iff α ⇒∗^ x γ, for some γ.