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