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