Homework 3 Solutions Problem 4.35 (10 Points)
Homework 3 Solutions Problem 4.35 (10 Points)
Homework 3 Solutions
0 1 2 3 4 5 6 7 8 9
a b $ E T F s3 s4 8 1 2 s3 s4 r(E ! T:) 7 r(T ! F:) r(T ! F:) r(T ! F:) r(F ! a:) r(F ! a:) r(F ! a:) r(F ! b:) r(F ! b:) r(F ! b:) s3 s4 6 2 s3 s4 r(E ! E + T:) 7 r(T ! TF:) r(T ! TF:) r(T ! TF:)
r(F ! F :)
accept
action
goto
b) Construct the LALR parsing table. Construct the sets of LR(1) items:
I0 : E 0 ! :E $ E ! :E + T $=+ E ! :T $=+ T ! :TF $= + =a=b T ! :F $= + =a=b F ! :F $= + =a=b= F ! :a $= + =a=b= F ! :b $= + =a=b= I1 : E ! T: $=+ E ! T:F $= + =a=b E ! :F $= + =a=b= E ! :a $= + =a=b= E ! :b $= + =a=b= I2 : T ! F: $= + =a=b F ! F: $= + =a=b= I3 : F ! a: $= + =a=b= I4 : F ! b: $= + =a=b=
State
I5 : E ! E + :T $=+ T ! :TF $= + =a=b T ! :F $= + =a=b T ! :F $= + =a=b= T ! :a $= + =a=b= T ! :b $= + =a=b= I6 : E ! E + T: $=+ T ! T:F $= + =a=b T ! :F $= + =a=b= T ! :a $= + =a=b= T ! :b $= + =a=b= I7 : T ! TF: $= + =a=b F ! F: $= + =a=b= I8 : E 0 ! E: $ E ! E: + T $=+ I9 : F ! F : $= + =a=b=
Now construct the LALR parsing table: 0 1 2 3 4 5 6 7 8 9 + r(E ! T:) r(T ! F:) r(F ! a:) r(F ! b:) s9 r(F ! a:) r(F ! b:)
a b $ E T F s3 s4 8 1 2 s3 s4 r(E ! T:) 7 r(T ! F:) r(T ! F:) r(T ! F:) r(F ! a:) r(F ! a:) r(F ! a:) r(F ! b:) r(F ! b:) r(F ! b:) s3 s4 6 2 s3 s4 r(E ! E + T:) 7 r(T ! TF:) r(T ! TF:) r(T ! TF:)
r(F ! F :)
accept
action
goto
But the FOL1 (A) = fa; bg and FOL1 (B ) = fa; bg. Since the lookahead sets are not disjoint there is a reduce/reduce con ict and the grammar is not SLR(1). On the other hand it is LL(1) because FIRST1(AaBb) 1 FOL1 (S ) = fag FIRST1(BbAa) 1 FOL1 (S ) = fbg and the intersection of fag and fbg is empty b) Show that every LL(1) grammar is an LR(1) grammar. (Optional) If you're interested there is a proof that every LL(k) grammar is LR(k) in Chapman, Nigel P. ,LR Parsing Theory and Practice, Cambridge University Press 1987 p. 74
0 1 r(A ! d) s2 2 r(S ! dc) 3 s4 6 4 s5 r(A ! d) 5 r(S ! bda) 6 s7 7 r(S ! bAc) 8 s9 9 r(S ! Aa) 10 accept The grammar is LALR(1) since there are no parsing action con icts in the table. The grammar is not SLR(1) because the following state in the LR(0) machine: I1 : S ! d:c A ! d: 3
b s3
action
d s1
S A 10 8
goto
0 1 accept 2 r(A ! d) r(B ! d) 3 s9 4 s10 11 7 5 s6 6 r(S ! Bc) 7 s8 8 r(S ! bBa) 9 r(S ! Aa) 10 r(B ! d) r(A ! d) 11 s12 12 r(S ! bAc) The grammar is LR(1) since there are no parsing action con icts in the table. The grammar is not LALR(1) because when we merge state 2 and state 10 we get: I210: A ! d: a=c B ! d: a=c which has a reduce/reduce con ict. 4
b s4
action
d s2
S A B 1 3 5
goto