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