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