资源描述:
《【精品】编译原理--词法分析》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、词法分析#includedostream>#include#includeusingnamespacestd;#defineMAXN20000intsyn,p,sum,kk,m,n,row;doubledsum,pos;charindex[800],len;//id录指数形式的浮点数charr[6][10]={“function",”if”,吐hen”,”while”,“do”,“endfbnc”};chartoken[MAXN],s[MAXN];charch;boolis_letter(charc){returnc>='a'&&c<='z'IIo='A'&&
2、c<='Z';}boolis_digtial(charc){returnc>='0*&&c<='9';}boolis_dot(charc){returnc=='/IIc==';}voididentifier()//标示符的判断{m=0;while(ch>='a,&&ch<=,z,IIch>=,0,&&chv=9){token[m++]=ch;ch=s[++pj;ch=s[-p];syn=l();for(n=0;n<6;n++)if(strcmp(token,r[n])==0){syn=n+l;break;voiddigit(boolpositive)//数字的判断{len=sum=0;ch=
3、s[p];while(ch>=,0,&&ch<='9,){sum=sum*10+ch-'O1;ch=s[++p];}if(ch=7){dsum=sum;ch=s[++p];pos=0.1;while(ch>-0'&&ch<=,9,){dsum=dsum+(ch-,0,)*pos;pos=pos*0.1;ch二s[++p];}if(ch==,e,){index[len++]=ch;ch=s[++p];if(ch==,-1IIch==,+,){index[len++]=ch;ch=s[++p];}if(!(ch>=,0,&&chv=9))syn=-1;elsewhile(ch>=tO,&&chv=
4、9)index[len++J=ch;ch=s[++pj;)1)if(syn==-lII(ch>='a'&&ch<=,z,)IIch==7){syn=・l;〃对数字开头的标识符述行判错。while(ch>=,0,&&ch<='9,IIch>=,a,&&ch<=,z,IIch==7)ch=s[++pj;//找到下一次要判断的开头ch=s[-p];}else{ch=s[-p];syn=12;if(!positive)dsum*=-1.0;))else{if(ch>='a‘&&ch<=,z,){syn=・l;〃对数字开头的标识符进行判错。while(ch>='0'&&chv=9IIch>=*a'&&c
5、h<='z')ch=s[++p];〃找到下一次要判断的开头ch=sf-p];}else{ch=s[-p];syn=lI;if(!positive)sum*二-1;)boolcheck_behind_digit(){inti=p+1;while(s[i]!= r)if(s[i]>=,()'&&s[i]<=,9,)returntrue;elseif(s[i]!='&&s[i]!=t‘&&s[i]!=,,)returnfalse;i++;}returnfalse;}boolcheck_pre_prog(){inti=p-l;while(i>=0){if(s[i]!=,*&&sfiJHV&&s
6、[i]!=W){if(s[i]>=,0,&&s[i]<=,9,IIs[i]>=,a,&&s[i]<=,z,)returnfalse;elsereturntrue;}i-;}returntrue;}voidpot(){while(l){ch=s[++p];if(ch==')TOW++;if(!(ch=='1IIch==fIIch==,,))break;}}voidscaner(){memset(token,O,sizeof(token));pot();//cout«p«,f«ch«endl;if(is_letter(ch))syn=10;identifierO;elseif(is_di
7、gtial(ch)){syn=l1;digit(true);}else{if(ch=='<,){len=0,token[len++]=ch;if(s[p+1]=='='){syn=22;token[len++]=s[p+1];p++;}elsesyn=20;}elseif(ch==*>,){len=0,token[len++]=ch;if(s[p+l]=='='){syn=24;token[len