《编译原理-实验报告》由会员分享,可在线阅读,更多相关《编译原理-实验报告(28页珍藏版)》请在金锄头文库上搜索。
1、程序清单1. 分工:2. 词法分析:#include#include#include#define keywordSum 8char *keywordkeywordSum=if,else,for,while,do,int,read,write;char singleword50=+ - * ( ) ; , :;char doubleword10=!;extern char Scanin300,Scanout300;extern FILE *fin,*fout;int TESTscan()char ch,token40;int es=0,j,n;printf(请输入源程序文件名(包括路径):);
2、scanf(%s,Scanin);printf(请输入词法分析输出文件名(包括路径):);scanf(%s,Scanout);if(fin=fopen(Scanin,r)=NULL)printf(n打开词法分析输入文件出错!n);return(1);if(fout=fopen(Scanout,w)=NULL)printf(n创建词法分析输出文件出错!n);return(2); ch=getc(fin); while(ch!=EOF) while(ch= |ch=n|ch=t) ch=getc(fin); if(isalpha(ch) token0=ch;j=1; ch=getc(fin); w
3、hile(isalnum(ch) tokenj+=ch; ch=getc(fin); tokenj=0; n=0; while (n=keywordSum) fprintf(fout,%st%sn,ID,token); else fprintf(fout,%st%sn,token,token); else if (isdigit(ch) token0=ch;j=1; ch=getc(fin); while(isdigit(ch) tokenj+=ch; ch=getc(fin); tokenj=0; fprintf(fout,%st%sn,NUM,token); else if(strchr(
4、singleword,ch)0) token0=ch;token1=0; ch=getc(fin); fprintf(fout,%st%sn,token,token); else if (strchr(doubleword,ch)0) token0=ch; ch=getc(fin); if(token0=!) if (ch = =) token1=ch; token2=0; ch = getc(fin); fprintf(fout,%st%sn,token,token); else token1=0; es=1; fprintf(fout,%st%sn,ERROR,token); else i
5、f (ch = =) token1=ch; token2=0; ch = getc(fin); else token1=0; fprintf(fout,%st%sn,token,token); else if (ch=/) ch = getc(fin); if(ch =*) char ch1; ch1=getc(fin); do ch=ch1; ch1=getc(fin); while(ch!=* | ch1!=/) & ch1!=EOF); ch = getc(fin); else if(ch=/)doch=getc(fin);while(ch!=n & ch!=EOF);ch=getc(f
6、in);else token0=/; token1=0; fprintf(fout,%st%sn,token,token); else token0=ch; token1=0; ch=getc(fin); es = 3; fprintf(fout,%st%sn,ERROR,token); fclose(fin); fclose(fout); return (es);3. 语法分析:#include#include#include#includeint TESTparse();int program();int compound_Stat();int statement();/int expre
7、ssion_Stat();int expression_stat();int expression();int bool_expr();int additive_expr();int term();int factor();int if_stat();int while_stat();int for_stat();int write_stat();int read_stat();int declaration_stat();int declaration_list();int statement_list();int compound_stat();char token20, token140
8、; /token保存单词符号,token1保存单词值extern char Scanout300; /保存词法分析输出文件名FILE * fp; /用于指向输入文件的指针#define keywordSum 8char *keywordkeywordSum=if,else,for,while,do,int,read,write;char singleword50=+ - * ( ) ; , :;char doubleword10=!;extern char Scanin300,Scanout300;extern FILE *fin,*fout;/语法分析程序int TESTparse() in
9、t es = 0; if (fp=fopen(Scanout,r)=NULL) printf(n打开%s错误!n,Scanout); es = 0; if (es=0) es=program(); printf(=语法分析结果!=n); switch(es) case 0: printf(语法分析成功!n); break; case 10: printf(打开文件%s失败!n); break; case 1: printf(缺少!n); break; case 2: printf(缺少!n); break; case 3: printf(缺少标识符!n); break; case 4: printf(少分号!n); break; case 5: printf(缺少(!n); break; case 6: printf(缺少)!n); break; case 7: printf(缺少操作数!n); break; fclose(fp); return(es);/:=int program() int es = 0; fscanf(fp,