– Exercise: construct the SLR parsing table for grammar:

advertisement
– Exercise: construct the SLR parsing table for grammar:
S->L=R,
S->R
L->*R
L->id
R->L
– The grammar can have shift/reduce conflict or
reduce/reduce conflict.
• What about shift/shift conflict?
– SLR does not always remember the right
context -- using the follow set to determine
when to reduce is sometimes too general.
– LR(1) parsing table has more context
information in its items.
• An LR(1) item is of the form
[ A     , a], where A   is a production and a is a terminal
– terminal a has not effect when  is not  .
– When  is  , an item of the form [ A   , a] means to
reduce only when the next input symbol is a.
• Computing sets of LR(1) items.
– Closure(I) is now slightly different
for each item [ A    B , a ] in I
each production B   in the grammar,
and each termi nal b in First ( a )
add [ B   , b] to I (if not there)
– Start the construction of the set of LR(1) items
by computing the closure of
{[ S '  S ,$]}
• Example 1: first page
• Example 2:
S’ -> S
S -> CC
C ->cC
C ->d
• Constructing the LR(1) parsing table
Let C  {I 0 , I1 ,..., I n }
1. if [ A    a , x] is in I i and goto( I i , a )  I j then
set action[i, a ] to " shift j".
2. If [ A   , a ] is in I i , then set action[ I i , a ] to reduce A  
3. if [ S '  S ,$] is in I i , then set action[i,$] to " accept"
4. if goto[ I i , A]  I j , then set goto[i, A] to j.
5. set all other tabl e entries to error
6. The initial state is the one holding [S'  S, $].
– The number of states in LR(1) parsing table is
much more than that in SLR parsing table.
– LALR reduces the number of states in LR(1)
parsing table.
• LALR (LookAhead LR) is less powerful than LR(1)
• reducing states may introduce reduce-reduce
conflict, but not shift-reduce conflict.
• LALR has the same number of states as SLR, but
more powerful.
– Constructing LALR parsing table.
• Combine LR(1) sets with the same sets of first parts
(ignore lookahead).
• Algorithms exist that skip constructing the LR(1)
sets.
– Using ambiguous grammars
• ambiguous grammars will results in conflicts
• Can use precedence and assocativity to resolve the
conflicts
• May result in a smaller parsing table in comparison
to using un-ambiguous grammars.
• Example:
E->E+E
E->E*E
E->(E)
E->id
Download