Updated with Tizen:Base source codes
[external/byacc.git] / symtab.c
1 /* $Id: symtab.c,v 1.7 2008/11/24 21:30:35 tom Exp $ */
2
3 #include "defs.h"
4
5 /* TABLE_SIZE is the number of entries in the symbol table. */
6 /* TABLE_SIZE must be a power of two.                       */
7
8 #define TABLE_SIZE 1024
9
10 static bucket **symbol_table = 0;
11 bucket *first_symbol;
12 bucket *last_symbol;
13
14 int
15 hash(const char *name)
16 {
17     const char *s;
18     int c, k;
19
20     assert(name && *name);
21     s = name;
22     k = *s;
23     while ((c = *++s) != 0)
24         k = (31 * k + c) & (TABLE_SIZE - 1);
25
26     return (k);
27 }
28
29 bucket *
30 make_bucket(const char *name)
31 {
32     bucket *bp;
33
34     assert(name);
35     bp = (bucket *)MALLOC(sizeof(bucket));
36     if (bp == 0)
37         no_space();
38     bp->link = 0;
39     bp->next = 0;
40     bp->name = MALLOC(strlen(name) + 1);
41     if (bp->name == 0)
42         no_space();
43     bp->tag = 0;
44     bp->value = UNDEFINED;
45     bp->index = 0;
46     bp->prec = 0;
47     bp->class = UNKNOWN;
48     bp->assoc = TOKEN;
49
50     if (bp->name == 0)
51         no_space();
52     strcpy(bp->name, name);
53
54     return (bp);
55 }
56
57 bucket *
58 lookup(const char *name)
59 {
60     bucket *bp, **bpp;
61
62     bpp = symbol_table + hash(name);
63     bp = *bpp;
64
65     while (bp)
66     {
67         if (strcmp(name, bp->name) == 0)
68             return (bp);
69         bpp = &bp->link;
70         bp = *bpp;
71     }
72
73     *bpp = bp = make_bucket(name);
74     last_symbol->next = bp;
75     last_symbol = bp;
76
77     return (bp);
78 }
79
80 void
81 create_symbol_table(void)
82 {
83     int i;
84     bucket *bp;
85
86     symbol_table = (bucket **)MALLOC(TABLE_SIZE * sizeof(bucket *));
87     if (symbol_table == 0)
88         no_space();
89     for (i = 0; i < TABLE_SIZE; i++)
90         symbol_table[i] = 0;
91
92     bp = make_bucket("error");
93     bp->index = 1;
94     bp->class = TERM;
95
96     first_symbol = bp;
97     last_symbol = bp;
98     symbol_table[hash("error")] = bp;
99 }
100
101 void
102 free_symbol_table(void)
103 {
104     FREE(symbol_table);
105     symbol_table = 0;
106 }
107
108 void
109 free_symbols(void)
110 {
111     bucket *p, *q;
112
113     for (p = first_symbol; p; p = q)
114     {
115         q = p->next;
116         FREE(p);
117     }
118 }