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