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