#include #include #include "token.h" #include "symbol.h" #include "emalloc.h" struct symbol { /* various stuff about type, etc, would go here in a compiler */ char *name; int index; /* you can add other data here if desired */ struct symbol *next; /* next symbol in the same bucket (leave this) */ }; #define HASHSIZE 67 static struct symbol *bucket[HASHSIZE]; /* default init to null pointers */ static int hash(char *name) /* you are not expected to understand this... */ { int retval = 0; char *p; for (p = name; *p; p++) retval = (retval + (*p & 255)) % HASHSIZE; return retval; } struct symbol *symbol_lookup(char *name) { FILL THIS IN. 1) Try to find the symbol in the linked list number hash(name) (i.e. "top" pointer is bucket[hash(name)]) 2) If it's not there, allocate a new struct symbol with emalloc, fill its contents in, and link it in to the linked list. 2a) To fill in the "name" member of struct symbol, do this: p->name = emalloc(strlen(name) + 1); strcpy(p->name, name); 3) Return value is the symbol of name "name", whether found in step 1 or freshly created in step 2. } char *symbol_getname(struct symbol *p) { return p->name; } void symbol_setindex(struct symbol *p, int i) { p->index = i; } int symbol_getindex(struct symbol *p) { return p->index; } int symbol_count() { /* FILL THIS IN if you need it; else delete this function */ } void symbol_set_seen(struct symbol *p, int stmt) { /* FILL THIS IN */ } int live_range_is_overlapping(struct symbol *p, struct symbol *q) { /* FILL THIS IN */ } /* iterator class */ struct symbol_iter { int bucket; struct symbol *cur; }; struct symbol_iter *new_symbol_iter() { struct symbol_iter *p = (struct symbol_iter *)emalloc(sizeof(struct symbol_iter)); p->bucket = -1; p->cur = NULL; return p; } struct symbol *first_symbol(struct symbol_iter *p) { p->bucket = -1; p->cur = NULL; return next_symbol(p); } struct symbol *next_symbol(struct symbol_iter *p) { if (p->cur) p->cur = p->cur->next; if (!p->cur) { while (++p->bucket < HASHSIZE && !(p->cur = bucket[p->bucket])) ; } return p->cur; }