资源描述:
《电子科技大学-计算机学院-编译原理实验-词法分析.doc》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、#include#include#include#defineMAX_COUNT1024#defineILLEGAL_CHAR_ERR1#defineUNKNOWN_OPERATOR_ERR2/*从标准输入读入第一个非空白字符(换行符除外)*/chargetnbc(){charch;ch=getchar();while(1){if(ch=='r'
2、
3、ch=='t'
4、
5、ch==''){ch=getchar();}else{break;}}returnch;}/*判断character是否为字母*/boollet
6、ter(charcharacter){if((character>='a'&&character<='z')
7、
8、(character>='A'&&character<='Z'))returntrue;elsereturnfalse;}/*判断character是否为数字*/booldigit(charcharacter){if(character>='0'&&character<='9')returntrue;elsereturnfalse;}/*回退字符*/voidretract(char&character){ungetc(character,stdin);chara
9、cter=NULL;}/*返回保留字的对应种别*/intreserve(char*token){if(strcmp(token,"begin")==0)return1;elseif(strcmp(token,"end")==0)return2;elseif(strcmp(token,"integer")==0)return3;elseif(strcmp(token,"if")==0)return4;elseif(strcmp(token,"then")==0)return5;elseif(strcmp(token,"else")==0)return6;elseif(str
10、cmp(token,"function")==0)return7;elseif(strcmp(token,"read")==0)return8;elseif(strcmp(token,"write")==0)return9;elsereturn0;}/*返回标识符的对应种别*/intsymbol(){return10;}/*返回常数的对应种别*/intconstant(){return11;}/*按照格式输出单词符号和种别*/voidoutput(constchar*token,intkindNum){printf("%16s%2d",token,kindNum);}
11、/*根据行号和错误码输出错误*/boolerror(intlineNum,interrNum){char*errInfo;switch(errNum){caseILLEGAL_CHAR_ERR:errInfo="出现字母表以外的非法字符";break;caseUNKNOWN_OPERATOR_ERR:errInfo="出现未知运算符";break;default:errInfo="未知错误";}if(fprintf(stderr,"***LINE:%d%s",lineNum,errInfo)>=0)returntrue;elsereturnfalse;}/*词法分析函
12、数,每调用一次识别一个符号*/boolLexAnalyze(){staticintlineNum=1;charcharacter;chartoken[17]="";character=getnbc();switch(character){case'':output("EOLN",24);lineNum++;break;caseEOF:output("EOF",25);returnfalse;//false表示已读到文件末尾case'a':case'b':case'c':case'd':case'e':case'f':case'g':case'h':case'i':ca
13、se'j':case'k':case'l':case'm':case'n':case'o':case'p':case'q':case'r':case's':case't':case'u':case'v':case'w':case'x':case'y':case'z':case'A':case'B':case'C':case'D':case'E':case'F':case'G':case'H':case'I':case'J':case'K':case'L':case'M':case'N':case'O':case'P':case