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