1 /* tsort - topological sort.
2 Copyright (C) 1998-2017 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* Written by Mark Kettenis <kettenis@phys.uva.nl>. */
19 /* The topological sort is done according to Algorithm T (Topological
20 sort) in Donald E. Knuth, The Art of Computer Programming, Volume
21 1/Fundamental Algorithms, page 262. */
27 #include <sys/types.h>
30 #include "long-options.h"
34 #include "readtokens.h"
38 /* The official name of this program (e.g., no 'g' prefix). */
39 #define PROGRAM_NAME "tsort"
41 #define AUTHORS proper_name ("Mark Kettenis")
43 static struct option
const long_options
[] =
48 /* Token delimiters when reading from a file. */
51 /* Members of the list of successors. */
55 struct successor
*next
;
58 /* Each string is held in core as the head of a list of successors. */
62 struct item
*left
, *right
;
63 int balance
; /* -1, 0, or +1 */
66 struct successor
*top
;
69 /* The head of the sorted list. */
70 static struct item
*head
= NULL
;
72 /* The tail of the list of 'zeros', strings that have no predecessors. */
73 static struct item
*zeros
= NULL
;
75 /* Used for loop detection. */
76 static struct item
*loop
= NULL
;
78 /* The number of strings to sort. */
79 static size_t n_strings
= 0;
84 if (status
!= EXIT_SUCCESS
)
89 Usage: %s [OPTION] [FILE]\n\
90 Write totally ordered list consistent with the partial ordering in FILE.\n\
98 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
99 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
100 emit_ancillary_info (PROGRAM_NAME
);
106 /* Create a new item/node for STR. */
108 new_item (const char *str
)
110 struct item
*k
= xmalloc (sizeof *k
);
112 k
->str
= (str
? xstrdup (str
): NULL
);
113 k
->left
= k
->right
= NULL
;
116 /* T1. Initialize (COUNT[k] <- 0 and TOP[k] <- ^). */
124 /* Search binary tree rooted at *ROOT for STR. Allocate a new tree if
125 *ROOT is NULL. Insert a node/item for STR if not found. Return
126 the node/item found/created for STR.
128 This is done according to Algorithm A (Balanced tree search and
129 insertion) in Donald E. Knuth, The Art of Computer Programming,
130 Volume 3/Searching and Sorting, pages 455--457. */
133 search_item (struct item
*root
, const char *str
)
135 struct item
*p
, *q
, *r
, *s
, *t
;
140 /* Make sure the tree is not empty, since that is what the algorithm
142 if (root
->right
== NULL
)
143 return (root
->right
= new_item (str
));
145 /* A1. Initialize. */
152 a
= strcmp (str
, p
->str
);
156 /* A3 & A4. Move left & right. */
167 /* A3 & A4. (continued). */
173 /* A6. Adjust balance factors. */
174 assert (!STREQ (str
, s
->str
));
175 if (strcmp (str
, s
->str
) < 0)
188 assert (!STREQ (str
, p
->str
));
189 if (strcmp (str
, p
->str
) < 0)
201 /* A7. Balancing act. */
202 if (s
->balance
== 0 || s
->balance
== -a
)
210 /* A8. Single Rotation. */
222 s
->balance
= r
->balance
= 0;
226 /* A9. Double rotation. */
248 else if (p
->balance
== -a
)
253 /* A10. Finishing touch. */
262 /* A3 & A4. (continued). */
275 /* Record the fact that J precedes K. */
278 record_relation (struct item
*j
, struct item
*k
)
282 if (!STREQ (j
->str
, k
->str
))
285 p
= xmalloc (sizeof *p
);
293 count_items (struct item
*unused _GL_UNUSED
)
300 scan_zeros (struct item
*k
)
302 /* Ignore strings that have already been printed. */
303 if (k
->count
== 0 && k
->str
)
316 /* Try to detect the loop. If we have detected that K is part of a
317 loop, print the loop on standard error, remove a relation to break
318 the loop, and return true.
320 The loop detection strategy is as follows: Realise that what we're
321 dealing with is essentially a directed graph. If we find an item
322 that is part of a graph that contains a cycle we traverse the graph
323 in backwards direction. In general there is no unique way to do
324 this, but that is no problem. If we encounter an item that we have
325 encountered before, we know that we've found a cycle. All we have
326 to do now is retrace our steps, printing out the items until we
327 encounter that item again. (This is not necessarily the item that
328 we started from originally.) Since the order in which the items
329 are stored in the tree is not related to the specified partial
330 ordering, we may need to walk the tree several times before the
331 loop has completely been constructed. If the loop was found, the
332 global variable LOOP will be NULL. */
335 detect_loop (struct item
*k
)
339 /* K does not have to be part of a cycle. It is however part of
340 a graph that contains a cycle. */
343 /* Start traversing the graph at K. */
347 struct successor
**p
= &k
->top
;
351 if ((*p
)->suc
== loop
)
355 /* We have found a loop. Retrace our steps. */
358 struct item
*tmp
= loop
->qlink
;
360 error (0, 0, "%s", (loop
->str
));
362 /* Until we encounter K again. */
365 /* Remove relation. */
371 /* Tidy things up since we might have to
372 detect another loop. */
379 struct item
*tmp
= loop
->qlink
;
385 /* Since we have found the loop, stop walking
405 /* Recurse (sub)tree rooted at ROOT, calling ACTION for each node.
406 Stop when ACTION returns true. */
409 recurse_tree (struct item
*root
, bool (*action
) (struct item
*))
411 if (root
->left
== NULL
&& root
->right
== NULL
)
412 return (*action
) (root
);
415 if (root
->left
!= NULL
)
416 if (recurse_tree (root
->left
, action
))
418 if ((*action
) (root
))
420 if (root
->right
!= NULL
)
421 if (recurse_tree (root
->right
, action
))
428 /* Walk the tree specified by the head ROOT, calling ACTION for
432 walk_tree (struct item
*root
, bool (*action
) (struct item
*))
435 recurse_tree (root
->right
, action
);
438 /* Do a topological sort on FILE. Return true if successful. */
441 tsort (const char *file
)
445 struct item
*j
= NULL
;
446 struct item
*k
= NULL
;
447 token_buffer tokenbuffer
;
448 bool is_stdin
= STREQ (file
, "-");
450 /* Intialize the head of the tree will hold the strings we're sorting. */
451 root
= new_item (NULL
);
453 if (!is_stdin
&& ! freopen (file
, "r", stdin
))
454 die (EXIT_FAILURE
, errno
, "%s", quotef (file
));
456 fadvise (stdin
, FADVISE_SEQUENTIAL
);
458 init_tokenbuffer (&tokenbuffer
);
462 /* T2. Next Relation. */
463 size_t len
= readtoken (stdin
, DELIM
, sizeof (DELIM
) - 1, &tokenbuffer
);
464 if (len
== (size_t) -1)
469 k
= search_item (root
, tokenbuffer
.buffer
);
472 /* T3. Record the relation. */
473 record_relation (j
, k
);
481 die (EXIT_FAILURE
, 0, _("%s: input contains an odd number of tokens"),
484 /* T1. Initialize (N <- n). */
485 walk_tree (root
, count_items
);
487 while (n_strings
> 0)
489 /* T4. Scan for zeros. */
490 walk_tree (root
, scan_zeros
);
494 struct successor
*p
= head
->top
;
496 /* T5. Output front of queue. */
499 /* suppress valgrind "definitely lost" warnings. */
500 void *head_str
= (void *) head
->str
;
503 head
->str
= NULL
; /* Avoid printing the same string twice. */
506 /* T6. Erase relations. */
510 if (p
->suc
->count
== 0)
512 zeros
->qlink
= p
->suc
;
519 /* T7. Remove from queue. */
523 /* T8. End of process. */
526 /* The input contains a loop. */
527 error (0, 0, _("%s: input contains a loop:"), quotef (file
));
530 /* Print the loop and remove a relation to break it. */
532 walk_tree (root
, detect_loop
);
537 IF_LINT (free (root
));
539 if (fclose (stdin
) != 0)
540 die (EXIT_FAILURE
, errno
, "%s",
541 is_stdin
? _("standard input") : quotef (file
));
547 main (int argc
, char **argv
)
551 initialize_main (&argc
, &argv
);
552 set_program_name (argv
[0]);
553 setlocale (LC_ALL
, "");
554 bindtextdomain (PACKAGE
, LOCALEDIR
);
555 textdomain (PACKAGE
);
557 atexit (close_stdout
);
559 parse_long_options (argc
, argv
, PROGRAM_NAME
, PACKAGE
, Version
,
560 usage
, AUTHORS
, (char const *) NULL
);
561 if (getopt_long (argc
, argv
, "", long_options
, NULL
) != -1)
562 usage (EXIT_FAILURE
);
564 if (1 < argc
- optind
)
566 error (0, 0, _("extra operand %s"), quote (argv
[optind
+ 1]));
567 usage (EXIT_FAILURE
);
570 ok
= tsort (optind
== argc
? "-" : argv
[optind
]);
572 return ok
? EXIT_SUCCESS
: EXIT_FAILURE
;