您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 招聘面试 > Tiny-C-语言编译程序实验一-Scanner
TinyC语言编译程序实验一Scanner1TinyC语言编译程序实验一Scanner要求:填写getToken()函数,完成词法分析器scan.c。约定:仅允许整数类型,不允许实数类型标识符由大小写英文字母组成,最多52个。其识别按最长匹配原则整数后紧跟非数字,或标识符后紧跟非字母认为是一个新Token开始由{}括起来符号串都认为是注释部分,该部分在词法分析时被过滤掉识别出的Token由两个变量:currentToken,tokenString识别,其中currentToken代表Token的类属,为一个名为TokenType的枚举类型,在文件globals.h中定义;tokenString代表Token在程序中出现的形式,即其本来面目。例如整数10的currentToken值为NUM,而tokenString值为‘10’;标识符i的currentToken值为ID,而tokenString值为‘i’typedefenum{ENDFILE,ERROR,IF,THEN,ELSE,END,REPEAT,UNTIL,READ,WRITE,/*保留字*/ID,NUM,ASSIGN,EQ,LT,PLUS,MINUS,TIMES,OVER,LPAREN,RPAREN,SEMI:==+-*/();}TokenType;画识别符合TINYC语言构词规则的DFA。然后用直接编码的方法构造词法分析器/****************************************************//*File:scan.c*//*ThescannerimplementationfortheTINYcompiler*//****************************************************/#includeglobals.h#includeutil.h#includescan.htypedefenum{START,INASSIGN,INCOMMENT,INNUM,INID,DONE}StateType;chartokenString[MAXTOKENLEN+1];staticintgetNextChar(void)//获得下一字符TinyC语言编译程序实验一Scanner2staticstruct{char*str;TokenTypetok;}reservedWords[MAXRESERVED]={{if,IF},{then,THEN},{else,ELSE},{end,END},{repeat,REPEAT},{until,UNTIL},{read,READ},{write,WRITE}};//定义保留字表staticTokenTypereservedLookup(char*s)//进行保留字的匹配{实现请自己看scan.c文件}/**********************************************//*theprimaryfunctionofthescanner*//*functiongetTokenreturnsthenexttokeninsourcefile*//**********************************************/TokenTypegetToken(void){inttokenStringIndex=0;TokenTypecurrentToken;//保存被识别Token的类属StateTypestate=START;//初始状态为STARTintsave;//标识当前字符是否保存,如空格,换行符\n、TAB符\t及注释中的任何字符while(state!=DONE)//DONE状态表示已识别出一个Token{intc=getNextChar();save=TRUE;switch(state){caseSTART:if(isdigit(c))state=INNUM;elseif(isletter(c))state=INID;elseif(c==':')state=INASSIGN;elseif(c=='{')state=INCOMMENT;else{state=DONE;currentToken=END;}break;caseINCOMMENT:if(c=='}')TinyC语言编译程序实验一Scanner3{state=DONE;currentToken=END;}break;caseINASSIGN:if(c=='='){state=DONE;currentToken=ASSIGN;}else{error();currentToken=ERROR};/*此处已填写完整*/break;caseINNUM:if(!isdigit(c)){/*backupintheinput*/ungetNextChar();save=FALSE;state=DONE;currentToken=NUM;}break;caseINID:if(!isletter(c)){/*backupintheinput*/ungetNextChar();save=FALSE;state=DONE;currentToken=ID;break;caseDONE://不可能到default:/*shouldneverhappen*/fprintf(listing,ScannerBug:state=%d\n,state);state=DONE;currentToken=ERROR;break;}if((save)&&(tokenStringIndex=MAXTOKENLEN))tokenString[tokenStringIndex++]=(char)c;if(state==DONE)TinyC语言编译程序实验一Scanner4{tokenString[tokenStringIndex]='\0';if(currentToken==ID)currentToken=reservedLookup(tokenString);}}---------endWHILEif(TraceScan){fprintf(listing,\t%d:,lineno);printToken(currentToken,tokenString);}returncurrentToken;}/*endgetToken*/
本文标题:Tiny-C-语言编译程序实验一-Scanner
链接地址:https://www.777doc.com/doc-5630799 .html