1. 文法 G(S):

(1)S -> AB

(2)A ->Da|ε

(3)B -> cC

(4)C -> aADC |ε

(5)D -> b|ε

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

  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)文法?

  SELECT(E-> +TE') =  { + }

  SELECT(E' -> ɛ) = {  ) , # }

  SELECT(T-> *FT' ) ={ * }

  SELECT(T -> ɛ) = {  + , ) , # }

  SELECT(F -> (E) ) = { ( }

  SELECT(F -> i ) = { i } 

  因为 

  SELECT(E-> +TE') ∩ SELECT(E' -> ɛ) = ∅

  SELECT(T-> *FT' ) ∩ SELECT(T -> ɛ) = ∅

  SELECT(F -> (E) ) ∩ SELECT(F -> i ) = ∅

  所以 消除左递归后的文法是 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);

    }

  }