实验一 手工编程实现词法分析器
1.实验目的: 熟悉词法分析阶段的要求,掌握利用状态图手工实现词法分析器的方法。
2.实验设备: 硬件:PC 机一台 软件:Windows系统,高级语言集成开发环境
3.实验内容: 根据词法要求手工实现词法分析器
4.实验要求及步骤
- 理解以下词法表述和状态图表示。
- 参考教科书3.2.4章节编写代码实现词法分析器。实现语言不限,推荐使用C语言,不可用脚本类语言;不允许使用任何语言的正规式控件实现实验要求。
- 提交词法分析器代码与实验报告。实验报告为word形式文档,内容是10对如下形式的输入输出。
输入语句任意自设,可包含错误单词($ERR类);若含错误单词,则词法分析器运行需报告错误,错误信息含第一个错误单词位置。
代码如下:
#include "stdlib.h"
#include "ctype.h"
#include "string.h"
#include "stdio.h"
#define _MYTEX
#define STRSIZE 1024
void init();
void getChar();
void getBC();
void concat();
int reserve();
void retract();
void insertID();
void insertConst();
void over();
int run();
char ch;
char *strToken;
int strTokenLen;
char *str;
int strIndex;
int strSize;
char resTable[5][5] = {"DIM\0", "IF\0", "DO\0", "STOP\0", "END\0"};
void init() {
ch = '\0';
str = (char *) malloc(STRSIZE * sizeof(char));
str[0] = '\0';
strIndex = 0;
strToken = (char *) malloc(STRSIZE * sizeof(char));
strToken[0] = '\0';
strTokenLen = 0;
}
void getChar() {
ch = str[strIndex++];
}
void getBC() {
while (isblank(ch)) {
getChar();
}
}
void concat() {
strToken[strTokenLen++] = ch;
strToken[strTokenLen] = '\0';
}
int reserve() {
int i = 0;
for (i = 0; i < 5; i++) {
if (strcmp(strToken, resTable[i]) == 0) {
printf("$%s\n", resTable[i]);
return i;
}
}
return -1;
}
void retract() {
strIndex--;
ch = '\0';
}
void insertID() {
printf("$ID\t\t %-20s\n", strToken);
}
void insertConst() {
printf("$INT\t %-20s\n", strToken);
}
void over() {
free(strToken);
strToken = (char *) malloc(STRSIZE * sizeof(char));
strTokenLen = 0;
}
int run() {
init();
printf("\nPlease input code: ");
fflush(stdout);
scanf("%[^\n]", str);
scanf("%c", &ch);
strSize = strlen(str);
printf("编码\t值\n---------------\n");
int status = 1;
while (status) {
getChar();
getBC();
if (isalpha(ch)) {
while (isalnum(ch)) {
concat();
getChar();
}
retract();
int resCode = reserve();
if (resCode == -1) {
insertID();
}
} else if (isdigit(ch)) {
while (isdigit(ch)) {
concat();
getChar();
}
retract();
insertConst();
} else if (ch == '=') {
printf("$ASSIGN\n");
} else if (ch == '+') {
printf("$PLUS\n");
} else if (ch == '*') {
getChar();
if (ch == '*') {
printf("$POWER\n");
} else {
retract();
printf("$STAR\n");
}
} else if (ch == ',') {
printf("$COMMA\n");
} else if (ch == '(') {
printf("$LPAR\n");
} else if (ch == ')') {
printf("$RPAR\n");
} else {
if (strIndex > strSize) {
status = 0;
} else if (!isblank(ch)) {
printf("$ERR\t %-20c\n", ch);
status = 0;
}
}
over();
}
return strSize;
}
int main ()
{
while (run()) {
}
return 0;
}