第十一次作业

1. 文法 G(S):

(1)S -> AB

(2)A ->Da|ε

(3)B -> cC

(4)C -> aADC |ε

(5)D -> b|ε

验证文法 G(S)是不是 LL(1)文法?

   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 -> ε) ≠ ∅         Select(C -> aADC) ∩ Select(C -> ε) = ∅         Select(D -> b) ∩ Select(D -> ε) = ∅

 ∴文法G(s)不是LL(1)文法。

2.法消除左递归之后的表达式文法是否是LL(1)文法?

 Select(E' -> +TE') = First(+TE') = {+}                 Select(E' -> ε) = (First(ε)-{ε})∪Follow(E') = {),#}                Select(T' -> *FT') = First(*FT') = {*}               Select(T' -> ε) = (First(ε)-{ε})∪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 ) = ∅

∴ 文法G‘(s)是LL(1)文法。

3.接2,如果是LL(1)文法,写出它的递归下降语法分析程序代码。

E()

    {T();

       E'();

     }

E'()

T()

T'()

F()

解:

void ParseE(){
    switch(lookahead){
        case (,i:
            ParseT();
            ParseE'();
            break;
        default:
            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(){
    switch(lookahead){
        case (,i:
            ParseF();
            ParseT'();
            break;
        default:
            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.加上实验一的词法分析程序,形成可运行的语法分析程序,分析任意输入的符号串是不是合法的表达式。

 

posted on 2019-11-21 20:54  321木头人123  阅读(100)  评论(0编辑  收藏  举报

导航