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