LL(1)文法的判断,递归下降分析程序
作者:互联网
1. 文法 G(S):
(1)S -> AB
(2)A ->Da|ε
(3)B -> cC
(4)C -> aADC |ε
(5)D -> b|ε
验证文法 G(S)是不是 LL(1)文法?
2.(上次作业)消除左递归之后的表达式文法是否是LL(1)文法?
3.接2,如果是LL(1)文法,写出它的递归下降语法分析程序代码。
E()
{T();
E'();
}
E'()
T()
T'()
F()
4.加上实验一的词法分析程序,形成可运行的语法分析程序,分析任意输入的符号串是不是合法的表达式。
1.
解:
Select(A -> Da) = First(Da) = {b,a}
Select(A -> ε) = (Follow(ε)-{ε})∪Follow(A) = {b,a,c,ε}
Select(C -> aADC) = First(aADC) = {a}
Select(C -> ε) = (Follow(ε)-{ε})∪Follow(C) = {ε}
Select(D -> b) = First(b) = {b}
Select(D -> ε) = (Follow(ε)-{ε})∪Follow(D) = {a,ε}
∵Select(A -> Da) ∩ Select(A -> ε) ≠ ∅
∴文法G(s)不是LL(1)文法。
2
解:
消除左递归后:
E -> TE'
E' -> +TE' | ε
T -> FT'
T' -> *FT' | ε
F -> (E) | i
SELECT(E' -> +TE') = FIRST(+TE') = {+}
SELECT(E' -> ε) = (FIRST(ε) - { ε }) U FOLLOW(E') = FOLLOW(E') = { ) , ε }
SELECT(T' -> *FT') = FRIST(*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 -> i) = ø
∴ 该文法是LL(1)文法。
3
E()
{T();
E'();
}
E'()
T()
T'()
F()
解:
void ParseE() {
switch (lookahead) {
case'(','i':
ParseT();
ParseE'();
break;
default:
print("syntax error\n");
exit(0);
}
}
void ParseE'(){
switch(lookahead){
case '+':
MatchToken('+');
ParseT();
ParseE'();
break;
case ')','#':
break;
default:
print("syntax error\n");
exit(0);
}
}
void ParseT(){
switch (lookahead) {
case '(','i':
ParseF();
ParseT'();
break;
default:
print("syntax error \n");
exit(0);
}
}
void ParseT'(){
switch(lookahead){
case '*':
MatchToken('*');
ParseF();
ParseT'();
break;
case '+',')','#':
break;
default:
print("syntax error \n");
exit(0);
}
}
void ParseF(){
switch(lookahead){
case '(':
MatchToken('(');
ParseE();
MatchToken(')');
break;
case 'i':
MatchToken('i');
break;
default:
print("syntax error \n");
exit(0);
}
}
4不是合法
标签:case,文法,LL,分析程序,break,SELECT,Select 来源: https://www.cnblogs.com/hzxx/p/11914008.html