[project @ 1997-05-18 04:56:43 by sof]
[ghc-hetmet.git] / ghc / compiler / utils / FiniteMap.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1996
3 %
4 \section[FiniteMap]{An implementation of finite maps}
5
6 ``Finite maps'' are the heart of the compiler's
7 lookup-tables/environments and its implementation of sets.  Important
8 stuff!
9
10 This code is derived from that in the paper:
11 \begin{display}
12         S Adams
13         "Efficient sets: a balancing act"
14         Journal of functional programming 3(4) Oct 1993, pp553-562
15 \end{display}
16
17 The code is SPECIALIZEd to various highly-desirable types (e.g., Id)
18 near the end (only \tr{#ifdef COMPILING_GHC}).
19
20 \begin{code}
21 #ifdef COMPILING_GHC
22 #include "HsVersions.h"
23 #define IF_NOT_GHC(a) {--}
24 #else
25 #define ASSERT(e) {--}
26 #define IF_NOT_GHC(a) a
27 #define COMMA ,
28 #define _tagCmp compare
29 #define _LT LT
30 #define _GT GT
31 #define _EQ EQ
32 #endif
33
34 #if defined(COMPILING_GHC) && defined(DEBUG_FINITEMAPS)/* NB NB NB */
35 #define OUTPUTABLE_key , Outputable key
36 #else
37 #define OUTPUTABLE_key {--}
38 #endif
39
40 module FiniteMap (
41         FiniteMap,              -- abstract type
42
43         emptyFM, unitFM, listToFM,
44
45         addToFM,
46         addToFM_C,
47         addListToFM,
48         addListToFM_C,
49         delFromFM,
50         delListFromFM,
51
52         plusFM,
53         plusFM_C,
54         minusFM,
55         foldFM,
56
57         intersectFM,
58         intersectFM_C,
59         mapFM, filterFM,
60
61         sizeFM, isEmptyFM, elemFM, lookupFM, lookupWithDefaultFM,
62
63         fmToList, keysFM, eltsFM
64
65 #ifdef COMPILING_GHC
66         , bagToFM
67         , SYN_IE(FiniteSet), emptySet, mkSet, isEmptySet
68         , elementOf, setToList, union, minusSet
69 #endif
70     ) where
71
72 IMPORT_DELOOPER(SpecLoop)
73 #if __GLASGOW_HASKELL__ >= 202
74 import GlaExts
75 #endif
76 #if defined(USE_FAST_STRINGS)
77 import FastString
78 #endif
79 import Maybes
80 import Bag        ( Bag, foldrBag )
81 import Outputable ( Outputable(..) )
82 import PprStyle ( PprStyle )
83 import Pretty   ( Doc )
84
85 #ifdef COMPILING_GHC
86
87 # if ! OMIT_NATIVE_CODEGEN
88 #  define IF_NCG(a) a
89 # else
90 #  define IF_NCG(a) {--}
91 # endif
92 #endif
93
94 -- SIGH: but we use unboxed "sizes"...
95 #if __GLASGOW_HASKELL__
96 #define IF_GHC(a,b) a
97 #else /* not GHC */
98 #define IF_GHC(a,b) b
99 #endif /* not GHC */
100 \end{code}
101
102
103 %************************************************************************
104 %*                                                                      *
105 \subsection{The signature of the module}
106 %*                                                                      *
107 %************************************************************************
108
109 \begin{code}
110 --      BUILDING
111 emptyFM         :: FiniteMap key elt
112 unitFM          :: key -> elt -> FiniteMap key elt
113 listToFM        :: (Ord key OUTPUTABLE_key) => [(key,elt)] -> FiniteMap key elt
114                         -- In the case of duplicates, the last is taken
115 #ifdef COMPILING_GHC
116 bagToFM         :: (Ord key OUTPUTABLE_key) => Bag (key,elt) -> FiniteMap key elt
117                         -- In the case of duplicates, who knows which is taken
118 #endif
119
120 --      ADDING AND DELETING
121                    -- Throws away any previous binding
122                    -- In the list case, the items are added starting with the
123                    -- first one in the list
124 addToFM         :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> key -> elt  -> FiniteMap key elt
125 addListToFM     :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> [(key,elt)] -> FiniteMap key elt
126
127                    -- Combines with previous binding
128 addToFM_C       :: (Ord key OUTPUTABLE_key) => (elt -> elt -> elt)
129                            -> FiniteMap key elt -> key -> elt
130                            -> FiniteMap key elt
131 addListToFM_C   :: (Ord key OUTPUTABLE_key) => (elt -> elt -> elt)
132                            -> FiniteMap key elt -> [(key,elt)]
133                            -> FiniteMap key elt
134
135                    -- Deletion doesn't complain if you try to delete something
136                    -- which isn't there
137 delFromFM       :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> key   -> FiniteMap key elt
138 delListFromFM   :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> [key] -> FiniteMap key elt
139
140 --      COMBINING
141                    -- Bindings in right argument shadow those in the left
142 plusFM          :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> FiniteMap key elt
143                            -> FiniteMap key elt
144
145                    -- Combines bindings for the same thing with the given function
146 plusFM_C        :: (Ord key OUTPUTABLE_key) => (elt -> elt -> elt)
147                            -> FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
148
149 minusFM         :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
150                    -- (minusFM a1 a2) deletes from a1 any bindings which are bound in a2
151
152 intersectFM     :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
153 intersectFM_C   :: (Ord key OUTPUTABLE_key) => (elt -> elt -> elt2)
154                            -> FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt2
155
156 --      MAPPING, FOLDING, FILTERING
157 foldFM          :: (key -> elt -> a -> a) -> a -> FiniteMap key elt -> a
158 mapFM           :: (key -> elt1 -> elt2) -> FiniteMap key elt1 -> FiniteMap key elt2
159 filterFM        :: (Ord key OUTPUTABLE_key) => (key -> elt -> Bool)
160                            -> FiniteMap key elt -> FiniteMap key elt
161
162 --      INTERROGATING
163 sizeFM          :: FiniteMap key elt -> Int
164 isEmptyFM       :: FiniteMap key elt -> Bool
165
166 elemFM          :: (Ord key OUTPUTABLE_key) => key -> FiniteMap key elt -> Bool
167 lookupFM        :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> key -> Maybe elt
168 lookupWithDefaultFM
169                 :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> elt -> key -> elt
170                 -- lookupWithDefaultFM supplies a "default" elt
171                 -- to return for an unmapped key
172
173 --      LISTIFYING
174 fmToList        :: FiniteMap key elt -> [(key,elt)]
175 keysFM          :: FiniteMap key elt -> [key]
176 eltsFM          :: FiniteMap key elt -> [elt]
177 \end{code}
178
179 %************************************************************************
180 %*                                                                      *
181 \subsection{The @FiniteMap@ data type, and building of same}
182 %*                                                                      *
183 %************************************************************************
184
185 Invariants about @FiniteMap@:
186 \begin{enumerate}
187 \item
188 all keys in a FiniteMap are distinct
189 \item
190 all keys in left  subtree are $<$ key in Branch and
191 all keys in right subtree are $>$ key in Branch
192 \item
193 size field of a Branch gives number of Branch nodes in the tree
194 \item
195 size of left subtree is differs from size of right subtree by a
196 factor of at most \tr{sIZE_RATIO}
197 \end{enumerate}
198
199 \begin{code}
200 data FiniteMap key elt
201   = EmptyFM
202   | Branch key elt              -- Key and elt stored here
203     IF_GHC(Int#,Int{-STRICT-})  -- Size >= 1
204     (FiniteMap key elt)         -- Children
205     (FiniteMap key elt)
206 \end{code}
207
208 \begin{code}
209 emptyFM = EmptyFM
210 {-
211 emptyFM
212   = Branch bottom bottom IF_GHC(0#,0) bottom bottom
213   where
214     bottom = panic "emptyFM"
215 -}
216
217 -- #define EmptyFM (Branch _ _ IF_GHC(0#,0) _ _)
218
219 unitFM key elt = Branch key elt IF_GHC(1#,1) emptyFM emptyFM
220
221 listToFM = addListToFM emptyFM
222
223 #ifdef COMPILING_GHC
224 bagToFM = foldrBag (\(k,v) fm -> addToFM fm k v) emptyFM
225 #endif
226 \end{code}
227
228 %************************************************************************
229 %*                                                                      *
230 \subsection{Adding to and deleting from @FiniteMaps@}
231 %*                                                                      *
232 %************************************************************************
233
234 \begin{code}
235 addToFM fm key elt = addToFM_C (\ old new -> new) fm key elt
236
237 addToFM_C combiner EmptyFM key elt = unitFM key elt
238 addToFM_C combiner (Branch key elt size fm_l fm_r) new_key new_elt
239 #ifdef __GLASGOW_HASKELL__
240   = case _tagCmp new_key key of
241         _LT -> mkBalBranch key elt (addToFM_C combiner fm_l new_key new_elt) fm_r
242         _GT -> mkBalBranch key elt fm_l (addToFM_C combiner fm_r new_key new_elt)
243         _EQ -> Branch new_key (combiner elt new_elt) size fm_l fm_r
244 #else
245   | new_key < key = mkBalBranch key elt (addToFM_C combiner fm_l new_key new_elt) fm_r
246   | new_key > key = mkBalBranch key elt fm_l (addToFM_C combiner fm_r new_key new_elt)
247   | otherwise     = Branch new_key (combiner elt new_elt) size fm_l fm_r
248 #endif
249
250 addListToFM fm key_elt_pairs = addListToFM_C (\ old new -> new) fm key_elt_pairs
251
252 addListToFM_C combiner fm key_elt_pairs
253   = foldl add fm key_elt_pairs  -- foldl adds from the left
254   where
255     add fmap (key,elt) = addToFM_C combiner fmap key elt
256 \end{code}
257
258 \begin{code}
259 delFromFM EmptyFM del_key = emptyFM
260 delFromFM (Branch key elt size fm_l fm_r) del_key
261 #ifdef __GLASGOW_HASKELL__
262   = case _tagCmp del_key key of
263         _GT -> mkBalBranch key elt fm_l (delFromFM fm_r del_key)
264         _LT -> mkBalBranch key elt (delFromFM fm_l del_key) fm_r
265         _EQ -> glueBal fm_l fm_r
266 #else
267   | del_key > key
268   = mkBalBranch key elt fm_l (delFromFM fm_r del_key)
269
270   | del_key < key
271   = mkBalBranch key elt (delFromFM fm_l del_key) fm_r
272
273   | key == del_key
274   = glueBal fm_l fm_r
275 #endif
276
277 delListFromFM fm keys = foldl delFromFM fm keys
278 \end{code}
279
280 %************************************************************************
281 %*                                                                      *
282 \subsection{Combining @FiniteMaps@}
283 %*                                                                      *
284 %************************************************************************
285
286 \begin{code}
287 plusFM_C combiner EmptyFM fm2 = fm2
288 plusFM_C combiner fm1 EmptyFM = fm1
289 plusFM_C combiner fm1 (Branch split_key elt2 _ left right)
290   = mkVBalBranch split_key new_elt
291                  (plusFM_C combiner lts left)
292                  (plusFM_C combiner gts right)
293   where
294     lts     = splitLT fm1 split_key
295     gts     = splitGT fm1 split_key
296     new_elt = case lookupFM fm1 split_key of
297                 Nothing   -> elt2
298                 Just elt1 -> combiner elt1 elt2
299
300 -- It's worth doing plusFM specially, because we don't need
301 -- to do the lookup in fm1.
302
303 plusFM EmptyFM fm2 = fm2
304 plusFM fm1 EmptyFM = fm1
305 plusFM fm1 (Branch split_key elt1 _ left right)
306   = mkVBalBranch split_key elt1 (plusFM lts left) (plusFM gts right)
307   where
308     lts     = splitLT fm1 split_key
309     gts     = splitGT fm1 split_key
310
311 minusFM EmptyFM fm2 = emptyFM
312 minusFM fm1 EmptyFM = fm1
313 minusFM fm1 (Branch split_key elt _ left right)
314   = glueVBal (minusFM lts left) (minusFM gts right)
315         -- The two can be way different, so we need glueVBal
316   where
317     lts = splitLT fm1 split_key         -- NB gt and lt, so the equal ones
318     gts = splitGT fm1 split_key         -- are not in either.
319
320 intersectFM fm1 fm2 = intersectFM_C (\ left right -> right) fm1 fm2
321
322 intersectFM_C combiner fm1 EmptyFM = emptyFM
323 intersectFM_C combiner EmptyFM fm2 = emptyFM
324 intersectFM_C combiner fm1 (Branch split_key elt2 _ left right)
325
326   | maybeToBool maybe_elt1      -- split_elt *is* in intersection
327   = mkVBalBranch split_key (combiner elt1 elt2) (intersectFM_C combiner lts left)
328                                                 (intersectFM_C combiner gts right)
329
330   | otherwise                   -- split_elt is *not* in intersection
331   = glueVBal (intersectFM_C combiner lts left) (intersectFM_C combiner gts right)
332
333   where
334     lts = splitLT fm1 split_key         -- NB gt and lt, so the equal ones
335     gts = splitGT fm1 split_key         -- are not in either.
336
337     maybe_elt1 = lookupFM fm1 split_key
338     Just elt1  = maybe_elt1
339 \end{code}
340
341 %************************************************************************
342 %*                                                                      *
343 \subsection{Mapping, folding, and filtering with @FiniteMaps@}
344 %*                                                                      *
345 %************************************************************************
346
347 \begin{code}
348 foldFM k z EmptyFM = z
349 foldFM k z (Branch key elt _ fm_l fm_r)
350   = foldFM k (k key elt (foldFM k z fm_r)) fm_l
351
352 mapFM f EmptyFM = emptyFM
353 mapFM f (Branch key elt size fm_l fm_r)
354   = Branch key (f key elt) size (mapFM f fm_l) (mapFM f fm_r)
355
356 filterFM p EmptyFM = emptyFM
357 filterFM p (Branch key elt _ fm_l fm_r)
358   | p key elt           -- Keep the item
359   = mkVBalBranch key elt (filterFM p fm_l) (filterFM p fm_r)
360
361   | otherwise           -- Drop the item
362   = glueVBal (filterFM p fm_l) (filterFM p fm_r)
363 \end{code}
364
365 %************************************************************************
366 %*                                                                      *
367 \subsection{Interrogating @FiniteMaps@}
368 %*                                                                      *
369 %************************************************************************
370
371 \begin{code}
372 --{-# INLINE sizeFM #-}
373 sizeFM EmptyFM               = 0
374 sizeFM (Branch _ _ size _ _) = IF_GHC(I# size, size)
375
376 isEmptyFM fm = sizeFM fm == 0
377
378 lookupFM EmptyFM key = Nothing
379 lookupFM (Branch key elt _ fm_l fm_r) key_to_find
380 #ifdef __GLASGOW_HASKELL__
381   = case _tagCmp key_to_find key of
382         _LT -> lookupFM fm_l key_to_find
383         _GT -> lookupFM fm_r key_to_find
384         _EQ -> Just elt
385 #else
386   | key_to_find < key = lookupFM fm_l key_to_find
387   | key_to_find > key = lookupFM fm_r key_to_find
388   | otherwise     = Just elt
389 #endif
390
391 key `elemFM` fm
392   = case (lookupFM fm key) of { Nothing -> False; Just elt -> True }
393
394 lookupWithDefaultFM fm deflt key
395   = case (lookupFM fm key) of { Nothing -> deflt; Just elt -> elt }
396 \end{code}
397
398 %************************************************************************
399 %*                                                                      *
400 \subsection{Listifying @FiniteMaps@}
401 %*                                                                      *
402 %************************************************************************
403
404 \begin{code}
405 fmToList fm = foldFM (\ key elt rest -> (key,elt) : rest) [] fm
406 keysFM fm   = foldFM (\ key elt rest -> key : rest)       [] fm
407 eltsFM fm   = foldFM (\ key elt rest -> elt : rest)       [] fm
408 \end{code}
409
410
411 %************************************************************************
412 %*                                                                      *
413 \subsection{The implementation of balancing}
414 %*                                                                      *
415 %************************************************************************
416
417 %************************************************************************
418 %*                                                                      *
419 \subsubsection{Basic construction of a @FiniteMap@}
420 %*                                                                      *
421 %************************************************************************
422
423 @mkBranch@ simply gets the size component right.  This is the ONLY
424 (non-trivial) place the Branch object is built, so the ASSERTion
425 recursively checks consistency.  (The trivial use of Branch is in
426 @unitFM@.)
427
428 \begin{code}
429 sIZE_RATIO :: Int
430 sIZE_RATIO = 5
431
432 mkBranch :: (Ord key OUTPUTABLE_key)            -- Used for the assertion checking only
433          => Int
434          -> key -> elt
435          -> FiniteMap key elt -> FiniteMap key elt
436          -> FiniteMap key elt
437
438 mkBranch which key elt fm_l fm_r
439   = --ASSERT( left_ok && right_ok && balance_ok )
440 #if defined(COMPILING_GHC) && defined(DEBUG_FINITEMAPS)
441     if not ( left_ok && right_ok && balance_ok ) then
442         pprPanic ("mkBranch:"++show which) (vcat [ppr PprDebug [left_ok, right_ok, balance_ok],
443                                        ppr PprDebug key,
444                                        ppr PprDebug fm_l,
445                                        ppr PprDebug fm_r])
446     else
447 #endif
448     let
449         result = Branch key elt (unbox (1 + left_size + right_size)) fm_l fm_r
450     in
451 --    if sizeFM result <= 8 then
452         result
453 --    else
454 --      pprTrace ("mkBranch:"++(show which)) (ppr PprDebug result) (
455 --      result
456 --      )
457   where
458     left_ok  = case fm_l of
459                 EmptyFM                  -> True
460                 Branch left_key _ _ _ _  -> let
461                                                 biggest_left_key = fst (findMax fm_l)
462                                             in
463                                             biggest_left_key < key
464     right_ok = case fm_r of
465                 EmptyFM                  -> True
466                 Branch right_key _ _ _ _ -> let
467                                                 smallest_right_key = fst (findMin fm_r)
468                                             in
469                                             key < smallest_right_key
470     balance_ok = True -- sigh
471 {- LATER:
472     balance_ok
473       = -- Both subtrees have one or no elements...
474         (left_size + right_size <= 1)
475 -- NO         || left_size == 0  -- ???
476 -- NO         || right_size == 0 -- ???
477         -- ... or the number of elements in a subtree does not exceed
478         -- sIZE_RATIO times the number of elements in the other subtree
479       || (left_size  * sIZE_RATIO >= right_size &&
480           right_size * sIZE_RATIO >= left_size)
481 -}
482
483     left_size  = sizeFM fm_l
484     right_size = sizeFM fm_r
485
486 #ifdef __GLASGOW_HASKELL__
487     unbox :: Int -> Int#
488     unbox (I# size) = size
489 #else
490     unbox :: Int -> Int
491     unbox x = x
492 #endif
493 \end{code}
494
495 %************************************************************************
496 %*                                                                      *
497 \subsubsection{{\em Balanced} construction of a @FiniteMap@}
498 %*                                                                      *
499 %************************************************************************
500
501 @mkBalBranch@ rebalances, assuming that the subtrees aren't too far
502 out of whack.
503
504 \begin{code}
505 mkBalBranch :: (Ord key OUTPUTABLE_key)
506             => key -> elt
507             -> FiniteMap key elt -> FiniteMap key elt
508             -> FiniteMap key elt
509
510 mkBalBranch key elt fm_L fm_R
511
512   | size_l + size_r < 2
513   = mkBranch 1{-which-} key elt fm_L fm_R
514
515   | size_r > sIZE_RATIO * size_l        -- Right tree too big
516   = case fm_R of
517         Branch _ _ _ fm_rl fm_rr
518                 | sizeFM fm_rl < 2 * sizeFM fm_rr -> single_L fm_L fm_R
519                 | otherwise                       -> double_L fm_L fm_R
520         -- Other case impossible
521
522   | size_l > sIZE_RATIO * size_r        -- Left tree too big
523   = case fm_L of
524         Branch _ _ _ fm_ll fm_lr
525                 | sizeFM fm_lr < 2 * sizeFM fm_ll -> single_R fm_L fm_R
526                 | otherwise                       -> double_R fm_L fm_R
527         -- Other case impossible
528
529   | otherwise                           -- No imbalance
530   = mkBranch 2{-which-} key elt fm_L fm_R
531
532   where
533     size_l   = sizeFM fm_L
534     size_r   = sizeFM fm_R
535
536     single_L fm_l (Branch key_r elt_r _ fm_rl fm_rr)
537         = mkBranch 3{-which-} key_r elt_r (mkBranch 4{-which-} key elt fm_l fm_rl) fm_rr
538
539     double_L fm_l (Branch key_r elt_r _ (Branch key_rl elt_rl _ fm_rll fm_rlr) fm_rr)
540         = mkBranch 5{-which-} key_rl elt_rl (mkBranch 6{-which-} key   elt   fm_l   fm_rll)
541                                  (mkBranch 7{-which-} key_r elt_r fm_rlr fm_rr)
542
543     single_R (Branch key_l elt_l _ fm_ll fm_lr) fm_r
544         = mkBranch 8{-which-} key_l elt_l fm_ll (mkBranch 9{-which-} key elt fm_lr fm_r)
545
546     double_R (Branch key_l elt_l _ fm_ll (Branch key_lr elt_lr _ fm_lrl fm_lrr)) fm_r
547         = mkBranch 10{-which-} key_lr elt_lr (mkBranch 11{-which-} key_l elt_l fm_ll  fm_lrl)
548                                  (mkBranch 12{-which-} key   elt   fm_lrr fm_r)
549 \end{code}
550
551
552 \begin{code}
553 mkVBalBranch :: (Ord key OUTPUTABLE_key)
554              => key -> elt
555              -> FiniteMap key elt -> FiniteMap key elt
556              -> FiniteMap key elt
557
558 -- Assert: in any call to (mkVBalBranch_C comb key elt l r),
559 --         (a) all keys in l are < all keys in r
560 --         (b) all keys in l are < key
561 --         (c) all keys in r are > key
562
563 mkVBalBranch key elt EmptyFM fm_r = addToFM fm_r key elt
564 mkVBalBranch key elt fm_l EmptyFM = addToFM fm_l key elt
565
566 mkVBalBranch key elt fm_l@(Branch key_l elt_l _ fm_ll fm_lr)
567                      fm_r@(Branch key_r elt_r _ fm_rl fm_rr)
568   | sIZE_RATIO * size_l < size_r
569   = mkBalBranch key_r elt_r (mkVBalBranch key elt fm_l fm_rl) fm_rr
570
571   | sIZE_RATIO * size_r < size_l
572   = mkBalBranch key_l elt_l fm_ll (mkVBalBranch key elt fm_lr fm_r)
573
574   | otherwise
575   = mkBranch 13{-which-} key elt fm_l fm_r
576
577   where
578     size_l = sizeFM fm_l
579     size_r = sizeFM fm_r
580 \end{code}
581
582 %************************************************************************
583 %*                                                                      *
584 \subsubsection{Gluing two trees together}
585 %*                                                                      *
586 %************************************************************************
587
588 @glueBal@ assumes its two arguments aren't too far out of whack, just
589 like @mkBalBranch@.  But: all keys in first arg are $<$ all keys in
590 second.
591
592 \begin{code}
593 glueBal :: (Ord key OUTPUTABLE_key)
594         => FiniteMap key elt -> FiniteMap key elt
595         -> FiniteMap key elt
596
597 glueBal EmptyFM fm2 = fm2
598 glueBal fm1 EmptyFM = fm1
599 glueBal fm1 fm2
600         -- The case analysis here (absent in Adams' program) is really to deal
601         -- with the case where fm2 is a singleton. Then deleting the minimum means
602         -- we pass an empty tree to mkBalBranch, which breaks its invariant.
603   | sizeFM fm2 > sizeFM fm1
604   = mkBalBranch mid_key2 mid_elt2 fm1 (deleteMin fm2)
605
606   | otherwise
607   = mkBalBranch mid_key1 mid_elt1 (deleteMax fm1) fm2
608   where
609     (mid_key1, mid_elt1) = findMax fm1
610     (mid_key2, mid_elt2) = findMin fm2
611 \end{code}
612
613 @glueVBal@ copes with arguments which can be of any size.
614 But: all keys in first arg are $<$ all keys in second.
615
616 \begin{code}
617 glueVBal :: (Ord key OUTPUTABLE_key)
618          => FiniteMap key elt -> FiniteMap key elt
619          -> FiniteMap key elt
620
621 glueVBal EmptyFM fm2 = fm2
622 glueVBal fm1 EmptyFM = fm1
623 glueVBal fm_l@(Branch key_l elt_l _ fm_ll fm_lr)
624          fm_r@(Branch key_r elt_r _ fm_rl fm_rr)
625   | sIZE_RATIO * size_l < size_r
626   = mkBalBranch key_r elt_r (glueVBal fm_l fm_rl) fm_rr
627
628   | sIZE_RATIO * size_r < size_l
629   = mkBalBranch key_l elt_l fm_ll (glueVBal fm_lr fm_r)
630
631   | otherwise           -- We now need the same two cases as in glueBal above.
632   = glueBal fm_l fm_r
633   where
634     (mid_key_l,mid_elt_l) = findMax fm_l
635     (mid_key_r,mid_elt_r) = findMin fm_r
636     size_l = sizeFM fm_l
637     size_r = sizeFM fm_r
638 \end{code}
639
640 %************************************************************************
641 %*                                                                      *
642 \subsection{Local utilities}
643 %*                                                                      *
644 %************************************************************************
645
646 \begin{code}
647 splitLT, splitGT :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> key -> FiniteMap key elt
648
649 -- splitLT fm split_key  =  fm restricted to keys <  split_key
650 -- splitGT fm split_key  =  fm restricted to keys >  split_key
651
652 splitLT EmptyFM split_key = emptyFM
653 splitLT (Branch key elt _ fm_l fm_r) split_key
654 #ifdef __GLASGOW_HASKELL__
655   = case _tagCmp split_key key of
656         _LT -> splitLT fm_l split_key
657         _GT -> mkVBalBranch key elt fm_l (splitLT fm_r split_key)
658         _EQ -> fm_l
659 #else
660   | split_key < key = splitLT fm_l split_key
661   | split_key > key = mkVBalBranch key elt fm_l (splitLT fm_r split_key)
662   | otherwise       = fm_l
663 #endif
664
665 splitGT EmptyFM split_key = emptyFM
666 splitGT (Branch key elt _ fm_l fm_r) split_key
667 #ifdef __GLASGOW_HASKELL__
668   = case _tagCmp split_key key of
669         _GT -> splitGT fm_r split_key
670         _LT -> mkVBalBranch key elt (splitGT fm_l split_key) fm_r
671         _EQ -> fm_r
672 #else
673   | split_key > key = splitGT fm_r split_key
674   | split_key < key = mkVBalBranch key elt (splitGT fm_l split_key) fm_r
675   | otherwise       = fm_r
676 #endif
677
678 findMin :: FiniteMap key elt -> (key,elt)
679 findMin (Branch key elt _ EmptyFM _) = (key,elt)
680 findMin (Branch key elt _ fm_l    _) = findMin fm_l
681
682 deleteMin :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> FiniteMap key elt
683 deleteMin (Branch key elt _ EmptyFM fm_r) = fm_r
684 deleteMin (Branch key elt _ fm_l    fm_r) = mkBalBranch key elt (deleteMin fm_l) fm_r
685
686 findMax :: FiniteMap key elt -> (key,elt)
687 findMax (Branch key elt _ _ EmptyFM) = (key,elt)
688 findMax (Branch key elt _ _    fm_r) = findMax fm_r
689
690 deleteMax :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> FiniteMap key elt
691 deleteMax (Branch key elt _ fm_l EmptyFM) = fm_l
692 deleteMax (Branch key elt _ fm_l    fm_r) = mkBalBranch key elt fm_l (deleteMax fm_r)
693 \end{code}
694
695 %************************************************************************
696 %*                                                                      *
697 \subsection{Output-ery}
698 %*                                                                      *
699 %************************************************************************
700
701 \begin{code}
702 #if defined(COMPILING_GHC) && defined(DEBUG_FINITEMAPS)
703
704 instance (Outputable key) => Outputable (FiniteMap key elt) where
705     ppr sty fm = pprX sty fm
706
707 pprX sty EmptyFM = char '!'
708 pprX sty (Branch key elt sz fm_l fm_r)
709  = parens (hcat [pprX sty fm_l, space,
710                       ppr sty key, space, int (IF_GHC(I# sz, sz)), space,
711                       pprX sty fm_r])
712 #endif
713
714 #ifndef COMPILING_GHC
715 instance (Eq key, Eq elt) => Eq (FiniteMap key elt) where
716   fm_1 == fm_2 = (sizeFM   fm_1 == sizeFM   fm_2) &&   -- quick test
717                  (fmToList fm_1 == fmToList fm_2)
718
719 {- NO: not clear what The Right Thing to do is:
720 instance (Ord key, Ord elt) => Ord (FiniteMap key elt) where
721   fm_1 <= fm_2 = (sizeFM   fm_1 <= sizeFM   fm_2) &&   -- quick test
722                  (fmToList fm_1 <= fmToList fm_2)
723 -}
724 #endif
725 \end{code}
726
727 %************************************************************************
728 %*                                                                      *
729 \subsection{FiniteSets---a thin veneer}
730 %*                                                                      *
731 %************************************************************************
732
733 \begin{code}
734 #ifdef COMPILING_GHC
735
736 type FiniteSet key = FiniteMap key ()
737 emptySet        :: FiniteSet key
738 mkSet           :: (Ord key OUTPUTABLE_key) => [key] -> FiniteSet key
739 isEmptySet      :: FiniteSet key -> Bool
740 elementOf       :: (Ord key OUTPUTABLE_key) => key -> FiniteSet key -> Bool
741 minusSet        :: (Ord key OUTPUTABLE_key) => FiniteSet key -> FiniteSet key -> FiniteSet key
742 setToList       :: FiniteSet key -> [key]
743 union           :: (Ord key OUTPUTABLE_key) => FiniteSet key -> FiniteSet key -> FiniteSet key
744
745 emptySet = emptyFM
746 mkSet xs = listToFM [ (x, ()) | x <- xs]
747 isEmptySet = isEmptyFM
748 elementOf = elemFM
749 minusSet  = minusFM
750 setToList = keysFM
751 union = plusFM
752
753 #endif
754 \end{code}
755
756 %************************************************************************
757 %*                                                                      *
758 \subsection{Efficiency pragmas for GHC}
759 %*                                                                      *
760 %************************************************************************
761
762 When the FiniteMap module is used in GHC, we specialise it for
763 \tr{Uniques}, for dastardly efficiency reasons.
764
765 \begin{code}
766 #if defined(COMPILING_GHC) && __GLASGOW_HASKELL__ && !defined(REALLY_HASKELL_1_3)
767
768 {-# SPECIALIZE addListToFM
769                 :: FiniteMap (FAST_STRING, FAST_STRING) elt -> [((FAST_STRING, FAST_STRING),elt)] -> FiniteMap (FAST_STRING, FAST_STRING) elt
770                  , FiniteMap RdrName elt -> [(RdrName,elt)] -> FiniteMap RdrName elt
771     IF_NCG(COMMA   FiniteMap Reg elt -> [(Reg COMMA elt)] -> FiniteMap Reg elt)
772     #-}
773 {-# SPECIALIZE addListToFM_C
774                 :: (elt -> elt -> elt) -> FiniteMap TyCon elt -> [(TyCon,elt)] -> FiniteMap TyCon elt
775                  , (elt -> elt -> elt) -> FiniteMap FAST_STRING elt -> [(FAST_STRING,elt)] -> FiniteMap FAST_STRING elt
776     IF_NCG(COMMA   (elt -> elt -> elt) -> FiniteMap Reg elt -> [(Reg COMMA elt)] -> FiniteMap Reg elt)
777     #-}
778 {-# SPECIALIZE addToFM
779                 :: FiniteMap CLabel elt -> CLabel -> elt  -> FiniteMap CLabel elt
780                  , FiniteMap FAST_STRING elt -> FAST_STRING -> elt  -> FiniteMap FAST_STRING elt
781                  , FiniteMap (FAST_STRING, FAST_STRING) elt -> (FAST_STRING, FAST_STRING) -> elt  -> FiniteMap (FAST_STRING, FAST_STRING) elt
782                  , FiniteMap RdrName elt -> RdrName -> elt  -> FiniteMap RdrName elt
783     IF_NCG(COMMA   FiniteMap Reg elt -> Reg -> elt  -> FiniteMap Reg elt)
784     #-}
785 {-# SPECIALIZE addToFM_C
786                 :: (elt -> elt -> elt) -> FiniteMap (RdrName, RdrName) elt -> (RdrName, RdrName) -> elt -> FiniteMap (RdrName, RdrName) elt
787                  , (elt -> elt -> elt) -> FiniteMap FAST_STRING elt -> FAST_STRING -> elt -> FiniteMap FAST_STRING elt
788     IF_NCG(COMMA   (elt -> elt -> elt) -> FiniteMap Reg elt -> Reg -> elt -> FiniteMap Reg elt)
789     #-}
790 {-# SPECIALIZE bagToFM
791                 :: Bag (FAST_STRING,elt) -> FiniteMap FAST_STRING elt
792     #-}
793 {-# SPECIALIZE delListFromFM
794                 :: FiniteMap RdrName elt -> [RdrName]   -> FiniteMap RdrName elt
795                  , FiniteMap FAST_STRING elt -> [FAST_STRING]   -> FiniteMap FAST_STRING elt
796     IF_NCG(COMMA   FiniteMap Reg elt -> [Reg]   -> FiniteMap Reg elt)
797     #-}
798 {-# SPECIALIZE listToFM
799                 :: [([Char],elt)] -> FiniteMap [Char] elt
800                  , [(FAST_STRING,elt)] -> FiniteMap FAST_STRING elt
801                  , [((FAST_STRING,FAST_STRING),elt)] -> FiniteMap (FAST_STRING, FAST_STRING) elt
802     IF_NCG(COMMA   [(Reg COMMA elt)] -> FiniteMap Reg elt)
803     #-}
804 {-# SPECIALIZE lookupFM
805                 :: FiniteMap CLabel elt -> CLabel -> Maybe elt
806                  , FiniteMap [Char] elt -> [Char] -> Maybe elt
807                  , FiniteMap FAST_STRING elt -> FAST_STRING -> Maybe elt
808                  , FiniteMap (FAST_STRING,FAST_STRING) elt -> (FAST_STRING,FAST_STRING) -> Maybe elt
809                  , FiniteMap RdrName elt -> RdrName -> Maybe elt
810                  , FiniteMap (RdrName,RdrName) elt -> (RdrName,RdrName) -> Maybe elt
811     IF_NCG(COMMA   FiniteMap Reg elt -> Reg -> Maybe elt)
812     #-}
813 {-# SPECIALIZE lookupWithDefaultFM
814                 :: FiniteMap FAST_STRING elt -> elt -> FAST_STRING -> elt
815     IF_NCG(COMMA   FiniteMap Reg elt -> elt -> Reg -> elt)
816     #-}
817 {-# SPECIALIZE plusFM
818                 :: FiniteMap RdrName elt -> FiniteMap RdrName elt -> FiniteMap RdrName elt
819                  , FiniteMap FAST_STRING elt -> FiniteMap FAST_STRING elt -> FiniteMap FAST_STRING elt
820     IF_NCG(COMMA   FiniteMap Reg elt -> FiniteMap Reg elt -> FiniteMap Reg elt)
821     #-}
822 {-# SPECIALIZE plusFM_C
823                 :: (elt -> elt -> elt) -> FiniteMap FAST_STRING elt -> FiniteMap FAST_STRING elt -> FiniteMap FAST_STRING elt
824     IF_NCG(COMMA   (elt -> elt -> elt) -> FiniteMap Reg elt -> FiniteMap Reg elt -> FiniteMap Reg elt)
825     #-}
826
827 #endif {- compiling for GHC -}
828 \end{code}