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