De-orphan the Eq/Ord [a] instances
[ghc-base.git] / GHC / Base.lhs
1 \section[GHC.Base]{Module @GHC.Base@}
2
3 The overall structure of the GHC Prelude is a bit tricky.
4
5   a) We want to avoid "orphan modules", i.e. ones with instance
6         decls that don't belong either to a tycon or a class
7         defined in the same module
8
9   b) We want to avoid giant modules
10
11 So the rough structure is as follows, in (linearised) dependency order
12
13
14 GHC.Prim                Has no implementation.  It defines built-in things, and
15                 by importing it you bring them into scope.
16                 The source file is GHC.Prim.hi-boot, which is just
17                 copied to make GHC.Prim.hi
18
19 GHC.Base        Classes: Eq, Ord, Functor, Monad
20                 Types:   list, (), Int, Bool, Ordering, Char, String
21
22 Data.Tuple      Types: tuples, plus instances for GHC.Base classes
23
24 GHC.Show        Class: Show, plus instances for GHC.Base/GHC.Tup types
25
26 GHC.Enum        Class: Enum,  plus instances for GHC.Base/GHC.Tup types
27
28 Data.Maybe      Type: Maybe, plus instances for GHC.Base classes
29
30 GHC.List        List functions
31
32 GHC.Num         Class: Num, plus instances for Int
33                 Type:  Integer, plus instances for all classes so far (Eq, Ord, Num, Show)
34
35                 Integer is needed here because it is mentioned in the signature
36                 of 'fromInteger' in class Num
37
38 GHC.Real        Classes: Real, Integral, Fractional, RealFrac
39                          plus instances for Int, Integer
40                 Types:  Ratio, Rational
41                         plus intances for classes so far
42
43                 Rational is needed here because it is mentioned in the signature
44                 of 'toRational' in class Real
45
46 GHC.ST  The ST monad, instances and a few helper functions
47
48 Ix              Classes: Ix, plus instances for Int, Bool, Char, Integer, Ordering, tuples
49
50 GHC.Arr         Types: Array, MutableArray, MutableVar
51
52                 Arrays are used by a function in GHC.Float
53
54 GHC.Float       Classes: Floating, RealFloat
55                 Types:   Float, Double, plus instances of all classes so far
56
57                 This module contains everything to do with floating point.
58                 It is a big module (900 lines)
59                 With a bit of luck, many modules can be compiled without ever reading GHC.Float.hi
60
61
62 Other Prelude modules are much easier with fewer complex dependencies.
63
64 \begin{code}
65 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
66 {-# OPTIONS_GHC -fno-warn-orphans #-}
67 {-# OPTIONS_HADDOCK hide #-}
68 -----------------------------------------------------------------------------
69 -- |
70 -- Module      :  GHC.Base
71 -- Copyright   :  (c) The University of Glasgow, 1992-2002
72 -- License     :  see libraries/base/LICENSE
73 -- 
74 -- Maintainer  :  cvs-ghc@haskell.org
75 -- Stability   :  internal
76 -- Portability :  non-portable (GHC extensions)
77 --
78 -- Basic data types and classes.
79 -- 
80 -----------------------------------------------------------------------------
81
82 #include "MachDeps.h"
83
84 -- #hide
85 module GHC.Base
86         (
87         module GHC.Base,
88         module GHC.Bool,
89         module GHC.Classes,
90         module GHC.Generics,
91         module GHC.Ordering,
92         module GHC.Types,
93         module GHC.Prim,        -- Re-export GHC.Prim and GHC.Err, to avoid lots
94         module GHC.Err          -- of people having to import it explicitly
95   ) 
96         where
97
98 import GHC.Types
99 import GHC.Bool
100 import GHC.Classes
101 import GHC.Generics
102 import GHC.Ordering
103 import GHC.Prim
104 import {-# SOURCE #-} GHC.Show
105 import {-# SOURCE #-} GHC.Err
106 import {-# SOURCE #-} GHC.IO (failIO)
107
108 -- These two are not strictly speaking required by this module, but they are
109 -- implicit dependencies whenever () or tuples are mentioned, so adding them
110 -- as imports here helps to get the dependencies right in the new build system.
111 import GHC.Tuple ()
112 import GHC.Unit ()
113
114 infixr 9  .
115 infixr 5  ++
116 infixl 4  <$
117 infixl 1  >>, >>=
118 infixr 0  $
119
120 default ()              -- Double isn't available yet
121 \end{code}
122
123
124 %*********************************************************
125 %*                                                      *
126 \subsection{DEBUGGING STUFF}
127 %*  (for use when compiling GHC.Base itself doesn't work)
128 %*                                                      *
129 %*********************************************************
130
131 \begin{code}
132 {-
133 data  Bool  =  False | True
134 data Ordering = LT | EQ | GT 
135 data Char = C# Char#
136 type  String = [Char]
137 data Int = I# Int#
138 data  ()  =  ()
139 data [] a = MkNil
140
141 not True = False
142 (&&) True True = True
143 otherwise = True
144
145 build = error "urk"
146 foldr = error "urk"
147
148 unpackCString# :: Addr# -> [Char]
149 unpackFoldrCString# :: Addr# -> (Char  -> a -> a) -> a -> a 
150 unpackAppendCString# :: Addr# -> [Char] -> [Char]
151 unpackCStringUtf8# :: Addr# -> [Char]
152 unpackCString# a = error "urk"
153 unpackFoldrCString# a = error "urk"
154 unpackAppendCString# a = error "urk"
155 unpackCStringUtf8# a = error "urk"
156 -}
157 \end{code}
158
159
160 %*********************************************************
161 %*                                                      *
162 \subsection{Monadic classes @Functor@, @Monad@ }
163 %*                                                      *
164 %*********************************************************
165
166 \begin{code}
167 {- | The 'Functor' class is used for types that can be mapped over.
168 Instances of 'Functor' should satisfy the following laws:
169
170 > fmap id  ==  id
171 > fmap (f . g)  ==  fmap f . fmap g
172
173 The instances of 'Functor' for lists, 'Data.Maybe.Maybe' and 'System.IO.IO'
174 defined in the "Prelude" satisfy these laws.
175 -}
176
177 class  Functor f  where
178     fmap        :: (a -> b) -> f a -> f b
179
180     -- | Replace all locations in the input with the same value.
181     -- The default definition is @'fmap' . 'const'@, but this may be
182     -- overridden with a more efficient version.
183     (<$)        :: a -> f b -> f a
184     (<$)        =  fmap . const
185
186 {- | The 'Monad' class defines the basic operations over a /monad/,
187 a concept from a branch of mathematics known as /category theory/.
188 From the perspective of a Haskell programmer, however, it is best to
189 think of a monad as an /abstract datatype/ of actions.
190 Haskell's @do@ expressions provide a convenient syntax for writing
191 monadic expressions.
192
193 Minimal complete definition: '>>=' and 'return'.
194
195 Instances of 'Monad' should satisfy the following laws:
196
197 > return a >>= k  ==  k a
198 > m >>= return  ==  m
199 > m >>= (\x -> k x >>= h)  ==  (m >>= k) >>= h
200
201 Instances of both 'Monad' and 'Functor' should additionally satisfy the law:
202
203 > fmap f xs  ==  xs >>= return . f
204
205 The instances of 'Monad' for lists, 'Data.Maybe.Maybe' and 'System.IO.IO'
206 defined in the "Prelude" satisfy these laws.
207 -}
208
209 class  Monad m  where
210     -- | Sequentially compose two actions, passing any value produced
211     -- by the first as an argument to the second.
212     (>>=)       :: forall a b. m a -> (a -> m b) -> m b
213     -- | Sequentially compose two actions, discarding any value produced
214     -- by the first, like sequencing operators (such as the semicolon)
215     -- in imperative languages.
216     (>>)        :: forall a b. m a -> m b -> m b
217         -- Explicit for-alls so that we know what order to
218         -- give type arguments when desugaring
219
220     -- | Inject a value into the monadic type.
221     return      :: a -> m a
222     -- | Fail with a message.  This operation is not part of the
223     -- mathematical definition of a monad, but is invoked on pattern-match
224     -- failure in a @do@ expression.
225     fail        :: String -> m a
226
227     {-# INLINE (>>) #-}
228     m >> k      = m >>= \_ -> k
229     fail s      = error s
230 \end{code}
231
232
233 %*********************************************************
234 %*                                                      *
235 \subsection{The list type}
236 %*                                                      *
237 %*********************************************************
238
239 \begin{code}
240 instance Functor [] where
241     fmap = map
242
243 instance  Monad []  where
244     m >>= k             = foldr ((++) . k) [] m
245     m >> k              = foldr ((++) . (\ _ -> k)) [] m
246     return x            = [x]
247     fail _              = []
248 \end{code}
249
250 A few list functions that appear here because they are used here.
251 The rest of the prelude list functions are in GHC.List.
252
253 ----------------------------------------------
254 --      foldr/build/augment
255 ----------------------------------------------
256   
257 \begin{code}
258 -- | 'foldr', applied to a binary operator, a starting value (typically
259 -- the right-identity of the operator), and a list, reduces the list
260 -- using the binary operator, from right to left:
261 --
262 -- > foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)
263
264 foldr            :: (a -> b -> b) -> b -> [a] -> b
265 -- foldr _ z []     =  z
266 -- foldr f z (x:xs) =  f x (foldr f z xs)
267 {-# INLINE [0] foldr #-}
268 -- Inline only in the final stage, after the foldr/cons rule has had a chance
269 -- Also note that we inline it when it has *two* parameters, which are the 
270 -- ones we are keen about specialising!
271 foldr k z = go
272           where
273             go []     = z
274             go (y:ys) = y `k` go ys
275
276 -- | A list producer that can be fused with 'foldr'.
277 -- This function is merely
278 --
279 -- >    build g = g (:) []
280 --
281 -- but GHC's simplifier will transform an expression of the form
282 -- @'foldr' k z ('build' g)@, which may arise after inlining, to @g k z@,
283 -- which avoids producing an intermediate list.
284
285 build   :: forall a. (forall b. (a -> b -> b) -> b -> b) -> [a]
286 {-# INLINE [1] build #-}
287         -- The INLINE is important, even though build is tiny,
288         -- because it prevents [] getting inlined in the version that
289         -- appears in the interface file.  If [] *is* inlined, it
290         -- won't match with [] appearing in rules in an importing module.
291         --
292         -- The "1" says to inline in phase 1
293
294 build g = g (:) []
295
296 -- | A list producer that can be fused with 'foldr'.
297 -- This function is merely
298 --
299 -- >    augment g xs = g (:) xs
300 --
301 -- but GHC's simplifier will transform an expression of the form
302 -- @'foldr' k z ('augment' g xs)@, which may arise after inlining, to
303 -- @g k ('foldr' k z xs)@, which avoids producing an intermediate list.
304
305 augment :: forall a. (forall b. (a->b->b) -> b -> b) -> [a] -> [a]
306 {-# INLINE [1] augment #-}
307 augment g xs = g (:) xs
308
309 {-# RULES
310 "fold/build"    forall k z (g::forall b. (a->b->b) -> b -> b) . 
311                 foldr k z (build g) = g k z
312
313 "foldr/augment" forall k z xs (g::forall b. (a->b->b) -> b -> b) . 
314                 foldr k z (augment g xs) = g k (foldr k z xs)
315
316 "foldr/id"                        foldr (:) [] = \x  -> x
317 "foldr/app"     [1] forall ys. foldr (:) ys = \xs -> xs ++ ys
318         -- Only activate this from phase 1, because that's
319         -- when we disable the rule that expands (++) into foldr
320
321 -- The foldr/cons rule looks nice, but it can give disastrously
322 -- bloated code when commpiling
323 --      array (a,b) [(1,2), (2,2), (3,2), ...very long list... ]
324 -- i.e. when there are very very long literal lists
325 -- So I've disabled it for now. We could have special cases
326 -- for short lists, I suppose.
327 -- "foldr/cons" forall k z x xs. foldr k z (x:xs) = k x (foldr k z xs)
328
329 "foldr/single"  forall k z x. foldr k z [x] = k x z
330 "foldr/nil"     forall k z.   foldr k z []  = z 
331
332 "augment/build" forall (g::forall b. (a->b->b) -> b -> b)
333                        (h::forall b. (a->b->b) -> b -> b) .
334                        augment g (build h) = build (\c n -> g c (h c n))
335 "augment/nil"   forall (g::forall b. (a->b->b) -> b -> b) .
336                         augment g [] = build g
337  #-}
338
339 -- This rule is true, but not (I think) useful:
340 --      augment g (augment h t) = augment (\cn -> g c (h c n)) t
341 \end{code}
342
343
344 ----------------------------------------------
345 --              map     
346 ----------------------------------------------
347
348 \begin{code}
349 -- | 'map' @f xs@ is the list obtained by applying @f@ to each element
350 -- of @xs@, i.e.,
351 --
352 -- > map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn]
353 -- > map f [x1, x2, ...] == [f x1, f x2, ...]
354
355 map :: (a -> b) -> [a] -> [b]
356 map _ []     = []
357 map f (x:xs) = f x : map f xs
358
359 -- Note eta expanded
360 mapFB ::  (elt -> lst -> lst) -> (a -> elt) -> a -> lst -> lst
361 {-# INLINE [0] mapFB #-}
362 mapFB c f x ys = c (f x) ys
363
364 -- The rules for map work like this.
365 -- 
366 -- Up to (but not including) phase 1, we use the "map" rule to
367 -- rewrite all saturated applications of map with its build/fold 
368 -- form, hoping for fusion to happen.
369 -- In phase 1 and 0, we switch off that rule, inline build, and
370 -- switch on the "mapList" rule, which rewrites the foldr/mapFB
371 -- thing back into plain map.  
372 --
373 -- It's important that these two rules aren't both active at once 
374 -- (along with build's unfolding) else we'd get an infinite loop 
375 -- in the rules.  Hence the activation control below.
376 --
377 -- The "mapFB" rule optimises compositions of map.
378 --
379 -- This same pattern is followed by many other functions: 
380 -- e.g. append, filter, iterate, repeat, etc.
381
382 {-# RULES
383 "map"       [~1] forall f xs.   map f xs                = build (\c n -> foldr (mapFB c f) n xs)
384 "mapList"   [1]  forall f.      foldr (mapFB (:) f) []  = map f
385 "mapFB"     forall c f g.       mapFB (mapFB c f) g     = mapFB c (f.g) 
386   #-}
387 \end{code}
388
389
390 ----------------------------------------------
391 --              append  
392 ----------------------------------------------
393 \begin{code}
394 -- | Append two lists, i.e.,
395 --
396 -- > [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn]
397 -- > [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]
398 --
399 -- If the first list is not finite, the result is the first list.
400
401 (++) :: [a] -> [a] -> [a]
402 (++) []     ys = ys
403 (++) (x:xs) ys = x : xs ++ ys
404
405 {-# RULES
406 "++"    [~1] forall xs ys. xs ++ ys = augment (\c n -> foldr c n xs) ys
407   #-}
408
409 \end{code}
410
411
412 %*********************************************************
413 %*                                                      *
414 \subsection{Type @Bool@}
415 %*                                                      *
416 %*********************************************************
417
418 \begin{code}
419 -- |'otherwise' is defined as the value 'True'.  It helps to make
420 -- guards more readable.  eg.
421 --
422 -- >  f x | x < 0     = ...
423 -- >      | otherwise = ...
424 otherwise               :: Bool
425 otherwise               =  True
426 \end{code}
427
428 %*********************************************************
429 %*                                                      *
430 \subsection{Type @Char@ and @String@}
431 %*                                                      *
432 %*********************************************************
433
434 \begin{code}
435 -- | A 'String' is a list of characters.  String constants in Haskell are values
436 -- of type 'String'.
437 --
438 type String = [Char]
439
440 {-| The character type 'Char' is an enumeration whose values represent
441 Unicode (or equivalently ISO\/IEC 10646) characters
442 (see <http://www.unicode.org/> for details).
443 This set extends the ISO 8859-1 (Latin-1) character set
444 (the first 256 charachers), which is itself an extension of the ASCII
445 character set (the first 128 characters).
446 A character literal in Haskell has type 'Char'.
447
448 To convert a 'Char' to or from the corresponding 'Int' value defined
449 by Unicode, use 'Prelude.toEnum' and 'Prelude.fromEnum' from the
450 'Prelude.Enum' class respectively (or equivalently 'ord' and 'chr').
451 -}
452
453 {-# RULES
454 "x# `eqChar#` x#" forall x#. x# `eqChar#` x# = True
455 "x# `neChar#` x#" forall x#. x# `neChar#` x# = False
456 "x# `gtChar#` x#" forall x#. x# `gtChar#` x# = False
457 "x# `geChar#` x#" forall x#. x# `geChar#` x# = True
458 "x# `leChar#` x#" forall x#. x# `leChar#` x# = True
459 "x# `ltChar#` x#" forall x#. x# `ltChar#` x# = False
460   #-}
461
462 -- | The 'Prelude.toEnum' method restricted to the type 'Data.Char.Char'.
463 chr :: Int -> Char
464 chr i@(I# i#)
465  | int2Word# i# `leWord#` int2Word# 0x10FFFF# = C# (chr# i#)
466  | otherwise
467     = error ("Prelude.chr: bad argument: " ++ showSignedInt (I# 9#) i "")
468
469 unsafeChr :: Int -> Char
470 unsafeChr (I# i#) = C# (chr# i#)
471
472 -- | The 'Prelude.fromEnum' method restricted to the type 'Data.Char.Char'.
473 ord :: Char -> Int
474 ord (C# c#) = I# (ord# c#)
475 \end{code}
476
477 String equality is used when desugaring pattern-matches against strings.
478
479 \begin{code}
480 eqString :: String -> String -> Bool
481 eqString []       []       = True
482 eqString (c1:cs1) (c2:cs2) = c1 == c2 && cs1 `eqString` cs2
483 eqString _        _        = False
484
485 {-# RULES "eqString" (==) = eqString #-}
486 -- eqString also has a BuiltInRule in PrelRules.lhs:
487 --      eqString (unpackCString# (Lit s1)) (unpackCString# (Lit s2) = s1==s2
488 \end{code}
489
490
491 %*********************************************************
492 %*                                                      *
493 \subsection{Type @Int@}
494 %*                                                      *
495 %*********************************************************
496
497 \begin{code}
498 zeroInt, oneInt, twoInt, maxInt, minInt :: Int
499 zeroInt = I# 0#
500 oneInt  = I# 1#
501 twoInt  = I# 2#
502
503 {- Seems clumsy. Should perhaps put minInt and MaxInt directly into MachDeps.h -}
504 #if WORD_SIZE_IN_BITS == 31
505 minInt  = I# (-0x40000000#)
506 maxInt  = I# 0x3FFFFFFF#
507 #elif WORD_SIZE_IN_BITS == 32
508 minInt  = I# (-0x80000000#)
509 maxInt  = I# 0x7FFFFFFF#
510 #else 
511 minInt  = I# (-0x8000000000000000#)
512 maxInt  = I# 0x7FFFFFFFFFFFFFFF#
513 #endif
514
515 instance Eq Int where
516     (==) = eqInt
517     (/=) = neInt
518
519 instance Ord Int where
520     compare = compareInt
521     (<)     = ltInt
522     (<=)    = leInt
523     (>=)    = geInt
524     (>)     = gtInt
525
526 compareInt :: Int -> Int -> Ordering
527 (I# x#) `compareInt` (I# y#) = compareInt# x# y#
528
529 compareInt# :: Int# -> Int# -> Ordering
530 compareInt# x# y#
531     | x# <#  y# = LT
532     | x# ==# y# = EQ
533     | otherwise = GT
534 \end{code}
535
536
537 %*********************************************************
538 %*                                                      *
539 \subsection{The function type}
540 %*                                                      *
541 %*********************************************************
542
543 \begin{code}
544 -- | Identity function.
545 id                      :: a -> a
546 id x                    =  x
547
548 -- | The call '(lazy e)' means the same as 'e', but 'lazy' has a 
549 -- magical strictness property: it is lazy in its first argument, 
550 -- even though its semantics is strict.
551 lazy :: a -> a
552 lazy x = x
553 -- Implementation note: its strictness and unfolding are over-ridden
554 -- by the definition in MkId.lhs; in both cases to nothing at all.
555 -- That way, 'lazy' does not get inlined, and the strictness analyser
556 -- sees it as lazy.  Then the worker/wrapper phase inlines it.
557 -- Result: happiness
558
559 -- Assertion function.  This simply ignores its boolean argument.
560 -- The compiler may rewrite it to @('assertError' line)@.
561
562 -- | If the first argument evaluates to 'True', then the result is the
563 -- second argument.  Otherwise an 'AssertionFailed' exception is raised,
564 -- containing a 'String' with the source file and line number of the
565 -- call to 'assert'.
566 --
567 -- Assertions can normally be turned on or off with a compiler flag
568 -- (for GHC, assertions are normally on unless optimisation is turned on 
569 -- with @-O@ or the @-fignore-asserts@
570 -- option is given).  When assertions are turned off, the first
571 -- argument to 'assert' is ignored, and the second argument is
572 -- returned as the result.
573
574 --      SLPJ: in 5.04 etc 'assert' is in GHC.Prim,
575 --      but from Template Haskell onwards it's simply
576 --      defined here in Base.lhs
577 assert :: Bool -> a -> a
578 assert _pred r = r
579
580 breakpoint :: a -> a
581 breakpoint r = r
582
583 breakpointCond :: Bool -> a -> a
584 breakpointCond _ r = r
585
586 data Opaque = forall a. O a
587
588 -- | Constant function.
589 const                   :: a -> b -> a
590 const x _               =  x
591
592 -- | Function composition.
593 {-# INLINE (.) #-}
594 -- Make sure it has TWO args only on the left, so that it inlines
595 -- when applied to two functions, even if there is no final argument
596 (.)    :: (b -> c) -> (a -> b) -> a -> c
597 (.) f g = \x -> f (g x)
598
599 -- | @'flip' f@ takes its (first) two arguments in the reverse order of @f@.
600 flip                    :: (a -> b -> c) -> b -> a -> c
601 flip f x y              =  f y x
602
603 -- | Application operator.  This operator is redundant, since ordinary
604 -- application @(f x)@ means the same as @(f '$' x)@. However, '$' has
605 -- low, right-associative binding precedence, so it sometimes allows
606 -- parentheses to be omitted; for example:
607 --
608 -- >     f $ g $ h x  =  f (g (h x))
609 --
610 -- It is also useful in higher-order situations, such as @'map' ('$' 0) xs@,
611 -- or @'Data.List.zipWith' ('$') fs xs@.
612 {-# INLINE ($) #-}
613 ($)                     :: (a -> b) -> a -> b
614 f $ x                   =  f x
615
616 -- | @'until' p f@ yields the result of applying @f@ until @p@ holds.
617 until                   :: (a -> Bool) -> (a -> a) -> a -> a
618 until p f x | p x       =  x
619             | otherwise =  until p f (f x)
620
621 -- | 'asTypeOf' is a type-restricted version of 'const'.  It is usually
622 -- used as an infix operator, and its typing forces its first argument
623 -- (which is usually overloaded) to have the same type as the second.
624 asTypeOf                :: a -> a -> a
625 asTypeOf                =  const
626 \end{code}
627
628 %*********************************************************
629 %*                                                      *
630 \subsection{@Functor@ and @Monad@ instances for @IO@}
631 %*                                                      *
632 %*********************************************************
633
634 \begin{code}
635 instance  Functor IO where
636    fmap f x = x >>= (return . f)
637
638 instance  Monad IO  where
639     {-# INLINE return #-}
640     {-# INLINE (>>)   #-}
641     {-# INLINE (>>=)  #-}
642     m >> k    = m >>= \ _ -> k
643     return    = returnIO
644     (>>=)     = bindIO
645     fail s    = GHC.IO.failIO s
646
647 returnIO :: a -> IO a
648 returnIO x = IO $ \ s -> (# s, x #)
649
650 bindIO :: IO a -> (a -> IO b) -> IO b
651 bindIO (IO m) k = IO $ \ s -> case m s of (# new_s, a #) -> unIO (k a) new_s
652
653 thenIO :: IO a -> IO b -> IO b
654 thenIO (IO m) k = IO $ \ s -> case m s of (# new_s, _ #) -> unIO k new_s
655
656 unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
657 unIO (IO a) = a
658 \end{code}
659
660 %*********************************************************
661 %*                                                      *
662 \subsection{@getTag@}
663 %*                                                      *
664 %*********************************************************
665
666 Returns the 'tag' of a constructor application; this function is used
667 by the deriving code for Eq, Ord and Enum.
668
669 The primitive dataToTag# requires an evaluated constructor application
670 as its argument, so we provide getTag as a wrapper that performs the
671 evaluation before calling dataToTag#.  We could have dataToTag#
672 evaluate its argument, but we prefer to do it this way because (a)
673 dataToTag# can be an inline primop if it doesn't need to do any
674 evaluation, and (b) we want to expose the evaluation to the
675 simplifier, because it might be possible to eliminate the evaluation
676 in the case when the argument is already known to be evaluated.
677
678 \begin{code}
679 {-# INLINE getTag #-}
680 getTag :: a -> Int#
681 getTag x = x `seq` dataToTag# x
682 \end{code}
683
684 %*********************************************************
685 %*                                                      *
686 \subsection{Numeric primops}
687 %*                                                      *
688 %*********************************************************
689
690 \begin{code}
691 divInt# :: Int# -> Int# -> Int#
692 x# `divInt#` y#
693         -- Be careful NOT to overflow if we do any additional arithmetic
694         -- on the arguments...  the following  previous version of this
695         -- code has problems with overflow:
696 --    | (x# ># 0#) && (y# <# 0#) = ((x# -# y#) -# 1#) `quotInt#` y#
697 --    | (x# <# 0#) && (y# ># 0#) = ((x# -# y#) +# 1#) `quotInt#` y#
698     | (x# ># 0#) && (y# <# 0#) = ((x# -# 1#) `quotInt#` y#) -# 1#
699     | (x# <# 0#) && (y# ># 0#) = ((x# +# 1#) `quotInt#` y#) -# 1#
700     | otherwise                = x# `quotInt#` y#
701
702 modInt# :: Int# -> Int# -> Int#
703 x# `modInt#` y#
704     | (x# ># 0#) && (y# <# 0#) ||
705       (x# <# 0#) && (y# ># 0#)    = if r# /=# 0# then r# +# y# else 0#
706     | otherwise                   = r#
707     where
708     !r# = x# `remInt#` y#
709 \end{code}
710
711 Definitions of the boxed PrimOps; these will be
712 used in the case of partial applications, etc.
713
714 \begin{code}
715 {-# INLINE eqInt #-}
716 {-# INLINE neInt #-}
717 {-# INLINE gtInt #-}
718 {-# INLINE geInt #-}
719 {-# INLINE ltInt #-}
720 {-# INLINE leInt #-}
721 {-# INLINE plusInt #-}
722 {-# INLINE minusInt #-}
723 {-# INLINE timesInt #-}
724 {-# INLINE quotInt #-}
725 {-# INLINE remInt #-}
726 {-# INLINE negateInt #-}
727
728 plusInt, minusInt, timesInt, quotInt, remInt, divInt, modInt :: Int -> Int -> Int
729 (I# x) `plusInt`  (I# y) = I# (x +# y)
730 (I# x) `minusInt` (I# y) = I# (x -# y)
731 (I# x) `timesInt` (I# y) = I# (x *# y)
732 (I# x) `quotInt`  (I# y) = I# (x `quotInt#` y)
733 (I# x) `remInt`   (I# y) = I# (x `remInt#`  y)
734 (I# x) `divInt`   (I# y) = I# (x `divInt#`  y)
735 (I# x) `modInt`   (I# y) = I# (x `modInt#`  y)
736
737 {-# RULES
738 "x# +# 0#" forall x#. x# +# 0# = x#
739 "0# +# x#" forall x#. 0# +# x# = x#
740 "x# -# 0#" forall x#. x# -# 0# = x#
741 "x# -# x#" forall x#. x# -# x# = 0#
742 "x# *# 0#" forall x#. x# *# 0# = 0#
743 "0# *# x#" forall x#. 0# *# x# = 0#
744 "x# *# 1#" forall x#. x# *# 1# = x#
745 "1# *# x#" forall x#. 1# *# x# = x#
746   #-}
747
748 negateInt :: Int -> Int
749 negateInt (I# x) = I# (negateInt# x)
750
751 gtInt, geInt, eqInt, neInt, ltInt, leInt :: Int -> Int -> Bool
752 (I# x) `gtInt` (I# y) = x >#  y
753 (I# x) `geInt` (I# y) = x >=# y
754 (I# x) `eqInt` (I# y) = x ==# y
755 (I# x) `neInt` (I# y) = x /=# y
756 (I# x) `ltInt` (I# y) = x <#  y
757 (I# x) `leInt` (I# y) = x <=# y
758
759 {-# RULES
760 "x# ># x#"  forall x#. x# >#  x# = False
761 "x# >=# x#" forall x#. x# >=# x# = True
762 "x# ==# x#" forall x#. x# ==# x# = True
763 "x# /=# x#" forall x#. x# /=# x# = False
764 "x# <# x#"  forall x#. x# <#  x# = False
765 "x# <=# x#" forall x#. x# <=# x# = True
766   #-}
767
768 {-# RULES
769 "plusFloat x 0.0"   forall x#. plusFloat#  x#   0.0# = x#
770 "plusFloat 0.0 x"   forall x#. plusFloat#  0.0# x#   = x#
771 "minusFloat x 0.0"  forall x#. minusFloat# x#   0.0# = x#
772 "minusFloat x x"    forall x#. minusFloat# x#   x#   = 0.0#
773 "timesFloat x 0.0"  forall x#. timesFloat# x#   0.0# = 0.0#
774 "timesFloat0.0 x"   forall x#. timesFloat# 0.0# x#   = 0.0#
775 "timesFloat x 1.0"  forall x#. timesFloat# x#   1.0# = x#
776 "timesFloat 1.0 x"  forall x#. timesFloat# 1.0# x#   = x#
777 "divideFloat x 1.0" forall x#. divideFloat# x#  1.0# = x#
778   #-}
779
780 {-# RULES
781 "plusDouble x 0.0"   forall x#. (+##) x#    0.0## = x#
782 "plusDouble 0.0 x"   forall x#. (+##) 0.0## x#    = x#
783 "minusDouble x 0.0"  forall x#. (-##) x#    0.0## = x#
784 "timesDouble x 1.0"  forall x#. (*##) x#    1.0## = x#
785 "timesDouble 1.0 x"  forall x#. (*##) 1.0## x#    = x#
786 "divideDouble x 1.0" forall x#. (/##) x#    1.0## = x#
787   #-}
788
789 {-
790 We'd like to have more rules, but for example:
791
792 This gives wrong answer (0) for NaN - NaN (should be NaN):
793     "minusDouble x x"    forall x#. (-##) x#    x#    = 0.0##
794
795 This gives wrong answer (0) for 0 * NaN (should be NaN):
796     "timesDouble 0.0 x"  forall x#. (*##) 0.0## x#    = 0.0##
797
798 This gives wrong answer (0) for NaN * 0 (should be NaN):
799     "timesDouble x 0.0"  forall x#. (*##) x#    0.0## = 0.0##
800
801 These are tested by num014.
802 -}
803
804 -- Wrappers for the shift operations.  The uncheckedShift# family are
805 -- undefined when the amount being shifted by is greater than the size
806 -- in bits of Int#, so these wrappers perform a check and return
807 -- either zero or -1 appropriately.
808 --
809 -- Note that these wrappers still produce undefined results when the
810 -- second argument (the shift amount) is negative.
811
812 -- | Shift the argument left by the specified number of bits
813 -- (which must be non-negative).
814 shiftL# :: Word# -> Int# -> Word#
815 a `shiftL#` b   | b >=# WORD_SIZE_IN_BITS# = int2Word# 0#
816                 | otherwise                = a `uncheckedShiftL#` b
817
818 -- | Shift the argument right by the specified number of bits
819 -- (which must be non-negative).
820 shiftRL# :: Word# -> Int# -> Word#
821 a `shiftRL#` b  | b >=# WORD_SIZE_IN_BITS# = int2Word# 0#
822                 | otherwise                = a `uncheckedShiftRL#` b
823
824 -- | Shift the argument left by the specified number of bits
825 -- (which must be non-negative).
826 iShiftL# :: Int# -> Int# -> Int#
827 a `iShiftL#` b  | b >=# WORD_SIZE_IN_BITS# = 0#
828                 | otherwise                = a `uncheckedIShiftL#` b
829
830 -- | Shift the argument right (signed) by the specified number of bits
831 -- (which must be non-negative).
832 iShiftRA# :: Int# -> Int# -> Int#
833 a `iShiftRA#` b | b >=# WORD_SIZE_IN_BITS# = if a <# 0# then (-1#) else 0#
834                 | otherwise                = a `uncheckedIShiftRA#` b
835
836 -- | Shift the argument right (unsigned) by the specified number of bits
837 -- (which must be non-negative).
838 iShiftRL# :: Int# -> Int# -> Int#
839 a `iShiftRL#` b | b >=# WORD_SIZE_IN_BITS# = 0#
840                 | otherwise                = a `uncheckedIShiftRL#` b
841
842 #if WORD_SIZE_IN_BITS == 32
843 {-# RULES
844 "narrow32Int#"  forall x#. narrow32Int#   x# = x#
845 "narrow32Word#" forall x#. narrow32Word#   x# = x#
846    #-}
847 #endif
848
849 {-# RULES
850 "int2Word2Int"  forall x#. int2Word# (word2Int# x#) = x#
851 "word2Int2Word" forall x#. word2Int# (int2Word# x#) = x#
852   #-}
853 \end{code}
854
855
856 %********************************************************
857 %*                                                      *
858 \subsection{Unpacking C strings}
859 %*                                                      *
860 %********************************************************
861
862 This code is needed for virtually all programs, since it's used for
863 unpacking the strings of error messages.
864
865 \begin{code}
866 unpackCString# :: Addr# -> [Char]
867 {-# NOINLINE unpackCString# #-}
868     -- There's really no point in inlining this, ever, cos
869     -- the loop doesn't specialise in an interesting
870     -- But it's pretty small, so there's a danger that
871     -- it'll be inlined at every literal, which is a waste
872 unpackCString# addr 
873   = unpack 0#
874   where
875     unpack nh
876       | ch `eqChar#` '\0'# = []
877       | otherwise          = C# ch : unpack (nh +# 1#)
878       where
879         !ch = indexCharOffAddr# addr nh
880
881 unpackAppendCString# :: Addr# -> [Char] -> [Char]
882 {-# NOINLINE unpackAppendCString# #-}
883      -- See the NOINLINE note on unpackCString# 
884 unpackAppendCString# addr rest
885   = unpack 0#
886   where
887     unpack nh
888       | ch `eqChar#` '\0'# = rest
889       | otherwise          = C# ch : unpack (nh +# 1#)
890       where
891         !ch = indexCharOffAddr# addr nh
892
893 unpackFoldrCString# :: Addr# -> (Char  -> a -> a) -> a -> a 
894
895 -- Usually the unpack-list rule turns unpackFoldrCString# into unpackCString#
896
897 -- It also has a BuiltInRule in PrelRules.lhs:
898 --      unpackFoldrCString# "foo" c (unpackFoldrCString# "baz" c n)
899 --        =  unpackFoldrCString# "foobaz" c n
900
901 {-# NOINLINE unpackFoldrCString# #-}
902 -- At one stage I had NOINLINE [0] on the grounds that, unlike
903 -- unpackCString#, there *is* some point in inlining
904 -- unpackFoldrCString#, because we get better code for the
905 -- higher-order function call.  BUT there may be a lot of
906 -- literal strings, and making a separate 'unpack' loop for
907 -- each is highly gratuitous.  See nofib/real/anna/PrettyPrint.
908
909 unpackFoldrCString# addr f z 
910   = unpack 0#
911   where
912     unpack nh
913       | ch `eqChar#` '\0'# = z
914       | otherwise          = C# ch `f` unpack (nh +# 1#)
915       where
916         !ch = indexCharOffAddr# addr nh
917
918 unpackCStringUtf8# :: Addr# -> [Char]
919 unpackCStringUtf8# addr 
920   = unpack 0#
921   where
922     unpack nh
923       | ch `eqChar#` '\0'#   = []
924       | ch `leChar#` '\x7F'# = C# ch : unpack (nh +# 1#)
925       | ch `leChar#` '\xDF'# =
926           C# (chr# (((ord# ch                                  -# 0xC0#) `uncheckedIShiftL#`  6#) +#
927                      (ord# (indexCharOffAddr# addr (nh +# 1#)) -# 0x80#))) :
928           unpack (nh +# 2#)
929       | ch `leChar#` '\xEF'# =
930           C# (chr# (((ord# ch                                  -# 0xE0#) `uncheckedIShiftL#` 12#) +#
931                     ((ord# (indexCharOffAddr# addr (nh +# 1#)) -# 0x80#) `uncheckedIShiftL#`  6#) +#
932                      (ord# (indexCharOffAddr# addr (nh +# 2#)) -# 0x80#))) :
933           unpack (nh +# 3#)
934       | otherwise            =
935           C# (chr# (((ord# ch                                  -# 0xF0#) `uncheckedIShiftL#` 18#) +#
936                     ((ord# (indexCharOffAddr# addr (nh +# 1#)) -# 0x80#) `uncheckedIShiftL#` 12#) +#
937                     ((ord# (indexCharOffAddr# addr (nh +# 2#)) -# 0x80#) `uncheckedIShiftL#`  6#) +#
938                      (ord# (indexCharOffAddr# addr (nh +# 3#)) -# 0x80#))) :
939           unpack (nh +# 4#)
940       where
941         !ch = indexCharOffAddr# addr nh
942
943 unpackNBytes# :: Addr# -> Int# -> [Char]
944 unpackNBytes# _addr 0#   = []
945 unpackNBytes#  addr len# = unpack [] (len# -# 1#)
946     where
947      unpack acc i#
948       | i# <# 0#  = acc
949       | otherwise = 
950          case indexCharOffAddr# addr i# of
951             ch -> unpack (C# ch : acc) (i# -# 1#)
952
953 {-# RULES
954 "unpack"       [~1] forall a   . unpackCString# a             = build (unpackFoldrCString# a)
955 "unpack-list"  [1]  forall a   . unpackFoldrCString# a (:) [] = unpackCString# a
956 "unpack-append"     forall a n . unpackFoldrCString# a (:) n  = unpackAppendCString# a n
957
958 -- There's a built-in rule (in PrelRules.lhs) for
959 --      unpackFoldr "foo" c (unpackFoldr "baz" c n)  =  unpackFoldr "foobaz" c n
960
961   #-}
962 \end{code}
963
964 #ifdef __HADDOCK__
965 \begin{code}
966 -- | A special argument for the 'Control.Monad.ST.ST' type constructor,
967 -- indexing a state embedded in the 'Prelude.IO' monad by
968 -- 'Control.Monad.ST.stToIO'.
969 data RealWorld
970 \end{code}
971 #endif