现有PASCAL程序清单如下:
BEGIN
IF I=1 THEN
I:=I+1 #
ELSE *&^
IF I=2 THEN
I:=I+11;
END.
运行词法分析程序后,显示如下结果:
BEGIN (1,1)
IF (1,4)
I (6,0)
= (4,2)
1 (5,0)
THEN (1,5)
I (6,0)
:= (2,2)
I (6,0)
+ (3,0)
1 (5,0)
# error,not a word
ELSE (1,2)
* (3,2)
& error,not a word
^ error,not a word
IF (1,4)
I (6,0)
= (4,2)
2 (5,1)
THEN (1,5)
I (6,0)
:= (2,2)
I (6,0)
+ (3,0)
11 (5,2)
; (2,1)
END (1,3)
. (2,3)
over
结果完全正确。
[源程序清单]
以下是词法分析程序的源程序清单,该程序在Pentium 133,16M,Turbo c 2.0环境下运行通过。
int search(char searchchar[],int wordtype)
{
int i=0;
switch (wordtype) {
case 1:for (i=0;i<=7;i++)
{
if (strcmp(key[i],searchchar)==0)
return(i+1);
};
case 2:{for (i=0;i<=5;i++)
{
if (strcmp(border[i],searchchar)==0)
return(i+1);
};
return(0);
}
case 3:{for (i=0;i<=3;i++)
{
if (strcmp(arithmetic[i],searchchar)==0)
{
return(i+1);
};
};
return(0);
};
case 4:{for (i=0;i<=5;i++)
{
if (strcmp(relation[i],searchchar)==0)
{
return(i+1);
};
};
return(0);
};
case 5:{for (i=0;i<=constnum;i++)
{
if (strcmp(consts[i],searchchar)==0)
{
return(i+1);
};
}
consts[i-1]=(char *)malloc(sizeof(searchchar));
strcpy(consts[i-1],searchchar);
constnum++;
return(i);
};
case 6:{for (i=0;i<=labelnum;i++)
{
if (strcmp(label[i],searchchar)==0)
{
return(i+1);
};
}
label[i-1]=(char *)malloc(sizeof(searchchar));
strcpy(label[i-1],searchchar);
labelnum++;
return(i);
};
}
}
char alphaprocess(char buffer)
{
int atype;
int i=-1;
char alphatp[20];
while ((isalpha(buffer))||(isdigit(buffer)))
{
alphatp[++i]=buffer;
buffer=fgetc(fp);
};
alphatp[i+1]='\0';
if (atype=search(alphatp,1))
printf("%s (1,%d)\n",alphatp,atype-1);
else
{
atype=search(alphatp,6);
printf("%s (6,%d)\n",alphatp,atype-1);
};
return(buffer);
}
char digitprocess(char buffer)
{
int i=-1;
char digittp[20];
int dtype;
while ((isdigit(buffer)))
{
digittp[++i]=buffer;
buffer=fgetc(fp);
}
digittp[i+1]='\0';
dtype=search(digittp,5);
printf("%s (5,%d)\n",digittp,dtype-1);
return(buffer);
}
char otherprocess(char buffer)
{
int i=-1;
char othertp[20];
int otype,otypetp;
othertp[0]=buffer;
othertp[1]='\0';
if (otype=search(othertp,3))
{
printf("%s (3,%d)\n",othertp,otype-1);
buffer=fgetc(fp);
goto out;
};