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