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