《編譯原理及實(shí)踐實(shí)驗(yàn)課程》實(shí)驗(yàn)_第1頁
《編譯原理及實(shí)踐實(shí)驗(yàn)課程》實(shí)驗(yàn)_第2頁
《編譯原理及實(shí)踐實(shí)驗(yàn)課程》實(shí)驗(yàn)_第3頁
《編譯原理及實(shí)踐實(shí)驗(yàn)課程》實(shí)驗(yàn)_第4頁
《編譯原理及實(shí)踐實(shí)驗(yàn)課程》實(shí)驗(yàn)_第5頁
已閱讀5頁,還剩19頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

院系:計(jì)算機(jī)學(xué)院實(shí)驗(yàn)課程:編譯原理及實(shí)踐實(shí)驗(yàn)課程實(shí)驗(yàn)項(xiàng)目TINY擴(kuò)充語言的語法分析指導(dǎo)老師:XXX開課時(shí)間:XXXX?XXXX年度第1學(xué)期專業(yè):XXXXX班級(jí):XXXX級(jí)本XX班學(xué)生:XXX學(xué)號(hào):XXXX實(shí)驗(yàn)二:TINY擴(kuò)充語言的語法分析一、實(shí)驗(yàn)題目擴(kuò)充的語法規(guī)則有:實(shí)現(xiàn)while、dowhile、for語句和求余計(jì)算式子,具體文法規(guī)則自行構(gòu)造。可參考:P97及P136的文法規(guī)則。While-stmt-->whileexpdostmt-sequenceendwhileDowhile-stmt-->dostmt-sequencewhileexpfor-stmt-->foridentifier:=simple-exptosimple-expdostmt-sequenceenddo步長(zhǎng)遞增1for-stmt-->foridentifier:=simple-expdowntosimple-expdostmt-sequenceenddo 步長(zhǎng)遞減1二、 實(shí)驗(yàn)要求要提供一個(gè)源程序編輯界面,以讓用戶輸入源程序(可保存、打開源程序)??捎捎脩暨x擇是否生成語法樹,并可查看所生成的語法樹。應(yīng)該書寫完善的軟件文檔。三、 實(shí)驗(yàn)思路本次實(shí)驗(yàn)是擴(kuò)充TINY語言的語法分析,主要擴(kuò)充的語法是while、dowhile、for,通過添加三個(gè)函數(shù)來進(jìn)行實(shí)現(xiàn),函數(shù)聲明如下表示:/*新增加的函數(shù)聲明語句*/staticTreeNode*while_stmt(void);staticTreeNode*dowhile_stmt(void);staticTreeNode*for_stmt(void);/*新增加的函數(shù)聲明語句結(jié)束*/由于附錄B所給的代碼中,scan.cpp用于完成詞法分析、parse?cpp用于完成語法分析、ut訂.cpp用于完成結(jié)果的顯示,以及main.cpp作為主函數(shù)實(shí)現(xiàn)交互,因此主要修改這幾個(gè)函數(shù)的部分內(nèi)容即可,具體修改內(nèi)容如下所述。由于要對(duì)新增加的語法進(jìn)行詞法分析和語法分析,所以需要先定義相關(guān)保留字,而保留字是在globals.h中定義的,所以要在globals.h下定義一下內(nèi)容:在typedefenum{}TokenType中添加保留字:WHILE,DO,FOR,TO,DOWNTO,ENDWHILE,ENDDO,MOD, //新增加的保留字;在typedefenum{}StmtKind中添加語句類型:WhileK,DowhileK,ForIncK,ForDecK //新增加的語句類型把MAXRESERVED由8改為15:#defineMAXRESERVED15 //將原來的8改為15在scan.cpp中對(duì)結(jié)構(gòu)類型staticstruct{}添加相關(guān)保留字,并在TokenTypegetToken(void)中swicth判斷中添加求余的代碼,具體如下:staticstruct{}添加代碼:{"do",DO},{"for",FOR},{"endwhile",ENDWHILE},{"enddo",ENDDO},{"to",TO},{"downto",DOWNTO}//新增加的保留字TokenTypegetToken(void){}添加代碼:case'%': //添加求余的代碼currentToken=MOD;break; //添加求余代碼結(jié)束在parse.cpp中新增while/dowhile/for三個(gè)函數(shù)并對(duì)相關(guān)的語句進(jìn)行修改,具體如下所述:對(duì)新擴(kuò)充的while文法函數(shù)進(jìn)行定義:TreeNode*while_stmt(void) //新擴(kuò)充的while文法{TreeNode*t=newStmtNode(WhileK);match(WHILE);if(t!=NULL)t->child[0]=exp();match(DO);if(t!=NULL)t->child[1]=stmt_sequence();match(ENDWHILE);returnt;}對(duì)新擴(kuò)充的dowhile文法函數(shù)進(jìn)行定義:TreeNode*dowhile_stmt(void)//新擴(kuò)充的dowhile文法{TreeNode*t=newStmtNode(DowhileK);match(DO);if(t!=NULL)t->child[0]=stmt_sequence();match(WHILE);if(t!=NULL)t->child[1]=exp();returnt;}對(duì)新擴(kuò)充的for文法函數(shù)進(jìn)行定義:TreeNode*for_stmt(void)//新擴(kuò)充的for文法{TreeNode*t=newStmtNode(ForIncK);match(FOR);if(t!=NULL){t->child[0]=assign_stmt();if(token==TO) //實(shí)現(xiàn)步長(zhǎng)遞增1match(TO);elseif(token==DOWNTO)//實(shí)現(xiàn)步長(zhǎng)遞減1{match(DOWNTO);t->kind.stmt=ForDecK;}t->child[1]=simple_exp();match(DO);t->child[2]=stmt_sequence();match(ENDDO);}returnt;}④在TreeNode*stmt_sequence(void){}的while中添加以下代碼:&&(token!=ENDDO)&&(token!=ENDWHILE)&&(token!=WHILE)) //新增加的循環(huán)判斷語句,避免嵌套循環(huán)在TreeNode*statement(void){的switch(token)中添加以下代碼:/*新添加的內(nèi)容,實(shí)現(xiàn)求余操作*/caseWHILE:t=while_stmt();break;caseDO:t=dowhile_stmt();break;caseFOR:t=for_stmt();break;/*求余內(nèi)容操作結(jié)束*/在TreeNode*term(void){}中添加求余代碼:||(token==MOD))//此處為新增加的求余操作在util.cpp中添加界面顯示的代碼,具體如下所述:①在voidprintToken(TokenTypetoken,constchar*tokenstring的swicth中添加以下代碼:/*添加與保留字相對(duì)應(yīng)的內(nèi)容*/caseWHILE:caseDO:caseFOR:caseENDWHILE:caseENDDO:caseTO:caseDOWNTO:/*增加以上部分內(nèi)容*//*添加的保留字內(nèi)容*/caseMOD:fprintf(listing,"%c\n",ch);break;/*以上部分為添加的內(nèi)容*/②在voidprintTree(TreeNode*tree){的switch中添加以下代碼:/*添加以下部分內(nèi)容*/caseWhileK:fprintf(listing,"While\n");break;caseDowhileK:fprintf(listing,"Do\n");break;caseForIncK:fprintf(listing,"For(遞增)\n");break;caseForDecK:fprintf(listing,"For(遞減)\n");break;/*以上為添加的內(nèi)容*/四、源代碼此處只給出修改過的cpp文件和頭文件的代碼,其他代碼可直接查看源程序:globals.h代碼:TOC\o"1-5"\h\z/*File:globals.h *//*GlobaltypesandvarsforTINYcompiler *//*mustcomebeforeotherincludefiles *//*CompilerConstruction:PrinciplesandPractice*//*KennethC.Louden */#ifndef_GLOBALS_H_#define_GLOBALS_H_#include<stdio.h>#include<stdlib.h>#include<ctype.h>#include<string.h>#ifndefFALSE#defineFALSE0#endif#ifndefTRUE#defineTRUE1#endif/*MAXRESERVED=thenumberofreservedwords*/#defineMAXRESERVED15 //將原來的8改為15typedefenum/*book-keepingtokens*/{ENDFILE,ERROR,/*reservedwords*/IF,THEN,ELSE,END,REPEAT,UNTIL,READ,WRITE,WHILE,DO,FOR,TO,DOWNTO,ENDWHILE,ENDDO,MOD, //新增加的保留字/*multicharactertokens*/ID,NUM,/*specialsymbols*/ASSIGN,EQ,LT,PLUS,MINUS,TIMES,OVER,LPAREN,RPAREN,SEMI}TokenType;externFILE*source;/*sourcecodetextfile*/externFILE*listing;/*listingoutputtextfile*/externFILE*code;/*codetextfileforTMsimulator*/externintlineno;/*sourcelinenumberforlisting*/Syntaxtreeforparsing************/typedefenum{StmtK,ExpK}NodeKind;typedefenum{IfK,RepeatK,AssignK,ReadK,WriteK,//新增加的語句類型://新增加的語句類型:WhileK,DowhileK,ForIncK,ForDecK}StmtKind;typedefenum{OpK,ConstK,IdK}ExpKind;/*ExpTypeisusedfortypechecking*/typedefenum{Void,Integer,Boolean}ExpType;#defineMAXCHILDREN3typedefstructtreeNode{structtreeNode*child[MAXCHILDREN];structtreeNode*sibling;intlineno;NodeKindnodekind;union{StmtKindstmt;ExpKindexp;}kind;union{TokenTypeop;intval;char*name;}attr;ExpTypetype;/*fortypecheckingofexps*/}TreeNode;Flagsfortracing/*EchoSource=TRUEcausesthesourceprogramto*beechoedtothelistingfilewithlinenumbers*duringparsing*/externintEchoSource;/*TraceScan=TRUEcausestokeninformationtobe*printedtothelistingfileaseachtokenis*recognizedbythescanner*/externintTraceScan;/*TraceParse=TRUEcausesthesyntaxtreetobe*printedtothelistingfileinlinearizedform*(usingindentsforchildren)*/externintTraceParse;/*TraceAnalyze=TRUEcausessymboltableinserts

*andlookupstobereportedtothelistingfile*/externintTraceAnalyze;/*TraceCode=TRUEcausescommentstobewritten*totheTMcodefileascodeisgenerated*/externintTraceCode;/*Error=TRUEpreventsfurtherpassesifanerroroccurs*/externintError;#endif*/scan.cpp代碼:*//*File:scan.c/*ThescannerimplementationfortheTINYcompiler*//*CompilerConstruction:PrinciplesandPractice*//*KennethC.Louden */#include"globals.h"#include"util.h"#include"scan.h"/*statesinscannerDFA*/typedefenum{START,INASSIGN,INCOMMENT,INNUM,INID,DONE}StateType;/*lexemeofidentifierorreservedword*/chartokenString[MAXTOKENLEN+1];/*BUFLEN=lengthoftheinputbufferforsourcecodelines*/#defineBUFLEN256staticcharlineBuf[BUFLEN];/*holdsthecurrentline*/staticintlinepos=0;/*currentpositioninLineBuf*/staticintbufsize=0;/*currentsizeofbufferstring*/staticintEOF_flag=FALSE;/*correctsungetNextCharbehavioronEOF*//*getNextCharfetchesthenextnon-blankcharacterfromlineBuf,readinginanewlineiflineBufisexhausted*/staticintgetNextChar(void){if(!(linepos<bufsize)){lineno++;if(fgets(lineBuf,BUFLEN-1,source)){if(EchoSource)fprintf(listing,"%4d:%s",lineno,lineBuf);bufsize=strlen(lineBuf);linepos=0;returnlineBuf[linepos++];}else{EOF_flag=TRUE;returnEOF;}}elsereturnlineBuf[linepos++];}/*ungetNextCharbacktracksonecharacterinlineBuf*/staticvoidungetNextChar(void){if(!EOF_flag)linepos--;}/*lookuptableofreservedwords*/staticstruct{char*str;TokenTypetok;}reservedWords[MAXRESERVED]={{"if",IF},{"then",THEN},{"else",ELSE},{"end",END},{"repeat",REPEAT},{"until",UNTIL},{"read",READ},{"write",WRITE},{"while",WHILE},{"do",DO},{"for",FOR},{"endwhile",ENDWHILE},{"enddo",ENDDO},{"to",TO},{"downto",DOWNTO}//新增加的保留字};/*lookupanidentifiertoseeifitisareservedword*//*useslinearsearch*/staticTokenTypereservedLookup(char*s){inti;for(i=0;i<MAXRESERVED;i++)if(!strcmp(s,reservedWords[i].str))returnreservedWords[i].tok;returnID;/*/*theprimaryfunctionofthescanner*//*/*functiongetTokenreturnsthe*nexttokeninsourcefile*/TokenTypegetToken(void){/*indexforstoringintotokenString*/inttokenStringIndex=0;/*holdscurrenttokentobereturned*/TokenTypecurrentToken;/*currentstate-alwaysbeginsatSTART*/StateTypestate=START;/*flagtoindicatesavetotokenString*/intsave;while(state!=DONE){intc=getNextChar();save=TRUE;switch(state){caseSTART:if(isdigit(c))state=INNUM;elseif(isalpha(c))state=INID;elseif(c==':')state=INASSIGN;elseif((c=='')||(c=='\t')||(c=='\n'))save=FALSE;elseif(c=='{'){save=FALSE;state=INCOMMENT;}else{state=DONE;switch(c){caseEOF:save=FALSE;currentToken=ENDFILE;break;case'=':currentToken=EQ;break;case'<':currentToken=LT;break;case'+':currentToken=PLUS;break;case'-':currentToken=MINUS;break;case'*':currentToken=TIMES;break;case'/':currentToken=OVER;break;case'%': //添加求余的代碼currentToken=MOD;break; //添加求余代碼結(jié)束case'(':currentToken=LPAREN;break;case')':currentToken=RPAREN;break;case';':currentToken=SEMI;break;default:currentToken=ERROR;break;}}break;caseINCOMMENT:save=FALSE;if(c==EOF){state=DONE;currentToken=ENDFILE;}elseif(c=='}')state=START;break;caseINASSIGN:state=DONE;if(c=='=')currentToken=ASSIGN;else{/*backupintheinput*/ungetNextChar();save=FALSE;currentToken=ERROR;}break;caseINNUM:if(!isdigit(c)){/*backupintheinput*/ungetNextChar();save=FALSE;state=DONE;currentToken=NUM;}break;caseINID:if(!isalpha(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){tokenString[tokenStringIndex]='\0';if(currentToken==ID)currentToken=reservedLookup(tokenString);}}if(TraceScan){fprintf(listing,"\t%d:",lineno);printToken(currentToken,tokenString);}returncurrentToken;}/*endgetToken*/parse?cpp代碼:/*File:parse.c*//*TheparserimplementationfortheTINYcompiler*//*CompilerConstruction:PrinciplesandPractice*//*KennethC.Louden*/#include"globals.h"#include"util.h"#include"scan.h"#include"parse.h"staticTokenTypetoken;/*holdscurrenttoken*//*functionprototypesforrecursivecalls*/staticTreeNode*stmt_sequence(void);staticTreeNode*statement(void);staticTreeNode*if_stmt(void);staticTreeNode*repeat_stmt(void);staticTreeNode*assign_stmt(void);staticTreeNode*read_stmt(void);staticTreeNode*write_stmt(void);/*新增加的函數(shù)聲明語句*/staticTreeNode*while_stmt(void);staticTreeNode*dowhile_stmt(void);staticTreeNode*for_stmt(void);/*新增加的函數(shù)聲明語句結(jié)束*/staticTreeNode*exp(void);staticTreeNode*simple_exp(void);staticTreeNode*term(void);staticTreeNode*factor(void);staticvoidsyntaxError(char*message){fprintf(listing,"\n>>>");fprintf(listing,"Syntaxerroratline%d:%s",lineno,message);Error=TRUE;staticvoidmatch(TokenTypeexpected){if(token==expected)token=getToken();else{syntaxError("unexpectedtoken->");printToken(token,tokenString);fprintf(listing,"");}}TreeNode*stmt_sequence(void){TreeNode*t=statement();TreeNode*p=t;while((token!=ENDFILE)&&(token!=END)&&(token!=ELSE)&&(token!=UNTIL)&&(token!=ENDDO)&&(token!=ENDWHILE)&&(token!=WHILE))//新增加的循環(huán)判斷語句,避免嵌套循環(huán){TreeNode*q;match(SEMI);q=statement();if(q!=NULL){if(t==NULL)t=p=q;else/*nowpcannotbeNULLeither*/{p->sibling=q;p=q;}}}returnt;}TreeNode*statement(void){TreeNode*t=NULL;switch(token){caseIF:t=if_stmt();break;caseREPEAT:t=repeat_stmt();break;caseID:t=assign_stmt();break;caseREAD:t=read_stmt();break;caseWRITE:t=write_stmt();break;/*新添加的內(nèi)容,實(shí)現(xiàn)求余操作*/caseWHILE:t=while_stmt();break;caseDO:t=dowhile_stmt();break;caseFOR:t=for_stmt();break;/*求余內(nèi)容操作結(jié)束*/default:syntaxError("unexpectedtoken->");printToken(token,tokenString);token=getToken();break;}/*endcase*/returnt;}TreeNode*if_stmt(void){TreeNode*t=newStmtNode(IfK);match(IF);if(t!=NULL)t->child[0]=exp();match(THEN);if(t!=NULL)t->child[1]=stmt_sequence();if(token==ELSE){match(ELSE);if(t!=NULL)t->child[2]=stmt_sequence();}match(END);returnt;}TreeNode*repeat_stmt(void){TreeNode*t=newStmtNode(RepeatK);match(REPEAT);if(t!=NULL)t->child[0]=stmt_sequence();match(UNTIL);if(t!=NULL)t->child[1]=exp();returnt;}TreeNode*assign_stmt(void){TreeNode*t=newStmtNode(AssignK);if((t!=NULL)&&(token==ID))t->=copyString(tokenString);match(ID);match(ASSIGN);if(t!=NULL)t->child[0]=exp();returnt;}TreeNode*read_stmt(void){TreeNode*t=newStmtNode(ReadK);match(READ);if((t!=NULL)&&(token==ID))t->=copyString(tokenString);match(ID);returnt;}TreeNode*write_stmt(void){TreeNode*t=newStmtNode(WriteK);match(WRITE);if(t!=NULL)t->child[0]=exp();returnt;}/*以下部分為新增加的內(nèi)容*/TreeNode*while_stmt(void) //新擴(kuò)充的while文法{TreeNode*t=newStmtNode(WhileK);match(WHILE);if(t!=NULL)t->child[0]=exp();match(DO);if(t!=NULL)t->child[1]=stmt_sequence();match(ENDWHILE);returnt;}TreeNode*dowhile_stmt(void)//新擴(kuò)充的dowhile文法{TreeNode*t=newStmtNode(DowhileK);match(DO);if(t!=NULL)t->child[0]=stmt_sequence();match(WHILE);if(t!=NULL)t->child[1]=exp();returnt;}TreeNode*for_stmt(void)//新擴(kuò)充的for文法{TreeNode*t=newStmtNode(ForIncK);match(FOR);if(t!=NULL){t->child[0]=assign_stmt();if(token==TO) //實(shí)現(xiàn)步長(zhǎng)遞增1match(TO);elseif(token==DOWNTO)//實(shí)現(xiàn)步長(zhǎng)遞減1{match(DOWNTO);t->kind.stmt=ForDecK;}t->child[1]=simple_exp();match(DO);t->child[2]=stmt_sequence();match(ENDDO);}returnt;}/*新增加的內(nèi)容到此結(jié)束*/TreeNode*exp(void){TreeNode*t=simple_exp();if((token==LT)||(token==EQ)){TreeNode*p=newExpNode(OpK);if(p!=NULL){p->child[0]=t;p->attr.op=token;t=p;}match(token);if(t!=NULL)t->child[1]=simple_exp();}returnt;}TreeNode*simple_exp(void){TreeNode*t=term();while((token==PLUS)||(token==MINUS)){TreeNode*p=newExpNode(OpK);if(p!=NULL){p->child[0]=t;p->attr.op=token;t=p;match(token);t->child[1]=term();}returnt;}TreeNode*term(void){TreeNode*t=factor();while((token==TIMES)||(token==OVER)||(token==MOD))//此處為新增加的求余操作{TreeNode*p=newExpNode(OpK);if(p!=NULL){p->child[0]=t;p->attr.op=token;t=p;match(token);p->child[1]=factor();}}returnt;}TreeNode*factor(void){TreeNode*t=NULL;switch(token){caseNUM:t=newExpNode(ConstK);if((t!=NULL)&&(token==NUM))t->attr.val=atoi(tokenString);match(NUM);break;caseID:t=newExpNode(IdK);if((t!=NULL)&&(token==ID))t->=copyString(tokenString);match(ID);break;caseLPAREN:match(LPAREN);t=exp();match(RPAREN);break;default:syntaxError("unexpectedtoken->");printToken(token,tokenString);token=getToken();break;}returnt;}/*/*theprimaryfunctionoftheparser*//*/*Functionparsereturnsthenewly*constructedsyntaxtree*/TreeNode*parse(void){TreeNode*t;token=getToken();t=stmt_sequence();if(token!=ENDFILE)syntaxError("Codeendsbeforefile\n");returnt;}util.cpp代碼:TOC\o"1-5"\h\z/*File:util.c *//*Utilityfunctionimplementation *//*fortheTINYcompiler *//*CompilerConstruction:PrinciplesandPractice*//*KennethC.Louden */#include"globals.h"#include"util.h"/*ProcedureprintTokenprintsatoken*anditslexemetothelistingfile*/voidprintToken(TokenTypetoken,constchar*tokenString){charch='%';switch(token){caseIF:caseTHEN:caseELSE:caseEND:caseREPEAT:caseUNTIL:caseREAD:caseWRITE:/*添加與保留字相對(duì)應(yīng)的內(nèi)容*/caseWHILE:caseDO:caseFOR:caseENDWHILE:caseENDDO:caseTO:caseDOWNTO:/*增加以上部分內(nèi)容*/fprintf(listing,"reservedword:%s\n",tokenString);break;caseASSIGN:fprintf(listing,":=\n");break;caseLT:fprintf(listing,"<\n");break;caseEQ:fprintf(listing,"=\n");break;caseLPAREN:fprintf(listing,"(\n");break;caseRPAREN:fprintf(listing,")\n");break;caseSEMI:fprintf(listing,";\n");break;casePLUS:fprintf(listing,"+\n");break;caseMINUS:fprintf(listing,"-\n");break;caseTIMES:fprintf(listing,"*\n");break;caseOVER:fprintf(listing,"/\n");break;/*添加的保留字內(nèi)容*/caseMOD:fprintf(listing,"%c\n",ch);break;/*以上部分為添加的內(nèi)容*/caseENDFILE:fprintf(listing,"EOF\n");break;caseNUM:fprintf(listing,"NUM,val=%s\n",tokenString);break;caseID:fprintf(listing,"ID,name=%s\n",tokenString);break;caseERROR:fprintf(listing,"ERROR:%s\n",tokenString);break;default:/*shouldneverhappen*/fprintf(listing,"Unknowntoken:%d\n",token);/*FunctionnewStmtNodecreatesanewstatement*nodeforsyntaxtreeconstruction*/TreeNode*newStmtNode(StmtKindkind){TreeNode*t=(TreeNode*)malloc(sizeof(TreeNode));inti;if(t==NULL)fprintf(listing,"Outofmemoryerroratline%d\n",lineno);else{for(i=0;i<MAXCHILDREN;i++)t->child[i]=NULL;t->sibling=NULL;t->nodekind=StmtK;t->kind.stmt=kind;t->lineno=lineno;}returnt;}/*FunctionnewExpNodecreatesanewexpression*nodeforsyntaxtreeconstruction*/TreeNode*newExpNode(ExpKindkind){TreeNode*t=(TreeNode*)malloc(sizeof(TreeNode));inti;if(t==NULL)fprintf(listing,"Outofmemoryerroratline%d\n",lineno);else{for(i=0;i<MAXCHILDREN;i++)t->child[i]=NULL;t->sibling=NULL;t->nodekind=ExpK;t->kind.exp=kind;t->lineno=lineno;t->type=Void;}returnt;}/*FunctioncopyStringallocatesandmakesanew*copyofanexistingstring*/char*copyString(char*s){intn;char*t;if(s==NULL)returnNULL;n=strlen(s)+1;t=(char*)malloc(n);if(t==NULL)fprintf(listing,"Outofmemoryerroratline%d\n",lineno);elsestrcpy(t,s);returnt;}/*VariableindentnoisusedbyprintTreeto*storecurrentnumberofspacestoindent*/staticindentno=0;/*macrostoincrease/decreaseindentation*/#defineINDENTindentno+=2#defineUNINDENTindentno-=2/*printSpacesindentsbyprintingspaces*/staticvoidprintSpaces(void){inti;for(i=0;i<indentno;i++)fprintf(listing,"");}/*procedureprintTreeprintsasyntaxtreetothe*listingfileusingindentationtoindicatesubtrees*/voidprintTree(TreeNode*tree){inti;INDENT;while(tree!=NULL){printSpaces();if(tree->nodekind==StmtK){switch(tree->kind.stmt){caseIfK:fprintf(listing,"If\n");break;caseRepeatK:fprintf(listing,"Repeat\n");break;caseAssignK:fprintf(listing,"Assignto:%s\n",tree->);break;caseReadK:fprintf(listing,"Read:%s\n",tree->);break;caseWriteK:fprintf(listing,"Write\n");break;/*添加以下部分內(nèi)容*/caseWhileK:fprintf(listing,"While\n");break;caseDowhileK:fprintf(listing,"Do\n");break;caseForIncK:fprintf(listing,"For(遞增)\n");break;caseForDecK:fprintf(listing,"For(遞減)\n");break;/*以上為添加的內(nèi)容*/default:fprintf(listing,"UnknownExpNodekind\n");break;}}elseif(tree->nodekind==ExpK){switch(tree->kind.exp){caseOpK:fprintf(listing,"Op:");printToken(tree->attr.op,"\0");break;caseConstK:fprintf(listing,"Const:%d\n",tree->attr.val);break;caseIdK:fprintf(listing,"Id:%s\n",tree->);break;default:fprintf(listing,"UnknownExpNodekind\n");break;}}elsefprintf(listing,"Unknownnodekind\n");

for(i=0;i<MAXCHILDREN;i++)printTree(tree->child[i]);tree=tree->sibling;}UNINDENT;}五、程序執(zhí)行結(jié)果初始執(zhí)行結(jié)果:■Z'E:\L?]尢三l 第一學(xué)貯曙原理烷監(jiān)二Tiny曠充詣吞藥污法令折\Det>u日(I耐擴(kuò)充嗚菩打..卜watatkk比amatwwatw比.atac?atatwTIHY卞I'H?吾吉件丨1■吾 "辛T肚**** nk比nkatifatatwkkam■Fill<2>3<3>“更迥遠(yuǎn)原薦序文件圳’te.t.Lxt.百茁結(jié)黑存放;在:tinycnmpilatinn.txt捌的結(jié)巣存放在;巧Maxtreo.txt二:「加:卡進(jìn)薦代碼的編輯Fill<2>3<3>“更迥遠(yuǎn)原薦序文件圳’te.t.Lxt.百茁結(jié)黑存放;在:tinycnmpilatinn.txt捌的結(jié)巣存放在;巧Maxtreo.txt二:「加:卡進(jìn)薦代碼的編輯tinycoinxiilallan-txttest:.txttest.txt*syntaxtree.txt??在頂巨丁程文件中打開七1|1¥compilation.txtn查看結(jié)果1AAfl試樹請(qǐng)請(qǐng)箱法法編戒語語xt生成成.t要生生晨要.3>>■■12.當(dāng)選擇生成語法樹的結(jié)果:■3hE:\[3JXE\[1]弟一學(xué)期命原倉莫驗(yàn)二Ti町?dāng)U充洱言的語法令析匹EbuEVTiny曠充詣言的”,匸回.[巫[|K)C)CM:KX)C 逋:KXNKJCNWHXNWJCNKKXNT]NV扌廣tq"右的i?吾分?析耳NJOCNJ()(耳xz1>-XZ23

kktt>mxz1>-XZ23

kktt>m常輯an.teax編tiyt也annnn1iynfpi^7-ts5p件代m文魯苗-程存存屮ti源臬曰歹“試結(jié)結(jié)xt....t”swstxt用功法te.t第語“st序譯鑒te■txt"syntaxtree在項(xiàng)目工程文件中主冃五口xt生成成n要生生st否要不一仙是興xz\z主冃五口xt生成成n要生生st否要不

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論