Debian Codegraph @

lib/cgraph/acyclic.c

raw
1 /**
2 * @file
3 * @brief make directed graph acyclic, implements @ref graphviz_acyclic, used
4 * in cmd/tools/acyclic.c
5 *
6 * @ingroup cgraph_app
7 *
8 * Copyright (c) 2011 AT&T Intellectual Property
9 * All rights reserved. This program and the accompanying materials
10 * are made available under the terms of the Eclipse Public License v1.0
11 * which accompanies this distribution, and is available at
12 * https://www.eclipse.org/legal/epl-v10.html
13 *
14 * Authors: Stephen North, Emden Gansner
15 * Contributors: Details at https://graphviz.org
16 */
17
18 #include "config.h"
19
20 #include <cgraph/cghdr.h>
21 #include <stdbool.h>
22 #include <stddef.h>
23
24 typedef struct {
25 Agrec_t h;
26 int mark;
27 bool onstack : 1;
28 } Agnodeinfo_t;
29
30 #define ND_mark(n) (((Agnodeinfo_t *)((n)->base.data))->mark)
31 #define ND_onstack(n) (((Agnodeinfo_t *)((n)->base.data))->onstack)
32 #define graphName(g) (agnameof(g))
33
34 /* Add a reversed version of e. The new edge has the same key.
35 * We also copy the attributes, reversing the roles of head and
36 * tail ports.
37 * This assumes we've already checked that such an edge does not exist.
38 */
39 static void addRevEdge(Agraph_t *g, Agedge_t *e) {
40 Agsym_t *sym;
41 Agedge_t *f = agedge(g, aghead(e), agtail(e), agnameof(e), 1);
42
43 agcopyattr(e, f);
44
45 sym = agattr_text(g, AGEDGE, TAILPORT_ID, 0);
46 if (sym)
47 agsafeset(f, HEADPORT_ID, agxget(e, sym), "");
48 sym = agattr_text(g, AGEDGE, HEADPORT_ID, 0);
49 if (sym)
50 agsafeset(f, TAILPORT_ID, agxget(e, sym), "");
51 }
52
53 /// Return true if the graph has a cycle.
54 static bool dfs(Agraph_t *g, Agnode_t *t, bool hasCycle, size_t *num_rev) {
55 Agedge_t *e;
56 Agedge_t *f;
57 Agnode_t *h;
58
59 ND_mark(t) = 1;
60 ND_onstack(t) = true;
61 for (e = agfstout(g, t); e; e = f) {
62 f = agnxtout(g, e);
63 if (agtail(e) == aghead(e))
64 continue;
65 h = aghead(e);
66 if (ND_onstack(h)) {
67 if (agisstrict(g)) {
68 if (agedge(g, h, t, 0, 0) == 0) {
69 addRevEdge(g, e);
70 ++*num_rev;
71 }
72 } else {
73 char *key = agnameof(e);
74 if (!key || agedge(g, h, t, key, 0) == 0) {
75 addRevEdge(g, e);
76 ++*num_rev;
77 }
78 }
79 agdelete(g, e);
80 hasCycle = true;
81 } else if (ND_mark(h) == 0)
82 hasCycle |= dfs(g, h, hasCycle, num_rev);
83 }
84 ND_onstack(t) = false;
85 return hasCycle;
86 }
87
88 bool graphviz_acyclic(Agraph_t *g, const graphviz_acyclic_options_t *opts,
89 size_t *num_rev) {
90 bool has_cycle = false;
91 aginit(g, AGNODE, "info", sizeof(Agnodeinfo_t), true);
92 for (Agnode_t *n = agfstnode(g); n; n = agnxtnode(g, n)) {
93 if (ND_mark(n) == 0) {
94 has_cycle |= dfs(g, n, false, num_rev);
95 }
96 }
97 if (opts->doWrite) {
98 agwrite(g, opts->outFile);
99 fflush(opts->outFile);
100 }
101 return has_cycle;
102 }