資源描述:
《【精品】詞法分析實(shí)驗(yàn)報(bào)告.doc》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在工程資料-天天文庫(kù)。
1、實(shí)驗(yàn)?zāi)康脑O(shè)計(jì),編制并調(diào)試一個(gè)詞法分析稈序,加深對(duì)詞法分析原理的理解。實(shí)驗(yàn)要求待分析的簡(jiǎn)單語(yǔ)言的此法(I)關(guān)鍵字(32個(gè))”auto“,“break”,“case”,”char“,“const”,“continue”,“default",“do”,“double",“else叮'enumTexter,''float^'Tor0,"goto",,,ifn;,int,V,long,,;,registerH,"return,,;'shortn,,,signed,,,,,sizeof,,,,,static,,;,struct,,,Hswitch","typedef","union","unsig
2、ned","void","volatile","while"(2)運(yùn)算符和界符(40個(gè))(3)其他單詞是標(biāo)識(shí)符和整型常數(shù)(4)空格由空白,制表符和換行符組成??崭褚话阌脕?lái)分隔標(biāo)識(shí)符,整型常數(shù),運(yùn)算符,界符,關(guān)鍵字。各種單詞符號(hào)對(duì)應(yīng)的種別碼auto40#0break41(1case42)2char4313????■■■?■■■?volatile70+=37while71■ZZZ38ID150*=39DIGIT100/=39詞法分析程序的功能輸入:所給文法的源程序字符串。輸出:二元組(syn,token或sum)構(gòu)成的序列。其屮:syn為單詞種別碼;token為存放的單詞自身字符串;sum
3、為整型常數(shù);詞法分析程序的算法思想算法的基木任務(wù)是從字符串表示的源程序屮識(shí)別出具有獨(dú)立意義的單詞符號(hào),其基木思想是根據(jù)掃描到單詞符號(hào)的第一個(gè)字符的種類,拼出相應(yīng)的單詞符號(hào)。主程序示意(1)關(guān)鍵字表的初值。關(guān)鍵字特殊標(biāo)識(shí)符處理,把他們預(yù)安排在一張表格屮,當(dāng)掃描程序識(shí)別岀標(biāo)識(shí)符時(shí),杳找關(guān)鍵字表。如能杳找到匹配的單詞,則該單詞為關(guān)鍵字,否則為一般標(biāo)識(shí)符。關(guān)鍵字表為一個(gè)字符串?dāng)?shù)組,其描述如下:char*keyO[]={"auton,"break","case","char","const'1,"continue","default","do”,“double”,“else",”enum”,“e
4、xtern",“float”,”for“,“goto",“if”,“l(fā)ong”,”「egi(2)稈序屮需要用到的主要變量為syn,token和sum;掃描子程序的算法思想首先設(shè)置3個(gè)變量:token用來(lái)存放構(gòu)成單詞符號(hào)的字符串;sum用來(lái)存放整型單詞;syn用來(lái)存放單詞符號(hào)的種別碼。詞法分析程序的C語(yǔ)言程序框架2:、:.V
5、拼數(shù)7Syn=15()對(duì)不同符號(hào)紿出相應(yīng)的synffl7源程序代碼#includeHstdio.hH#include"string.h"#include"iostream.h”char*keyO[]={"aiito","break","case","char",
6、"const","continue","default","do","double","else","enum'V*extern”float”,“for”,“goto",“if”,”long”,“wgister“,Return”,“short",“signed”,“sizeof",“static”,“struct”,”switchn,”typedefYunionTunsignedTvoicT「voIatiiyrwhiiy};//32個(gè)關(guān)鍵字intcompare(char*token)intn;for(n=0;nv40;n++)if(strcmp(token,key1[n])==0)br
7、eak;returnn;}voidscaner(constchar*prog,char*tokenjnt&syn,int&p){intn,i=0;charch;for(n=0;n<8;n++){token[n]=NULL;}ch=prog[p];while(ch==,’llch==)ch=prog[++p];1if(((ch>=,A,)&&(ch<=,Z,))ll((ch>=,a,)&&(ch<=,z,))ll(ch==,J)){while(((ch>=,A,)&&(ch<=,Z,))ll((ch>=,a,)&&(ch<=,z,))ll(ch>=,0'&&ch<=,9,)ll(ch
8、==,_')){token[i+4-]=ch;ch=prog[++p];}token[i]=AO*;syn=150;for(n=0;n<32;n++){if(strcmp(token,keyO[n])==0){syn=n+40;break;}}}elseif(ch>=,0,&&chv=9){while(l){token[i++]=ch;ch=prog[++p];if(ch==,#,llch==,,llch==,;*){token[i]=