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