symtable.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #include <string.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include "symtable.h"
  5. // number of entries on each symtable
  6. #define SYMMAX 100
  7. // symtable
  8. struct symtable {
  9. struct entry entry[SYMMAX];
  10. int lastentry;
  11. struct symtable *parent;
  12. } *symtable;
  13. /* init
  14. * allocate memory
  15. * no symbols inside
  16. */
  17. void symtable_init() {
  18. symtable = malloc(sizeof(struct symtable));
  19. symtable->lastentry = -1;
  20. symtable->parent = 0;
  21. }
  22. // find symbol, and return its index
  23. symtable_index lookup(char s[]) {
  24. int p;
  25. for (p = 0; p <= symtable->lastentry; p++) {
  26. if (strcmp(symtable->entry[p].lexptr, s) == 0) {
  27. return p;
  28. }
  29. }
  30. return -1;
  31. }
  32. // insert new symbol
  33. symtable_index symtable_insert(char s[], int tok) {
  34. // entry to be returned
  35. struct entry *symentry;
  36. // entry already in sym table - return it
  37. int index = lookup(s);
  38. if (index >= 0) {
  39. return index;
  40. }
  41. // make sure sym table has space
  42. if (symtable->lastentry +1 >= SYMMAX) {
  43. printf("symbol table full");
  44. return 0;
  45. }
  46. // sym table about to get a new symbol - prepare it
  47. int len;
  48. len = strlen(s);
  49. // entry's index
  50. symtable->lastentry++;
  51. // create new entry
  52. symentry = &symtable->entry[symtable->lastentry];
  53. symentry->token = tok;
  54. symentry->lexptr = malloc(sizeof(char) *len +1);
  55. symentry->value = 0;
  56. strcpy(symentry->lexptr, s);
  57. return symtable->lastentry;
  58. }
  59. // clean current system table and all it's parents
  60. void symtable_clean() {
  61. struct symtable *csymtable;
  62. while (symtable != 0) {
  63. csymtable = symtable->parent;
  64. for (int i = 0; i <= symtable->lastentry; i++) {
  65. free(symtable->entry[i].lexptr);
  66. }
  67. free(symtable);
  68. symtable = csymtable;
  69. }
  70. }
  71. // print symbol table
  72. void symtable_print() {
  73. printf("symtable:\n");
  74. for (int i = 0; i <= symtable->lastentry; i++) {
  75. printf("\t%s | token: %d\n", symtable->entry[i].lexptr, symtable->entry[i].token);
  76. }
  77. printf("end symtable:\n");
  78. }
  79. // get entry from index
  80. struct entry *symtable_entryat(symtable_index index) {
  81. return &symtable->entry[index];
  82. }