summaryrefslogtreecommitdiffstats
path: root/symbol-table.c
blob: 665c39caf200314eb5c902fcfeff8c68e9bfe690 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include "symbol-table.h"

#define TABLE_SIZE    256

symtab *hash_table[TABLE_SIZE];
extern int linenumber;

int HASH(char *str) {
    int idx = 0;
    while (*str) {
        idx = idx << 1;
        idx += *str;
        str++;
    }
    return (idx & (TABLE_SIZE-1));
}

/* returns the symbol table entry if found else NULL */
symtab *lookup(char *name) {
    int hash_key;
    symtab *symptr;
    if (!name)
        return NULL;
    hash_key = HASH(name);
    symptr = hash_table[hash_key];

    while (symptr) {
        if (!(strcmp(name, symptr->lexeme)))
            return symptr;
        symptr = symptr->front;
    }
    return NULL;
}


void insertID(char *name) {
    int hash_key;
    symtab *ptr;
    symtab *symptr = malloc(sizeof(symtab));

    hash_key = HASH(name);
    ptr = hash_table[hash_key];

    if (ptr == NULL) {
        /* first entry for this hash_key */
        hash_table[hash_key] = symptr;
        symptr->front = NULL;
        symptr->back = symptr;
    } else {
        symptr->front = ptr;
        ptr->back = symptr;
        symptr->back = symptr;
        hash_table[hash_key] = symptr;
    }

    strcpy(symptr->lexeme, name);
    symptr->line = linenumber;
    symptr->counter = 1;
}

void printSym(symtab *ptr) {
    printf(" Name = %s \n", ptr->lexeme);
    printf(" References = %d \n", ptr->counter);
}

void printSymTab(void) {
    puts("----- Symbol Table ---------");
    for (int i = 0; i < TABLE_SIZE; i++)
    {
        symtab *symptr;
        symptr = hash_table[i];
        while (symptr != NULL)
        {
             printf("====>  index = %d\n", i);
             printSym(symptr);
             symptr = symptr->front;
        }
    }
}

symtab **fillTab(int *len) {
    int cnt = 0;
    for (int i = 0; i < TABLE_SIZE; i++)
    {
        symtab *symptr = hash_table[i];
        while (symptr != NULL)
        {
             cnt++;
             symptr = symptr->front;
        }
    }

    symtab **tp = malloc(sizeof(symtab*)*cnt);
    cnt = 0;
    for (int i = 0; i < TABLE_SIZE; i++)
    {
        symtab *symptr = hash_table[i];
        while (symptr != NULL)
        {
             tp[cnt++] = symptr;
             symptr = symptr->front;
        }
    }
    *len = cnt;
    return tp;
}

// vim: set sw=4 ts=4 sts=4 et: