Bottom Up Parsing - LR Parsers (LR (0), SLR, CLR and LALR Parsers)
Bottom Up Parsing - LR Parsers (LR (0), SLR, CLR and LALR Parsers)
Steps:
SLR parser, CLR parser and LALR parser which are the parts of Bottom Up parser.
SLR Parser
The SLR parser is similar to LR(0) parser except that the reduced entry. The reduced productions are written
only in the FOLLOW of the variable whose production is reduced.
1. Construct C = { I0, I1, ……. In}, the collection of sets of LR(0) items for G’.
2. State i is constructed from Ii. The parsing actions for state i are determined as follow :
If [ A -> ?.a? ] is in Ii and GOTO(Ii , a) = Ij , then set ACTION[i, a] to “shift j”. Here a
must be terminal.
If [A -> ?.] is in I , then set ACTION[i, a] to “reduce A -> ?” for all a in
i
generated by the above rules we say that the grammar is not SLR.
3. The goto transitions for state i are constructed for all nonterminals A using the rule:
if GOTO( Ii , A ) = Ij then GOTO [i, A] = j.
4. All entries not defined by rules 2 and 3 are made error.
Eg:
If in the parsing table we have multiple entries then it is said to be a conflict.
E -> T+E | T
T ->id
E -> T+E | T
T -> id
CLR PARSER
In the SLR method we were working with LR(0)) items. In CLR parsing we will be using LR(1) items. LR(k)
item is defined to be an item using lookaheads of length k. So , the LR(1) item is comprised of two parts : the
LR(0) item and the lookahead associated with the item.
LR(1) parsers are more powerful parser.
For LR(1) items we modify the Closure and GOTO function.
Closure Operation
Closure(I)
repeat
return I;
Goto Operation
Goto(I, X)
Eg-
Repeat
Add GOTO(I, X) to C;
1. Construct C = { I0, I1, ……. In} , the collection of sets of LR(0) items for G’.
2. State i is constructed from Ii. The parsing actions for state i are determined as follow :
i) If [ A -> ?.a?, b ] is in Ii and GOTO(Ii , a) = Ij, then set ACTION[i, a] to “shift j”. Here a must be
terminal.
ii) If [A -> ?. , a] is in Ii , A ≠ S, then set ACTION[i, a] to “reduce A -> ?”.
iii) Is [S -> S. , $ ] is in Ii, then set action[i, $] to “accept”.
If any conflicting actions are generated by the above rules we say that the grammar is
not CLR.
Eg:
A -> ?
B -> ?
Augmented grammar –
S’ -> S
A -> ?
B -> ?
Note – if a state has two reductions and both have same lookahead then it will in multiple entries in parsing
table thus a conflict. If a state has one reduction and their is a shift from that state on a terminal same as the
lookahead of the reduction then it will lead to multiple entries in parsing table thus a conflict.
S ->AA
A -> aA | b
Augmented grammar
S’ -> S
S ->AA
A -> aA | b
Important Notes
1. Even though CLR parser does not have RR conflict but LALR may contain RR conflict.
2. If number of states LR(0) = n1,
number of states SLR = n2,
number of states LALR = n3,
number of states CLR = n4 then,