/* Return pointer to ST record of lexeme s, or NULL if not found */ STrec *STlookup(char *s) { /*Get the hash of s*/ int hash = SThash(s); /*Check to see if there are any lexemes at the given hash index. If there were, compare the strings. If theyre not the same, go on to the next STrec. */ STrec *recpt = NULL; if (symtab[hash]!= NULL) { recpt = symtab[hash]; } char *lex; STrec *link; do { if (recpt != NULL) { lex = recpt->lexptr; link = recpt->hashlink; if (lex == NULL) { return NULL; } else { if (strcmp(lex, s) == 0) { return recpt; } else { recpt = link; } } } else { return NULL; } } while (link != NULL); /*Looped through without finding anything, so return NULL */ return NULL; }
/* Insert lexeme s into symbol table and return pointer to new STrec */ STrec *STinsert(char *s) { STrec *node; int hash = SThash(s); node = (STrec *)malloc(sizeof(STrec)); node->lexptr = (char *)malloc(strlen(s)+1); strcpy(node->lexptr, s); node->declstack = NULL; /* NEW HW 4: initially empty stack of decldescs. */ STrec* target = symtab[hash]; /* If there is a clash, then we want to push node to the front * Do this by temporarily storing the existing node and setting * the temporary node (target) as the child of the new node */ node->hashlink = target; symtab[hash] = node; return node; }
/* Return pointer to ST record of lexeme s, or NULL if not found */ STrec *STlookup(char *s) { int hash = SThash(s); STrec* rec = symtab[hash]; /* Find the corresponding spot in the table to insert * If rec is null, this means the lexeme has not been inserted * If there is a hit, we have to iterate through the linked list * recursively and see if any strec points to the same lexeme */ while (rec != NULL) { if (strcmp(s, rec->lexptr) == 0) { return rec; } else { // printf("found %s, was looking for %s\n", rec->lexptr, s); rec = rec->hashlink; } } // printf("failed to find %s\n", s); return NULL; }
/* Insert lexeme s into symbol table and return pointer to new STrec */ STrec *STinsert(char *s) { STrec *node; int hash = SThash(s); node = (STrec *)malloc(sizeof(STrec)); node->lexptr = (char *)malloc(strlen(s)+1); strcpy(node->lexptr, s); /* (need to insert 'node' at beginning of linked list at 'symtab[hash]') */ STrec *oldSTrec = NULL; /* If there was an STrec at that index before, save it then place the pointer in node's hashlink */ if (symtab[hash] != NULL) { oldSTrec = symtab[hash]; } symtab[hash] = node; node->hashlink = oldSTrec; node->declstack = NULL; /* NEW HW4 */ return node; }