1. The purpose of the experiment
Write a recursive descent analysis program that implements the sequence of words provided by the lexical analyzer
grammar checking and structural analysis.
2. Experimental content
Use C language to compile recursive descent analysis program, and carry out grammatical analysis of simple language.
2.1 The grammar of the simple language to be analyzed
Expressed in extended BNF as follows:
⑴<program>::=begin<statement string>end
⑵<statement string>::=<statement>{;<statement>}
⑶ <statement>::=<assignment statement>
⑷<assignment statement>::=ID:=<expression>
⑸<expression>::=<item>{+<item> | -<item>}
⑹<item>::=<factor>{*<factor> | /<factor>
⑺<factor>::=ID|NUM|(<expression>)
2.2 Description of experimental requirements
Enter the word string, ending with "#", if it is a grammatically correct sentence, output the success message,
print "success," otherwise output "error."
E.g:
Enter begin a:=9; x:=2*3; b:=a+x end #
output success
Enter x:=a+b*c end #
output error
#include<stdio.h> #include<string.h> int id(char a[],int i) { if(a[i]<='z'&&a[i]>='a') { for(i++;(a[i]<='z'&&a[i]>='a')||(a[i]>='0'&&a[i]<='9');i++); if(a[i]==':'&&a[i+1]=='=') return i+2; else return -1; } else return -1; } int yinzi(char e[]) { int i=0; if(e[i]>='a'&&e[i]<='z') { for(i++;e[i]<='z'&&e[i]>='a'||e[i]>='0'&&e[i]<='9';i++); if(i!=strlen(e)) return -1; else return 1; } else if(e[i]>='0'&&e[i]<='9') { for(i++;e[i]<='9'&&e[i]>='0';i++); if(i!=strlen(e)) return -1; else return 1; } else return -1; } int biaodashi(char d[],int i); int kuohao(char d[],int i) { int kz=1,ky=0,j=0; char e [200] = {}; for(i+=1;d[i]!='\0'&&kz>ky;i++) { if(d[i]=='(') { kz++; e[j++]=d[i]; } else if(d[i]==')') { ky++; if(kz>ky) e[j++]=d[i]; } else e[j++]=d[i]; } if(kz!=ky) return -1; else { j=0; if(biaodashi(e,j)>0) return i; else return -1; } } int jiequ (char d [], int i) { int j=0; char e [200] = {}; while(!(d[i]=='+'||d[i]=='-'||d[i]=='*')&&i!=strlen(d)) e[j++]=d[i++]; int k = yinzi (e); if(k<0) return -1; else return i; } int biaodashi(char d[],int i) { int k=0; if(d[i]=='(') k=kuohao(d,i); else k=jiequ(d,i); if(k<0) return -1; else if(k==strlen(d)) return 1; else i=k; if(d[i]=='+'||d[i]=='-'||d[i]=='*'||d[i]=='/') { i++; if(biaodashi(d,i)<0) return -1; else return 1; } else if(d[i]==strlen(d)) return 1; else return -1; } intmain() { char a[200]={},b[10]={},c[10]={}; scanf("%s ",b); gets(a); int n=0,i=0,j=0,k=0; n=strlen(a); for(i=n-6;i<=n-1;i++) c[j++]=a[i]; if((strcmp("begin",b)!=0)||(strcmp(" end #",c)!=0)) printf("error\n"); else { for(i=0;i<=n-7;) { k=id(a,i); if(k<0) break; else { i=k; k=0; } char d[200]={}; j=0; while(a[i]!=';'&&i<=n-7) d[j++]=a[i++]; i+=2; k=biaodashi(d,0); if(k<0) break; else k=0; } if(k<0) printf("error\n"); else printf("success\n"); } return 0; }