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