Judgment of compiler theory LL (1) grammar, recursive descent parser

1. grammar  G (S):

(1)S -> AB

(2)A ->Da|ε

(3)B -> cC

(4)C -> aADC |ε

(5)D -> b|ε

Verify grammar  G (S) is not  LL (1) grammar?

Solution: Because

First(Da)={b, a}
First(ε)={ε}
First(aADC)={a}
First(b)={b}
Follow(A)={c.b.a, #}
  FIRST(B)
  FIRST(D), FIRST(C), FOLLOW(C)
Follow(C)={#}
Follow(D)={a,#}

and so

SELECT(A->Da)={b. a}
SELECT(A->ε)={c. b, a, #}
SELECT(C->aADC)={a}
SELECT(C->ε)={#}
SELECT(D->b)={b}
SELECT(D->ε)={a, #}

Wherein as SELECT (A-> Da) and SELECT (A-> ε) intersect so that G (S) is not LL (1) syntax.

 

2. The following determine whether the grammar is LL (1) grammar?

E -> TE'
E' -> +TE' | ε
T -> FT'
T' -> *FT' | ε
F -> (E) | i

 Solution: questions can be obtained from the

SELECT(E'->+TE')=FIRST(+TE')={+}
SELECT(E'->ε)=follow(E')=follow(E)={#, )}
SELECT(T'->*FT')=FRIST(*FT')={*}
SELECT(T'->ε)=follow(T')=follow(T)={#, ), +}
SELECT(F->(E))=FRIST((E)) ={(}
SELECT(F->i)=FRIST(i) ={i}

Wherein SELECT (E '-> + TE') and SELECT (E '-> ε) disjoint, SELECT (T' -> * FT ') and SELECT (T' - mutually> ε) cross, SELECT (F -> (E)) and SELECT (F-> i) are mutually exclusive, so that the original method of LL (1) syntax.

 

3. The connection 2, if it is LL (1) grammar, write its recursive descent parser code.

E()

    {T();

       E'();

     }

E'()

T()

T'()

F()

 solution:

 

SELECT(E->TE) =FIRST(TE')=FIRSI(T)-FIRST(F)U{*}={(, i, *}
SELECT(E'->+TE')=FIRST(+TE')={+}
SELECT(E'->ε)=follow(E')=follow(E)={#, )}
SELECT(T -> FT')=FRIST(FT')=FIRST(F)-{(, i}
SELECT(T'->*FT')=FRIST(*FT')={*}
SELECT(T'->ε)=follow(T')=follow(T)={#, ), +}
SELECT(F->(E))=FRIST((E)) ={(}
SELECT(F->i)=FRIST(i) ={i}

 

伪代码:

void ParseE(){
  switch(lookahead){
    case '(','i', '*':
      ParseT();
      ParseEP();
      break;
    default:
      print("语法错误 \n");
      exit(0);
  }
}

void ParseEP(){
  switch(lookahead){
    case '+':
      MatchToken('+');
      ParseT();
      ParseEP();
      break;
    case '#', ')':
        break;
    default:
      print("语法错误 \n");
      exit(0);
  }
}

void ParseT(){ 
  switch(lookahead){
    case '(','i':
      ParseF();
      ParseTP();
      break;
    default:
      print("语法错误 \n");
      exit(0);
  }
}
void ParseTP(){
  switch(lookahead){
    case '*':
      MatchToken('*');
      ParseF();
      ParseTP();
      break;
    case '#', ')', '+':
      break;
    default:
      print("语法错误 \n");
      exit(0);
    }
  }
void ParseF(){
  switch(lookahead){
    case '(':
      MatchToken('(');
      ParseE();
      MatchToken(')');
      break;
    case 'i':
      MatchToken('i');
      break;
    default:
      print("语法错误 \n");
      exit(0);
    }
  }

  

 

 4.加上词法分析程序,形成可运行的语法分析程序,分析任意输入的符号串是不是合法的表达式。

Guess you like

Origin www.cnblogs.com/Rakers1024/p/11896029.html