#define MAXKEY 1024 //哈希表容量
TkWord *tk_hashtable[MAXKEY]; //单词哈希表
DynArray tktable; //单词表
typedef struct TkWord
{
int tkcode; //单词编码
struct TkWord *next; //指向哈希冲突的同义词
char *spelling ; //单词字符串
struct Symbol *sym_struct; //指向单词所表示的结构定义
struct Symbol *sym_identifier; //指向单词所表示的标识符
}TkWord;
TkWord *tkword_direct_insert(TkWord *tp)/**功能:运算符,关键字,常量直接放入单词表**/
{
int keyno;
dynarray_add(&tktable,tp); /**把tp插入单词表**/
keyno=elf_hash(tp->spelling); /**找到tp在哈希表中位置然后逆序插入**/
tp->next=tk_hashtable[keyno];
tk_hashtable[keyno]=tp;
return tp;
}
TkWord *tkword_find(char *p,int keyno)/**在单词表中查找单词,p是要查找的单词,keyno是单词哈希值**/
{
TkWord *tp=NULL,*tp1;
for(tp1=tk_hashtable[keyno];tp1;tp1=tp1->next)
{
if(!strcmp(tp1->spelling,p))
{
token=tp1->tkcode; /**token是一个全局变量,记录单词的编码值,但现在这还没定义,了解就行**/
tp=tp1;
}
}
return tp; /**找到了就返回找到的值,没找到就返回它的初值NULL**/
}
TkWord *tkword_insert(char *p) /**功能:标识符插入单词表,先查找,查找不到再插入单词表**/
{
TkWord *tp;
int keyno;
char *s;
char *end;
int length;
keyno=elf_hash(p);
tp=tkword_find(p,keyno);
if(tp==NULL)
{
length=strlen(p);
tp=(TkWord*)malloc(sizeof(TkWord)+length+1);
tp->next=tk_hashtable[keyno];
tk_hashtable[keyno]=tp;
dynarray_add(&tktable,tp);
tp->tkcode=tktable.count-1;
s=(char *)tp+sizeof(TkWord);
/**tp是已经分配空间的一个指针,空间包含sizeof(TkWord)+length+1
先把tp强制转换成字符指针的形式,再加sizeof(TkWord),刚好把指针移到
指向tp->spelling的地址**/
tp->spelling=(char *)s;
for(end=p+length;p<end;)
{
*s++=*p++;
}
*s=(char)'\0';
}
return tp;
}
void *mallocz(int size) /**分配内存并把数据初始化为'0'**/
{
void *ptr;
ptr=malloc(size);
if(!ptr&&size) /**size是分配内存大小**/
error("内存分配失败");
memset(ptr,0,size); /**填充'0'**/
return ptr;
}
单词表及其函数
最新推荐文章于 2020-12-18 21:34:52 发布