Big tidy-up of deriving code
[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 #if __GLASGOW_HASKELL__ >= 504
256 newSTArray :: Ix i => (i,i) -> e -> ST s (STArray s i e)
257 newSTArray = newArray
258
259 readSTArray :: Ix i => STArray s i e -> i -> ST s e
260 readSTArray = readArray
261
262 writeSTArray :: Ix i => STArray s i e -> i -> e -> ST s ()
263 writeSTArray = writeArray
264 #endif
265
266 type Set s    = STArray s Vertex Bool
267
268 mkEmpty      :: Bounds -> ST s (Set s)
269 mkEmpty bnds  = newSTArray bnds False
270
271 contains     :: Set s -> Vertex -> ST s Bool
272 contains m v  = readSTArray m v
273
274 include      :: Set s -> Vertex -> ST s ()
275 include m v   = writeSTArray m v True
276 \end{code}
277
278 \begin{code}
279 dff          :: Graph -> Forest Vertex
280 dff g         = dfs g (vertices g)
281
282 dfs          :: Graph -> [Vertex] -> Forest Vertex
283 dfs g vs      = prune (bounds g) (map (generate g) vs)
284
285 generate     :: Graph -> Vertex -> Tree Vertex
286 generate g v  = Node v (map (generate g) (g!v))
287
288 prune        :: Bounds -> Forest Vertex -> Forest Vertex
289 prune bnds ts = runST (mkEmpty bnds  >>= \m ->
290                        chop m ts)
291
292 chop         :: Set s -> Forest Vertex -> ST s (Forest Vertex)
293 chop m []     = return []
294 chop m (Node v ts : us)
295               = contains m v >>= \visited ->
296                 if visited then
297                   chop m us
298                 else
299                   include m v >>= \_  ->
300                   chop m ts   >>= \as ->
301                   chop m us   >>= \bs ->
302                   return (Node v as : bs)
303 \end{code}
304
305
306 %************************************************************************
307 %*                                                                      *
308 %*      Algorithms
309 %*                                                                      *
310 %************************************************************************
311
312 ------------------------------------------------------------
313 -- Algorithm 1: depth first search numbering
314 ------------------------------------------------------------
315
316 \begin{code}
317 --preorder            :: Tree a -> [a]
318 preorder (Node a ts) = a : preorderF ts
319
320 preorderF           :: Forest a -> [a]
321 preorderF ts         = concat (map preorder ts)
322
323 tabulate        :: Bounds -> [Vertex] -> Table Int
324 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
325
326 preArr          :: Bounds -> Forest Vertex -> Table Int
327 preArr bnds      = tabulate bnds . preorderF
328 \end{code}
329
330
331 ------------------------------------------------------------
332 -- Algorithm 2: topological sorting
333 ------------------------------------------------------------
334
335 \begin{code}
336 --postorder :: Tree a -> [a]
337 postorder (Node a ts) = postorderF ts ++ [a]
338
339 postorderF   :: Forest a -> [a]
340 postorderF ts = concat (map postorder ts)
341
342 postOrd      :: Graph -> [Vertex]
343 postOrd       = postorderF . dff
344
345 topSort      :: Graph -> [Vertex]
346 topSort       = reverse . postOrd
347 \end{code}
348
349
350 ------------------------------------------------------------
351 -- Algorithm 3: connected components
352 ------------------------------------------------------------
353
354 \begin{code}
355 components   :: Graph -> Forest Vertex
356 components    = dff . undirected
357
358 undirected   :: Graph -> Graph
359 undirected g  = buildG (bounds g) (edges g ++ reverseE g)
360 \end{code}
361
362
363 -- Algorithm 4: strongly connected components
364
365 \begin{code}
366 scc  :: Graph -> Forest Vertex
367 scc g = dfs g (reverse (postOrd (transposeG g)))
368 \end{code}
369
370
371 ------------------------------------------------------------
372 -- Algorithm 5: Classifying edges
373 ------------------------------------------------------------
374
375 \begin{code}
376 back              :: Graph -> Table Int -> Graph
377 back g post        = mapT select g
378  where select v ws = [ w | w <- ws, post!v < post!w ]
379
380 cross             :: Graph -> Table Int -> Table Int -> Graph
381 cross g pre post   = mapT select g
382  where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
383
384 forward           :: Graph -> Graph -> Table Int -> Graph
385 forward g tree pre = mapT select g
386  where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
387 \end{code}
388
389
390 ------------------------------------------------------------
391 -- Algorithm 6: Finding reachable vertices
392 ------------------------------------------------------------
393
394 \begin{code}
395 reachable    :: Graph -> Vertex -> [Vertex]
396 reachable g v = preorderF (dfs g [v])
397
398 path         :: Graph -> Vertex -> Vertex -> Bool
399 path g v w    = w `elem` (reachable g v)
400 \end{code}
401
402
403 ------------------------------------------------------------
404 -- Algorithm 7: Biconnected components
405 ------------------------------------------------------------
406
407 \begin{code}
408 bcc :: Graph -> Forest [Vertex]
409 bcc g = (concat . map bicomps . map (do_label g dnum)) forest
410  where forest = dff g
411        dnum   = preArr (bounds g) forest
412
413 do_label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
414 do_label g dnum (Node v ts) = Node (v,dnum!v,lv) us
415  where us = map (do_label g dnum) ts
416        lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
417                      ++ [lu | Node (u,du,lu) xs <- us])
418
419 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
420 bicomps (Node (v,dv,lv) ts)
421       = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
422
423 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
424 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
425  where collected = map collect ts
426        vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
427        cs = concat [ if lw<dv then us else [Node (v:ws) us]
428                         | (lw, Node ws us) <- collected ]
429 \end{code}
430