1.将以下文法消除左递归,分析符号串 i*i+i 。
并分别求FIRST集、FOLLOW集,和SELECT集
E -> E+T | T
T -> T*F | F
F -> (E) | i
解:消除左递归:
(1) E->TE'
E'->+TE'|ε
(2) T->FT'
T'->*FT'|ε
(3) F->(E)|i
① FIRST集: ② FOLLOW集: ③ SELECT集:
First(TE') = {T} Follow(E) = {)} Select(E->TE') = First(TE') = {T}
First(+TE') = {+} Follow(E') = {#} Select(E'->+TE') = First(+TE') = {+}
First(ε) = {ε} Follow(T) = {E'} Select(E'->ε) = (First(ε) = {ε})∪Follow(E') = {)}
First(FT') = {F} Follow(T') = {#} Select(T->FT') = First(FT') = {F}
First(*FT') = {*} Select(T'->*FT') = First(+TE') = {*}
First(ε) = {ε} Select(T'->ε) = (First(ε) = {ε})∪Follow(T') = {#}
First((E)) = {( } Select( F->(E)) = First((E)) = {( }
First(i) = {i} Select( F->i) = First(i) = {i}
2.P101练习7(2)(3)文法改写,并分别求FIRST集、FOLLOW集,和SELECT集
(2)先对A提取公共左因子:
A -> aC
C -> ABe | ɛ
B -> dB'
B' -> bB' | ɛ
FIRST集: FOLLOW集: SELECT集:
FIRST(A) = { a } FOLLOW(A) = { d , # } SELECT(A -> aC) = { a }
FIRST(C) = { ABe , ɛ } = { e , ɛ } FOLLOW(B) = { e } SELECT(C -> ABe) = { e , ɛ }
FIRST(ɛ) = { ɛ } FOLLOW(B') = { e } SELECT(C -> ɛ) = { d , # }
FIRST(B) = { d } FOLLOW(C) = { d , # } SELECT(B -> dB') = { d }
FIRST(B') = { b ,ɛ } SELECT(B' -> bB') ={ b ,ɛ }
FIRST(ɛ) = { ɛ } SELECT(B' -> ɛ) ={ e }
(3)S -> SBa | b
S -> bS'
S' -> BaS' | ɛ
B -> ab
FIRST集: FOLLOW集:
FIRST(S) = { b } FOLLOW(S) = { # }
FIRST(S') = { Ba , ɛ } = { a , ɛ } FOLLOW(S') = { # }
FIRST(ɛ) = { ɛ } FOLLOW(B) = { b }
FIRST(B) = { a }
SELECT集:
SELECT(S -> bS') = { b }
SELECT(S' -> BaS' ) = { a , ɛ }
SELECT(S' -> ɛ) = { # }
SELECT(B -> ab) = { a }
3.课堂练习:
求以下文法的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(A) = { p }
FOLLOW(S) = { # }
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(S1) = FIRST(Ap) = { a , c }
FIRST(S2) = FIRST(Bq) = { b , d }
FIRST(a) = { a }
FIRST(cA) = { c }
FIRST(b) = { b }
FIRST(dB) = { d }
FOLLOW集:
FOLLOW(A) = { p }
FOLLOW(B) = { q }
FOLLOW(S) = { # }
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 }