新词法分析程序.docx
《新词法分析程序.docx》由会员分享,可在线阅读,更多相关《新词法分析程序.docx(14页珍藏版)》请在冰点文库上搜索。
![新词法分析程序.docx](https://file1.bingdoc.com/fileroot1/2023-4/28/9c429919-43f2-4a8f-b12a-f0eb25dbd3f8/9c429919-43f2-4a8f-b12a-f0eb25dbd3f81.gif)
新词法分析程序
编译原理—词法分析程序(清华大学版编译原理词法分析流程图)
#include
#include
#include
void getch();
void getsym();
typedef struct tag_keywordarray /* 存放关键字 */
{
char a[20];
}keywordarray[10];
typedef struct tag_token /* 存放种别码和值的 */
{
int sym;
char symbol[10];
}token[100];
keywordarray keyword={ "begin","end","for","if","integer","procedure","read",
"repeat","var","write"};
static token token_PL;
static int cc=0;
static int j=0;
static char line[50];
char ch;
bool RLP=true;
void main(void)
{
int i;
getsym();
for(i=0;i {
printf("<");
printf("%d,",token_PL.sym);
printf("%s> ",token_PL.symbol);
}
if(RLP==false)
{
printf("\nNone of ')'\n");
}
system("pause");
}
void getsym()
{
int k;
int i;
char A[10];
char id[10];
while(ch==NULL)
{
getch();
}
/* 判断ch是否有字 */
while(ch!
='\n')
{
if((ch>='A' && ch<='Z') ¦ ¦ (ch>='a' && ch<='z'))
/* 判断取出的字是否为字母 */
{
k=0;
A[k]=ch;
k=k+1;
getch();
while
(1)
{
if((ch>'A' && ch<'Z') ¦ ¦ (ch>='a' && ch<='z') ¦ ¦(ch>='0' && ch<='9'))
{
if(k<10)
{
A[k]=ch;
k=k+1;
getch();
}
else
{
getch();
/* k>10则继续取词,但对后面的不错处理,截取前10个 */
}
}
else
{
cc-=1;
break;
}
}
for(i=0;i {
id=A;
}
id='\0';
bool bKeyword=false;
for(i=0;i<10;i++)
{
if((stricmp(id,keyword.a))==0)
{
token_PL[j].sym=1;
strcpy(token_PL[j].symbol,keyword.a);
j=j+1;
bKeyword=true;
break;
}
}
if(!
bKeyword)
{
token_PL[j].sym=2;
strcpy(token_PL[j].symbol,id);
j=j+1;
}
}
else
{
if(ch>='0' && ch<='9') /* 判断是否为数字 */
{
k=0;
A[k]=ch;
k=k+1;
getch();
while
(1)
{
if(ch>='0' && ch<='9')
{
if(k<10)
{
A[k]=ch;
k=k+1;
getch();
}
else
{
getch();
}
}
else
{
cc-=1;
break;
}
}
token_PL[j].sym=4;
A[k]='\0';
strcpy(token_PL[j].symbol,A);
j=j+1;
}
else /* 是否为操作符 */
{
if(ch=='+')
{
k=0;
A[k]=ch;
token_PL[j].sym=3;
A[k+1]='\0';
strcpy(token_PL[j].symbol,A);
j=j+1;
}
else if(ch=='-')
{
k=0;
A[k]=ch;
token_PL[j].sym=3;
A[k+1]='\0';
strcpy(token_PL[j].symbol,A);
j=j+1;
}
else if(ch=='*')
{
k=0;
A[k]=ch;
token_PL[j].sym=3;
A[k+1]='\0';
strcpy(token_PL[j].symbol,A);
j=j+1;
}
else if(ch=='/')
{
k=0;
A[k]=ch;
token_PL[j].sym=3;
A[k+1]='\0';
strcpy(token_PL[j].symbol,A);
j=j+1;
}
else if(ch==':
')
{
k=0;
A[k]=ch;
getch();