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