消除左递归
S->AB: FIRST ( AB ) FOLLOW ( S ) SELECT( S->AB )
1.将以下文法消除左递归,分析符号串 i*i+i 。
并分别求FIRST集、FOLLOW集,和SELECT集
E -> E+T | T
T -> T*F | F
F -> (E) | i
消除左递归:
E -> TE'
E' -> +TE' | ε
T -> FT'
T' ->*FT' | ε
F -> (E) | i
FIRST集:
FIRST(E)→FIRST(T)→FIRST(F)→{ ( , i }
FIRST(E')→{+,ε}
FIRST(T)→FIRST(F)→{ ( , i }
FIRST(T')→{*,ε}
FIRST(F)→{ ( , i }
FOLLOW集:
FOLLOW(E)→{ ) , # } 可由 (E)得出
FOLLOW(E')→{ ) , # } 可由 (TE')得出
FOLLOW(T)→{ + , ) , # } 可由 (T+T)得出
FOLLOW(T')→{ + , ) , # } 可由 (T+FT')得出
FOLLOW(F)→{ * , + , ) , # } 可由 F+F 、F*F 、(i+i)得出
SELECT集:
SELECT(E→TE')={ ( , i }
SELECT(E'→+TE')={+}
SELECT(E'→ε)= FIRST(ε)-{ ε } U FOLLOW(E') = FOLLOW(E')= { ) , # } FIRST(ε)不存在,所以等于FOLLOW(E')
SELECT(T→FT')={ ( , i }
SELECT(T'→*FT')={*}
SELECT(T'→ε)= FIRST(ε)-{ ε } U FOLLOW(T') = FOLLOW(T')={+,),#} FIRST(ε)不存在,所以等于FOLLOW(T')
SELECT(F→(E))={(}
SELECT(F→i)={i}
2.P101练习7(2)(3)文法改写,并分别求FIRST集、FOLLOW集,和SELECT集.
(2)A→aABe|a
B→Bb|d
消除左递归:
A→aC'
C'→ABe| ε
B→dB'
B'→bB' | ε
FIRST集:
FIRST(A)→{a}
FIRST(A')→{a,ε}
FIRST(B)→{d}
FIRST(B')→{b,ε}
FOLLOW集:
FOLLOW(A)→{d,#}
FOLLOW(C')→{d,#} 可由 aaA'Be 得出 d
FOLLOW(B)→{e}
FOLLOW(B')→{e} 可由 aAdB'e 得出 e
SELECT集:
SELECT(A→aC')={a}
SELECT(C'→ABe)={a}
SELECT(C'→ε)=FIRST(ε) - {ε}∪FOLLOW(C')={ d , # }
SELECT(B→dB')={d}
SELECT(B'→bB')={b}
SELECT(B'→ε)=FIRST(ε) - {ε}∪FOLLOW(B')={e}
(3)S→Aa|b
A→SB
B→ab
即对:
S→SBa|b
B→ab
消除左递归:
S→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(S)→FIRST(Ap)→{a,c,p}
FIRST(A)→FIRST(a)→{a}
FIRST(A)→FIRST(ε)→{ε}
FIRST(A)→FIRST(cA)→{c}
FIRST(A)→FIRST(aA)→{a}
FOLLOW集:
FOLLOW(A)→{p}
FOLLOW(S)→{#}
SELECT集:
SELECT(S->Ap)={a,c,p}
SELECT(A→a)={a}
SELECT(A→ε)=FIRST(ε) - { ε } U FOLLOW(A) =FOLLOW(A)={p}
SELECT(A→cA)={c}
SELECT(A→aA)={a}
S->Ap
S->Bq
A->a
A->cA
B->b
B->dB
FIRST集:
FIRST(S)→FIRST(Ap)→{a,c}
FIRST(S)→FIRST(Bq)→{b,d}
FIRST(A)→FIRST(a)→{a}
FIRST(A)→FIRST(cA)→{c}
FIRST(B)→FIRST(b)→{b}
FIRST(B)→FIRST(dB)→{d}
FOLLOW集:
FOLLOW(S)→{#}
FOLLOW(A)→{p}
FOLLOW(B)→{q}
SELECT集:
SELECT(S->Ap)=FIRST(Ap)={a,c}
SELECT(S->Bq)=FIRST(Bq)={b,d}
SELECT(A->a)={a}
SELECT(A->cA)={c}
SELECT(B->b)={b}
SELECT(B->dB)={d}