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