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