资源描述:
《编译原理实验代码》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、[实验任务]完成以下正则文法所描述的Pascal语言子集单词符号的词法分析程序。<标识符>→字母︱<标识符>字母︱<标识符>数字<无符号整数>→数字︱<无符号整数>数字<单字符分界符>→+︱-︱*︱;︱(︱)<双字符分界符>→<大于>=︱<小于>=︱<小于>>︱<冒号>=︱<斜竖>*<小于>→<<等于>→=<大于>→><冒号>→:<斜竖>→/该语言的保留字:beginendifthenelsefordowhileandornot说明:1该语言大小写不敏感。2字母为a-zA-Z,数字为0-9。3可以对上述文法进行扩充和改造。4‘/*……*/’为程序的注释部分。[设计要求]1、给出各单词符号的
2、类别编码。2、词法分析程序应能发现输入串中的错误。3、词法分析作为单独一遍编写,词法分析结果为二元式序列组成的中间文件。4、设计两个测试用例(尽可能完备),并给出测试结果。demo.cpp#include#include#include#include"demo.h"chartoken[20];intlookup(char*token){for(inti=0;i<11;i++){if(strcmp(token,KEY_WORDS[i])==0){returni+1;}}return0;}chargetletter(FILE*fp){r
3、eturntolower(fgetc(fp));}voidout(FILE*fp,intc,char*value){fprintf(fp,"%d,%s",c,value);}voidreport_error(FILE*fp,charch){fprintf(fp,"Theremustbesomeerror.");fprintf(fp,"%c...",ch);fprintf(fp,"^");}voidscanner(FILE*infile,FILE*outfile){charch;inti,c;do{do{ch=getletter(infile);}while(isspace(
4、ch));if(isalpha(ch)){token[0]=ch;ch=getletter(infile);i=1;while(isalnum(ch)){token[i]=ch;i++;ch=getletter(infile);}token[i]=' ';fseek(infile,-1,1);c=lookup(token);if(c==0){out(outfile,ID,token);}else{out(outfile,c,"");}}else{if(isdigit(ch)){token[0]=ch;ch=getletter(infile);i=1;while(isdigit(ch)){
5、token[i]=ch;i++;ch=getletter(infile);}token[i]=' ';fseek(infile,-1,1);out(outfile,INT,token);}else{switch(ch){case'<':{ch=getletter(infile);if(ch=='='){out(outfile,LE,"");}elseif(ch=='>'){out(outfile,NE,"");}else{fseek(infile,-1,1);out(outfile,LT,"");}break;}case'=':{out(outfile,EQ,"");break;}cas
6、e'>':{ch=getletter(infile);if(ch=='='){out(outfile,GE,"");}else{fseek(infile,-1,1);out(outfile,GT,"");}break;}case':':{ch=getletter(infile);if(ch=='='){out(outfile,FU,"");}else{fseek(infile,-1,1);out(outfile,MAO,"");}break;}case'/':{ch=getletter(infile);if(ch=='*'){out(outfile,ZHU,"");}else{fseek(
7、infile,-1,1);out(outfile,XIE,"");}break;}case'+':{out(outfile,JIA,"");break;}case'-':{out(outfile,JIAN,"");break;}case'*':{out(outfile,CHEN,"");break;}case';':{out(outfile,FEN,"");break;}case'(':{out(outfile,ZUO,