home *** CD-ROM | disk | FTP | other *** search
- /* $Id: symbol.c 2.1 91/02/28 11:16:35 cthuang Exp $
- *
- * Symbol table maintenance. Implements an abstract data type called
- * the symbol table.
- */
- #include <stdio.h>
- #include "config.h"
- #include "symbol.h"
-
- /* Create a symbol table.
- * Return a pointer to the symbol table or NULL if an error occurs.
- */
- SymbolTable *
- create_symbol_table ()
- {
- SymbolTable *symtab;
- int i;
-
- if ((symtab = (SymbolTable *)malloc(sizeof(SymbolTable))) != NULL) {
- for (i = 0; i < SYM_MAX_HASH; ++i)
- symtab->bucket[i] = NULL;
- }
- return symtab;
- }
-
-
- /* This is a simple hash function mapping a symbol name to a hash bucket. */
-
- static int
- hash (name)
- char *name;
- {
- return (name[0] + name[1] + strlen(name)) % SYM_MAX_HASH;
- }
-
-
- /* Search the list of symbols <list> for the symbol <name>.
- * Return a pointer to the symbol or NULL if not found.
- */
- static Symbol *
- search_symbol_list (list, name)
- Symbol *list;
- char *name;
- {
- Symbol *sym;
-
- for (sym = list; sym != NULL; sym = sym->next) {
- if (strcmp(sym->name, name) == 0)
- return sym;
- }
- return NULL;
- }
-
-
- /* Look for symbol <name> in symbol table <symtab>.
- * Return a pointer to the symbol or NULL if not found.
- */
- Symbol *
- find_symbol (symtab, name)
- SymbolTable *symtab;
- char *name;
- {
- return search_symbol_list(symtab->bucket[hash(name)], name);
- }
-
-
- /* If the symbol <name> does not already exist in symbol table <symtab>,
- * then add the symbol to the symbol table.
- * Return a pointer to the symbol or NULL on an error.
- */
- Symbol *
- new_symbol (symtab, name)
- SymbolTable *symtab; /* symbol table */
- char *name; /* symbol name */
- {
- Symbol *sym;
- int i;
-
- if ((sym = find_symbol(symtab, name)) == NULL) {
- if ((sym = (Symbol *)malloc(sizeof(Symbol))) != NULL) {
- sym->name = strdup(name);
- i = hash(name);
- sym->next = symtab->bucket[i];
- symtab->bucket[i] = sym;
- }
- }
- return sym;
- }
-