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