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