根据之前定义的语法采用C语言实现语法分析。
#include "stdio.h" #include "string.h" char prog[100],token[8],ch; char *rwtab[6]={"begin","if","then","while","do","end"}; int syn,p,m,n,sum; int kk; factor(); expression(); yucu(); term(); statement(); lrparser(); scaner(); main() { p=kk=0; printf(" please input a string (end with '#'): "); do { scanf("%c",&ch); prog[p++]=ch; }while(ch!='#'); p=0; scaner(); lrparser(); getch(); } lrparser() { if(syn==1) { scaner(); /*读下一个单词符号*/ yucu(); /*调用yucu()函数;*/ if (syn==6) { scaner(); if ((syn==0)&&(kk==0)) printf("success! "); } else { if(kk!=1) printf("the string haven't got a 'end'! "); kk=1; } } else { printf("haven't got a 'begin'! "); kk=1; } return; } yucu() { statement(); /*调用函数statement();*/ while(syn==26) { scaner(); /*读下一个单词符号*/ if(syn!=6) statement(); /*调用函数statement();*/ } return; } statement() { if(syn==10) { scaner(); /*读下一个单词符号*/ if(syn==18) { scaner(); /*读下一个单词符号*/ expression(); /*调用函数statement();*/ } else { printf("the sing ':=' is wrong! "); kk=1; } } else { printf("wrong sentence! "); kk=1; } return; } expression() { term(); while((syn==13)||(syn==14)) { scaner(); /*读下一个单词符号*/ term(); /*调用函数term();*/ } return; } term() { factor(); while((syn==15)||(syn==16)) { scaner(); /*读下一个单词符号*/ factor(); /*调用函数factor(); */ } return; } factor() { if((syn==10)||(syn==11)) scaner(); else if(syn==27) { scaner(); /*读下一个单词符号*/ expression(); /*调用函数statement();*/ if(syn==28) scaner(); /*读下一个单词符号*/ else { printf("the error on '(' "); kk=1; } } else { printf("the expression error! "); kk=1; } return; } scaner() { sum=0; for(m=0;m<8;m++)token[m++]=NULL; m=0; ch=prog[p++]; while(ch==' ')ch=prog[p++]; if(((ch<='z')&&(ch>='a'))||((ch<='Z')&&(ch>='A'))) { while(((ch<='z')&&(ch>='a'))||((ch<='Z')&&(ch>='A'))||((ch>='0')&&(ch<='9'))) {token[m++]=ch; ch=prog[p++]; } p--; syn=10; token[m++]='