xref: /netbsd-src/usr.bin/tsort/tsort.c (revision e9d867ef5010fbab8d48045c13025636f5cd7479)
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.2 1993/08/01 18:04:16 mycroft 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@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 	 * could check to see if this arc is here already, but it isn't
201 	 * worth the bother -- there usually isn't and it doesn't hurt if
202 	 * there is (I think :-).
203 	 */
204 	if (n1->n_narcs == n1->n_arcsize) {
205 		if (!n1->n_arcsize)
206 			n1->n_arcsize = 10;
207 		bsize = n1->n_arcsize * sizeof(*n1->n_arcs) * 2;
208 		n1->n_arcs = (NODE **)grow_buf((char *)n1->n_arcs, bsize);
209 		n1->n_arcsize = bsize / sizeof(*n1->n_arcs);
210 	}
211 	n1->n_arcs[n1->n_narcs++] = n2;
212 	++n2->n_refcnt;
213 }
214 
215 hash_string(s)
216 	char *s;
217 {
218 	register int hash, i;
219 
220 	for (hash = 0, i = 1; *s; s++, i++)
221 		hash += *s * i;
222 	return(hash % HASHSIZE);
223 }
224 
225 /*
226  * find a node in the graph and return a pointer to it - returns null if not
227  * found.
228  */
229 NODE *
230 find_node(name)
231 	char *name;
232 {
233 	register NODE *n;
234 
235 	for (n = hashtable[hash_string(name)]; n; n = n->n_hash)
236 		if (!strcmp(n->n_name, name))
237 			return(n);
238 	return((NODE *)NULL);
239 }
240 
241 /* Add a node to the graph and return a pointer to it. */
242 NODE *
243 add_node(name)
244 	char *name;
245 {
246 	register NODE *n;
247 	int hash;
248 
249 	if (!(n = (NODE *)malloc(sizeof(NODE))) || !(n->n_name = strdup(name)))
250 		no_memory();
251 
252 	n->n_narcs = 0;
253 	n->n_arcsize = 0;
254 	n->n_arcs = (NODE **)NULL;
255 	n->n_refcnt = 0;
256 	n->n_flags = 0;
257 
258 	/* add to linked list */
259 	if (n->n_next = graph)
260 		graph->n_prevp = &n->n_next;
261 	n->n_prevp = &graph;
262 	graph = n;
263 
264 	/* add to hash table */
265 	hash = hash_string(name);
266 	n->n_hash = hashtable[hash];
267 	hashtable[hash] = n;
268 	return(n);
269 }
270 
271 /* do topological sort on graph */
272 void
273 tsort()
274 {
275 	register NODE *n, *next;
276 	register int cnt;
277 
278 	while (graph) {
279 		/*
280 		 * keep getting rid of simple cases until there are none left,
281 		 * if there are any nodes still in the graph, then there is
282 		 * a cycle in it.
283 		 */
284 		do {
285 			for (cnt = 0, n = graph; n; n = next) {
286 				next = n->n_next;
287 				if (n->n_refcnt == 0) {
288 					remove_node(n);
289 					++cnt;
290 				}
291 			}
292 		} while (graph && cnt);
293 
294 		if (!graph)
295 			break;
296 
297 		if (!cycle_buf) {
298 			/*
299 			 * allocate space for two cycle logs - one to be used
300 			 * as scratch space, the other to save the longest
301 			 * cycle.
302 			 */
303 			for (cnt = 0, n = graph; n; n = n->n_next)
304 				++cnt;
305 			cycle_buf =
306 			    (NODE **)malloc((u_int)sizeof(NODE *) * cnt);
307 			longest_cycle =
308 			    (NODE **)malloc((u_int)sizeof(NODE *) * cnt);
309 			if (!cycle_buf || !longest_cycle)
310 				no_memory();
311 		}
312 		for (n = graph; n; n = n->n_next)
313 			if (!(n->n_flags & NF_ACYCLIC)) {
314 				if (cnt = find_cycle(n, n, 0, 0)) {
315 					register int i;
316 
317 					(void)fprintf(stderr,
318 					    "tsort: cycle in data.\n");
319 					for (i = 0; i < cnt; i++)
320 						(void)fprintf(stderr,
321 				"tsort: %s.\n", longest_cycle[i]->n_name);
322 					remove_node(n);
323 					break;
324 				} else
325 					/* to avoid further checks */
326 					n->n_flags  = NF_ACYCLIC;
327 			}
328 
329 		if (!n) {
330 			(void)fprintf(stderr,
331 			    "tsort: internal error -- could not find cycle.\n");
332 			exit(1);
333 		}
334 	}
335 }
336 
337 /* print node and remove from graph (does not actually free node) */
338 void
339 remove_node(n)
340 	register NODE *n;
341 {
342 	register NODE **np;
343 	register int i;
344 
345 	(void)printf("%s\n", n->n_name);
346 	for (np = n->n_arcs, i = n->n_narcs; --i >= 0; np++)
347 		--(*np)->n_refcnt;
348 	n->n_narcs = 0;
349 	*n->n_prevp = n->n_next;
350 	if (n->n_next)
351 		n->n_next->n_prevp = n->n_prevp;
352 }
353 
354 /* look for the longest cycle from node from to node to. */
355 find_cycle(from, to, longest_len, depth)
356 	NODE *from, *to;
357 	int depth, longest_len;
358 {
359 	register NODE **np;
360 	register int i, len;
361 
362 	/*
363 	 * avoid infinite loops and ignore portions of the graph known
364 	 * to be acyclic
365 	 */
366 	if (from->n_flags & (NF_MARK|NF_ACYCLIC))
367 		return(0);
368 	from->n_flags = NF_MARK;
369 
370 	for (np = from->n_arcs, i = from->n_narcs; --i >= 0; np++) {
371 		cycle_buf[depth] = *np;
372 		if (*np == to) {
373 			if (depth + 1 > longest_len) {
374 				longest_len = depth + 1;
375 				(void)memcpy((char *)longest_cycle,
376 				    (char *)cycle_buf,
377 				    longest_len * sizeof(NODE *));
378 			}
379 		} else {
380 			len = find_cycle(*np, to, longest_len, depth + 1);
381 			if (len > longest_len)
382 				longest_len = len;
383 		}
384 	}
385 	from->n_flags &= ~NF_MARK;
386 	return(longest_len);
387 }
388 
389 void
390 no_memory()
391 {
392 	(void)fprintf(stderr, "tsort: %s.\n", strerror(ENOMEM));
393 	exit(1);
394 }
395