1. 文法 G(S):
(1)S -> AB
(2)A ->Da|ε
(3)B -> cC
(4)C -> aADC |ε
(5)D -> b|ε
验证文法 G(S)是不是 LL(1)文法?
FIRST集:
FIRST(A) = { b , a , ε}
FIRST(C) = { a , ε}
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.加上实验一的词法分析程序,形成可运行的语法分析程序,分析任意输入的符号串是不是合法的表达式。