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