Remove Control.Parallel*, now in package parallel
[haskell-directory.git] / GHC / IOBase.lhs
1 \begin{code}
2 {-# OPTIONS_GHC -fno-implicit-prelude #-}
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  GHC.IOBase
6 -- Copyright   :  (c) The University of Glasgow 1994-2002
7 -- License     :  see libraries/base/LICENSE
8 -- 
9 -- Maintainer  :  cvs-ghc@haskell.org
10 -- Stability   :  internal
11 -- Portability :  non-portable (GHC Extensions)
12 --
13 -- Definitions for the 'IO' monad and its friends.
14 --
15 -----------------------------------------------------------------------------
16
17 -- #hide
18 module GHC.IOBase(
19     IO(..), unIO, failIO, liftIO, bindIO, thenIO, returnIO, 
20     unsafePerformIO, unsafeInterleaveIO,
21     unsafeDupablePerformIO, unsafeDupableInterleaveIO,
22     noDuplicate,
23   
24         -- To and from from ST
25     stToIO, ioToST, unsafeIOToST, unsafeSTToIO,
26
27         -- References
28     IORef(..), newIORef, readIORef, writeIORef, 
29     IOArray(..), newIOArray, readIOArray, writeIOArray, unsafeReadIOArray, unsafeWriteIOArray,
30     MVar(..),
31
32         -- Handles, file descriptors,
33     FilePath,  
34     Handle(..), Handle__(..), HandleType(..), IOMode(..), FD, 
35     isReadableHandleType, isWritableHandleType, isReadWriteHandleType, showHandle,
36   
37         -- Buffers
38     Buffer(..), RawBuffer, BufferState(..), BufferList(..), BufferMode(..),
39     bufferIsWritable, bufferEmpty, bufferFull, 
40
41         -- Exceptions
42     Exception(..), ArithException(..), AsyncException(..), ArrayException(..),
43     stackOverflow, heapOverflow, throw, throwIO, ioException, 
44     IOError, IOException(..), IOErrorType(..), ioError, userError,
45     ExitCode(..) 
46   ) where
47         
48 import GHC.ST
49 import GHC.Arr  -- to derive Ix class
50 import GHC.Enum -- to derive Enum class
51 import GHC.STRef
52 import GHC.Base
53 --  import GHC.Num      -- To get fromInteger etc, needed because of -fno-implicit-prelude
54 import Data.Maybe  ( Maybe(..) )
55 import GHC.Show
56 import GHC.List
57 import GHC.Read
58 import Foreign.C.Types (CInt)
59
60 #ifndef __HADDOCK__
61 import {-# SOURCE #-} Data.Typeable     ( showsTypeRep )
62 import {-# SOURCE #-} Data.Dynamic      ( Dynamic, dynTypeRep )
63 #endif
64
65 -- ---------------------------------------------------------------------------
66 -- The IO Monad
67
68 {-
69 The IO Monad is just an instance of the ST monad, where the state is
70 the real world.  We use the exception mechanism (in GHC.Exception) to
71 implement IO exceptions.
72
73 NOTE: The IO representation is deeply wired in to various parts of the
74 system.  The following list may or may not be exhaustive:
75
76 Compiler  - types of various primitives in PrimOp.lhs
77
78 RTS       - forceIO (StgMiscClosures.hc)
79           - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast 
80             (Exceptions.hc)
81           - raiseAsync (Schedule.c)
82
83 Prelude   - GHC.IOBase.lhs, and several other places including
84             GHC.Exception.lhs.
85
86 Libraries - parts of hslibs/lang.
87
88 --SDM
89 -}
90
91 {-|
92 A value of type @'IO' a@ is a computation which, when performed,
93 does some I\/O before returning a value of type @a@.  
94
95 There is really only one way to \"perform\" an I\/O action: bind it to
96 @Main.main@ in your program.  When your program is run, the I\/O will
97 be performed.  It isn't possible to perform I\/O from an arbitrary
98 function, unless that function is itself in the 'IO' monad and called
99 at some point, directly or indirectly, from @Main.main@.
100
101 'IO' is a monad, so 'IO' actions can be combined using either the do-notation
102 or the '>>' and '>>=' operations from the 'Monad' class.
103 -}
104 newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #))
105
106 unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
107 unIO (IO a) = a
108
109 instance  Functor IO where
110    fmap f x = x >>= (return . f)
111
112 instance  Monad IO  where
113     {-# INLINE return #-}
114     {-# INLINE (>>)   #-}
115     {-# INLINE (>>=)  #-}
116     m >> k      =  m >>= \ _ -> k
117     return x    = returnIO x
118
119     m >>= k     = bindIO m k
120     fail s      = failIO s
121
122 failIO :: String -> IO a
123 failIO s = ioError (userError s)
124
125 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
126 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
127
128 bindIO :: IO a -> (a -> IO b) -> IO b
129 bindIO (IO m) k = IO ( \ s ->
130   case m s of 
131     (# new_s, a #) -> unIO (k a) new_s
132   )
133
134 thenIO :: IO a -> IO b -> IO b
135 thenIO (IO m) k = IO ( \ s ->
136   case m s of 
137     (# new_s, a #) -> unIO k new_s
138   )
139
140 returnIO :: a -> IO a
141 returnIO x = IO (\ s -> (# s, x #))
142
143 -- ---------------------------------------------------------------------------
144 -- Coercions between IO and ST
145
146 -- | A monad transformer embedding strict state transformers in the 'IO'
147 -- monad.  The 'RealWorld' parameter indicates that the internal state
148 -- used by the 'ST' computation is a special one supplied by the 'IO'
149 -- monad, and thus distinct from those used by invocations of 'runST'.
150 stToIO        :: ST RealWorld a -> IO a
151 stToIO (ST m) = IO m
152
153 ioToST        :: IO a -> ST RealWorld a
154 ioToST (IO m) = (ST m)
155
156 -- This relies on IO and ST having the same representation modulo the
157 -- constraint on the type of the state
158 --
159 unsafeIOToST        :: IO a -> ST s a
160 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
161
162 unsafeSTToIO :: ST s a -> IO a
163 unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
164
165 -- ---------------------------------------------------------------------------
166 -- Unsafe IO operations
167
168 {-|
169 This is the \"back door\" into the 'IO' monad, allowing
170 'IO' computation to be performed at any time.  For
171 this to be safe, the 'IO' computation should be
172 free of side effects and independent of its environment.
173
174 If the I\/O computation wrapped in 'unsafePerformIO'
175 performs side effects, then the relative order in which those side
176 effects take place (relative to the main I\/O trunk, or other calls to
177 'unsafePerformIO') is indeterminate.  You have to be careful when 
178 writing and compiling modules that use 'unsafePerformIO':
179
180   * Use @{\-\# NOINLINE foo \#-\}@ as a pragma on any function @foo@
181         that calls 'unsafePerformIO'.  If the call is inlined,
182         the I\/O may be performed more than once.
183
184   * Use the compiler flag @-fno-cse@ to prevent common sub-expression
185         elimination being performed on the module, which might combine
186         two side effects that were meant to be separate.  A good example
187         is using multiple global variables (like @test@ in the example below).
188
189   * Make sure that the either you switch off let-floating, or that the 
190         call to 'unsafePerformIO' cannot float outside a lambda.  For example, 
191         if you say:
192         @
193            f x = unsafePerformIO (newIORef [])
194         @
195         you may get only one reference cell shared between all calls to @f@.
196         Better would be
197         @
198            f x = unsafePerformIO (newIORef [x])
199         @
200         because now it can't float outside the lambda.
201
202 It is less well known that
203 'unsafePerformIO' is not type safe.  For example:
204
205 >     test :: IORef [a]
206 >     test = unsafePerformIO $ newIORef []
207 >     
208 >     main = do
209 >             writeIORef test [42]
210 >             bang <- readIORef test
211 >             print (bang :: [Char])
212
213 This program will core dump.  This problem with polymorphic references
214 is well known in the ML community, and does not arise with normal
215 monadic use of references.  There is no easy way to make it impossible
216 once you use 'unsafePerformIO'.  Indeed, it is
217 possible to write @coerce :: a -> b@ with the
218 help of 'unsafePerformIO'.  So be careful!
219 -}
220 unsafePerformIO :: IO a -> a
221 unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)
222
223 {-| 
224 This version of 'unsafePerformIO' is slightly more efficient,
225 because it omits the check that the IO is only being performed by a
226 single thread.  Hence, when you write 'unsafeDupablePerformIO',
227 there is a possibility that the IO action may be performed multiple
228 times (on a multiprocessor), and you should therefore ensure that
229 it gives the same results each time.
230 -}
231 {-# NOINLINE unsafeDupablePerformIO #-}
232 unsafeDupablePerformIO  :: IO a -> a
233 unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
234
235 -- Why do we NOINLINE unsafeDupablePerformIO?  See the comment with
236 -- GHC.ST.runST.  Essentially the issue is that the IO computation
237 -- inside unsafePerformIO must be atomic: it must either all run, or
238 -- not at all.  If we let the compiler see the application of the IO
239 -- to realWorld#, it might float out part of the IO.
240
241 -- Why is there a call to 'lazy' in unsafeDupablePerformIO?
242 -- If we don't have it, the demand analyser discovers the following strictness
243 -- for unsafeDupablePerformIO:  C(U(AV))
244 -- But then consider
245 --      unsafeDupablePerformIO (\s -> let r = f x in 
246 --                             case writeIORef v r s of (# s1, _ #) ->
247 --                             (# s1, r #)
248 -- The strictness analyser will find that the binding for r is strict,
249 -- (becuase of uPIO's strictness sig), and so it'll evaluate it before 
250 -- doing the writeIORef.  This actually makes tests/lib/should_run/memo002
251 -- get a deadlock!  
252 --
253 -- Solution: don't expose the strictness of unsafeDupablePerformIO,
254 --           by hiding it with 'lazy'
255
256 {-|
257 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
258 When passed a value of type @IO a@, the 'IO' will only be performed
259 when the value of the @a@ is demanded.  This is used to implement lazy
260 file reading, see 'System.IO.hGetContents'.
261 -}
262 {-# INLINE unsafeInterleaveIO #-}
263 unsafeInterleaveIO :: IO a -> IO a
264 unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)
265
266 -- We believe that INLINE on unsafeInterleaveIO is safe, because the
267 -- state from this IO thread is passed explicitly to the interleaved
268 -- IO, so it cannot be floated out and shared.
269
270 {-# INLINE unsafeDupableInterleaveIO #-}
271 unsafeDupableInterleaveIO :: IO a -> IO a
272 unsafeDupableInterleaveIO (IO m)
273   = IO ( \ s -> let
274                    r = case m s of (# _, res #) -> res
275                 in
276                 (# s, r #))
277
278 {-| 
279 Ensures that the suspensions under evaluation by the current thread
280 are unique; that is, the current thread is not evaluating anything
281 that is also under evaluation by another thread that has also executed
282 'noDuplicate'.
283
284 This operation is used in the definition of 'unsafePerformIO' to
285 prevent the IO action from being executed multiple times, which is usually
286 undesirable.
287 -}
288 noDuplicate :: IO ()
289 noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)
290
291 -- ---------------------------------------------------------------------------
292 -- Handle type
293
294 data MVar a = MVar (MVar# RealWorld a)
295 {- ^
296 An 'MVar' (pronounced \"em-var\") is a synchronising variable, used
297 for communication between concurrent threads.  It can be thought of
298 as a a box, which may be empty or full.
299 -}
300
301 -- pull in Eq (Mvar a) too, to avoid GHC.Conc being an orphan-instance module
302 instance Eq (MVar a) where
303         (MVar mvar1#) == (MVar mvar2#) = sameMVar# mvar1# mvar2#
304
305 --  A Handle is represented by (a reference to) a record 
306 --  containing the state of the I/O port/device. We record
307 --  the following pieces of info:
308
309 --    * type (read,write,closed etc.)
310 --    * the underlying file descriptor
311 --    * buffering mode 
312 --    * buffer, and spare buffers
313 --    * user-friendly name (usually the
314 --      FilePath used when IO.openFile was called)
315
316 -- Note: when a Handle is garbage collected, we want to flush its buffer
317 -- and close the OS file handle, so as to free up a (precious) resource.
318
319 -- | Haskell defines operations to read and write characters from and to files,
320 -- represented by values of type @Handle@.  Each value of this type is a
321 -- /handle/: a record used by the Haskell run-time system to /manage/ I\/O
322 -- with file system objects.  A handle has at least the following properties:
323 -- 
324 --  * whether it manages input or output or both;
325 --
326 --  * whether it is /open/, /closed/ or /semi-closed/;
327 --
328 --  * whether the object is seekable;
329 --
330 --  * whether buffering is disabled, or enabled on a line or block basis;
331 --
332 --  * a buffer (whose length may be zero).
333 --
334 -- Most handles will also have a current I\/O position indicating where the next
335 -- input or output operation will occur.  A handle is /readable/ if it
336 -- manages only input or both input and output; likewise, it is /writable/ if
337 -- it manages only output or both input and output.  A handle is /open/ when
338 -- first allocated.
339 -- Once it is closed it can no longer be used for either input or output,
340 -- though an implementation cannot re-use its storage while references
341 -- remain to it.  Handles are in the 'Show' and 'Eq' classes.  The string
342 -- produced by showing a handle is system dependent; it should include
343 -- enough information to identify the handle for debugging.  A handle is
344 -- equal according to '==' only to itself; no attempt
345 -- is made to compare the internal state of different handles for equality.
346 --
347 -- GHC note: a 'Handle' will be automatically closed when the garbage
348 -- collector detects that it has become unreferenced by the program.
349 -- However, relying on this behaviour is not generally recommended:
350 -- the garbage collector is unpredictable.  If possible, use explicit
351 -- an explicit 'hClose' to close 'Handle's when they are no longer
352 -- required.  GHC does not currently attempt to free up file
353 -- descriptors when they have run out, it is your responsibility to
354 -- ensure that this doesn't happen.
355
356 data Handle 
357   = FileHandle                          -- A normal handle to a file
358         FilePath                        -- the file (invariant)
359         !(MVar Handle__)
360
361   | DuplexHandle                        -- A handle to a read/write stream
362         FilePath                        -- file for a FIFO, otherwise some
363                                         --   descriptive string.
364         !(MVar Handle__)                -- The read side
365         !(MVar Handle__)                -- The write side
366
367 -- NOTES:
368 --    * A 'FileHandle' is seekable.  A 'DuplexHandle' may or may not be
369 --      seekable.
370
371 instance Eq Handle where
372  (FileHandle _ h1)     == (FileHandle _ h2)     = h1 == h2
373  (DuplexHandle _ h1 _) == (DuplexHandle _ h2 _) = h1 == h2
374  _ == _ = False 
375
376 type FD = CInt
377
378 data Handle__
379   = Handle__ {
380       haFD          :: !FD,                  -- file descriptor
381       haType        :: HandleType,           -- type (read/write/append etc.)
382       haIsBin       :: Bool,                 -- binary mode?
383       haIsStream    :: Bool,                 -- Windows : is this a socket?
384                                              -- Unix    : is O_NONBLOCK set?
385       haBufferMode  :: BufferMode,           -- buffer contains read/write data?
386       haBuffer      :: !(IORef Buffer),      -- the current buffer
387       haBuffers     :: !(IORef BufferList),  -- spare buffers
388       haOtherSide   :: Maybe (MVar Handle__) -- ptr to the write side of a 
389                                              -- duplex handle.
390     }
391
392 -- ---------------------------------------------------------------------------
393 -- Buffers
394
395 -- The buffer is represented by a mutable variable containing a
396 -- record, where the record contains the raw buffer and the start/end
397 -- points of the filled portion.  We use a mutable variable so that
398 -- the common operation of writing (or reading) some data from (to)
399 -- the buffer doesn't need to modify, and hence copy, the handle
400 -- itself, it just updates the buffer.  
401
402 -- There will be some allocation involved in a simple hPutChar in
403 -- order to create the new Buffer structure (below), but this is
404 -- relatively small, and this only has to be done once per write
405 -- operation.
406
407 -- The buffer contains its size - we could also get the size by
408 -- calling sizeOfMutableByteArray# on the raw buffer, but that tends
409 -- to be rounded up to the nearest Word.
410
411 type RawBuffer = MutableByteArray# RealWorld
412
413 -- INVARIANTS on a Buffer:
414 --
415 --   * A handle *always* has a buffer, even if it is only 1 character long
416 --     (an unbuffered handle needs a 1 character buffer in order to support
417 --      hLookAhead and hIsEOF).
418 --   * r <= w
419 --   * if r == w, then r == 0 && w == 0
420 --   * if state == WriteBuffer, then r == 0
421 --   * a write buffer is never full.  If an operation
422 --     fills up the buffer, it will always flush it before 
423 --     returning.
424 --   * a read buffer may be full as a result of hLookAhead.  In normal
425 --     operation, a read buffer always has at least one character of space.
426
427 data Buffer 
428   = Buffer {
429         bufBuf   :: RawBuffer,
430         bufRPtr  :: !Int,
431         bufWPtr  :: !Int,
432         bufSize  :: !Int,
433         bufState :: BufferState
434   }
435
436 data BufferState = ReadBuffer | WriteBuffer deriving (Eq)
437
438 -- we keep a few spare buffers around in a handle to avoid allocating
439 -- a new one for each hPutStr.  These buffers are *guaranteed* to be the
440 -- same size as the main buffer.
441 data BufferList 
442   = BufferListNil 
443   | BufferListCons RawBuffer BufferList
444
445
446 bufferIsWritable :: Buffer -> Bool
447 bufferIsWritable Buffer{ bufState=WriteBuffer } = True
448 bufferIsWritable _other = False
449
450 bufferEmpty :: Buffer -> Bool
451 bufferEmpty Buffer{ bufRPtr=r, bufWPtr=w } = r == w
452
453 -- only makes sense for a write buffer
454 bufferFull :: Buffer -> Bool
455 bufferFull b@Buffer{ bufWPtr=w } = w >= bufSize b
456
457 --  Internally, we classify handles as being one
458 --  of the following:
459
460 data HandleType
461  = ClosedHandle
462  | SemiClosedHandle
463  | ReadHandle
464  | WriteHandle
465  | AppendHandle
466  | ReadWriteHandle
467
468 isReadableHandleType ReadHandle         = True
469 isReadableHandleType ReadWriteHandle    = True
470 isReadableHandleType _                  = False
471
472 isWritableHandleType AppendHandle    = True
473 isWritableHandleType WriteHandle     = True
474 isWritableHandleType ReadWriteHandle = True
475 isWritableHandleType _               = False
476
477 isReadWriteHandleType ReadWriteHandle{} = True
478 isReadWriteHandleType _                 = False
479
480 -- | File and directory names are values of type 'String', whose precise
481 -- meaning is operating system dependent. Files can be opened, yielding a
482 -- handle which can then be used to operate on the contents of that file.
483
484 type FilePath = String
485
486 -- ---------------------------------------------------------------------------
487 -- Buffering modes
488
489 -- | Three kinds of buffering are supported: line-buffering, 
490 -- block-buffering or no-buffering.  These modes have the following
491 -- effects. For output, items are written out, or /flushed/,
492 -- from the internal buffer according to the buffer mode:
493 --
494 --  * /line-buffering/: the entire output buffer is flushed
495 --    whenever a newline is output, the buffer overflows, 
496 --    a 'System.IO.hFlush' is issued, or the handle is closed.
497 --
498 --  * /block-buffering/: the entire buffer is written out whenever it
499 --    overflows, a 'System.IO.hFlush' is issued, or the handle is closed.
500 --
501 --  * /no-buffering/: output is written immediately, and never stored
502 --    in the buffer.
503 --
504 -- An implementation is free to flush the buffer more frequently,
505 -- but not less frequently, than specified above.
506 -- The output buffer is emptied as soon as it has been written out.
507 --
508 -- Similarly, input occurs according to the buffer mode for the handle:
509 --
510 --  * /line-buffering/: when the buffer for the handle is not empty,
511 --    the next item is obtained from the buffer; otherwise, when the
512 --    buffer is empty, characters up to and including the next newline
513 --    character are read into the buffer.  No characters are available
514 --    until the newline character is available or the buffer is full.
515 --
516 --  * /block-buffering/: when the buffer for the handle becomes empty,
517 --    the next block of data is read into the buffer.
518 --
519 --  * /no-buffering/: the next input item is read and returned.
520 --    The 'System.IO.hLookAhead' operation implies that even a no-buffered
521 --    handle may require a one-character buffer.
522 --
523 -- The default buffering mode when a handle is opened is
524 -- implementation-dependent and may depend on the file system object
525 -- which is attached to that handle.
526 -- For most implementations, physical files will normally be block-buffered 
527 -- and terminals will normally be line-buffered.
528
529 data BufferMode  
530  = NoBuffering  -- ^ buffering is disabled if possible.
531  | LineBuffering
532                 -- ^ line-buffering should be enabled if possible.
533  | BlockBuffering (Maybe Int)
534                 -- ^ block-buffering should be enabled if possible.
535                 -- The size of the buffer is @n@ items if the argument
536                 -- is 'Just' @n@ and is otherwise implementation-dependent.
537    deriving (Eq, Ord, Read, Show)
538
539 -- ---------------------------------------------------------------------------
540 -- IORefs
541
542 -- |A mutable variable in the 'IO' monad
543 newtype IORef a = IORef (STRef RealWorld a)
544
545 -- explicit instance because Haddock can't figure out a derived one
546 instance Eq (IORef a) where
547   IORef x == IORef y = x == y
548
549 -- |Build a new 'IORef'
550 newIORef    :: a -> IO (IORef a)
551 newIORef v = stToIO (newSTRef v) >>= \ var -> return (IORef var)
552
553 -- |Read the value of an 'IORef'
554 readIORef   :: IORef a -> IO a
555 readIORef  (IORef var) = stToIO (readSTRef var)
556
557 -- |Write a new value into an 'IORef'
558 writeIORef  :: IORef a -> a -> IO ()
559 writeIORef (IORef var) v = stToIO (writeSTRef var v)
560
561 -- ---------------------------------------------------------------------------
562 -- | An 'IOArray' is a mutable, boxed, non-strict array in the 'IO' monad.  
563 -- The type arguments are as follows:
564 --
565 --  * @i@: the index type of the array (should be an instance of 'Ix')
566 --
567 --  * @e@: the element type of the array.
568 --
569 -- 
570
571 newtype IOArray i e = IOArray (STArray RealWorld i e)
572
573 -- explicit instance because Haddock can't figure out a derived one
574 instance Eq (IOArray i e) where
575   IOArray x == IOArray y = x == y
576
577 -- |Build a new 'IOArray'
578 newIOArray :: Ix i => (i,i) -> e -> IO (IOArray i e)
579 {-# INLINE newIOArray #-}
580 newIOArray lu init  = stToIO $ do {marr <- newSTArray lu init; return (IOArray marr)}
581
582 -- | Read a value from an 'IOArray'
583 unsafeReadIOArray  :: Ix i => IOArray i e -> Int -> IO e
584 {-# INLINE unsafeReadIOArray #-}
585 unsafeReadIOArray (IOArray marr) i = stToIO (unsafeReadSTArray marr i)
586
587 -- | Write a new value into an 'IOArray'
588 unsafeWriteIOArray :: Ix i => IOArray i e -> Int -> e -> IO ()
589 {-# INLINE unsafeWriteIOArray #-}
590 unsafeWriteIOArray (IOArray marr) i e = stToIO (unsafeWriteSTArray marr i e)
591
592 -- | Read a value from an 'IOArray'
593 readIOArray  :: Ix i => IOArray i e -> i -> IO e
594 readIOArray (IOArray marr) i = stToIO (readSTArray marr i)
595
596 -- | Write a new value into an 'IOArray'
597 writeIOArray :: Ix i => IOArray i e -> i -> e -> IO ()
598 writeIOArray (IOArray marr) i e = stToIO (writeSTArray marr i e)
599
600
601 -- ---------------------------------------------------------------------------
602 -- Show instance for Handles
603
604 -- handle types are 'show'n when printing error msgs, so
605 -- we provide a more user-friendly Show instance for it
606 -- than the derived one.
607
608 instance Show HandleType where
609   showsPrec p t =
610     case t of
611       ClosedHandle      -> showString "closed"
612       SemiClosedHandle  -> showString "semi-closed"
613       ReadHandle        -> showString "readable"
614       WriteHandle       -> showString "writable"
615       AppendHandle      -> showString "writable (append)"
616       ReadWriteHandle   -> showString "read-writable"
617
618 instance Show Handle where 
619   showsPrec p (FileHandle   file _)   = showHandle file
620   showsPrec p (DuplexHandle file _ _) = showHandle file
621
622 showHandle file = showString "{handle: " . showString file . showString "}"
623
624 -- ------------------------------------------------------------------------
625 -- Exception datatype and operations
626
627 -- |The type of exceptions.  Every kind of system-generated exception
628 -- has a constructor in the 'Exception' type, and values of other
629 -- types may be injected into 'Exception' by coercing them to
630 -- 'Data.Dynamic.Dynamic' (see the section on Dynamic Exceptions:
631 -- "Control.Exception\#DynamicExceptions").
632 data Exception
633   = ArithException      ArithException
634         -- ^Exceptions raised by arithmetic
635         -- operations.  (NOTE: GHC currently does not throw
636         -- 'ArithException's except for 'DivideByZero').
637   | ArrayException      ArrayException
638         -- ^Exceptions raised by array-related
639         -- operations.  (NOTE: GHC currently does not throw
640         -- 'ArrayException's).
641   | AssertionFailed     String
642         -- ^This exception is thrown by the
643         -- 'assert' operation when the condition
644         -- fails.  The 'String' argument contains the
645         -- location of the assertion in the source program.
646   | AsyncException      AsyncException
647         -- ^Asynchronous exceptions (see section on Asynchronous Exceptions: "Control.Exception\#AsynchronousExceptions").
648   | BlockedOnDeadMVar
649         -- ^The current thread was executing a call to
650         -- 'Control.Concurrent.MVar.takeMVar' that could never return,
651         -- because there are no other references to this 'MVar'.
652   | BlockedIndefinitely
653         -- ^The current thread was waiting to retry an atomic memory transaction
654         -- that could never become possible to complete because there are no other
655         -- threads referring to any of teh TVars involved.
656   | NestedAtomically
657         -- ^The runtime detected an attempt to nest one STM transaction
658         -- inside another one, presumably due to the use of 
659         -- 'unsafePeformIO' with 'atomically'.
660   | Deadlock
661         -- ^There are no runnable threads, so the program is
662         -- deadlocked.  The 'Deadlock' exception is
663         -- raised in the main thread only (see also: "Control.Concurrent").
664   | DynException        Dynamic
665         -- ^Dynamically typed exceptions (see section on Dynamic Exceptions: "Control.Exception\#DynamicExceptions").
666   | ErrorCall           String
667         -- ^The 'ErrorCall' exception is thrown by 'error'.  The 'String'
668         -- argument of 'ErrorCall' is the string passed to 'error' when it was
669         -- called.
670   | ExitException       ExitCode
671         -- ^The 'ExitException' exception is thrown by 'System.Exit.exitWith' (and
672         -- 'System.Exit.exitFailure').  The 'ExitCode' argument is the value passed 
673         -- to 'System.Exit.exitWith'.  An unhandled 'ExitException' exception in the
674         -- main thread will cause the program to be terminated with the given 
675         -- exit code.
676   | IOException         IOException
677         -- ^These are the standard IO exceptions generated by
678         -- Haskell\'s @IO@ operations.  See also "System.IO.Error".
679   | NoMethodError       String
680         -- ^An attempt was made to invoke a class method which has
681         -- no definition in this instance, and there was no default
682         -- definition given in the class declaration.  GHC issues a
683         -- warning when you compile an instance which has missing
684         -- methods.
685   | NonTermination
686         -- ^The current thread is stuck in an infinite loop.  This
687         -- exception may or may not be thrown when the program is
688         -- non-terminating.
689   | PatternMatchFail    String
690         -- ^A pattern matching failure.  The 'String' argument should contain a
691         -- descriptive message including the function name, source file
692         -- and line number.
693   | RecConError         String
694         -- ^An attempt was made to evaluate a field of a record
695         -- for which no value was given at construction time.  The
696         -- 'String' argument gives the location of the
697         -- record construction in the source program.
698   | RecSelError         String
699         -- ^A field selection was attempted on a constructor that
700         -- doesn\'t have the requested field.  This can happen with
701         -- multi-constructor records when one or more fields are
702         -- missing from some of the constructors.  The
703         -- 'String' argument gives the location of the
704         -- record selection in the source program.
705   | RecUpdError         String
706         -- ^An attempt was made to update a field in a record,
707         -- where the record doesn\'t have the requested field.  This can
708         -- only occur with multi-constructor records, when one or more
709         -- fields are missing from some of the constructors.  The
710         -- 'String' argument gives the location of the
711         -- record update in the source program.
712
713 -- |The type of arithmetic exceptions
714 data ArithException
715   = Overflow
716   | Underflow
717   | LossOfPrecision
718   | DivideByZero
719   | Denormal
720   deriving (Eq, Ord)
721
722
723 -- |Asynchronous exceptions
724 data AsyncException
725   = StackOverflow
726         -- ^The current thread\'s stack exceeded its limit.
727         -- Since an exception has been raised, the thread\'s stack
728         -- will certainly be below its limit again, but the
729         -- programmer should take remedial action
730         -- immediately.
731   | HeapOverflow
732         -- ^The program\'s heap is reaching its limit, and
733         -- the program should take action to reduce the amount of
734         -- live data it has. Notes:
735         --
736         --      * It is undefined which thread receives this exception.
737         --
738         --      * GHC currently does not throw 'HeapOverflow' exceptions.
739   | ThreadKilled
740         -- ^This exception is raised by another thread
741         -- calling 'Control.Concurrent.killThread', or by the system
742         -- if it needs to terminate the thread for some
743         -- reason.
744   deriving (Eq, Ord)
745
746 -- | Exceptions generated by array operations
747 data ArrayException
748   = IndexOutOfBounds    String
749         -- ^An attempt was made to index an array outside
750         -- its declared bounds.
751   | UndefinedElement    String
752         -- ^An attempt was made to evaluate an element of an
753         -- array that had not been initialized.
754   deriving (Eq, Ord)
755
756 stackOverflow, heapOverflow :: Exception -- for the RTS
757 stackOverflow = AsyncException StackOverflow
758 heapOverflow  = AsyncException HeapOverflow
759
760 instance Show ArithException where
761   showsPrec _ Overflow        = showString "arithmetic overflow"
762   showsPrec _ Underflow       = showString "arithmetic underflow"
763   showsPrec _ LossOfPrecision = showString "loss of precision"
764   showsPrec _ DivideByZero    = showString "divide by zero"
765   showsPrec _ Denormal        = showString "denormal"
766
767 instance Show AsyncException where
768   showsPrec _ StackOverflow   = showString "stack overflow"
769   showsPrec _ HeapOverflow    = showString "heap overflow"
770   showsPrec _ ThreadKilled    = showString "thread killed"
771
772 instance Show ArrayException where
773   showsPrec _ (IndexOutOfBounds s)
774         = showString "array index out of range"
775         . (if not (null s) then showString ": " . showString s
776                            else id)
777   showsPrec _ (UndefinedElement s)
778         = showString "undefined array element"
779         . (if not (null s) then showString ": " . showString s
780                            else id)
781
782 instance Show Exception where
783   showsPrec _ (IOException err)          = shows err
784   showsPrec _ (ArithException err)       = shows err
785   showsPrec _ (ArrayException err)       = shows err
786   showsPrec _ (ErrorCall err)            = showString err
787   showsPrec _ (ExitException err)        = showString "exit: " . shows err
788   showsPrec _ (NoMethodError err)        = showString err
789   showsPrec _ (PatternMatchFail err)     = showString err
790   showsPrec _ (RecSelError err)          = showString err
791   showsPrec _ (RecConError err)          = showString err
792   showsPrec _ (RecUpdError err)          = showString err
793   showsPrec _ (AssertionFailed err)      = showString err
794   showsPrec _ (DynException err)         = showString "exception :: " . showsTypeRep (dynTypeRep err)
795   showsPrec _ (AsyncException e)         = shows e
796   showsPrec _ (BlockedOnDeadMVar)        = showString "thread blocked indefinitely"
797   showsPrec _ (BlockedIndefinitely)      = showString "thread blocked indefinitely"
798   showsPrec _ (NestedAtomically)         = showString "Control.Concurrent.STM.atomically was nested"
799   showsPrec _ (NonTermination)           = showString "<<loop>>"
800   showsPrec _ (Deadlock)                 = showString "<<deadlock>>"
801
802 instance Eq Exception where
803   IOException e1      == IOException e2      = e1 == e2
804   ArithException e1   == ArithException e2   = e1 == e2
805   ArrayException e1   == ArrayException e2   = e1 == e2
806   ErrorCall e1        == ErrorCall e2        = e1 == e2
807   ExitException e1    == ExitException e2    = e1 == e2
808   NoMethodError e1    == NoMethodError e2    = e1 == e2
809   PatternMatchFail e1 == PatternMatchFail e2 = e1 == e2
810   RecSelError e1      == RecSelError e2      = e1 == e2
811   RecConError e1      == RecConError e2      = e1 == e2
812   RecUpdError e1      == RecUpdError e2      = e1 == e2
813   AssertionFailed e1  == AssertionFailed e2  = e1 == e2
814   DynException _      == DynException _      = False -- incomparable
815   AsyncException e1   == AsyncException e2   = e1 == e2
816   BlockedOnDeadMVar   == BlockedOnDeadMVar   = True
817   NonTermination      == NonTermination      = True
818   NestedAtomically    == NestedAtomically    = True
819   Deadlock            == Deadlock            = True
820   _                   == _                   = False
821
822 -- -----------------------------------------------------------------------------
823 -- The ExitCode type
824
825 -- We need it here because it is used in ExitException in the
826 -- Exception datatype (above).
827
828 data ExitCode
829   = ExitSuccess -- ^ indicates successful termination;
830   | ExitFailure Int
831                 -- ^ indicates program failure with an exit code.
832                 -- The exact interpretation of the code is
833                 -- operating-system dependent.  In particular, some values
834                 -- may be prohibited (e.g. 0 on a POSIX-compliant system).
835   deriving (Eq, Ord, Read, Show)
836
837 -- --------------------------------------------------------------------------
838 -- Primitive throw
839
840 -- | Throw an exception.  Exceptions may be thrown from purely
841 -- functional code, but may only be caught within the 'IO' monad.
842 throw :: Exception -> a
843 throw exception = raise# exception
844
845 -- | A variant of 'throw' that can be used within the 'IO' monad.
846 --
847 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
848 -- two functions are subtly different:
849 --
850 -- > throw e   `seq` x  ===> throw e
851 -- > throwIO e `seq` x  ===> x
852 --
853 -- The first example will cause the exception @e@ to be raised,
854 -- whereas the second one won\'t.  In fact, 'throwIO' will only cause
855 -- an exception to be raised when it is used within the 'IO' monad.
856 -- The 'throwIO' variant should be used in preference to 'throw' to
857 -- raise an exception within the 'IO' monad because it guarantees
858 -- ordering with respect to other 'IO' operations, whereas 'throw'
859 -- does not.
860 throwIO         :: Exception -> IO a
861 throwIO err     =  IO $ raiseIO# err
862
863 ioException     :: IOException -> IO a
864 ioException err =  IO $ raiseIO# (IOException err)
865
866 -- | Raise an 'IOError' in the 'IO' monad.
867 ioError         :: IOError -> IO a 
868 ioError         =  ioException
869
870 -- ---------------------------------------------------------------------------
871 -- IOError type
872
873 -- | The Haskell 98 type for exceptions in the 'IO' monad.
874 -- Any I\/O operation may raise an 'IOError' instead of returning a result.
875 -- For a more general type of exception, including also those that arise
876 -- in pure code, see 'Control.Exception.Exception'.
877 --
878 -- In Haskell 98, this is an opaque type.
879 type IOError = IOException
880
881 -- |Exceptions that occur in the @IO@ monad.
882 -- An @IOException@ records a more specific error type, a descriptive
883 -- string and maybe the handle that was used when the error was
884 -- flagged.
885 data IOException
886  = IOError {
887      ioe_handle   :: Maybe Handle,   -- the handle used by the action flagging 
888                                      -- the error.
889      ioe_type     :: IOErrorType,    -- what it was.
890      ioe_location :: String,         -- location.
891      ioe_description :: String,      -- error type specific information.
892      ioe_filename :: Maybe FilePath  -- filename the error is related to.
893    }
894
895 instance Eq IOException where
896   (IOError h1 e1 loc1 str1 fn1) == (IOError h2 e2 loc2 str2 fn2) = 
897     e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && fn1==fn2
898
899 -- | An abstract type that contains a value for each variant of 'IOError'.
900 data IOErrorType
901   -- Haskell 98:
902   = AlreadyExists
903   | NoSuchThing
904   | ResourceBusy
905   | ResourceExhausted
906   | EOF
907   | IllegalOperation
908   | PermissionDenied
909   | UserError
910   -- GHC only:
911   | UnsatisfiedConstraints
912   | SystemError
913   | ProtocolError
914   | OtherError
915   | InvalidArgument
916   | InappropriateType
917   | HardwareFault
918   | UnsupportedOperation
919   | TimeExpired
920   | ResourceVanished
921   | Interrupted
922   | DynIOError Dynamic -- cheap&cheerful extensible IO error type.
923
924 instance Eq IOErrorType where
925    x == y = 
926      case x of
927        DynIOError{} -> False -- from a strictness POV, compatible with a derived Eq inst?
928        _ -> getTag x ==# getTag y
929  
930 instance Show IOErrorType where
931   showsPrec _ e =
932     showString $
933     case e of
934       AlreadyExists     -> "already exists"
935       NoSuchThing       -> "does not exist"
936       ResourceBusy      -> "resource busy"
937       ResourceExhausted -> "resource exhausted"
938       EOF               -> "end of file"
939       IllegalOperation  -> "illegal operation"
940       PermissionDenied  -> "permission denied"
941       UserError         -> "user error"
942       HardwareFault     -> "hardware fault"
943       InappropriateType -> "inappropriate type"
944       Interrupted       -> "interrupted"
945       InvalidArgument   -> "invalid argument"
946       OtherError        -> "failed"
947       ProtocolError     -> "protocol error"
948       ResourceVanished  -> "resource vanished"
949       SystemError       -> "system error"
950       TimeExpired       -> "timeout"
951       UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise!
952       UnsupportedOperation -> "unsupported operation"
953       DynIOError{}      -> "unknown IO error"
954
955 -- | Construct an 'IOError' value with a string describing the error.
956 -- The 'fail' method of the 'IO' instance of the 'Monad' class raises a
957 -- 'userError', thus:
958 --
959 -- > instance Monad IO where 
960 -- >   ...
961 -- >   fail s = ioError (userError s)
962 --
963 userError       :: String  -> IOError
964 userError str   =  IOError Nothing UserError "" str Nothing
965
966 -- ---------------------------------------------------------------------------
967 -- Showing IOErrors
968
969 instance Show IOException where
970     showsPrec p (IOError hdl iot loc s fn) =
971       (case fn of
972          Nothing -> case hdl of
973                         Nothing -> id
974                         Just h  -> showsPrec p h . showString ": "
975          Just name -> showString name . showString ": ") .
976       (case loc of
977          "" -> id
978          _  -> showString loc . showString ": ") .
979       showsPrec p iot . 
980       (case s of
981          "" -> id
982          _  -> showString " (" . showString s . showString ")")
983
984 -- -----------------------------------------------------------------------------
985 -- IOMode type
986
987 data IOMode      =  ReadMode | WriteMode | AppendMode | ReadWriteMode
988                     deriving (Eq, Ord, Ix, Enum, Read, Show)
989 \end{code}