xref: /original-bsd/usr.bin/m4/look.c (revision 1b11f3a3)
1 /*
2  * Copyright (c) 1989 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Ozan Yigit.
7  *
8  * %sccs.include.redist.c%
9  */
10 
11 #ifndef lint
12 static char sccsid[] = "@(#)look.c	5.4 (Berkeley) 09/03/91";
13 #endif /* not lint */
14 
15 /*
16  * look.c
17  * Facility: m4 macro processor
18  * by: oz
19  */
20 
21 #include <sys/types.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include "mdef.h"
26 #include "stdd.h"
27 #include "extern.h"
28 
29 int
30 hash(name)
31 register char *name;
32 {
33 	register unsigned long h = 0;
34 	while (*name)
35 		h = (h << 5) + h + *name++;
36 	return (h % HASHSIZE);
37 }
38 
39 /*
40  * find name in the hash table
41  */
42 ndptr
43 lookup(name)
44 char *name;
45 {
46 	register ndptr p;
47 
48 	for (p = hashtab[hash(name)]; p != nil; p = p->nxtptr)
49 		if (STREQ(name, p->name))
50 			break;
51 	return (p);
52 }
53 
54 /*
55  * hash and create an entry in the hash table.
56  * The new entry is added in front of a hash bucket.
57  */
58 ndptr
59 addent(name)
60 char *name;
61 {
62 	register int h;
63 	ndptr p;
64 
65 	h = hash(name);
66 	p = (ndptr) xalloc(sizeof(struct ndblock));
67 	p->nxtptr = hashtab[h];
68 	hashtab[h] = p;
69 	p->name = xstrdup(name);
70 	return p;
71 }
72 
73 static void
74 freent(p)
75 ndptr p;
76 {
77 	if (!(p->type & STATIC)) {
78 		free((char *) p->name);
79 		if (p->defn != null)
80 			free((char *) p->defn);
81 	}
82 	free((char *) p);
83 }
84 
85 /*
86  * remove an entry from the hashtable
87  */
88 void
89 remhash(name, all)
90 char *name;
91 int all;
92 {
93 	register int h;
94 	register ndptr xp, tp, mp;
95 
96 	h = hash(name);
97 	mp = hashtab[h];
98 	tp = nil;
99 	while (mp != nil) {
100 		if (STREQ(mp->name, name)) {
101 			mp = mp->nxtptr;
102 			if (tp == nil) {
103 				freent(hashtab[h]);
104 				hashtab[h] = mp;
105 			}
106 			else {
107 				xp = tp->nxtptr;
108 				tp->nxtptr = mp;
109 				freent(xp);
110 			}
111 			if (!all)
112 				break;
113 		}
114 		else {
115 			tp = mp;
116 			mp = mp->nxtptr;
117 		}
118 	}
119 }
120