Module 8 · 18 min read · Free chapter
Parsing: top-down and bottom-up
Top-down parsers such as LL(1) trace a leftmost derivation and need a grammar without left recursion or ambiguity. Bottom-up LR parsers shift and reduce, tracing a rightmost derivation in reverse. Power grows as LR(0), SLR(1), LALR(1), CLR(1). LALR has as many states as SLR, and merging can add only reduce-reduce conflicts.
Start from zero: checking a sentence in Hindi class
In a Hindi grammar class, the teacher writes "राम ने आम खाया" and asks whether it is a correct sentence. One student starts from the top: "A sentence has a subject, an object and a verb, so let me look for each." Another starts from the bottom: "राम ने is a subject, आम is an object, खाया is a verb, and together they make a sentence."
Both students reach the same tree, one from the root down and one from the leaves up. A compiler's parser does exactly this with tokens. It checks the order of tokens against a grammar, and builds a parse tree that later phases use.
This chapter teaches both styles. Top-down parsers, such as LL(1) and recursive descent, grow the tree from the start symbol. Bottom-up parsers, such as LR(0), SLR(1), LALR(1) and CLR(1), build it from the tokens upwards by shifting and reducing.
Why it matters. Parsing is the most heavily tested part of compiler design in GATE. FIRST and FOLLOW sets, LL(1) tables, LR items and conflicts appear almost every year.
Grammars, derivations and ambiguity
A context-free grammar has terminals (tokens), non-terminals, a start symbol and productions, as you saw in context-free grammars. Take this expression grammar.
A derivation replaces one non-terminal at a time. In a leftmost derivation the leftmost non-terminal is always replaced, and in a rightmost derivation the rightmost one is. For id + id, the rightmost derivation is shown below.
A top-down parser traces a leftmost derivation from the start symbol. A bottom-up parser traces a rightmost derivation in reverse, starting from the tokens. Each line of a derivation is a sentential form, and a sentential form with only terminals is a sentence.
A grammar is ambiguous if some sentence has two different parse trees, or equivalently two leftmost derivations. The grammar is ambiguous, because id + id * id can group as id + (id * id) or (id + id) * id. The grammar above removes this by giving * its own level , so * binds tighter, and by making the recursion left-sided, so both operators group from the left.
Why it matters. Ambiguity is the root of most parser conflicts. No ambiguous grammar is LL(1) or LR(1), so the first step with a troublesome grammar is to check whether it is ambiguous.
Removing left recursion and left factoring
A top-down parser that meets would call the procedure for , which calls again before reading any token, forever. This is left recursion, and top-down parsing must remove it first. The rule for immediate left recursion is short.
Applied to the expression grammar, it gives the standard LL(1) grammar that the rest of this chapter uses.
Worked example (indirect recursion). Take and . Here calls and calls , so substitute into the rule first: . Now remove the immediate recursion, which gives and .
Left factoring solves a different problem. If two alternatives start with the same symbols, one token of lookahead cannot choose between them. The fix is to delay the choice until the common part has been read.
Worked example (dangling else). The grammar left-factors into and . It is still not LL(1), because the grammar is ambiguous: an else can belong to either if.
Why it matters. GATE often gives a grammar and asks for its form after removing left recursion, or asks why a grammar is not LL(1). These two rewrites are the first things to try.
FIRST and FOLLOW sets
A predictive parser looks at the next token and must know which production to use. Two sets give it that knowledge. FIRST() is the set of terminals that can begin a string derived from , with added if can vanish. FOLLOW() is the set of terminals that can come right after in some sentential form.
Rules for FIRST. For a terminal , FIRST() is . For , add FIRST() without ; if can vanish, add FIRST() as well, and so on. If every can vanish, add .
Rules for FOLLOW. First, put the end marker in FOLLOW of the start symbol. Second, for , add FIRST() without to FOLLOW(). Third, for , or where can vanish, add all of FOLLOW() to FOLLOW().
Worked example. For the LL(1) expression grammar of the last section, the sets are as follows.
| Non-terminal | FIRST | FOLLOW |
|---|---|---|
Trace two entries to see the rules at work. FOLLOW() gets from FIRST() in , and because can vanish it also gets all of FOLLOW(), which is and . FOLLOW() gets from FIRST(), and since can vanish, all of FOLLOW() too.
Why it matters. Nearly every LL(1) and SLR(1) question in GATE starts with these two sets. A single missed changes the table and the answer.
The LL(1) table, its conflicts and recursive descent
LL(1) means the input is read Left to right, a Leftmost derivation is built, and 1 token of lookahead is used. The parser keeps a stack and a table indexed by a non-terminal and a terminal. The table is filled with two rules.
- For each production and each terminal in FIRST(), put in .
- If is in FIRST(), also put in for every in FOLLOW(), including .
| Non-terminal | ||||||
|---|---|---|---|---|---|---|
An empty cell means a syntax error. Every cell here has at most one entry, so the grammar is LL(1); in fact it has 13 filled cells. If a cell receives two productions, that is an LL(1) conflict, and the grammar is not LL(1).
For two alternatives , the grammar is LL(1) only if FIRST() and FIRST() are disjoint, and, when can vanish, FIRST() and FOLLOW() are disjoint. In the dangling-else grammar, and both land in , because is in FOLLOW(). That double entry is the conflict.
A recursive-descent parser writes one procedure per non-terminal. When the grammar is LL(1), each procedure chooses its production by looking at one token, so no backtracking is ever needed. Such a parser is called predictive.
void E() { T(); Eprime(); }
void Eprime() { if (look == '+') { match('+'); T(); Eprime(); } }
void T() { F(); Tprime(); }
void Tprime() { if (look == '*') { match('*'); F(); Tprime(); } }
void F() { if (look == '(') { match('('); E(); match(')'); } else match(ID); }
Notice that becomes "do nothing" when the lookahead is not +. A parser that tries alternatives and undoes them on failure is a backtracking parser, which can take exponential time.
Why it matters. Many GATE questions give a grammar and ask how many cells of the LL(1) table are filled, or which cell has a conflict. With FIRST and FOLLOW in hand, the table takes two minutes.
Shift-reduce parsing and handles
A bottom-up parser keeps a stack, starting with , and reads the input left to right. At each step it does one of four things. It can shift the next token onto the stack, reduce the top of the stack by replacing the right side of a production with its left side, accept when the stack holds only the start symbol and the input is used up, or report an error.
The part of the stack that should be reduced next is the handle. Formally, a handle is a right side of a production whose reduction is one step backwards along the rightmost derivation. The whole difficulty of bottom-up parsing is to find the handle without guessing.
Worked example. Parse id + id * id with , , .
| Stack | Input | Action |
|---|---|---|
| Shift | ||
| Reduce | ||
| Reduce | ||
| Reduce | ||
| Shift twice | ||
| Reduce , then | ||
| Shift, not reduce | ||
| Shift | ||
| Reduce | ||
| Reduce | ||
| Reduce | ||
| Accept |
Count the moves: there are 5 shifts, one per token, and 8 reductions, one per interior node of the parse tree. The key moment is the row with on the stack and * next. Reducing there would be wrong, because * binds tighter, and an LR table knows to shift.
Two kinds of conflict can stop a shift-reduce parser. A shift-reduce conflict means the parser cannot decide whether to shift or reduce, as in the dangling else. A reduce-reduce conflict means two different productions could be used to reduce. A viable prefix is any prefix of a right sentential form that can appear on the stack, and the set of viable prefixes is a regular language.
Why it matters. GATE asks for the number of shifts and reductions, or for the handle at a given step. The trace table above is the standard way to answer.
LR(0) items and SLR(1) parsing
How does an LR parser know when the top of the stack is a handle? It runs a DFA over the stack, and the states of that DFA are sets of items. An LR(0) item is a production with a dot in its right side. For example, means "we have seen and expect an next".
Two operations build the DFA. Closure of a set of items adds for every item with the dot just before a non-terminal , repeating until nothing new appears. Goto on a symbol moves the dot past in every item where that is possible, and then takes the closure.
Worked example. Take , , augmented with .
| State | Items | Moves |
|---|---|---|
| , , , | to , to , to , to | |
| Accept on the end marker | ||
| , , | to , to , to | |
| , , | to , to , to | |
| Reduce | ||
| Reduce | ||
| Reduce |
There are 7 states. Each reduce state holds a single completed item and nothing else, so the grammar is LR(0). An LR(0) parser reduces in such a state whatever the next token is.
The LR(0) rule fails when a state has both a completed item and a shift item. Take and : after reading , the state holds and . LR(0) does not know whether to shift + or reduce, which is a shift-reduce conflict.
SLR(1) adds one simple idea: reduce by only on tokens in FOLLOW(). Here FOLLOW() is , which does not contain +. So SLR shifts on + and reduces on , and the conflict disappears.
Why it matters. GATE often asks for the number of states in the LR(0) collection, or whether a grammar is LR(0) or SLR(1). Building the item sets carefully is the only reliable way.
CLR(1), LALR(1), their power and operator precedence
SLR uses FOLLOW(), which lists tokens that can follow anywhere in the grammar. In a particular state, fewer tokens may actually be possible. The classic case is , , .
In this grammar, one state holds and . FOLLOW() contains =, so SLR wants to reduce on = and also to shift =, which is a conflict. Yet in that state an can never be followed by =, so the grammar is not SLR(1) but is fine for a stronger method.
Canonical LR(1), or CLR(1), attaches a lookahead to each item: means "reduce only if the next token is ". The lookaheads are computed during closure, from FIRST of what follows the non-terminal. CLR(1) is the most powerful of the four LR methods, but it has many more states; for , it has 10 states against 7.
LALR(1) keeps the lookaheads but merges CLR states whose items are the same apart from lookaheads, that is, states with the same core. The result has exactly as many states as the LR(0) collection, 7 in the example. Parser generators such as YACC produce LALR(1) parsers for this reason.
Merging can cause trouble, but only of one kind. Take , , . CLR has one state with and , and another with and , and both are conflict-free. Merging them puts both reductions on both and , a reduce-reduce conflict; a new shift-reduce conflict can never arise this way, because shifts do not depend on lookaheads.
Each inclusion is strict. Every LL(1) grammar is also LR(1), and no ambiguous grammar is LL(1) or LR(1). By number of states, LR(0), SLR(1) and LALR(1) are equal, and CLR(1) has at least as many.
Operator-precedence parsing is an older bottom-up method for expressions. It needs an operator grammar, with no -production and no two non-terminals side by side on any right side. Between terminals it defines ( yields to ), and ( takes precedence); for example , , and for left associativity, and the handle lies between and . It can even parse the ambiguous grammar , but it handles operators such as unary minus badly.
Why it matters. "Which parser is most powerful?" and "can LALR merging create a shift-reduce conflict?" are standard GATE questions. The chain of inclusions and the one-line merging rule answer both.
Descriptive lens: how written papers ask this
Written papers for scientist posts and university examinations ask about parsing in four ways:
- Compute FIRST and FOLLOW sets for a grammar and build its LL(1) table, then say whether the grammar is LL(1).
- Construct the canonical LR(0) or LR(1) collection for a small grammar and fill the parsing table.
- Trace a shift-reduce parse of a given input, showing the stack, the input and each action.
- Compare the parsing methods by power, table size and the conflicts each can face.
Practice questions (our own, not previous-year questions).
- Remove left recursion from , , . Compute FIRST and FOLLOW and build the LL(1) table. (15 marks)
- Show that the grammar , , is not SLR(1) but is LALR(1). (15 marks)
- Compare LR(0), SLR(1), LALR(1) and CLR(1) parsers. Explain why merging states in LALR(1) can create only reduce-reduce conflicts. (10 marks)
Answer plan for question 3.
- Begin by defining an LR parser as a shift-reduce parser driven by a DFA over item sets.
- Explain that LR(0) reduces on every token, SLR(1) reduces on FOLLOW of the left side, and CLR(1) reduces only on the item's own lookahead.
- State that LALR(1) merges CLR(1) states with the same core, so it has as many states as LR(0) while keeping most of CLR's power.
- Write the strict chain of grammar classes from LR(0) to CLR(1), and add that every LL(1) grammar is LR(1).
- Argue that shift actions depend only on the core, so a shift-reduce conflict after merging would already exist in one of the CLR states.
- Show the grammar with and as an example where merging creates a reduce-reduce conflict.
- Conclude that LALR(1) is the practical choice, which is why parser generators use it.
Quick revision
- Top-down parsing traces a leftmost derivation, and bottom-up parsing traces a rightmost derivation in reverse.
- becomes and .
- FIRST can contain , FOLLOW never does, and the end marker is in FOLLOW of the start symbol.
- A grammar is LL(1) when no cell of its table has two entries, and left-recursive or ambiguous grammars never are.
- A shift-reduce parse of tokens has shifts and one reduction per interior node of the tree.
- LR(0) reduces on every token, SLR(1) on FOLLOW, and CLR(1) on the item's lookahead.
- LALR(1) merges CLR(1) states with the same core and has as many states as LR(0).
- Merging can create reduce-reduce conflicts but never new shift-reduce conflicts.
- The power chain is LR(0), SLR(1), LALR(1), CLR(1), each strictly larger, and every LL(1) grammar is LR(1).
- An operator grammar has no -production and no two adjacent non-terminals.