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