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