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