Rewrite of signal-handling (base patch; see also ghc and unix patches)
[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, 
31     unsafeWriteIOArray, boundsIOArray,
32     MVar(..),
33
34         -- Handles, file descriptors,
35     FilePath,  
36     Handle(..), Handle__(..), HandleType(..), IOMode(..), FD, 
37     isReadableHandleType, isWritableHandleType, isReadWriteHandleType, showHandle,
38
39         -- Buffers
40     Buffer(..), RawBuffer, BufferState(..), BufferList(..), BufferMode(..),
41     bufferIsWritable, bufferEmpty, bufferFull, 
42
43         -- Exceptions
44     Exception(..), ArithException(..), AsyncException(..), ArrayException(..),
45     stackOverflow, heapOverflow, ioException, 
46     IOError, IOException(..), IOErrorType(..), ioError, userError,
47     ExitCode(..),
48     throwIO, block, unblock, blocked, catchAny, catchException,
49     evaluate,
50     ErrorCall(..), AssertionFailed(..), assertError, untangle,
51     BlockedOnDeadMVar(..), BlockedIndefinitely(..), Deadlock(..),
52     blockedOnDeadMVar, blockedIndefinitely
53   ) where
54
55 import GHC.ST
56 import GHC.Arr  -- to derive Ix class
57 import GHC.Enum -- to derive Enum class
58 import GHC.STRef
59 import GHC.Base
60 --  import GHC.Num      -- To get fromInteger etc, needed because of -XNoImplicitPrelude
61 import Data.Maybe  ( Maybe(..) )
62 import GHC.Show
63 import GHC.List
64 import GHC.Read
65 import Foreign.C.Types (CInt)
66 import GHC.Exception
67
68 #ifndef __HADDOCK__
69 import {-# SOURCE #-} Data.Typeable     ( Typeable )
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, _ #) -> 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 :: HandleType -> Bool
476 isReadableHandleType ReadHandle         = True
477 isReadableHandleType ReadWriteHandle    = True
478 isReadableHandleType _                  = False
479
480 isWritableHandleType :: HandleType -> Bool
481 isWritableHandleType AppendHandle    = True
482 isWritableHandleType WriteHandle     = True
483 isWritableHandleType ReadWriteHandle = True
484 isWritableHandleType _               = False
485
486 isReadWriteHandleType :: HandleType -> Bool
487 isReadWriteHandleType ReadWriteHandle{} = True
488 isReadWriteHandleType _                 = False
489
490 -- | File and directory names are values of type 'String', whose precise
491 -- meaning is operating system dependent. Files can be opened, yielding a
492 -- handle which can then be used to operate on the contents of that file.
493
494 type FilePath = String
495
496 -- ---------------------------------------------------------------------------
497 -- Buffering modes
498
499 -- | Three kinds of buffering are supported: line-buffering, 
500 -- block-buffering or no-buffering.  These modes have the following
501 -- effects. For output, items are written out, or /flushed/,
502 -- from the internal buffer according to the buffer mode:
503 --
504 --  * /line-buffering/: the entire output buffer is flushed
505 --    whenever a newline is output, the buffer overflows, 
506 --    a 'System.IO.hFlush' is issued, or the handle is closed.
507 --
508 --  * /block-buffering/: the entire buffer is written out whenever it
509 --    overflows, a 'System.IO.hFlush' is issued, or the handle is closed.
510 --
511 --  * /no-buffering/: output is written immediately, and never stored
512 --    in the buffer.
513 --
514 -- An implementation is free to flush the buffer more frequently,
515 -- but not less frequently, than specified above.
516 -- The output buffer is emptied as soon as it has been written out.
517 --
518 -- Similarly, input occurs according to the buffer mode for the handle:
519 --
520 --  * /line-buffering/: when the buffer for the handle is not empty,
521 --    the next item is obtained from the buffer; otherwise, when the
522 --    buffer is empty, characters up to and including the next newline
523 --    character are read into the buffer.  No characters are available
524 --    until the newline character is available or the buffer is full.
525 --
526 --  * /block-buffering/: when the buffer for the handle becomes empty,
527 --    the next block of data is read into the buffer.
528 --
529 --  * /no-buffering/: the next input item is read and returned.
530 --    The 'System.IO.hLookAhead' operation implies that even a no-buffered
531 --    handle may require a one-character buffer.
532 --
533 -- The default buffering mode when a handle is opened is
534 -- implementation-dependent and may depend on the file system object
535 -- which is attached to that handle.
536 -- For most implementations, physical files will normally be block-buffered 
537 -- and terminals will normally be line-buffered.
538
539 data BufferMode  
540  = NoBuffering  -- ^ buffering is disabled if possible.
541  | LineBuffering
542                 -- ^ line-buffering should be enabled if possible.
543  | BlockBuffering (Maybe Int)
544                 -- ^ block-buffering should be enabled if possible.
545                 -- The size of the buffer is @n@ items if the argument
546                 -- is 'Just' @n@ and is otherwise implementation-dependent.
547    deriving (Eq, Ord, Read, Show)
548
549 -- ---------------------------------------------------------------------------
550 -- IORefs
551
552 -- |A mutable variable in the 'IO' monad
553 newtype IORef a = IORef (STRef RealWorld a)
554
555 -- explicit instance because Haddock can't figure out a derived one
556 instance Eq (IORef a) where
557   IORef x == IORef y = x == y
558
559 -- |Build a new 'IORef'
560 newIORef    :: a -> IO (IORef a)
561 newIORef v = stToIO (newSTRef v) >>= \ var -> return (IORef var)
562
563 -- |Read the value of an 'IORef'
564 readIORef   :: IORef a -> IO a
565 readIORef  (IORef var) = stToIO (readSTRef var)
566
567 -- |Write a new value into an 'IORef'
568 writeIORef  :: IORef a -> a -> IO ()
569 writeIORef (IORef var) v = stToIO (writeSTRef var v)
570
571 -- ---------------------------------------------------------------------------
572 -- | An 'IOArray' is a mutable, boxed, non-strict array in the 'IO' monad.  
573 -- The type arguments are as follows:
574 --
575 --  * @i@: the index type of the array (should be an instance of 'Ix')
576 --
577 --  * @e@: the element type of the array.
578 --
579 -- 
580
581 newtype IOArray i e = IOArray (STArray RealWorld i e)
582
583 -- explicit instance because Haddock can't figure out a derived one
584 instance Eq (IOArray i e) where
585   IOArray x == IOArray y = x == y
586
587 -- |Build a new 'IOArray'
588 newIOArray :: Ix i => (i,i) -> e -> IO (IOArray i e)
589 {-# INLINE newIOArray #-}
590 newIOArray lu initial  = stToIO $ do {marr <- newSTArray lu initial; return (IOArray marr)}
591
592 -- | Read a value from an 'IOArray'
593 unsafeReadIOArray  :: Ix i => IOArray i e -> Int -> IO e
594 {-# INLINE unsafeReadIOArray #-}
595 unsafeReadIOArray (IOArray marr) i = stToIO (unsafeReadSTArray marr i)
596
597 -- | Write a new value into an 'IOArray'
598 unsafeWriteIOArray :: Ix i => IOArray i e -> Int -> e -> IO ()
599 {-# INLINE unsafeWriteIOArray #-}
600 unsafeWriteIOArray (IOArray marr) i e = stToIO (unsafeWriteSTArray marr i e)
601
602 -- | Read a value from an 'IOArray'
603 readIOArray  :: Ix i => IOArray i e -> i -> IO e
604 readIOArray (IOArray marr) i = stToIO (readSTArray marr i)
605
606 -- | Write a new value into an 'IOArray'
607 writeIOArray :: Ix i => IOArray i e -> i -> e -> IO ()
608 writeIOArray (IOArray marr) i e = stToIO (writeSTArray marr i e)
609
610 {-# INLINE boundsIOArray #-}
611 boundsIOArray :: IOArray i e -> (i,i)  
612 boundsIOArray (IOArray marr) = boundsSTArray marr
613
614 -- ---------------------------------------------------------------------------
615 -- Show instance for Handles
616
617 -- handle types are 'show'n when printing error msgs, so
618 -- we provide a more user-friendly Show instance for it
619 -- than the derived one.
620
621 instance Show HandleType where
622   showsPrec _ t =
623     case t of
624       ClosedHandle      -> showString "closed"
625       SemiClosedHandle  -> showString "semi-closed"
626       ReadHandle        -> showString "readable"
627       WriteHandle       -> showString "writable"
628       AppendHandle      -> showString "writable (append)"
629       ReadWriteHandle   -> showString "read-writable"
630
631 instance Show Handle where 
632   showsPrec _ (FileHandle   file _)   = showHandle file
633   showsPrec _ (DuplexHandle file _ _) = showHandle file
634
635 showHandle :: FilePath -> String -> String
636 showHandle file = showString "{handle: " . showString file . showString "}"
637
638 -- ------------------------------------------------------------------------
639 -- Exception datatypes and operations
640
641 -- |The thread is blocked on an @MVar@, but there are no other references
642 -- to the @MVar@ so it can't ever continue.
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 blockedOnDeadMVar :: SomeException -- for the RTS
652 blockedOnDeadMVar = toException BlockedOnDeadMVar
653
654 -----
655
656 -- |The thread is awiting to retry an STM transaction, but there are no
657 -- other references to any @TVar@s involved, so it can't ever continue.
658 data BlockedIndefinitely = BlockedIndefinitely
659     deriving Typeable
660
661 instance Exception BlockedIndefinitely
662
663 instance Show BlockedIndefinitely where
664     showsPrec _ BlockedIndefinitely = showString "thread blocked indefinitely"
665
666 blockedIndefinitely :: SomeException -- for the RTS
667 blockedIndefinitely = toException BlockedIndefinitely
668
669 -----
670
671 -- |There are no runnable threads, so the program is deadlocked.
672 -- The @Deadlock@ exception is raised in the main thread only.
673 data Deadlock = Deadlock
674     deriving Typeable
675
676 instance Exception Deadlock
677
678 instance Show Deadlock where
679     showsPrec _ Deadlock = showString "<<deadlock>>"
680
681 -----
682
683 -- |Exceptions generated by 'assert'. The @String@ gives information
684 -- about the source location of the assertion.
685 data AssertionFailed = AssertionFailed String
686     deriving Typeable
687
688 instance Exception AssertionFailed
689
690 instance Show AssertionFailed where
691     showsPrec _ (AssertionFailed err) = showString err
692
693 -----
694
695 -- |Asynchronous exceptions.
696 data AsyncException
697   = StackOverflow
698         -- ^The current thread\'s stack exceeded its limit.
699         -- Since an exception has been raised, the thread\'s stack
700         -- will certainly be below its limit again, but the
701         -- programmer should take remedial action
702         -- immediately.
703   | HeapOverflow
704         -- ^The program\'s heap is reaching its limit, and
705         -- the program should take action to reduce the amount of
706         -- live data it has. Notes:
707         --
708         --      * It is undefined which thread receives this exception.
709         --
710         --      * GHC currently does not throw 'HeapOverflow' exceptions.
711   | ThreadKilled
712         -- ^This exception is raised by another thread
713         -- calling 'Control.Concurrent.killThread', or by the system
714         -- if it needs to terminate the thread for some
715         -- reason.
716   | UserInterrupt
717         -- ^This exception is raised by default in the main thread of
718         -- the program when the user requests to terminate the program
719         -- via the usual mechanism(s) (e.g. Control-C in the console).
720   deriving (Eq, Ord, Typeable)
721
722 instance Exception AsyncException
723
724 -- | Exceptions generated by array operations
725 data ArrayException
726   = IndexOutOfBounds    String
727         -- ^An attempt was made to index an array outside
728         -- its declared bounds.
729   | UndefinedElement    String
730         -- ^An attempt was made to evaluate an element of an
731         -- array that had not been initialized.
732   deriving (Eq, Ord, Typeable)
733
734 instance Exception ArrayException
735
736 stackOverflow, heapOverflow :: SomeException -- for the RTS
737 stackOverflow = toException StackOverflow
738 heapOverflow  = toException HeapOverflow
739
740 instance Show AsyncException where
741   showsPrec _ StackOverflow   = showString "stack overflow"
742   showsPrec _ HeapOverflow    = showString "heap overflow"
743   showsPrec _ ThreadKilled    = showString "thread killed"
744   showsPrec _ UserInterrupt   = showString "user interrupt"
745
746 instance Show ArrayException where
747   showsPrec _ (IndexOutOfBounds s)
748         = showString "array index out of range"
749         . (if not (null s) then showString ": " . showString s
750                            else id)
751   showsPrec _ (UndefinedElement s)
752         = showString "undefined array element"
753         . (if not (null s) then showString ": " . showString s
754                            else id)
755
756 -- -----------------------------------------------------------------------------
757 -- The ExitCode type
758
759 -- We need it here because it is used in ExitException in the
760 -- Exception datatype (above).
761
762 data ExitCode
763   = ExitSuccess -- ^ indicates successful termination;
764   | ExitFailure Int
765                 -- ^ indicates program failure with an exit code.
766                 -- The exact interpretation of the code is
767                 -- operating-system dependent.  In particular, some values
768                 -- may be prohibited (e.g. 0 on a POSIX-compliant system).
769   deriving (Eq, Ord, Read, Show, Typeable)
770
771 instance Exception ExitCode
772
773 ioException     :: IOException -> IO a
774 ioException err = throwIO err
775
776 -- | Raise an 'IOError' in the 'IO' monad.
777 ioError         :: IOError -> IO a 
778 ioError         =  ioException
779
780 -- ---------------------------------------------------------------------------
781 -- IOError type
782
783 -- | The Haskell 98 type for exceptions in the 'IO' monad.
784 -- Any I\/O operation may raise an 'IOError' instead of returning a result.
785 -- For a more general type of exception, including also those that arise
786 -- in pure code, see 'Control.Exception.Exception'.
787 --
788 -- In Haskell 98, this is an opaque type.
789 type IOError = IOException
790
791 -- |Exceptions that occur in the @IO@ monad.
792 -- An @IOException@ records a more specific error type, a descriptive
793 -- string and maybe the handle that was used when the error was
794 -- flagged.
795 data IOException
796  = IOError {
797      ioe_handle   :: Maybe Handle,   -- the handle used by the action flagging 
798                                      -- the error.
799      ioe_type     :: IOErrorType,    -- what it was.
800      ioe_location :: String,         -- location.
801      ioe_description :: String,      -- error type specific information.
802      ioe_errno    :: Maybe CInt,     -- errno leading to this error, if any.
803      ioe_filename :: Maybe FilePath  -- filename the error is related to.
804    }
805     deriving Typeable
806
807 instance Exception IOException
808
809 instance Eq IOException where
810   (IOError h1 e1 loc1 str1 en1 fn1) == (IOError h2 e2 loc2 str2 en2 fn2) = 
811     e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && en1==en2 && fn1==fn2
812
813 -- | An abstract type that contains a value for each variant of 'IOError'.
814 data IOErrorType
815   -- Haskell 98:
816   = AlreadyExists
817   | NoSuchThing
818   | ResourceBusy
819   | ResourceExhausted
820   | EOF
821   | IllegalOperation
822   | PermissionDenied
823   | UserError
824   -- GHC only:
825   | UnsatisfiedConstraints
826   | SystemError
827   | ProtocolError
828   | OtherError
829   | InvalidArgument
830   | InappropriateType
831   | HardwareFault
832   | UnsupportedOperation
833   | TimeExpired
834   | ResourceVanished
835   | Interrupted
836
837 instance Eq IOErrorType where
838    x == y = getTag x ==# getTag y
839  
840 instance Show IOErrorType where
841   showsPrec _ e =
842     showString $
843     case e of
844       AlreadyExists     -> "already exists"
845       NoSuchThing       -> "does not exist"
846       ResourceBusy      -> "resource busy"
847       ResourceExhausted -> "resource exhausted"
848       EOF               -> "end of file"
849       IllegalOperation  -> "illegal operation"
850       PermissionDenied  -> "permission denied"
851       UserError         -> "user error"
852       HardwareFault     -> "hardware fault"
853       InappropriateType -> "inappropriate type"
854       Interrupted       -> "interrupted"
855       InvalidArgument   -> "invalid argument"
856       OtherError        -> "failed"
857       ProtocolError     -> "protocol error"
858       ResourceVanished  -> "resource vanished"
859       SystemError       -> "system error"
860       TimeExpired       -> "timeout"
861       UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise!
862       UnsupportedOperation -> "unsupported operation"
863
864 -- | Construct an 'IOError' value with a string describing the error.
865 -- The 'fail' method of the 'IO' instance of the 'Monad' class raises a
866 -- 'userError', thus:
867 --
868 -- > instance Monad IO where 
869 -- >   ...
870 -- >   fail s = ioError (userError s)
871 --
872 userError       :: String  -> IOError
873 userError str   =  IOError Nothing UserError "" str Nothing Nothing
874
875 -- ---------------------------------------------------------------------------
876 -- Showing IOErrors
877
878 instance Show IOException where
879     showsPrec p (IOError hdl iot loc s _ fn) =
880       (case fn of
881          Nothing -> case hdl of
882                         Nothing -> id
883                         Just h  -> showsPrec p h . showString ": "
884          Just name -> showString name . showString ": ") .
885       (case loc of
886          "" -> id
887          _  -> showString loc . showString ": ") .
888       showsPrec p iot . 
889       (case s of
890          "" -> id
891          _  -> showString " (" . showString s . showString ")")
892
893 -- -----------------------------------------------------------------------------
894 -- IOMode type
895
896 data IOMode      =  ReadMode | WriteMode | AppendMode | ReadWriteMode
897                     deriving (Eq, Ord, Ix, Enum, Read, Show)
898 \end{code}
899
900 %*********************************************************
901 %*                                                      *
902 \subsection{Primitive catch and throwIO}
903 %*                                                      *
904 %*********************************************************
905
906 catchException used to handle the passing around of the state to the
907 action and the handler.  This turned out to be a bad idea - it meant
908 that we had to wrap both arguments in thunks so they could be entered
909 as normal (remember IO returns an unboxed pair...).
910
911 Now catch# has type
912
913     catch# :: IO a -> (b -> IO a) -> IO a
914
915 (well almost; the compiler doesn't know about the IO newtype so we
916 have to work around that in the definition of catchException below).
917
918 \begin{code}
919 catchException :: Exception e => IO a -> (e -> IO a) -> IO a
920 catchException (IO io) handler = IO $ catch# io handler'
921     where handler' e = case fromException e of
922                        Just e' -> unIO (handler e')
923                        Nothing -> raise# e
924
925 catchAny :: IO a -> (forall e . Exception e => e -> IO a) -> IO a
926 catchAny (IO io) handler = IO $ catch# io handler'
927     where handler' (SomeException e) = unIO (handler e)
928
929 -- | A variant of 'throw' that can only be used within the 'IO' monad.
930 --
931 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
932 -- two functions are subtly different:
933 --
934 -- > throw e   `seq` x  ===> throw e
935 -- > throwIO e `seq` x  ===> x
936 --
937 -- The first example will cause the exception @e@ to be raised,
938 -- whereas the second one won\'t.  In fact, 'throwIO' will only cause
939 -- an exception to be raised when it is used within the 'IO' monad.
940 -- The 'throwIO' variant should be used in preference to 'throw' to
941 -- raise an exception within the 'IO' monad because it guarantees
942 -- ordering with respect to other 'IO' operations, whereas 'throw'
943 -- does not.
944 throwIO :: Exception e => e -> IO a
945 throwIO e = IO (raiseIO# (toException e))
946 \end{code}
947
948
949 %*********************************************************
950 %*                                                      *
951 \subsection{Controlling asynchronous exception delivery}
952 %*                                                      *
953 %*********************************************************
954
955 \begin{code}
956 -- | Applying 'block' to a computation will
957 -- execute that computation with asynchronous exceptions
958 -- /blocked/.  That is, any thread which
959 -- attempts to raise an exception in the current thread with 'Control.Exception.throwTo' will be
960 -- blocked until asynchronous exceptions are enabled again.  There\'s
961 -- no need to worry about re-enabling asynchronous exceptions; that is
962 -- done automatically on exiting the scope of
963 -- 'block'.
964 --
965 -- Threads created by 'Control.Concurrent.forkIO' inherit the blocked
966 -- state from the parent; that is, to start a thread in blocked mode,
967 -- use @block $ forkIO ...@.  This is particularly useful if you need to
968 -- establish an exception handler in the forked thread before any
969 -- asynchronous exceptions are received.
970 block :: IO a -> IO a
971
972 -- | To re-enable asynchronous exceptions inside the scope of
973 -- 'block', 'unblock' can be
974 -- used.  It scopes in exactly the same way, so on exit from
975 -- 'unblock' asynchronous exception delivery will
976 -- be disabled again.
977 unblock :: IO a -> IO a
978
979 block (IO io) = IO $ blockAsyncExceptions# io
980 unblock (IO io) = IO $ unblockAsyncExceptions# io
981
982 -- | returns True if asynchronous exceptions are blocked in the
983 -- current thread.
984 blocked :: IO Bool
985 blocked = IO $ \s -> case asyncExceptionsBlocked# s of
986                         (# s', i #) -> (# s', i /=# 0# #)
987 \end{code}
988
989 \begin{code}
990 -- | Forces its argument to be evaluated to weak head normal form when
991 -- the resultant 'IO' action is executed. It can be used to order
992 -- evaluation with respect to other 'IO' operations; its semantics are
993 -- given by
994 --
995 -- >   evaluate x `seq` y    ==>  y
996 -- >   evaluate x `catch` f  ==>  (return $! x) `catch` f
997 -- >   evaluate x >>= f      ==>  (return $! x) >>= f
998 --
999 -- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
1000 -- same as @(return $! x)@.  A correct definition is
1001 --
1002 -- >   evaluate x = (return $! x) >>= return
1003 --
1004 evaluate :: a -> IO a
1005 evaluate a = IO $ \s -> case a `seq` () of () -> (# s, a #)
1006         -- NB. can't write
1007         --      a `seq` (# s, a #)
1008         -- because we can't have an unboxed tuple as a function argument
1009 \end{code}
1010
1011 \begin{code}
1012 assertError :: Addr# -> Bool -> a -> a
1013 assertError str predicate v
1014   | predicate = v
1015   | otherwise = throw (AssertionFailed (untangle str "Assertion failed"))
1016
1017 {-
1018 (untangle coded message) expects "coded" to be of the form
1019         "location|details"
1020 It prints
1021         location message details
1022 -}
1023 untangle :: Addr# -> String -> String
1024 untangle coded message
1025   =  location
1026   ++ ": "
1027   ++ message
1028   ++ details
1029   ++ "\n"
1030   where
1031     coded_str = unpackCStringUtf8# coded
1032
1033     (location, details)
1034       = case (span not_bar coded_str) of { (loc, rest) ->
1035         case rest of
1036           ('|':det) -> (loc, ' ' : det)
1037           _         -> (loc, "")
1038         }
1039     not_bar c = c /= '|'
1040 \end{code}
1041