手工编写简易词法分析器

编译原理的作业,使用C手工编写词法简易词法分析器。大概内容就是根据指定的关键字,分隔符和其他的变量等,

在输入的一段程序中,将关键字,分隔符和变量,运算符等分别区分开来放到一个二元组里面,并且说明是第几个。

这个应该是书写编译器的开始,起初感觉很复杂,但是看看Demo还是可以的,下面来看一下源代码。

/* lexical analyzer */ #include #include #include #include #include #define NULL 0 #define MAX_KEY_NUM 10 #define MAX_BORDER_NUM 6 #define MAX_ARITH_NUM 4 #define MAX_RELATION_NUM 6 #define MAX_CONSTS_NUM 20 #define MAX_LABEL_NUM 20 FILE *fp; char cbuffer; char *key[MAX_KEY_NUM]={"if","else","for","while","do","return","break","continue","main","int"}; char *border[MAX_BORDER_NUM]={",",";","{","}","(",")"}; char *arithmetic[MAX_ARITH_NUM]={"+","-","*","/"}; char *relation[MAX_RELATION_NUM]={"<","<=","==",">=",">","="}; char *consts[MAX_CONSTS_NUM]; char *label[MAX_LABEL_NUM]; int constnum=0,labelnum=0; //=============================================== int search(char searchchar[],int wordtype) { int i=0; switch (wordtype) { case 1: for (i=0;i0) if (strcmp(consts[i],searchchar)==0) { return(i+1); } } consts[i]=(char *)malloc(sizeof(searchchar)); strcpy(consts[i],searchchar); constnum++; return(i+1); } case 6: { for (i=0;i 这样就算完成了。

你可能感兴趣的:(手工编写简易词法分析器)