[project @ 2002-09-27 08:20:43 by simonpj]
[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, 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 MONAD_ST
41
42 -- std interfaces
43 import Maybe
44 import Array
45 import List
46 import Outputable
47
48 #if __GLASGOW_HASKELL__ >= 504
49 import Data.Array.ST  hiding ( indices, bounds )
50 #else
51 import ST
52 #endif
53 \end{code}
54
55
56 %************************************************************************
57 %*                                                                      *
58 %*      External interface
59 %*                                                                      *
60 %************************************************************************
61
62 \begin{code}
63 data SCC vertex = AcyclicSCC vertex
64                 | CyclicSCC  [vertex]
65
66 flattenSCCs :: [SCC a] -> [a]
67 flattenSCCs = concatMap flattenSCC
68
69 flattenSCC (AcyclicSCC v) = [v]
70 flattenSCC (CyclicSCC vs) = vs
71
72 instance Outputable a => Outputable (SCC a) where
73    ppr (AcyclicSCC v) = text "NONREC" $$ (nest 3 (ppr v))
74    ppr (CyclicSCC vs) = text "REC" $$ (nest 3 (vcat (map ppr vs)))
75 \end{code}
76
77 \begin{code}
78 stronglyConnComp
79         :: Ord key
80         => [(node, key, [key])]         -- The graph; its ok for the
81                                         -- out-list to contain keys which arent
82                                         -- a vertex key, they are ignored
83         -> [SCC node]
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) = graphFromEdges edges
105     forest             = 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   = (graph, \v -> vertex_map ! v)
164   where
165     max_v           = length edges - 1
166     bounds          = (0,max_v) :: (Vertex, Vertex)
167     sorted_edges    = sortLt lt edges
168     edges1          = zipWith (,) [0..] sorted_edges
169
170     graph           = array bounds [(,) v (mapMaybe key_vertex ks) | (,) v (_,    _, ks) <- edges1]
171     key_map         = array bounds [(,) v k                        | (,) v (_,    k, _ ) <- edges1]
172     vertex_map      = array bounds edges1
173
174     (_,k1,_) `lt` (_,k2,_) = case k1 `compare` k2 of { LT -> True; other -> False }
175
176     -- key_vertex :: key -> Maybe Vertex
177     --  returns Nothing for non-interesting vertices
178     key_vertex k   = find 0 max_v 
179                    where
180                      find a b | a > b 
181                               = Nothing
182                      find a b = case compare k (key_map ! mid) of
183                                    LT -> find a (mid-1)
184                                    EQ -> Just mid
185                                    GT -> find (mid+1) b
186                               where
187                                 mid = (a + b) `div` 2
188 \end{code}
189
190 %************************************************************************
191 %*                                                                      *
192 %*      Trees and forests
193 %*                                                                      *
194 %************************************************************************
195
196 \begin{code}
197 data Tree a   = Node a (Forest a)
198 type Forest a = [Tree a]
199
200 mapTree              :: (a -> b) -> (Tree a -> Tree b)
201 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
202 \end{code}
203
204 \begin{code}
205 instance Show a => Show (Tree a) where
206   showsPrec p t s = showTree t ++ s
207
208 showTree :: Show a => Tree a -> String
209 showTree  = drawTree . mapTree show
210
211 showForest :: Show a => Forest a -> String
212 showForest  = unlines . map showTree
213
214 drawTree        :: Tree String -> String
215 drawTree         = unlines . draw
216
217 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
218  where this          = s1 ++ x ++ " "
219
220        space n       = replicate n ' '
221
222        stLoop []     = [""]
223        stLoop [t]    = grp s2 "  " (draw t)
224        stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
225
226        rsLoop [t]    = grp s5 "  " (draw t)
227        rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
228
229        grp fst rst   = zipWith (++) (fst:repeat rst)
230
231        [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
232 \end{code}
233
234
235 %************************************************************************
236 %*                                                                      *
237 %*      Depth first search
238 %*                                                                      *
239 %************************************************************************
240
241 \begin{code}
242 #if __GLASGOW_HASKELL__ >= 504
243 newSTArray :: Ix i => (i,i) -> e -> ST s (STArray s i e)
244 newSTArray = newArray
245
246 readSTArray :: Ix i => STArray s i e -> i -> ST s e
247 readSTArray = readArray
248
249 writeSTArray :: Ix i => STArray s i e -> i -> e -> ST s ()
250 writeSTArray = writeArray
251 #endif
252
253 type Set s    = STArray s Vertex Bool
254
255 mkEmpty      :: Bounds -> ST s (Set s)
256 mkEmpty bnds  = newSTArray bnds False
257
258 contains     :: Set s -> Vertex -> ST s Bool
259 contains m v  = readSTArray m v
260
261 include      :: Set s -> Vertex -> ST s ()
262 include m v   = writeSTArray m v True
263 \end{code}
264
265 \begin{code}
266 dff          :: Graph -> Forest Vertex
267 dff g         = dfs g (vertices g)
268
269 dfs          :: Graph -> [Vertex] -> Forest Vertex
270 dfs g vs      = prune (bounds g) (map (generate g) vs)
271
272 generate     :: Graph -> Vertex -> Tree Vertex
273 generate g v  = Node v (map (generate g) (g!v))
274
275 prune        :: Bounds -> Forest Vertex -> Forest Vertex
276 prune bnds ts = runST (mkEmpty bnds  >>= \m ->
277                        chop m ts)
278
279 chop         :: Set s -> Forest Vertex -> ST s (Forest Vertex)
280 chop m []     = return []
281 chop m (Node v ts : us)
282               = contains m v >>= \visited ->
283                 if visited then
284                   chop m us
285                 else
286                   include m v >>= \_  ->
287                   chop m ts   >>= \as ->
288                   chop m us   >>= \bs ->
289                   return (Node v as : bs)
290 \end{code}
291
292
293 %************************************************************************
294 %*                                                                      *
295 %*      Algorithms
296 %*                                                                      *
297 %************************************************************************
298
299 ------------------------------------------------------------
300 -- Algorithm 1: depth first search numbering
301 ------------------------------------------------------------
302
303 \begin{code}
304 --preorder            :: Tree a -> [a]
305 preorder (Node a ts) = a : preorderF ts
306
307 preorderF           :: Forest a -> [a]
308 preorderF ts         = concat (map preorder ts)
309
310 preOrd :: Graph -> [Vertex]
311 preOrd  = preorderF . dff
312
313 tabulate        :: Bounds -> [Vertex] -> Table Int
314 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
315
316 preArr          :: Bounds -> Forest Vertex -> Table Int
317 preArr bnds      = tabulate bnds . preorderF
318 \end{code}
319
320
321 ------------------------------------------------------------
322 -- Algorithm 2: topological sorting
323 ------------------------------------------------------------
324
325 \begin{code}
326 --postorder :: Tree a -> [a]
327 postorder (Node a ts) = postorderF ts ++ [a]
328
329 postorderF   :: Forest a -> [a]
330 postorderF ts = concat (map postorder ts)
331
332 postOrd      :: Graph -> [Vertex]
333 postOrd       = postorderF . dff
334
335 topSort      :: Graph -> [Vertex]
336 topSort       = reverse . postOrd
337 \end{code}
338
339
340 ------------------------------------------------------------
341 -- Algorithm 3: connected components
342 ------------------------------------------------------------
343
344 \begin{code}
345 components   :: Graph -> Forest Vertex
346 components    = dff . undirected
347
348 undirected   :: Graph -> Graph
349 undirected g  = buildG (bounds g) (edges g ++ reverseE g)
350 \end{code}
351
352
353 -- Algorithm 4: strongly connected components
354
355 \begin{code}
356 scc  :: Graph -> Forest Vertex
357 scc g = dfs g (reverse (postOrd (transposeG g)))
358 \end{code}
359
360
361 ------------------------------------------------------------
362 -- Algorithm 5: Classifying edges
363 ------------------------------------------------------------
364
365 \begin{code}
366 tree              :: Bounds -> Forest Vertex -> Graph
367 tree bnds ts       = buildG bnds (concat (map flat ts))
368                    where
369                      flat (Node v rs) = [ (v, w) | Node w us <- ts ] ++
370                                         concat (map flat ts)
371
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