编辑: 戴静菡 | 2019-07-17 |
实验内容 词法分析 词法分析是编制一个读单词的过程,从输入的源程序中,识别出各个具有独立意义的单词,即基本保留字、标识符、常数、运算符、分隔符五大类.并依次输出各个单词的内部编码及单词符号自身值.程序语言的单词符号一般分为五种:关键字:有if、while等;
标识符:常量名、变量名…;
常数;
运算符:+、-、*等;
界限符:等. 词法分析的功能是输入源程序,输出单词符号.词法分析器的单词符号常常表示成以下的二元式(单词,单词种类). 在本实验中,以分析如下代码: main( ) { int a, b, c ;
a =
3 ;
b =
2 ;
c = (a+b)*5+3 ;
} 要求实验输出的结果是每一个单词对应于一个单词种类,使用一个二元式表示的. 其主要代码: void Scan() { struct stat buffer;
int i = 0;
char ch;
char filename[40];
FILE *inFile;
printf( Please input the file name: );
gets(filename);
stat( filename , &
buffer);
file = (char*)malloc(sizeof(buffer.st_size));
if((inFile=fopen( source.txt , r ))==NULL) { printf( Cannot open file. );
getchar();
exit(0);
} while((ch = getc(inFile)) != EOF) file[i++] = ch;
fclose(inFile) ;
file[i++] = '
\0'
;
fileLength = i;
initRecord();
printf( \n-词法分析-n );
while((ch = getCharacter(0'
) { if((ch != '
\n'
) &
&
(ch ch != '
\t'
)) { if( islower(ch) || isupper(ch) || ch == '
_'
) recogId(ch);
else if(isdigit(ch)) recogDigit(ch);
else recogOther(ch);
};
} insertToken(13,-1);
} void recogId(char ch) { int i = 0;
int code;
int keyword = 0;
strcpy(strToken, );
while(islower(ch) || isupper(ch) || isdigit(ch)) { strToken[i] = ch;
ch = getCharacter();
i++;
} strToken[i] = '
\0'
;
cursor--;
row--;
code = Reserve();
if (code) printf( %s\t关键字\n ,strToken);
else printf( %s\t标识符\n ,strToken);
for(i = 0;
i <
13;
i++) { if(strcmp(record[i].symbol,strToken) == 0) { insertToken(record[i].id, -1);
keyword = 1;
} } if(!keyword) { struct entryType *head, * tempEntry;
int word = 0;
if(headEntry == NULL) { head = (struct entryType*)malloc(sizeof(struct entryType));
strcpy(head->
idName, strToken);
head->
address = entry;
head->
type = NULL;
head->
next = NULL;
headEntry = tailEntry = head;
entry++;
insertToken(3, entry - 1);
} else { tempEntry = headEntry;
while(tempEntry != NULL) { if(strcmp(tempEntry->
idName, strToken) == 0) { insertToken(3, tempEntry->
address);
word = 1;
} tempEntry = tempEntry->
next;
} if(!word) { head = (struct entryType*)malloc(sizeof(struct entryType));
strcpy(head->
idName, strToken);
head->
address = entry;
head->
type = NULL;
head->
next = NULL;
tailEntry = tailEntry->
next = head;
entry++;
insertToken(3, entry - 1);
} } } } //识别数字 void recogDigit(char ch) { int i = 0;
do { i = i *
10 + ch - '
0'
;
ch = getCharacter();
}while(isdigit(ch));
row--;
cursor--;
printf( %d\t常数\n ,i);
insertDigit(i);
insertToken(2, digit - 1);
} //识别界限符、运算符 void recogOther(char ch) { switch(ch) { case '
{'
: insertToken(4, -1);
printf( %c\t界限符\n ,ch);
break;