1. 文法 G(S):
(1)S -> AB
(2)A ->Da|ε
(3)B -> cC
(4)C -> aADC |ε
(5)D -> b|ε
验证文法 G(S)是不是 LL(1)文法?
SELECT(A->Da) = {b,a}
SELECT(A->ε) = {c,b,a,#}SELECT(C->aADC) = {a}
SELECT(C->ε) = {#}
SELECT(D->b) = {a,#}
SELECT(D->ε) = {a,#}
因为:
SELECT(A->Da) ∩ SELECT(A->ε) ≠ Φ
SELECT(C->aADC) ∩ SELECT(C->ε) = Φ
SELECT(D->b) ∩ SELECT(D->ε) = Φ
所以G(S)不是LL(1)文法。
2.(上次作业)消除左递归之后的表达式文法是否是LL(1)文法?
SELECT(E'-> +TE') = FIRST(+TE')={+}
SELECT(E'->ε) = FOLLOW(E') = FOLLOW(E) = {#, )}
SELECT(T'->*FT') = FRIST(*FT') = {*}
SELECT(T'->ε) = FOLLOW(T') = FOLLOW(T) = {#, ), +}
SELECT(F->(E)) = FRIST((E)) = {(}
SELECT(F->i) =FRIST(i) = {i}
因为:
SELECT(E' -> +TE') ∩ SELECT(E' -> ɛ) = ΦSELECT(T' -> *FT' ) ∩ SELECT(T' -> ɛ) = Φ
SELECT(F -> (E) ) ∩ SELECT(F -> i ) = Φ
所以消除左递归后的文法是 LL(1)文法
3.接2,如果是LL(1)文法,写出它的递归下降语法分析程序代码。
E()
{T();
E'();
}
E'()
T()
T'()
F()
代码如下:
void ParseE(){ switch(lookahead){ case ‘(‘,‘i‘, ‘*‘: ParseT(); ParseEP(); break; default: print("syntx error! "); exit(0); } }
void ParseEP(){ switch(lookahead){ case ‘+‘: MatchToken(‘+‘); ParseT(); ParseEP(); break; case ‘#‘, ‘)‘: break; default: print("syntx error! "); exit(0); } } void ParseT(){ switch(lookahead){ case ‘(‘,‘i‘: ParseF(); ParseTP(); break; default: print("syntx error! "); exit(0); } } void ParseTP(){ switch(lookahead){ case ‘*‘: MatchToken(‘*‘); ParseF(); ParseTP(); break; case ‘#‘, ‘)‘, ‘+‘: break; default: print("syntx error! "); exit(0); } } void ParseF(){ switch(lookahead){ case ‘(‘: MatchToken(‘(‘); ParseE(); MatchToken(‘)‘); break; case ‘i‘: MatchToken(‘i‘); break; default: print("syntx error! "); exit(0); } }
4.加上实验一的词法分析程序,形成可运行的语法分析程序,分析任意输入的符号串是不是合法的表达式。