Year 2 compilers coureswork

symbol_table.c 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Adapted from
  3. * CM20029 Coursework Assignment 1
  4. * Tom Crick
  5. * cs1tc@bath.ac.uk
  6. * 30 Apr 2003
  7. *
  8. * symbol_table.c
  9. */
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include "token.h"
  14. #include "C.tab.h"
  15. static TOKEN** symbtable;
  16. #define HASH_SIZE (1000)
  17. TOKEN *int_token, *void_token, *function_token;
  18. void init_symbtable(void)
  19. {
  20. symbtable = (TOKEN**)calloc(HASH_SIZE, sizeof(TOKEN*));
  21. int_token = new_token(INT);
  22. int_token->lexeme = "int";
  23. function_token = new_token(FUNCTION);
  24. function_token->lexeme = "function";
  25. void_token = new_token(VOID);
  26. void_token->lexeme = "void";
  27. }
  28. int hash(char *s)
  29. {
  30. int h = 0;
  31. while (*s != '\0') {
  32. h = (h<<4) ^ *s++;
  33. }
  34. return (0x7fffffff&h) % HASH_SIZE;
  35. }
  36. TOKEN* lookup_token(char *s)
  37. {
  38. int h = hash(s);
  39. TOKEN *a = symbtable[h];
  40. TOKEN *ans;
  41. /* printf("\nLookup: %s\n", s); */
  42. while (a!=NULL) {
  43. if (strcmp(a->lexeme, s)==0) return a;
  44. a = a->next;
  45. }
  46. ans = new_token(IDENTIFIER);
  47. ans->lexeme = (char*)malloc(1+strlen(s));
  48. strcpy(ans->lexeme, s);
  49. ans->next = symbtable[h];
  50. symbtable[h] = ans;
  51. /* printf(" stored at %p\n", ans); */
  52. return ans;
  53. }