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