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