[project @ 1998-01-08 18:03:08 by simonm]
[ghc-hetmet.git] / ghc / compiler / utils / Digraph.lhs
1 \begin{code}
2 module Digraph(
3
4         -- At present the only one with a "nice" external interface
5         stronglyConnComp, stronglyConnCompR, SCC(..),
6
7         Graph, Vertex, 
8         graphFromEdges, buildG, transposeG, reverseE, outdegree, indegree,
9
10         Tree(..), Forest,
11         showTree, showForest,
12
13         dfs, dff,
14         topSort,
15         components,
16         scc,
17         back, cross, forward,
18         reachable, path,
19         bcc
20
21     ) where
22
23 # include "HsVersions.h"
24
25 ------------------------------------------------------------------------------
26 -- A version of the graph algorithms described in:
27 -- 
28 -- ``Lazy Depth-First Search and Linear Graph Algorithms in Haskell''
29 --   by David King and John Launchbury
30 -- 
31 -- Also included is some additional code for printing tree structures ...
32 ------------------------------------------------------------------------------
33
34
35 #define ARR_ELT         (COMMA)
36
37 import Array
38 import List
39 import ST
40 import ArrBase
41 import Maybe
42 import Util     ( sortLt )
43 \end{code}
44
45
46 %************************************************************************
47 %*                                                                      *
48 %*      External interface
49 %*                                                                      *
50 %************************************************************************
51
52 \begin{code}
53 data SCC vertex = AcyclicSCC vertex
54                 | CyclicSCC  [vertex]
55
56 stronglyConnComp
57         :: Ord key
58         => [(node, key, [key])]         -- The graph; its ok for the
59                                         -- out-list to contain keys which arent
60                                         -- a vertex key, they are ignored
61         -> [SCC node]
62
63 stronglyConnComp edges
64   = map get_node (stronglyConnCompR edges)
65   where
66     get_node (AcyclicSCC (n, _, _)) = AcyclicSCC n
67     get_node (CyclicSCC triples)     = CyclicSCC [n | (n,_,_) <- triples]
68
69 -- The "R" interface is used when you expect to apply SCC to
70 -- the (some of) the result of SCC, so you dont want to lose the dependency info
71 stronglyConnCompR
72         :: Ord key
73         => [(node, key, [key])]         -- The graph; its ok for the
74                                         -- out-list to contain keys which arent
75                                         -- a vertex key, they are ignored
76         -> [SCC (node, key, [key])]
77
78 stronglyConnCompR [] = []  -- added to avoid creating empty array in graphFromEdges -- SOF
79 stronglyConnCompR edges
80   = map decode forest
81   where
82     (graph, vertex_fn) = graphFromEdges edges
83     forest             = scc graph
84     decode (Node v []) | mentions_itself v = CyclicSCC [vertex_fn v]
85                        | otherwise         = AcyclicSCC (vertex_fn v)
86     decode other = CyclicSCC (dec other [])
87                  where
88                    dec (Node v ts) vs = vertex_fn v : foldr dec vs ts
89     mentions_itself v = v `elem` (graph ! v)
90 \end{code}
91
92 %************************************************************************
93 %*                                                                      *
94 %*      Graphs
95 %*                                                                      *
96 %************************************************************************
97
98
99 \begin{code}
100 type Vertex  = Int
101 type Table a = Array Vertex a
102 type Graph   = Table [Vertex]
103 type Bounds  = (Vertex, Vertex)
104 type Edge    = (Vertex, Vertex)
105 \end{code}
106
107 \begin{code}
108 vertices :: Graph -> [Vertex]
109 vertices  = indices
110
111 edges    :: Graph -> [Edge]
112 edges g   = [ (v, w) | v <- vertices g, w <- g!v ]
113
114 mapT    :: (Vertex -> a -> b) -> Table a -> Table b
115 mapT f t = array (bounds t) [ (,) v (f v (t!v)) | v <- indices t ]
116
117 buildG :: Bounds -> [Edge] -> Graph
118 #ifdef REALLY_HASKELL_1_3
119 buildG bounds edges = accumArray (flip (:)) [] bounds edges
120 #else
121 buildG bounds edges = accumArray (flip (:)) [] bounds [(,) k v | (k,v) <- edges]
122 #endif
123
124 transposeG  :: Graph -> Graph
125 transposeG g = buildG (bounds g) (reverseE g)
126
127 reverseE    :: Graph -> [Edge]
128 reverseE g   = [ (w, v) | (v, w) <- edges g ]
129
130 outdegree :: Graph -> Table Int
131 outdegree  = mapT numEdges
132              where numEdges v ws = length ws
133
134 indegree :: Graph -> Table Int
135 indegree  = outdegree . transposeG
136 \end{code}
137
138
139 \begin{code}
140 graphFromEdges
141         :: Ord key
142         => [(node, key, [key])]
143         -> (Graph, Vertex -> (node, key, [key]))
144 graphFromEdges edges
145   = (graph, \v -> vertex_map ! v)
146   where
147     max_v           = length edges - 1
148     bounds          = (0,max_v) :: (Vertex, Vertex)
149     sorted_edges    = sortLt lt edges
150     edges1          = zipWith (,) [0..] sorted_edges
151
152     graph           = array bounds [(,) v (mapMaybe key_vertex ks) | (,) v (_,    _, ks) <- edges1]
153     key_map         = array bounds [(,) v k                            | (,) v (_,    k, _ ) <- edges1]
154     vertex_map      = array bounds edges1
155
156     (_,k1,_) `lt` (_,k2,_) = case k1 `compare` k2 of { LT -> True; other -> False }
157
158     -- key_vertex :: key -> Maybe Vertex
159     --  returns Nothing for non-interesting vertices
160     key_vertex k   = find 0 max_v 
161                    where
162                      find a b | a > b 
163                               = Nothing
164                      find a b = case compare k (key_map ! mid) of
165                                    LT -> find a (mid-1)
166                                    EQ -> Just mid
167                                    GT -> find (mid+1) b
168                               where
169                                 mid = (a + b) `div` 2
170 \end{code}
171
172 %************************************************************************
173 %*                                                                      *
174 %*      Trees and forests
175 %*                                                                      *
176 %************************************************************************
177
178 \begin{code}
179 data Tree a   = Node a (Forest a)
180 type Forest a = [Tree a]
181
182 mapTree              :: (a -> b) -> (Tree a -> Tree b)
183 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
184 \end{code}
185
186 \begin{code}
187 instance Show a => Show (Tree a) where
188   showsPrec p t s = showTree t ++ s
189
190 showTree :: Show a => Tree a -> String
191 showTree  = drawTree . mapTree show
192
193 showForest :: Show a => Forest a -> String
194 showForest  = unlines . map showTree
195
196 drawTree        :: Tree String -> String
197 drawTree         = unlines . draw
198
199 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
200  where this          = s1 ++ x ++ " "
201
202        space n       = take n (repeat ' ')
203
204        stLoop []     = [""]
205        stLoop [t]    = grp s2 "  " (draw t)
206        stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
207
208        rsLoop [t]    = grp s5 "  " (draw t)
209        rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
210
211        grp fst rst   = zipWith (++) (fst:repeat rst)
212
213        [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
214 \end{code}
215
216
217 %************************************************************************
218 %*                                                                      *
219 %*      Depth first search
220 %*                                                                      *
221 %************************************************************************
222
223 \begin{code}
224 type Set s    = MutableArray s Vertex Bool
225
226 mkEmpty      :: Bounds -> ST s (Set s)
227 mkEmpty bnds  = newArray bnds False
228
229 contains     :: Set s -> Vertex -> ST s Bool
230 contains m v  = readArray m v
231
232 include      :: Set s -> Vertex -> ST s ()
233 include m v   = writeArray m v True
234 \end{code}
235
236 \begin{code}
237 dff          :: Graph -> Forest Vertex
238 dff g         = dfs g (vertices g)
239
240 dfs          :: Graph -> [Vertex] -> Forest Vertex
241 dfs g vs      = prune (bounds g) (map (generate g) vs)
242
243 generate     :: Graph -> Vertex -> Tree Vertex
244 generate g v  = Node v (map (generate g) (g!v))
245
246 prune        :: Bounds -> Forest Vertex -> Forest Vertex
247 prune bnds ts = runST (mkEmpty bnds  >>= \m ->
248                        chop m ts)
249
250 chop         :: Set s -> Forest Vertex -> ST s (Forest Vertex)
251 chop m []     = return []
252 chop m (Node v ts : us)
253               = contains m v >>= \visited ->
254                 if visited then
255                   chop m us
256                 else
257                   include m v >>= \_  ->
258                   chop m ts   >>= \as ->
259                   chop m us   >>= \bs ->
260                   return (Node v as : bs)
261 \end{code}
262
263
264 %************************************************************************
265 %*                                                                      *
266 %*      Algorithms
267 %*                                                                      *
268 %************************************************************************
269
270 ------------------------------------------------------------
271 -- Algorithm 1: depth first search numbering
272 ------------------------------------------------------------
273
274 \begin{code}
275 --preorder            :: Tree a -> [a]
276 preorder (Node a ts) = a : preorderF ts
277
278 preorderF           :: Forest a -> [a]
279 preorderF ts         = concat (map preorder ts)
280
281 preOrd :: Graph -> [Vertex]
282 preOrd  = preorderF . dff
283
284 tabulate        :: Bounds -> [Vertex] -> Table Int
285 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
286
287 preArr          :: Bounds -> Forest Vertex -> Table Int
288 preArr bnds      = tabulate bnds . preorderF
289 \end{code}
290
291
292 ------------------------------------------------------------
293 -- Algorithm 2: topological sorting
294 ------------------------------------------------------------
295
296 \begin{code}
297 --postorder :: Tree a -> [a]
298 postorder (Node a ts) = postorderF ts ++ [a]
299
300 postorderF   :: Forest a -> [a]
301 postorderF ts = concat (map postorder ts)
302
303 postOrd      :: Graph -> [Vertex]
304 postOrd       = postorderF . dff
305
306 topSort      :: Graph -> [Vertex]
307 topSort       = reverse . postOrd
308 \end{code}
309
310
311 ------------------------------------------------------------
312 -- Algorithm 3: connected components
313 ------------------------------------------------------------
314
315 \begin{code}
316 components   :: Graph -> Forest Vertex
317 components    = dff . undirected
318
319 undirected   :: Graph -> Graph
320 undirected g  = buildG (bounds g) (edges g ++ reverseE g)
321 \end{code}
322
323
324 -- Algorithm 4: strongly connected components
325
326 \begin{code}
327 scc  :: Graph -> Forest Vertex
328 scc g = dfs g (reverse (postOrd (transposeG g)))
329 \end{code}
330
331
332 ------------------------------------------------------------
333 -- Algorithm 5: Classifying edges
334 ------------------------------------------------------------
335
336 \begin{code}
337 tree              :: Bounds -> Forest Vertex -> Graph
338 tree bnds ts       = buildG bnds (concat (map flat ts))
339                    where
340                      flat (Node v rs) = [ (v, w) | Node w us <- ts ] ++
341                                         concat (map flat ts)
342
343 back              :: Graph -> Table Int -> Graph
344 back g post        = mapT select g
345  where select v ws = [ w | w <- ws, post!v < post!w ]
346
347 cross             :: Graph -> Table Int -> Table Int -> Graph
348 cross g pre post   = mapT select g
349  where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
350
351 forward           :: Graph -> Graph -> Table Int -> Graph
352 forward g tree pre = mapT select g
353  where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
354 \end{code}
355
356
357 ------------------------------------------------------------
358 -- Algorithm 6: Finding reachable vertices
359 ------------------------------------------------------------
360
361 \begin{code}
362 reachable    :: Graph -> Vertex -> [Vertex]
363 reachable g v = preorderF (dfs g [v])
364
365 path         :: Graph -> Vertex -> Vertex -> Bool
366 path g v w    = w `elem` (reachable g v)
367 \end{code}
368
369
370 ------------------------------------------------------------
371 -- Algorithm 7: Biconnected components
372 ------------------------------------------------------------
373
374 \begin{code}
375 bcc :: Graph -> Forest [Vertex]
376 bcc g = (concat . map bicomps . map (label g dnum)) forest
377  where forest = dff g
378        dnum   = preArr (bounds g) forest
379
380 label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
381 label g dnum (Node v ts) = Node (v,dnum!v,lv) us
382  where us = map (label g dnum) ts
383        lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
384                      ++ [lu | Node (u,du,lu) xs <- us])
385
386 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
387 bicomps (Node (v,dv,lv) ts)
388       = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
389
390 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
391 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
392  where collected = map collect ts
393        vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
394        cs = concat [ if lw<dv then us else [Node (v:ws) us]
395                         | (lw, Node ws us) <- collected ]
396 \end{code}
397