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