[project @ 1997-05-18 04:58:22 by sof]
[ghc-hetmet.git] / ghc / compiler / utils / Digraph.lhs
1 \begin{code}
2 #if defined(COMPILING_GHC)
3 # include "HsVersions.h"
4 #endif
5
6 module Digraph(
7
8         -- At present the only one with a "nice" external interface
9         stronglyConnComp, stronglyConnCompR, SCC(..),
10
11         SYN_IE(Graph), SYN_IE(Vertex), 
12         graphFromEdges, buildG, transposeG, reverseE, outdegree, indegree,
13
14         Tree(..), SYN_IE(Forest),
15         showTree, showForest,
16
17         dfs, dff,
18         topSort,
19         components,
20         scc,
21         back, cross, forward,
22         reachable, path,
23         bcc
24
25     ) where
26
27 ------------------------------------------------------------------------------
28 -- A version of the graph algorithms described in:
29 -- 
30 -- ``Lazy Depth-First Search and Linear Graph Algorithms in Haskell''
31 --   by David King and John Launchbury
32 -- 
33 -- Also included is some additional code for printing tree structures ...
34 ------------------------------------------------------------------------------
35
36 #ifdef REALLY_HASKELL_1_3
37
38 #define ARR_ELT         (COMMA)
39
40 import Array
41 import List
42 import ST
43 import ArrBase
44 import Maybe
45
46 #else
47
48 #define ARR_ELT         (:=)
49 #define runST           _runST
50 #define MutableArray    _MutableArray
51 #define Show            Text
52
53 import PreludeGlaST
54 import Maybes           ( mapMaybe )
55
56 #endif
57
58 import Util     ( Ord3(..), 
59                   sortLt
60                 )
61 \end{code}
62
63
64 %************************************************************************
65 %*                                                                      *
66 %*      External interface
67 %*                                                                      *
68 %************************************************************************
69
70 \begin{code}
71 data SCC vertex = AcyclicSCC vertex
72                 | CyclicSCC  [vertex]
73
74 stronglyConnComp
75         :: Ord3 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]
80
81 stronglyConnComp edges
82   = map get_node (stronglyConnCompR edges)
83   where
84     get_node (AcyclicSCC (n, _, _)) = AcyclicSCC n
85     get_node (CyclicSCC triples)     = CyclicSCC [n | (n,_,_) <- triples]
86
87 -- The "R" interface is used when you expect to apply SCC to
88 -- the (some of) the result of SCC, so you dont want to lose the dependency info
89 stronglyConnCompR
90         :: Ord3 key
91         => [(node, key, [key])]         -- The graph; its ok for the
92                                         -- out-list to contain keys which arent
93                                         -- a vertex key, they are ignored
94         -> [SCC (node, key, [key])]
95
96 stronglyConnCompR [] = []  -- added to avoid creating empty array in graphFromEdges -- SOF
97 stronglyConnCompR edges
98   = map decode forest
99   where
100     (graph, vertex_fn) = graphFromEdges edges
101     forest             = scc graph
102     decode (Node v []) | mentions_itself v = CyclicSCC [vertex_fn v]
103                        | otherwise         = AcyclicSCC (vertex_fn v)
104     decode other = CyclicSCC (dec other [])
105                  where
106                    dec (Node v ts) vs = vertex_fn v : foldr dec vs ts
107     mentions_itself v = v `elem` (graph ! v)
108 \end{code}
109
110 %************************************************************************
111 %*                                                                      *
112 %*      Graphs
113 %*                                                                      *
114 %************************************************************************
115
116
117 \begin{code}
118 type Vertex  = Int
119 type Table a = Array Vertex a
120 type Graph   = Table [Vertex]
121 type Bounds  = (Vertex, Vertex)
122 type Edge    = (Vertex, Vertex)
123 \end{code}
124
125 \begin{code}
126 vertices :: Graph -> [Vertex]
127 vertices  = indices
128
129 edges    :: Graph -> [Edge]
130 edges g   = [ (v, w) | v <- vertices g, w <- g!v ]
131
132 mapT    :: (Vertex -> a -> b) -> Table a -> Table b
133 mapT f t = array (bounds t) [ ARR_ELT v (f v (t!v)) | v <- indices t ]
134
135 buildG :: Bounds -> [Edge] -> Graph
136 #ifdef REALLY_HASKELL_1_3
137 buildG bounds edges = accumArray (flip (:)) [] bounds edges
138 #else
139 buildG bounds edges = accumArray (flip (:)) [] bounds [ARR_ELT k v | (k,v) <- edges]
140 #endif
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         :: Ord3 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 ARR_ELT [0..] sorted_edges
169
170     graph           = array bounds [ARR_ELT v (mapMaybe key_vertex ks) | ARR_ELT v (_,    _, ks) <- edges1]
171     key_map         = array bounds [ARR_ELT v k                        | ARR_ELT v (_,    k, _ ) <- edges1]
172     vertex_map      = array bounds edges1
173
174     (_,k1,_) `lt` (_,k2,_) = case k1 `cmp` 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 cmp 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       = take n (repeat ' ')
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 type Set s    = MutableArray s Vertex Bool
243
244 mkEmpty      :: Bounds -> ST s (Set s)
245 mkEmpty bnds  = newArray bnds False
246
247 contains     :: Set s -> Vertex -> ST s Bool
248 contains m v  = readArray m v
249
250 include      :: Set s -> Vertex -> ST s ()
251 include m v   = writeArray m v True
252 \end{code}
253
254 \begin{code}
255 dff          :: Graph -> Forest Vertex
256 dff g         = dfs g (vertices g)
257
258 dfs          :: Graph -> [Vertex] -> Forest Vertex
259 dfs g vs      = prune (bounds g) (map (generate g) vs)
260
261 generate     :: Graph -> Vertex -> Tree Vertex
262 generate g v  = Node v (map (generate g) (g!v))
263
264 prune        :: Bounds -> Forest Vertex -> Forest Vertex
265 prune bnds ts = runST (mkEmpty bnds  `thenST` \m ->
266                        chop m ts)
267
268 chop         :: Set s -> Forest Vertex -> ST s (Forest Vertex)
269 chop m []     = returnST []
270 chop m (Node v ts : us)
271               = contains m v `thenStrictlyST` \visited ->
272                 if visited then
273                   chop m us
274                 else
275                   include m v `thenStrictlyST` \_  ->
276                   chop m ts   `thenStrictlyST` \as ->
277                   chop m us   `thenStrictlyST` \bs ->
278                   returnST (Node v as : bs)
279 \end{code}
280
281
282 %************************************************************************
283 %*                                                                      *
284 %*      Algorithms
285 %*                                                                      *
286 %************************************************************************
287
288 ------------------------------------------------------------
289 -- Algorithm 1: depth first search numbering
290 ------------------------------------------------------------
291
292 \begin{code}
293 --preorder            :: Tree a -> [a]
294 preorder (Node a ts) = a : preorderF ts
295
296 preorderF           :: Forest a -> [a]
297 preorderF ts         = concat (map preorder ts)
298
299 preOrd :: Graph -> [Vertex]
300 preOrd  = preorderF . dff
301
302 tabulate        :: Bounds -> [Vertex] -> Table Int
303 tabulate bnds vs = array bnds (zipWith ARR_ELT vs [1..])
304
305 preArr          :: Bounds -> Forest Vertex -> Table Int
306 preArr bnds      = tabulate bnds . preorderF
307 \end{code}
308
309
310 ------------------------------------------------------------
311 -- Algorithm 2: topological sorting
312 ------------------------------------------------------------
313
314 \begin{code}
315 --postorder :: Tree a -> [a]
316 postorder (Node a ts) = postorderF ts ++ [a]
317
318 postorderF   :: Forest a -> [a]
319 postorderF ts = concat (map postorder ts)
320
321 postOrd      :: Graph -> [Vertex]
322 postOrd       = postorderF . dff
323
324 topSort      :: Graph -> [Vertex]
325 topSort       = reverse . postOrd
326 \end{code}
327
328
329 ------------------------------------------------------------
330 -- Algorithm 3: connected components
331 ------------------------------------------------------------
332
333 \begin{code}
334 components   :: Graph -> Forest Vertex
335 components    = dff . undirected
336
337 undirected   :: Graph -> Graph
338 undirected g  = buildG (bounds g) (edges g ++ reverseE g)
339 \end{code}
340
341
342 -- Algorithm 4: strongly connected components
343
344 \begin{code}
345 scc  :: Graph -> Forest Vertex
346 scc g = dfs g (reverse (postOrd (transposeG g)))
347 \end{code}
348
349
350 ------------------------------------------------------------
351 -- Algorithm 5: Classifying edges
352 ------------------------------------------------------------
353
354 \begin{code}
355 tree              :: Bounds -> Forest Vertex -> Graph
356 tree bnds ts       = buildG bnds (concat (map flat ts))
357                    where
358                      flat (Node v rs) = [ (v, w) | Node w us <- ts ] ++
359                                         concat (map flat ts)
360
361 back              :: Graph -> Table Int -> Graph
362 back g post        = mapT select g
363  where select v ws = [ w | w <- ws, post!v < post!w ]
364
365 cross             :: Graph -> Table Int -> Table Int -> Graph
366 cross g pre post   = mapT select g
367  where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
368
369 forward           :: Graph -> Graph -> Table Int -> Graph
370 forward g tree pre = mapT select g
371  where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
372 \end{code}
373
374
375 ------------------------------------------------------------
376 -- Algorithm 6: Finding reachable vertices
377 ------------------------------------------------------------
378
379 \begin{code}
380 reachable    :: Graph -> Vertex -> [Vertex]
381 reachable g v = preorderF (dfs g [v])
382
383 path         :: Graph -> Vertex -> Vertex -> Bool
384 path g v w    = w `elem` (reachable g v)
385 \end{code}
386
387
388 ------------------------------------------------------------
389 -- Algorithm 7: Biconnected components
390 ------------------------------------------------------------
391
392 \begin{code}
393 bcc :: Graph -> Forest [Vertex]
394 bcc g = (concat . map bicomps . map (label g dnum)) forest
395  where forest = dff g
396        dnum   = preArr (bounds g) forest
397
398 label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
399 label g dnum (Node v ts) = Node (v,dnum!v,lv) us
400  where us = map (label g dnum) ts
401        lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
402                      ++ [lu | Node (u,du,lu) xs <- us])
403
404 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
405 bicomps (Node (v,dv,lv) ts)
406       = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
407
408 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
409 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
410  where collected = map collect ts
411        vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
412        cs = concat [ if lw<dv then us else [Node (v:ws) us]
413                         | (lw, Node ws us) <- collected ]
414 \end{code}
415