LL文法的判断,递归下降分析程序
Posted azan1999
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LL文法的判断,递归下降分析程序相关的知识,希望对你有一定的参考价值。
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)文法?
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)文法,写出它的递归下降语法分析程序代码。
E()
{T();
E‘();
}
E‘()
T()
T‘()
F()
答:
void ParseE(){
if(lookhead ==‘(‘ || lookhead == ‘i‘ ){
ParseT();
ParseE‘();
}
else{
printf("syntx error ");
exit(0);
}
}
void ParseE‘(){
switch(lookahead){
case ‘+‘:
MatchToken( ‘+‘ );
ParseT();
ParseE‘();
break;
case ‘)‘ , ‘#‘:
break;
default:
printf("syntx error ");
exit(0);
}
}
void ParseT(){
if(lookhead == ‘(‘ || lookhead == ‘i‘ ){
ParseF();
ParseT‘();
}
else{
printf("syntx error ");
exit(0);
}
}
void ParseT‘(){
switch(lookahead){
case ‘*‘:
MatchToken( ‘*‘ );
ParseF();
ParseT‘();
break;
case ‘+‘ , ‘)‘ , ‘#‘:
break;
default:
printf("syntx error ");
exit(0);
}
}
void ParseF(){
switch(lookahead){
case ‘(‘:
MatchToken( ‘(‘ );
ParseE();
MatchToken( ‘)‘ );
break;
case ‘i‘:
MatchToken( ‘i‘ );
break;
default:
printf("syntx error ");
exit(0);
}
}
以上是关于LL文法的判断,递归下降分析程序的主要内容,如果未能解决你的问题,请参考以下文章