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