tsort.c revision 1.3 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 * Michael Rendell of Memorial University of Newfoundland.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37 #ifndef lint
38 char copyright[] =
39 "@(#) Copyright (c) 1989 The Regents of the University of California.\n\
40 All rights reserved.\n";
41 #endif /* not lint */
42
43 #ifndef lint
44 /*static char sccsid[] = "from: @(#)tsort.c 5.3 (Berkeley) 6/1/90";*/
45 static char rcsid[] = "$Id: tsort.c,v 1.3 1993/11/17 12:01:04 cgd Exp $";
46 #endif /* not lint */
47
48 #include <sys/types.h>
49 #include <errno.h>
50 #include <stdio.h>
51 #include <ctype.h>
52 #include <string.h>
53
54 /*
55 * Topological sort. Input is a list of pairs of strings seperated by
56 * white space (spaces, tabs, and/or newlines); strings are written to
57 * standard output in sorted order, one per line.
58 *
59 * usage:
60 * tsort [inputfile]
61 * If no input file is specified, standard input is read.
62 *
63 * Should be compatable with AT&T tsort HOWEVER the output is not identical
64 * (i.e. for most graphs there is more than one sorted order, and this tsort
65 * usually generates a different one then the AT&T tsort). Also, cycle
66 * reporting seems to be more accurate in this version (the AT&T tsort
67 * sometimes says a node is in a cycle when it isn't).
68 *
69 * Michael Rendell, michael (at) stretch.cs.mun.ca - Feb 26, '90
70 */
71 #define HASHSIZE 53 /* doesn't need to be big */
72 #define NF_MARK 0x1 /* marker for cycle detection */
73 #define NF_ACYCLIC 0x2 /* this node is cycle free */
74
75 typedef struct node_str NODE;
76
77 struct node_str {
78 char *n_name; /* name of this node */
79 NODE **n_prevp; /* pointer to previous node's n_next */
80 NODE *n_next; /* next node in graph */
81 NODE *n_hash; /* next node in hash table */
82 int n_narcs; /* number of arcs in n_arcs[] */
83 int n_arcsize; /* size of n_arcs[] array */
84 NODE **n_arcs; /* array of arcs to other nodes */
85 int n_refcnt; /* # of arcs pointing to this node */
86 int n_flags; /* NF_* */
87 };
88
89 typedef struct _buf {
90 char *b_buf;
91 int b_bsize;
92 } BUF;
93
94 NODE *add_node(), *find_node();
95 void add_arc(), no_memory(), remove_node(), tsort();
96 char *grow_buf(), *malloc();
97
98 extern int errno;
99 NODE *graph;
100 NODE *hashtable[HASHSIZE];
101 NODE **cycle_buf;
102 NODE **longest_cycle;
103
104 main(argc, argv)
105 int argc;
106 char **argv;
107 {
108 register BUF *b;
109 register int c, n;
110 FILE *fp;
111 int bsize, nused;
112 BUF bufs[2];
113
114 if (argc < 2)
115 fp = stdin;
116 else if (argc == 2) {
117 (void)fprintf(stderr, "usage: tsort [ inputfile ]\n");
118 exit(1);
119 } else if (!(fp = fopen(argv[1], "r"))) {
120 (void)fprintf(stderr, "tsort: %s.\n", strerror(errno));
121 exit(1);
122 }
123
124 for (b = bufs, n = 2; --n >= 0; b++)
125 b->b_buf = grow_buf((char *)NULL, b->b_bsize = 1024);
126
127 /* parse input and build the graph */
128 for (n = 0, c = getc(fp);;) {
129 while (c != EOF && isspace(c))
130 c = getc(fp);
131 if (c == EOF)
132 break;
133
134 nused = 0;
135 b = &bufs[n];
136 bsize = b->b_bsize;
137 do {
138 b->b_buf[nused++] = c;
139 if (nused == bsize) {
140 bsize *= 2;
141 b->b_buf = grow_buf(b->b_buf, bsize);
142 }
143 c = getc(fp);
144 } while (c != EOF && !isspace(c));
145
146 b->b_buf[nused] = '\0';
147 b->b_bsize = bsize;
148 if (n)
149 add_arc(bufs[0].b_buf, bufs[1].b_buf);
150 n = !n;
151 }
152 (void)fclose(fp);
153 if (n) {
154 (void)fprintf(stderr, "tsort: odd data count.\n");
155 exit(1);
156 }
157
158 /* do the sort */
159 tsort();
160 exit(0);
161 }
162
163 /* double the size of oldbuf and return a pointer to the new buffer. */
164 char *
165 grow_buf(bp, size)
166 char *bp;
167 int size;
168 {
169 char *realloc();
170
171 if (!(bp = realloc(bp, (u_int)size)))
172 no_memory();
173 return(bp);
174 }
175
176 /*
177 * add an arc from node s1 to node s2 in the graph. If s1 or s2 are not in
178 * the graph, then add them.
179 */
180 void
181 add_arc(s1, s2)
182 char *s1, *s2;
183 {
184 register NODE *n1;
185 NODE *n2;
186 int bsize;
187
188 n1 = find_node(s1);
189 if (!n1)
190 n1 = add_node(s1);
191
192 if (!strcmp(s1, s2))
193 return;
194
195 n2 = find_node(s2);
196 if (!n2)
197 n2 = add_node(s2);
198
199 /*
200 * Check if this arc is already here.
201 */
202 for (i = 0; i < n1->n_narcs; i++)
203 if (n1->n_arcs[i] == n2)
204 return;
205
206 /*
207 * Add it.
208 */
209 if (n1->n_narcs == n1->n_arcsize) {
210 if (!n1->n_arcsize)
211 n1->n_arcsize = 10;
212 bsize = n1->n_arcsize * sizeof(*n1->n_arcs) * 2;
213 n1->n_arcs = (NODE **)grow_buf((char *)n1->n_arcs, bsize);
214 n1->n_arcsize = bsize / sizeof(*n1->n_arcs);
215 }
216 n1->n_arcs[n1->n_narcs++] = n2;
217 ++n2->n_refcnt;
218 }
219
220 hash_string(s)
221 char *s;
222 {
223 register int hash, i;
224
225 for (hash = 0, i = 1; *s; s++, i++)
226 hash += *s * i;
227 return(hash % HASHSIZE);
228 }
229
230 /*
231 * find a node in the graph and return a pointer to it - returns null if not
232 * found.
233 */
234 NODE *
235 find_node(name)
236 char *name;
237 {
238 register NODE *n;
239
240 for (n = hashtable[hash_string(name)]; n; n = n->n_hash)
241 if (!strcmp(n->n_name, name))
242 return(n);
243 return((NODE *)NULL);
244 }
245
246 /* Add a node to the graph and return a pointer to it. */
247 NODE *
248 add_node(name)
249 char *name;
250 {
251 register NODE *n;
252 int hash;
253
254 if (!(n = (NODE *)malloc(sizeof(NODE))) || !(n->n_name = strdup(name)))
255 no_memory();
256
257 n->n_narcs = 0;
258 n->n_arcsize = 0;
259 n->n_arcs = (NODE **)NULL;
260 n->n_refcnt = 0;
261 n->n_flags = 0;
262
263 /* add to linked list */
264 if (n->n_next = graph)
265 graph->n_prevp = &n->n_next;
266 n->n_prevp = &graph;
267 graph = n;
268
269 /* add to hash table */
270 hash = hash_string(name);
271 n->n_hash = hashtable[hash];
272 hashtable[hash] = n;
273 return(n);
274 }
275
276 /* do topological sort on graph */
277 void
278 tsort()
279 {
280 register NODE *n, *next;
281 register int cnt;
282
283 while (graph) {
284 /*
285 * keep getting rid of simple cases until there are none left,
286 * if there are any nodes still in the graph, then there is
287 * a cycle in it.
288 */
289 do {
290 for (cnt = 0, n = graph; n; n = next) {
291 next = n->n_next;
292 if (n->n_refcnt == 0) {
293 remove_node(n);
294 ++cnt;
295 }
296 }
297 } while (graph && cnt);
298
299 if (!graph)
300 break;
301
302 if (!cycle_buf) {
303 /*
304 * allocate space for two cycle logs - one to be used
305 * as scratch space, the other to save the longest
306 * cycle.
307 */
308 for (cnt = 0, n = graph; n; n = n->n_next)
309 ++cnt;
310 cycle_buf =
311 (NODE **)malloc((u_int)sizeof(NODE *) * cnt);
312 longest_cycle =
313 (NODE **)malloc((u_int)sizeof(NODE *) * cnt);
314 if (!cycle_buf || !longest_cycle)
315 no_memory();
316 }
317 for (n = graph; n; n = n->n_next)
318 if (!(n->n_flags & NF_ACYCLIC)) {
319 if (cnt = find_cycle(n, n, 0, 0)) {
320 register int i;
321
322 (void)fprintf(stderr,
323 "tsort: cycle in data.\n");
324 for (i = 0; i < cnt; i++)
325 (void)fprintf(stderr,
326 "tsort: %s.\n", longest_cycle[i]->n_name);
327 remove_node(n);
328 break;
329 } else
330 /* to avoid further checks */
331 n->n_flags = NF_ACYCLIC;
332 }
333
334 if (!n) {
335 (void)fprintf(stderr,
336 "tsort: internal error -- could not find cycle.\n");
337 exit(1);
338 }
339 }
340 }
341
342 /* print node and remove from graph (does not actually free node) */
343 void
344 remove_node(n)
345 register NODE *n;
346 {
347 register NODE **np;
348 register int i;
349
350 (void)printf("%s\n", n->n_name);
351 for (np = n->n_arcs, i = n->n_narcs; --i >= 0; np++)
352 --(*np)->n_refcnt;
353 n->n_narcs = 0;
354 *n->n_prevp = n->n_next;
355 if (n->n_next)
356 n->n_next->n_prevp = n->n_prevp;
357 }
358
359 /* look for the longest cycle from node from to node to. */
360 find_cycle(from, to, longest_len, depth)
361 NODE *from, *to;
362 int depth, longest_len;
363 {
364 register NODE **np;
365 register int i, len;
366
367 /*
368 * avoid infinite loops and ignore portions of the graph known
369 * to be acyclic
370 */
371 if (from->n_flags & (NF_MARK|NF_ACYCLIC))
372 return(0);
373 from->n_flags = NF_MARK;
374
375 for (np = from->n_arcs, i = from->n_narcs; --i >= 0; np++) {
376 cycle_buf[depth] = *np;
377 if (*np == to) {
378 if (depth + 1 > longest_len) {
379 longest_len = depth + 1;
380 (void)memcpy((char *)longest_cycle,
381 (char *)cycle_buf,
382 longest_len * sizeof(NODE *));
383 }
384 } else {
385 len = find_cycle(*np, to, longest_len, depth + 1);
386 if (len > longest_len)
387 longest_len = len;
388 }
389 }
390 from->n_flags &= ~NF_MARK;
391 return(longest_len);
392 }
393
394 void
395 no_memory()
396 {
397 (void)fprintf(stderr, "tsort: %s.\n", strerror(ENOMEM));
398 exit(1);
399 }
400