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