Compiler Design and Construction - Old Questions
3. What are the problem with top down parsers? Explain the LR parsing algorithm.
Top-down parser is the parser which generates parse for the given input string with the help of grammar productions by expanding the non-terminals i.e. it starts from the start symbol and ends on the terminals.
Problems with top-down parsers are:
- Only judges grammatically
- Stops when it finds a single derivation.
- No semantic knowledge employed.
- No way to rank the derivations.
- Problems with left-recursive rules.
- Problems with ungrammatical sentences.
LR Parsing algorithm:
An LR parser comprises of a stack, an input buffer and a parsing table that has two parts: action and goto. Its stack comprises of entries of the form so X1 s1 X2s2 ... Xm sm where every si is called a state and every Xi is a grammar symbol(terminal or non-terminal)
If top of the stack is Sm and input symbol is a, the LR parser consults action[sm,a] which can be one of four actions.
1. Shift s , where s is a state.
2. Reduce using production A→ b
3. Accept
4. Error
The function goto takes a state and grammar symbol as arguments and produces a state.
The configuration of the LR parser is a tuple comprising of the stack contents and the contents of the unconsumed input buffer. It is of the form
(so X1 s1 X2s2 ... Xm sm , ai ai+1 ... an $)
1. If action[sm,ai] = shift s, the parser executes a shift move entering the configuration
(so X1 s1 X2s2 ... Xm smais , ai+1 ... an $) shifting both ai and the state s onto stack.
2. If action[sm,ai] = reduce A→ β , the parser executes a reduce move entering the configuration
(so X1 s1 X2s2 ... Xm-r sm-r As , ai ai+1 ... an $) . Here s = goto[sm-r,A] and r is the length of handle β.
Note: if r is the length of β then the parser pops 2r symbols from the stack and push the state as on goto[sm-r,A] . After reduction , the parser outputs the production used on reduce operation. A→β
3. If action[sm,ai] = Accept, then parser accept i.e. parsing successfully complete and stop.
4. If action[sm,ai] = error then call the error recovery routine.