6fa596a5c30f6e71b21c9ba62fadcaced75d842f
[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 -- Why do we NOINLINE unsafePerformIO?  See the comment with
185 -- GHC.ST.runST.  Essentially the issue is that the IO computation
186 -- inside unsafePerformIO must be atomic: it must either all run, or
187 -- not at all.  If we let the compiler see the application of the IO
188 -- to realWorld#, it might float out part of the IO.
189
190 {-|
191 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
192 When passed a value of type @IO a@, the 'IO' will only be performed
193 when the value of the @a@ is demanded.  This is used to implement lazy
194 file reading, see 'System.IO.hGetContents'.
195 -}
196 {-# INLINE unsafeInterleaveIO #-}
197 unsafeInterleaveIO :: IO a -> IO a
198 unsafeInterleaveIO (IO m)
199   = IO ( \ s -> let
200                    r = case m s of (# _, res #) -> res
201                 in
202                 (# s, r #))
203
204 -- We believe that INLINE on unsafeInterleaveIO is safe, because the
205 -- state from this IO thread is passed explicitly to the interleaved
206 -- IO, so it cannot be floated out and shared.
207
208 -- ---------------------------------------------------------------------------
209 -- Handle type
210
211 data MVar a = MVar (MVar# RealWorld a)
212 {- ^
213 An 'MVar' (pronounced \"em-var\") is a synchronising variable, used
214 for communication between concurrent threads.  It can be thought of
215 as a a box, which may be empty or full.
216 -}
217
218 -- pull in Eq (Mvar a) too, to avoid GHC.Conc being an orphan-instance module
219 instance Eq (MVar a) where
220         (MVar mvar1#) == (MVar mvar2#) = sameMVar# mvar1# mvar2#
221
222 --  A Handle is represented by (a reference to) a record 
223 --  containing the state of the I/O port/device. We record
224 --  the following pieces of info:
225
226 --    * type (read,write,closed etc.)
227 --    * the underlying file descriptor
228 --    * buffering mode 
229 --    * buffer, and spare buffers
230 --    * user-friendly name (usually the
231 --      FilePath used when IO.openFile was called)
232
233 -- Note: when a Handle is garbage collected, we want to flush its buffer
234 -- and close the OS file handle, so as to free up a (precious) resource.
235
236 -- | Haskell defines operations to read and write characters from and to files,
237 -- represented by values of type @Handle@.  Each value of this type is a
238 -- /handle/: a record used by the Haskell run-time system to /manage/ I\/O
239 -- with file system objects.  A handle has at least the following properties:
240 -- 
241 --  * whether it manages input or output or both;
242 --
243 --  * whether it is /open/, /closed/ or /semi-closed/;
244 --
245 --  * whether the object is seekable;
246 --
247 --  * whether buffering is disabled, or enabled on a line or block basis;
248 --
249 --  * a buffer (whose length may be zero).
250 --
251 -- Most handles will also have a current I\/O position indicating where the next
252 -- input or output operation will occur.  A handle is /readable/ if it
253 -- manages only input or both input and output; likewise, it is /writable/ if
254 -- it manages only output or both input and output.  A handle is /open/ when
255 -- first allocated.
256 -- Once it is closed it can no longer be used for either input or output,
257 -- though an implementation cannot re-use its storage while references
258 -- remain to it.  Handles are in the 'Show' and 'Eq' classes.  The string
259 -- produced by showing a handle is system dependent; it should include
260 -- enough information to identify the handle for debugging.  A handle is
261 -- equal according to '==' only to itself; no attempt
262 -- is made to compare the internal state of different handles for equality.
263
264 data Handle 
265   = FileHandle                          -- A normal handle to a file
266         FilePath                        -- the file (invariant)
267         !(MVar Handle__)
268
269   | DuplexHandle                        -- A handle to a read/write stream
270         FilePath                        -- file for a FIFO, otherwise some
271                                         --   descriptive string.
272         !(MVar Handle__)                -- The read side
273         !(MVar Handle__)                -- The write side
274
275 -- NOTES:
276 --    * A 'FileHandle' is seekable.  A 'DuplexHandle' may or may not be
277 --      seekable.
278
279 instance Eq Handle where
280  (FileHandle _ h1)     == (FileHandle _ h2)     = h1 == h2
281  (DuplexHandle _ h1 _) == (DuplexHandle _ h2 _) = h1 == h2
282  _ == _ = False 
283
284 type FD = Int -- XXX ToDo: should be CInt
285
286 data Handle__
287   = Handle__ {
288       haFD          :: !FD,                  -- file descriptor
289       haType        :: HandleType,           -- type (read/write/append etc.)
290       haIsBin       :: Bool,                 -- binary mode?
291       haIsStream    :: Bool,                 -- is this a stream handle?
292       haBufferMode  :: BufferMode,           -- buffer contains read/write data?
293       haBuffer      :: !(IORef Buffer),      -- the current buffer
294       haBuffers     :: !(IORef BufferList),  -- spare buffers
295       haOtherSide   :: Maybe (MVar Handle__) -- ptr to the write side of a 
296                                              -- duplex handle.
297     }
298
299 -- ---------------------------------------------------------------------------
300 -- Buffers
301
302 -- The buffer is represented by a mutable variable containing a
303 -- record, where the record contains the raw buffer and the start/end
304 -- points of the filled portion.  We use a mutable variable so that
305 -- the common operation of writing (or reading) some data from (to)
306 -- the buffer doesn't need to modify, and hence copy, the handle
307 -- itself, it just updates the buffer.  
308
309 -- There will be some allocation involved in a simple hPutChar in
310 -- order to create the new Buffer structure (below), but this is
311 -- relatively small, and this only has to be done once per write
312 -- operation.
313
314 -- The buffer contains its size - we could also get the size by
315 -- calling sizeOfMutableByteArray# on the raw buffer, but that tends
316 -- to be rounded up to the nearest Word.
317
318 type RawBuffer = MutableByteArray# RealWorld
319
320 -- INVARIANTS on a Buffer:
321 --
322 --   * A handle *always* has a buffer, even if it is only 1 character long
323 --     (an unbuffered handle needs a 1 character buffer in order to support
324 --      hLookAhead and hIsEOF).
325 --   * r <= w
326 --   * if r == w, then r == 0 && w == 0
327 --   * if state == WriteBuffer, then r == 0
328 --   * a write buffer is never full.  If an operation
329 --     fills up the buffer, it will always flush it before 
330 --     returning.
331 --   * a read buffer may be full as a result of hLookAhead.  In normal
332 --     operation, a read buffer always has at least one character of space.
333
334 data Buffer 
335   = Buffer {
336         bufBuf   :: RawBuffer,
337         bufRPtr  :: !Int,
338         bufWPtr  :: !Int,
339         bufSize  :: !Int,
340         bufState :: BufferState
341   }
342
343 data BufferState = ReadBuffer | WriteBuffer deriving (Eq)
344
345 -- we keep a few spare buffers around in a handle to avoid allocating
346 -- a new one for each hPutStr.  These buffers are *guaranteed* to be the
347 -- same size as the main buffer.
348 data BufferList 
349   = BufferListNil 
350   | BufferListCons RawBuffer BufferList
351
352
353 bufferIsWritable :: Buffer -> Bool
354 bufferIsWritable Buffer{ bufState=WriteBuffer } = True
355 bufferIsWritable _other = False
356
357 bufferEmpty :: Buffer -> Bool
358 bufferEmpty Buffer{ bufRPtr=r, bufWPtr=w } = r == w
359
360 -- only makes sense for a write buffer
361 bufferFull :: Buffer -> Bool
362 bufferFull b@Buffer{ bufWPtr=w } = w >= bufSize b
363
364 --  Internally, we classify handles as being one
365 --  of the following:
366
367 data HandleType
368  = ClosedHandle
369  | SemiClosedHandle
370  | ReadHandle
371  | WriteHandle
372  | AppendHandle
373  | ReadWriteHandle
374
375 isReadableHandleType ReadHandle         = True
376 isReadableHandleType ReadWriteHandle    = True
377 isReadableHandleType _                  = False
378
379 isWritableHandleType AppendHandle    = True
380 isWritableHandleType WriteHandle     = True
381 isWritableHandleType ReadWriteHandle = True
382 isWritableHandleType _               = False
383
384 -- | File and directory names are values of type 'String', whose precise
385 -- meaning is operating system dependent. Files can be opened, yielding a
386 -- handle which can then be used to operate on the contents of that file.
387
388 type FilePath = String
389
390 -- ---------------------------------------------------------------------------
391 -- Buffering modes
392
393 -- | Three kinds of buffering are supported: line-buffering, 
394 -- block-buffering or no-buffering.  These modes have the following
395 -- effects. For output, items are written out, or /flushed/,
396 -- from the internal buffer according to the buffer mode:
397 --
398 --  * /line-buffering/: the entire output buffer is flushed
399 --    whenever a newline is output, the buffer overflows, 
400 --    a 'System.IO.hFlush' is issued, or the handle is closed.
401 --
402 --  * /block-buffering/: the entire buffer is written out whenever it
403 --    overflows, a 'System.IO.hFlush' is issued, or the handle is closed.
404 --
405 --  * /no-buffering/: output is written immediately, and never stored
406 --    in the buffer.
407 --
408 -- An implementation is free to flush the buffer more frequently,
409 -- but not less frequently, than specified above.
410 -- The output buffer is emptied as soon as it has been written out.
411 --
412 -- Similarly, input occurs according to the buffer mode for the handle:
413 --
414 --  * /line-buffering/: when the buffer for the handle is not empty,
415 --    the next item is obtained from the buffer; otherwise, when the
416 --    buffer is empty, characters up to and including the next newline
417 --    character are read into the buffer.  No characters are available
418 --    until the newline character is available or the buffer is full.
419 --
420 --  * /block-buffering/: when the buffer for the handle becomes empty,
421 --    the next block of data is read into the buffer.
422 --
423 --  * /no-buffering/: the next input item is read and returned.
424 --    The 'System.IO.hLookAhead' operation implies that even a no-buffered
425 --    handle may require a one-character buffer.
426 --
427 -- The default buffering mode when a handle is opened is
428 -- implementation-dependent and may depend on the file system object
429 -- which is attached to that handle.
430 -- For most implementations, physical files will normally be block-buffered 
431 -- and terminals will normally be line-buffered.
432
433 data BufferMode  
434  = NoBuffering  -- ^ buffering is disabled if possible.
435  | LineBuffering
436                 -- ^ line-buffering should be enabled if possible.
437  | BlockBuffering (Maybe Int)
438                 -- ^ block-buffering should be enabled if possible.
439                 -- The size of the buffer is @n@ items if the argument
440                 -- is 'Just' @n@ and is otherwise implementation-dependent.
441    deriving (Eq, Ord, Read, Show)
442
443 -- ---------------------------------------------------------------------------
444 -- IORefs
445
446 -- |A mutable variable in the 'IO' monad
447 newtype IORef a = IORef (STRef RealWorld a)
448
449 -- explicit instance because Haddock can't figure out a derived one
450 instance Eq (IORef a) where
451   IORef x == IORef y = x == y
452
453 -- |Build a new 'IORef'
454 newIORef    :: a -> IO (IORef a)
455 newIORef v = stToIO (newSTRef v) >>= \ var -> return (IORef var)
456
457 -- |Read the value of an 'IORef'
458 readIORef   :: IORef a -> IO a
459 readIORef  (IORef var) = stToIO (readSTRef var)
460
461 -- |Write a new value into an 'IORef'
462 writeIORef  :: IORef a -> a -> IO ()
463 writeIORef (IORef var) v = stToIO (writeSTRef var v)
464
465 -- ---------------------------------------------------------------------------
466 -- | An 'IOArray' is a mutable, boxed, non-strict array in the 'IO' monad.  
467 -- The type arguments are as follows:
468 --
469 --  * @i@: the index type of the array (should be an instance of 'Ix')
470 --
471 --  * @e@: the element type of the array.
472 --
473 -- 
474
475 newtype IOArray i e = IOArray (STArray RealWorld i e)
476
477 -- explicit instance because Haddock can't figure out a derived one
478 instance Eq (IOArray i e) where
479   IOArray x == IOArray y = x == y
480
481 -- |Build a new 'IOArray'
482 newIOArray :: Ix i => (i,i) -> e -> IO (IOArray i e)
483 {-# INLINE newIOArray #-}
484 newIOArray lu init  = stToIO $ do {marr <- newSTArray lu init; return (IOArray marr)}
485
486 -- | Read a value from an 'IOArray'
487 unsafeReadIOArray  :: Ix i => IOArray i e -> Int -> IO e
488 {-# INLINE unsafeReadIOArray #-}
489 unsafeReadIOArray (IOArray marr) i = stToIO (unsafeReadSTArray marr i)
490
491 -- | Write a new value into an 'IOArray'
492 unsafeWriteIOArray :: Ix i => IOArray i e -> Int -> e -> IO ()
493 {-# INLINE unsafeWriteIOArray #-}
494 unsafeWriteIOArray (IOArray marr) i e = stToIO (unsafeWriteSTArray marr i e)
495
496 -- | Read a value from an 'IOArray'
497 readIOArray  :: Ix i => IOArray i e -> i -> IO e
498 readIOArray (IOArray marr) i = stToIO (readSTArray marr i)
499
500 -- | Write a new value into an 'IOArray'
501 writeIOArray :: Ix i => IOArray i e -> i -> e -> IO ()
502 writeIOArray (IOArray marr) i e = stToIO (writeSTArray marr i e)
503
504
505 -- ---------------------------------------------------------------------------
506 -- Show instance for Handles
507
508 -- handle types are 'show'n when printing error msgs, so
509 -- we provide a more user-friendly Show instance for it
510 -- than the derived one.
511
512 instance Show HandleType where
513   showsPrec p t =
514     case t of
515       ClosedHandle      -> showString "closed"
516       SemiClosedHandle  -> showString "semi-closed"
517       ReadHandle        -> showString "readable"
518       WriteHandle       -> showString "writable"
519       AppendHandle      -> showString "writable (append)"
520       ReadWriteHandle   -> showString "read-writable"
521
522 instance Show Handle where 
523   showsPrec p (FileHandle   file _)   = showHandle file
524   showsPrec p (DuplexHandle file _ _) = showHandle file
525
526 showHandle file = showString "{handle: " . showString file . showString "}"
527
528 -- ------------------------------------------------------------------------
529 -- Exception datatype and operations
530
531 -- |The type of exceptions.  Every kind of system-generated exception
532 -- has a constructor in the 'Exception' type, and values of other
533 -- types may be injected into 'Exception' by coercing them to
534 -- 'Data.Dynamic.Dynamic' (see the section on Dynamic Exceptions:
535 -- "Control.Exception\#DynamicExceptions").
536 data Exception
537   = ArithException      ArithException
538         -- ^Exceptions raised by arithmetic
539         -- operations.  (NOTE: GHC currently does not throw
540         -- 'ArithException's except for 'DivideByZero').
541   | ArrayException      ArrayException
542         -- ^Exceptions raised by array-related
543         -- operations.  (NOTE: GHC currently does not throw
544         -- 'ArrayException's).
545   | AssertionFailed     String
546         -- ^This exception is thrown by the
547         -- 'assert' operation when the condition
548         -- fails.  The 'String' argument contains the
549         -- location of the assertion in the source program.
550   | AsyncException      AsyncException
551         -- ^Asynchronous exceptions (see section on Asynchronous Exceptions: "Control.Exception\#AsynchronousExceptions").
552   | BlockedOnDeadMVar
553         -- ^The current thread was executing a call to
554         -- 'Control.Concurrent.MVar.takeMVar' that could never return,
555         -- because there are no other references to this 'MVar'.
556   | Deadlock
557         -- ^There are no runnable threads, so the program is
558         -- deadlocked.  The 'Deadlock' exception is
559         -- raised in the main thread only (see also: "Control.Concurrent").
560   | DynException        Dynamic
561         -- ^Dynamically typed exceptions (see section on Dynamic Exceptions: "Control.Exception\#DynamicExceptions").
562   | ErrorCall           String
563         -- ^The 'ErrorCall' exception is thrown by 'error'.  The 'String'
564         -- argument of 'ErrorCall' is the string passed to 'error' when it was
565         -- called.
566   | ExitException       ExitCode
567         -- ^The 'ExitException' exception is thrown by 'System.Exit.exitWith' (and
568         -- 'System.Exit.exitFailure').  The 'ExitCode' argument is the value passed 
569         -- to 'System.Exit.exitWith'.  An unhandled 'ExitException' exception in the
570         -- main thread will cause the program to be terminated with the given 
571         -- exit code.
572   | IOException         IOException
573         -- ^These are the standard IO exceptions generated by
574         -- Haskell\'s @IO@ operations.  See also "System.IO.Error".
575   | NoMethodError       String
576         -- ^An attempt was made to invoke a class method which has
577         -- no definition in this instance, and there was no default
578         -- definition given in the class declaration.  GHC issues a
579         -- warning when you compile an instance which has missing
580         -- methods.
581   | NonTermination
582         -- ^The current thread is stuck in an infinite loop.  This
583         -- exception may or may not be thrown when the program is
584         -- non-terminating.
585   | PatternMatchFail    String
586         -- ^A pattern matching failure.  The 'String' argument should contain a
587         -- descriptive message including the function name, source file
588         -- and line number.
589   | RecConError         String
590         -- ^An attempt was made to evaluate a field of a record
591         -- for which no value was given at construction time.  The
592         -- 'String' argument gives the location of the
593         -- record construction in the source program.
594   | RecSelError         String
595         -- ^A field selection was attempted on a constructor that
596         -- doesn\'t have the requested field.  This can happen with
597         -- multi-constructor records when one or more fields are
598         -- missing from some of the constructors.  The
599         -- 'String' argument gives the location of the
600         -- record selection in the source program.
601   | RecUpdError         String
602         -- ^An attempt was made to update a field in a record,
603         -- where the record doesn\'t have the requested field.  This can
604         -- only occur with multi-constructor records, when one or more
605         -- fields are missing from some of the constructors.  The
606         -- 'String' argument gives the location of the
607         -- record update in the source program.
608
609 -- |The type of arithmetic exceptions
610 data ArithException
611   = Overflow
612   | Underflow
613   | LossOfPrecision
614   | DivideByZero
615   | Denormal
616   deriving (Eq, Ord)
617
618
619 -- |Asynchronous exceptions
620 data AsyncException
621   = StackOverflow
622         -- ^The current thread\'s stack exceeded its limit.
623         -- Since an exception has been raised, the thread\'s stack
624         -- will certainly be below its limit again, but the
625         -- programmer should take remedial action
626         -- immediately.
627   | HeapOverflow
628         -- ^The program\'s heap is reaching its limit, and
629         -- the program should take action to reduce the amount of
630         -- live data it has. Notes:
631         --
632         --      * It is undefined which thread receives this exception.
633         --
634         --      * GHC currently does not throw 'HeapOverflow' exceptions.
635   | ThreadKilled
636         -- ^This exception is raised by another thread
637         -- calling 'Control.Concurrent.killThread', or by the system
638         -- if it needs to terminate the thread for some
639         -- reason.
640   deriving (Eq, Ord)
641
642 -- | Exceptions generated by array operations
643 data ArrayException
644   = IndexOutOfBounds    String
645         -- ^An attempt was made to index an array outside
646         -- its declared bounds.
647   | UndefinedElement    String
648         -- ^An attempt was made to evaluate an element of an
649         -- array that had not been initialized.
650   deriving (Eq, Ord)
651
652 stackOverflow, heapOverflow :: Exception -- for the RTS
653 stackOverflow = AsyncException StackOverflow
654 heapOverflow  = AsyncException HeapOverflow
655
656 instance Show ArithException where
657   showsPrec _ Overflow        = showString "arithmetic overflow"
658   showsPrec _ Underflow       = showString "arithmetic underflow"
659   showsPrec _ LossOfPrecision = showString "loss of precision"
660   showsPrec _ DivideByZero    = showString "divide by zero"
661   showsPrec _ Denormal        = showString "denormal"
662
663 instance Show AsyncException where
664   showsPrec _ StackOverflow   = showString "stack overflow"
665   showsPrec _ HeapOverflow    = showString "heap overflow"
666   showsPrec _ ThreadKilled    = showString "thread killed"
667
668 instance Show ArrayException where
669   showsPrec _ (IndexOutOfBounds s)
670         = showString "array index out of range"
671         . (if not (null s) then showString ": " . showString s
672                            else id)
673   showsPrec _ (UndefinedElement s)
674         = showString "undefined array element"
675         . (if not (null s) then showString ": " . showString s
676                            else id)
677
678 instance Show Exception where
679   showsPrec _ (IOException err)          = shows err
680   showsPrec _ (ArithException err)       = shows err
681   showsPrec _ (ArrayException err)       = shows err
682   showsPrec _ (ErrorCall err)            = showString err
683   showsPrec _ (ExitException err)        = showString "exit: " . shows err
684   showsPrec _ (NoMethodError err)        = showString err
685   showsPrec _ (PatternMatchFail err)     = showString err
686   showsPrec _ (RecSelError err)          = showString err
687   showsPrec _ (RecConError err)          = showString err
688   showsPrec _ (RecUpdError err)          = showString err
689   showsPrec _ (AssertionFailed err)      = showString err
690   showsPrec _ (DynException _err)        = showString "unknown exception"
691   showsPrec _ (AsyncException e)         = shows e
692   showsPrec _ (BlockedOnDeadMVar)        = showString "thread blocked indefinitely"
693   showsPrec _ (NonTermination)           = showString "<<loop>>"
694   showsPrec _ (Deadlock)                 = showString "<<deadlock>>"
695
696 instance Eq Exception where
697   IOException e1      == IOException e2      = e1 == e2
698   ArithException e1   == ArithException e2   = e1 == e2
699   ArrayException e1   == ArrayException e2   = e1 == e2
700   ErrorCall e1        == ErrorCall e2        = e1 == e2
701   ExitException e1    == ExitException e2    = e1 == e2
702   NoMethodError e1    == NoMethodError e2    = e1 == e2
703   PatternMatchFail e1 == PatternMatchFail e2 = e1 == e2
704   RecSelError e1      == RecSelError e2      = e1 == e2
705   RecConError e1      == RecConError e2      = e1 == e2
706   RecUpdError e1      == RecUpdError e2      = e1 == e2
707   AssertionFailed e1  == AssertionFailed e2  = e1 == e2
708   DynException _      == DynException _      = False -- incomparable
709   AsyncException e1   == AsyncException e2   = e1 == e2
710   BlockedOnDeadMVar   == BlockedOnDeadMVar   = True
711   NonTermination      == NonTermination      = True
712   Deadlock            == Deadlock            = True
713   _                   == _                   = False
714
715 -- -----------------------------------------------------------------------------
716 -- The ExitCode type
717
718 -- We need it here because it is used in ExitException in the
719 -- Exception datatype (above).
720
721 data ExitCode
722   = ExitSuccess -- ^ indicates successful termination;
723   | ExitFailure Int
724                 -- ^ indicates program failure with an exit code.
725                 -- The exact interpretation of the code is
726                 -- operating-system dependent.  In particular, some values
727                 -- may be prohibited (e.g. 0 on a POSIX-compliant system).
728   deriving (Eq, Ord, Read, Show)
729
730 -- --------------------------------------------------------------------------
731 -- Primitive throw
732
733 -- | Throw an exception.  Exceptions may be thrown from purely
734 -- functional code, but may only be caught within the 'IO' monad.
735 throw :: Exception -> a
736 throw exception = raise# exception
737
738 -- | A variant of 'throw' that can be used within the 'IO' monad.
739 --
740 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
741 -- two functions are subtly different:
742 --
743 -- > throw e   `seq` return ()  ===> throw e
744 -- > throwIO e `seq` return ()  ===> return ()
745 --
746 -- The first example will cause the exception @e@ to be raised,
747 -- whereas the second one won\'t.  In fact, 'throwIO' will only cause
748 -- an exception to be raised when it is used within the 'IO' monad.
749 -- The 'throwIO' variant should be used in preference to 'throw' to
750 -- raise an exception within the 'IO' monad because it guarantees
751 -- ordering with respect to other 'IO' operations, whereas 'throw'
752 -- does not.
753 throwIO         :: Exception -> IO a
754 throwIO err     =  IO $ raiseIO# err
755
756 ioException     :: IOException -> IO a
757 ioException err =  IO $ raiseIO# (IOException err)
758
759 -- | Raise an 'IOError' in the 'IO' monad.
760 ioError         :: IOError -> IO a 
761 ioError         =  ioException
762
763 -- ---------------------------------------------------------------------------
764 -- IOError type
765
766 -- | The Haskell 98 type for exceptions in the 'IO' monad.
767 -- Any I\/O operation may raise an 'IOError' instead of returning a result.
768 -- For a more general type of exception, including also those that arise
769 -- in pure code, see 'Control.Exception.Exception'.
770 --
771 -- In Haskell 98, this is an opaque type.
772 type IOError = IOException
773
774 -- |Exceptions that occur in the @IO@ monad.
775 -- An @IOException@ records a more specific error type, a descriptive
776 -- string and maybe the handle that was used when the error was
777 -- flagged.
778 data IOException
779  = IOError {
780      ioe_handle   :: Maybe Handle,   -- the handle used by the action flagging 
781                                      -- the error.
782      ioe_type     :: IOErrorType,    -- what it was.
783      ioe_location :: String,         -- location.
784      ioe_description :: String,      -- error type specific information.
785      ioe_filename :: Maybe FilePath  -- filename the error is related to.
786    }
787
788 instance Eq IOException where
789   (IOError h1 e1 loc1 str1 fn1) == (IOError h2 e2 loc2 str2 fn2) = 
790     e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && fn1==fn2
791
792 -- | An abstract type that contains a value for each variant of 'IOError'.
793 data IOErrorType
794   -- Haskell 98:
795   = AlreadyExists
796   | NoSuchThing
797   | ResourceBusy
798   | ResourceExhausted
799   | EOF
800   | IllegalOperation
801   | PermissionDenied
802   | UserError
803   -- GHC only:
804   | UnsatisfiedConstraints
805   | SystemError
806   | ProtocolError
807   | OtherError
808   | InvalidArgument
809   | InappropriateType
810   | HardwareFault
811   | UnsupportedOperation
812   | TimeExpired
813   | ResourceVanished
814   | Interrupted
815   | DynIOError Dynamic -- cheap&cheerful extensible IO error type.
816
817 instance Eq IOErrorType where
818    x == y = 
819      case x of
820        DynIOError{} -> False -- from a strictness POV, compatible with a derived Eq inst?
821        _ -> getTag x ==# getTag y
822  
823 instance Show IOErrorType where
824   showsPrec _ e =
825     showString $
826     case e of
827       AlreadyExists     -> "already exists"
828       NoSuchThing       -> "does not exist"
829       ResourceBusy      -> "resource busy"
830       ResourceExhausted -> "resource exhausted"
831       EOF               -> "end of file"
832       IllegalOperation  -> "illegal operation"
833       PermissionDenied  -> "permission denied"
834       UserError         -> "user error"
835       HardwareFault     -> "hardware fault"
836       InappropriateType -> "inappropriate type"
837       Interrupted       -> "interrupted"
838       InvalidArgument   -> "invalid argument"
839       OtherError        -> "failed"
840       ProtocolError     -> "protocol error"
841       ResourceVanished  -> "resource vanished"
842       SystemError       -> "system error"
843       TimeExpired       -> "timeout"
844       UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise!
845       UnsupportedOperation -> "unsupported operation"
846       DynIOError{}      -> "unknown IO error"
847
848 -- | Construct an 'IOError' value with a string describing the error.
849 -- The 'fail' method of the 'IO' instance of the 'Monad' class raises a
850 -- 'userError', thus:
851 --
852 -- > instance Monad IO where 
853 -- >   ...
854 -- >   fail s = ioError (userError s)
855 --
856 userError       :: String  -> IOError
857 userError str   =  IOError Nothing UserError "" str Nothing
858
859 -- ---------------------------------------------------------------------------
860 -- Showing IOErrors
861
862 instance Show IOException where
863     showsPrec p (IOError hdl iot loc s fn) =
864       (case fn of
865          Nothing -> case hdl of
866                         Nothing -> id
867                         Just h  -> showsPrec p h . showString ": "
868          Just name -> showString name . showString ": ") .
869       (case loc of
870          "" -> id
871          _  -> showString loc . showString ": ") .
872       showsPrec p iot . 
873       (case s of
874          "" -> id
875          _  -> showString " (" . showString s . showString ")")
876
877 -- -----------------------------------------------------------------------------
878 -- IOMode type
879
880 data IOMode      =  ReadMode | WriteMode | AppendMode | ReadWriteMode
881                     deriving (Eq, Ord, Ix, Enum, Read, Show)
882 \end{code}