-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnamestor.cpp
88 lines (72 loc) · 1.85 KB
/
namestor.cpp
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
//-----------------------------------------------------------------------
// namestore.cpp - identifier name store class of the Pascal- compiler
//
// Written by G. Wheeler for PLT Course, 1994
//-----------------------------------------------------------------------
#include <string.h>
#include <assert.h>
#include "error.h"
#include "namestore.h"
// Compute hash key for identifier
const int namestore_t::Key(const char *name)
{
int sum=0;
while (*name)
sum += *name++;
return sum % MAX_KEY;
}
// Look up a name in the hash table; return index or 0 if not present
const int namestore_t::Index(char *name)
{
strlwr(name);
for (hash_entry_t *e = hash[Key(name)] ; e ; e = e->next)
if (strcmp(name, Name(e->index)) == 0)
return e->index;
return 0;
}
// Look up a name in the name store, adding it if not yet present
int namestore_t::Lookup(char *name)
{
int rtn = Index(name); // is it already present?
if (rtn == 0) // no, this is a new name
{
if (next >= MAX_IDENTIFIERS)
ErrorHandler->Fatal(ERR_MAXIDENTS);
int key = Key(name);
// prepend a new hash entry to list for this key
hash_entry_t *e = new hash_entry_t;
e->index = next;
e->next = hash[key];
hash[key] = e;
map[next - NUM_RESERVED_WORDS] = top;
while (*name) store[top++] = *name++;
store[top++] = '\0';
rtn = next++;
}
return rtn;
}
// Get a name given its index
const char *namestore_t::Name(const int index) const
{
assert(index >= NUM_RESERVED_WORDS && index < next);
return (const char *)(store+map[index - NUM_RESERVED_WORDS]);
}
// create a name store
namestore_t::namestore_t()
{
for (int i = 0; i < MAX_KEY; i++)
hash[i] = NULL;
next = NUM_RESERVED_WORDS;
top = 0;
}
// destroy a name store
namestore_t::~namestore_t()
{
for (int i = 0; i < MAX_KEY; i++)
while (hash[i])
{
hash_entry_t *e = hash[i];
hash[i] = hash[i]->next;
delete e;
}
}