第十次作业——消除左递归
1.将以下文法消除左递归,分析符号串 i*i+i 。
并分别求FIRST集、FOLLOW集,和SELECT集
E -> E+T | T
T -> T*F | F
F -> (E) | i
FIRST集:
FIRST(E)={(,i}
FIRST(E')={+,ε}
FIRST(T)={(,i}
FIRST(T')={*,ε}
FIRST(F)={(,i}
FOLLOW集:
FOLLOW(E)={),#}
FOLLOW(E')={),#}
FOLLOW(T)={+,),#}
FOLLOW(T')={+,),#}
FOLLOW(F)={*,+,),#}
SELECT集:
SELECT(E→TE')={ ( , i }
SELECT(E'→+TE')={+}
SELECT(E'→ε)={),#}
SELECT(T→FT')={ ( , i }
SELECT(T'→*FT')={*}
SELECT(T'→ε)={+,),#}
SELECT(F→(E))={(}
SELECT(F→i)={i}
2.P101练习7(2)(3)文法改写,并分别求FIRST集、FOLLOW集,和SELECT集
2)
A->aABe|a
B->Bb|d
消除左递归和提取公共因子
A->aA'|a
A'->ABe
B->bB'|d
B'->bB'|ε
FIRST集:
FIRST(A)→{a}
FIRST(A')→{a,ε}
FIRST(B)→{d}
FIRST(B')→{b,ε}
FOLLOW集:
FOLLOW(A)→{d,#}
FOLLOW(A')→{d,#}
FOLLOW(B)→{e}
FOLLOW(B')→{e}
SELECT集:
SELECT(A→aA')={d,#}
SELECT(A'→ABe)={a}
SELECT(A'→ε)={d,#}
SELECT(B→dB')={e}
SELECT(B'→bB')={b}
SELECT(B'→ε)={e}
(3)
S->Aa|b
A->SB
B->ab
消除左递归:
S→Aa|b→SBa|b→bS'
S'→BaS'|ε
B→ab
FIRST集:
FIRST(S)→{b}
FIRST(S')→{a,ε}
FIRST(B)→{a}
FOLLOW集:
FOLLOW(S)→{#}
FOLLOW(S')→{#}
FOLLOW(B)→{a}
SELECT集:
SELECT(S→bS')={b}
SELECT(S'→BaS')={a}
SELECT(S'→ε)={#}
SELECT(B→ab)={a}
课堂练习:
求以下文法的FIRST集、FOLLOW集和SELECT集。
S->Ap
A->a |ε
A->cA
A->aA
答:
FIRST集:
FIRST(Ap)→{a,c,p}
FIRST(a)→{a}
FIRST(ε)→{ε}
FIRST(cA)→{c}
FIRST(aA)→{a}
FOLLOW集:
FOLLOW(S)→{#}
FOLLOW(A)→{p}
SELECT集:
SELECT(S→Ap)={a,c,p}
SELECT(A→a)={a}
SELECT(A→ε)={p}
SELECT(A→cA)={c}
SELECT(A→aA)={a}
S->Ap
S->Bq
A->a
A->cA
B->b
B->dB
答:
FIRST集:
FIRST(a)→{a}
FIRST(b)→{b}
FIRST(cA)→{c}
FIRST(dB)→{d}
FIRST(Bq)→{b,d}
FIRST(Ap)→{a,c}
FOLLOW集:
FOLLOW(S)→{#}
FOLLOW(A)→{p}
FOLLOW(B)→{q}
SELECT集:
SELECT(S->Ap)={a,c}
SELECT(S->Bq)={b,d}
SELECT(A->a)={a}
SELECT(A->cA)={c}
SELECT(B->b)={b}
SELECT(B->dB)={d}