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