📄 symbol.c
字号:
/*
* Author: zhangdi
* Date: 2008-11-10
* Description: symbol table, it has it's method to insert a symbol
* and method to lookup a symbol, it also has a method to distinguish if the
* identifier is a key word
*/
#include <string.h>
#include "global.h"
#include "error.h"
char lexemex[STRMAX]; /* array to store */
int lastchar = -1; /* memorize the last char of array store */
struct entry symtable[ARRAYMAX]; /* symtable array */
int lastentry = 0; /* memorize the last entry of symtable */
/* look up if a identifier is in the symbol table */
int lookup(char str[])
{
int position;
for (position = lastentry; position > 0; position = position -1)
{
if (strcmp(symtable[position].lexptr, str) == 0)
return position;
}
return 0;
}
/* insert identifier to symbol table */
int insert(char str[], int tok)
{
int length;
length = strlen(str);
if (lastentry + 1 >= ARRAYMAX)
error("symbol table full");
if (lastchar + length + 1 >= STRMAX)
error("lexemes array for symbol full");
/* modify the last entry of symtable */
lastentry += 1;
symtable[lastentry].token = tok;
symtable[lastentry].lexptr = &lexemex[lastchar + 1];
/* modify the last char of store array */
lastchar = lastchar + length + 1;
strcpy(symtable[lastentry].lexptr, str);
return lastentry;
}
/* distinguish a identifier is a symbol */
int searchkeyword(char key[])
{
int position;
for (position = 0; position < keynum; position++)
{
if (strcmp(keywords[position].lexptr, key) == 0)
return position;
}
return -1;
}
/* output symtable to a txt file */
int symtabledisplay()
{
int i;
FILE * fwp;
if ((fwp = fopen("symtable.txt", "wt")) == NULL)
{
fprintf(stderr, "can't create symtable.txt");
exit(-1);
}
for (i=1; i <= lastentry; i++)
{
switch(symtable[i].token)
{
case IF:
fprintf(fwp, "%s\tif\n", symtable[i].lexptr);
break;
case ELSE:
fprintf(fwp, "%s\telse\n", symtable[i].lexptr);
break;
case WHILE:
fprintf(fwp, "%s\twhile\n", symtable[i].lexptr);
break;
case INT:
fprintf(fwp, "%s\tint\n", symtable[i].lexptr);
break;
case ID:
fprintf(fwp, "%s\tid\n", symtable[i].lexptr);
break;
case FLOAT:
fprintf(fwp, "%s\tfloat\n", symtable[i].lexptr);
break;
case NUM:
fprintf(fwp, "%s\tnum\n", symtable[i].lexptr);
break;
case FNUM:
fprintf(fwp, "%s\tfnum\n", symtable[i].lexptr);
break;
case RELOP:
fprintf(fwp, "%s\trelop\n", symtable[i].lexptr);
break;
case ADDOP:
fprintf(fwp, "%s\taddop\n", symtable[i].lexptr);
break;
case MULOP:
fprintf(fwp, "%s\tmulop\n", symtable[i].lexptr);
break;
default:
fprintf(fwp, "%s\t%c\n", symtable[i].lexptr, symtable[i].token);
break;
}
}
fclose(fwp);
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -