1. 文法 G(S):遞歸
(1)S -> ABit
(2)A ->Da|εclass
(3)B -> cC語法
(4)C -> aADC |ε程序
(5)D -> b|εerror
驗證文法 G(S)是否是 LL(1)文法?filter
FIRST集:di
FIRST(A) = { b , a , ε}co
FIRST(C) = { a , ε}cas
FIRST(D) = { b , ε}
FOLLOW集:
FOLLOW (A) = { c , b , a , ε}
FOLLOW (C) = { # }
FOLLOW (D) = { a , #}
SELECT集:
SELECT( A -> Da ) = FIRST( Da ) = { b , a }
SELECT( A -> Da) = FIRST(Da) = { b, a }
SELECT( A -> ε) = FOLLOW( A) = { c, b, a, # }
SELECT( C -> aADC) = FIRST( aADC) = { a }
SELECT( C -> ε) = FOLLOW(C) = { # }
SELECT( D -> b) = FIRST(b) = { b }
SELECT( D -> ε ) =FOLLOW(D) = { a, # }
由於SELECT( A -> Da) ∩ SELECT( A -> ε) = { a } ≠ ∅,因此文法G(S)不是 LL(1)文法。
2.(上次做業)消除左遞歸以後的表達式文法是不是LL(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) = { ( , 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') = FIRST(TE') = { ( , i }
SELECT(E' -> +TE') = FIRST(+TE') = { + }
SELECT(E' -> ε) = FIRST(ε) - {ε} U FOLLOW(E') = FOLLOW(E') = { ) , # }
SELECT(T -> FT') = FIRST(FT') = { ( , i }
SELECT(T' -> *FT') = FIRST(*FT') = { * }
SELECT(T' -> ε) = FIRST(ε) - {ε} U FOLLOW(T') = FOLLOW(T') = { + , ) ,# }
SELECT(F -> (E)) = FIRST((E)) = { ( }
SELECT(F -> i) = FIRST(i) = { i }
由於SELECT(E' -> +TE') ∩ SELECT(E' -> ε) = ∅,
SELECT(T' -> *FT') ∩ SELECT(T' -> ε) = ∅,
SELECT(F -> (E)) ∩ SELECT(F -> (E)) = ∅,
因此該文法是 LL(1)文法
3.接2,若是是LL(1)文法,寫出它的遞歸降低語法分析程序代碼。
void ParseE(){
if(lookahead==’(’ || lookahead==’i’){
ParseT();
ParseE’();
}else{
printf(「syntax error \n」);
exit(0);
}
}
void ParseE’(){
switch(lookahead){
case ’+’:
MatchToken(’+’);
ParseT();
ParseE’();
break;
case ’)’,’#’:
break;
default:
printf(「syntax error \n」);
exit(0);
}
}
void ParseT(){
if(lookahead==’(’ || lookahead==’i’ ){
ParseF();
ParseT’();
} else{
printf(「syntax error \n」);
exit(0);
}
}
void ParseT’(){
switch(lookahead){
case ’*’:
MatchToken(’*’);
ParseF();
ParseT’();
break;
case ’+’,’)’,’#’:
break;
default:
printf(「syntax error \n」);
exit(0);
}
}
void ParseF(){
switch(lookahead){
case ’(’:
MatchToken( ’(’);
ParseE();
MatchToken(’)’ );
break;
case ’i’:
MatchToken(’i’);
break;
default:
printf(「syntax error \n」);
exit(0);
}
}
4.加上實驗一的詞法分析程序,造成可運行的語法分析程序,分析任意輸入的符號串是否是合法的表達式。