2 {-# OPTIONS_GHC -XNoImplicitPrelude -funbox-strict-fields #-}
3 {-# OPTIONS_HADDOCK hide #-}
4 -----------------------------------------------------------------------------
7 -- Copyright : (c) The University of Glasgow 1994-2002
8 -- License : see libraries/base/LICENSE
10 -- Maintainer : cvs-ghc@haskell.org
11 -- Stability : internal
12 -- Portability : non-portable (GHC Extensions)
14 -- Definitions for the 'IO' monad and its friends.
16 -----------------------------------------------------------------------------
20 IO(..), unIO, failIO, liftIO, bindIO, thenIO, returnIO,
21 unsafePerformIO, unsafeInterleaveIO,
22 unsafeDupablePerformIO, unsafeDupableInterleaveIO,
25 -- To and from from ST
26 stToIO, ioToST, unsafeIOToST, unsafeSTToIO,
29 IORef(..), newIORef, readIORef, writeIORef,
30 IOArray(..), newIOArray, readIOArray, writeIOArray, unsafeReadIOArray,
31 unsafeWriteIOArray, boundsIOArray,
34 -- Handles, file descriptors,
36 Handle(..), Handle__(..), HandleType(..), IOMode(..), FD,
37 isReadableHandleType, isWritableHandleType, isReadWriteHandleType, showHandle,
40 Buffer(..), RawBuffer, BufferState(..), BufferList(..), BufferMode(..),
41 bufferIsWritable, bufferEmpty, bufferFull,
44 Exception(..), ArithException(..), AsyncException(..), ArrayException(..),
45 stackOverflow, heapOverflow, ioException,
46 IOError, IOException(..), IOErrorType(..), ioError, userError,
48 throwIO, block, unblock, blocked, catchAny, catchException,
50 ErrorCall(..), AssertionFailed(..), assertError, untangle,
51 BlockedOnDeadMVar(..), BlockedIndefinitely(..), Deadlock(..),
52 blockedOnDeadMVar, blockedIndefinitely
56 import GHC.Arr -- to derive Ix class
57 import GHC.Enum -- to derive Enum class
60 -- import GHC.Num -- To get fromInteger etc, needed because of -XNoImplicitPrelude
61 import Data.Maybe ( Maybe(..) )
65 import Foreign.C.Types (CInt)
69 import {-# SOURCE #-} Data.Typeable ( Typeable )
72 -- ---------------------------------------------------------------------------
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.
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:
83 Compiler - types of various primitives in PrimOp.lhs
85 RTS - forceIO (StgMiscClosures.hc)
86 - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast
88 - raiseAsync (Schedule.c)
90 Prelude - GHC.IOBase.lhs, and several other places including
93 Libraries - parts of hslibs/lang.
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@.
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@.
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.
111 newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #))
113 unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
116 instance Functor IO where
117 fmap f x = x >>= (return . f)
119 instance Monad IO where
120 {-# INLINE return #-}
123 m >> k = m >>= \ _ -> k
124 return x = returnIO x
129 failIO :: String -> IO a
130 failIO s = ioError (userError s)
132 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
133 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
135 bindIO :: IO a -> (a -> IO b) -> IO b
136 bindIO (IO m) k = IO ( \ s ->
138 (# new_s, a #) -> unIO (k a) new_s
141 thenIO :: IO a -> IO b -> IO b
142 thenIO (IO m) k = IO ( \ s ->
144 (# new_s, _ #) -> unIO k new_s
147 returnIO :: a -> IO a
148 returnIO x = IO (\ s -> (# s, x #))
150 -- ---------------------------------------------------------------------------
151 -- Coercions between IO and ST
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
160 ioToST :: IO a -> ST RealWorld a
161 ioToST (IO m) = (ST m)
163 -- This relies on IO and ST having the same representation modulo the
164 -- constraint on the type of the state
166 unsafeIOToST :: IO a -> ST s a
167 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
169 unsafeSTToIO :: ST s a -> IO a
170 unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
172 -- ---------------------------------------------------------------------------
173 -- Unsafe IO operations
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.
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':
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.
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).
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,
200 f x = unsafePerformIO (newIORef [])
202 you may get only one reference cell shared between all calls to @f@.
205 f x = unsafePerformIO (newIORef [x])
207 because now it can't float outside the lambda.
209 It is less well known that
210 'unsafePerformIO' is not type safe. For example:
213 > test = unsafePerformIO $ newIORef []
216 > writeIORef test [42]
217 > bang <- readIORef test
218 > print (bang :: [Char])
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!
227 unsafePerformIO :: IO a -> a
228 unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)
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.
238 {-# NOINLINE unsafeDupablePerformIO #-}
239 unsafeDupablePerformIO :: IO a -> a
240 unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
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.
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))
252 -- unsafeDupablePerformIO (\s -> let r = f x in
253 -- case writeIORef v r s of (# s1, _ #) ->
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
260 -- Solution: don't expose the strictness of unsafeDupablePerformIO,
261 -- by hiding it with 'lazy'
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'.
269 {-# INLINE unsafeInterleaveIO #-}
270 unsafeInterleaveIO :: IO a -> IO a
271 unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)
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.
277 {-# INLINE unsafeDupableInterleaveIO #-}
278 unsafeDupableInterleaveIO :: IO a -> IO a
279 unsafeDupableInterleaveIO (IO m)
281 r = case m s of (# _, res #) -> res
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
291 This operation is used in the definition of 'unsafePerformIO' to
292 prevent the IO action from being executed multiple times, which is usually
296 noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)
298 -- ---------------------------------------------------------------------------
301 data MVar a = MVar (MVar# RealWorld a)
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.
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#
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:
316 -- * type (read,write,closed etc.)
317 -- * the underlying file descriptor
319 -- * buffer, and spare buffers
320 -- * user-friendly name (usually the
321 -- FilePath used when IO.openFile was called)
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.
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:
331 -- * whether it manages input or output or both;
333 -- * whether it is /open/, /closed/ or /semi-closed/;
335 -- * whether the object is seekable;
337 -- * whether buffering is disabled, or enabled on a line or block basis;
339 -- * a buffer (whose length may be zero).
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
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.
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.
364 = FileHandle -- A normal handle to a file
365 FilePath -- the file (invariant)
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
375 -- * A 'FileHandle' is seekable. A 'DuplexHandle' may or may not be
378 instance Eq Handle where
379 (FileHandle _ h1) == (FileHandle _ h2) = h1 == h2
380 (DuplexHandle _ h1 _) == (DuplexHandle _ h2 _) = h1 == h2
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
399 -- ---------------------------------------------------------------------------
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.
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
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.
418 type RawBuffer = MutableByteArray# RealWorld
420 -- INVARIANTS on a Buffer:
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).
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
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.
440 bufState :: BufferState
443 data BufferState = ReadBuffer | WriteBuffer deriving (Eq)
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.
450 | BufferListCons RawBuffer BufferList
453 bufferIsWritable :: Buffer -> Bool
454 bufferIsWritable Buffer{ bufState=WriteBuffer } = True
455 bufferIsWritable _other = False
457 bufferEmpty :: Buffer -> Bool
458 bufferEmpty Buffer{ bufRPtr=r, bufWPtr=w } = r == w
460 -- only makes sense for a write buffer
461 bufferFull :: Buffer -> Bool
462 bufferFull b@Buffer{ bufWPtr=w } = w >= bufSize b
464 -- Internally, we classify handles as being one
475 isReadableHandleType :: HandleType -> Bool
476 isReadableHandleType ReadHandle = True
477 isReadableHandleType ReadWriteHandle = True
478 isReadableHandleType _ = False
480 isWritableHandleType :: HandleType -> Bool
481 isWritableHandleType AppendHandle = True
482 isWritableHandleType WriteHandle = True
483 isWritableHandleType ReadWriteHandle = True
484 isWritableHandleType _ = False
486 isReadWriteHandleType :: HandleType -> Bool
487 isReadWriteHandleType ReadWriteHandle{} = True
488 isReadWriteHandleType _ = False
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.
494 type FilePath = String
496 -- ---------------------------------------------------------------------------
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:
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.
508 -- * /block-buffering/: the entire buffer is written out whenever it
509 -- overflows, a 'System.IO.hFlush' is issued, or the handle is closed.
511 -- * /no-buffering/: output is written immediately, and never stored
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.
518 -- Similarly, input occurs according to the buffer mode for the handle:
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.
526 -- * /block-buffering/: when the buffer for the handle becomes empty,
527 -- the next block of data is read into the buffer.
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.
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.
540 = NoBuffering -- ^ buffering is disabled if possible.
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)
549 -- ---------------------------------------------------------------------------
552 -- |A mutable variable in the 'IO' monad
553 newtype IORef a = IORef (STRef RealWorld a)
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
559 -- |Build a new 'IORef'
560 newIORef :: a -> IO (IORef a)
561 newIORef v = stToIO (newSTRef v) >>= \ var -> return (IORef var)
563 -- |Read the value of an 'IORef'
564 readIORef :: IORef a -> IO a
565 readIORef (IORef var) = stToIO (readSTRef var)
567 -- |Write a new value into an 'IORef'
568 writeIORef :: IORef a -> a -> IO ()
569 writeIORef (IORef var) v = stToIO (writeSTRef var v)
571 -- ---------------------------------------------------------------------------
572 -- | An 'IOArray' is a mutable, boxed, non-strict array in the 'IO' monad.
573 -- The type arguments are as follows:
575 -- * @i@: the index type of the array (should be an instance of 'Ix')
577 -- * @e@: the element type of the array.
581 newtype IOArray i e = IOArray (STArray RealWorld i e)
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
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)}
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)
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)
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)
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)
610 {-# INLINE boundsIOArray #-}
611 boundsIOArray :: IOArray i e -> (i,i)
612 boundsIOArray (IOArray marr) = boundsSTArray marr
614 -- ---------------------------------------------------------------------------
615 -- Show instance for Handles
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.
621 instance Show HandleType where
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"
631 instance Show Handle where
632 showsPrec _ (FileHandle file _) = showHandle file
633 showsPrec _ (DuplexHandle file _ _) = showHandle file
635 showHandle :: FilePath -> String -> String
636 showHandle file = showString "{handle: " . showString file . showString "}"
638 -- ------------------------------------------------------------------------
639 -- Exception datatypes and operations
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
646 instance Exception BlockedOnDeadMVar
648 instance Show BlockedOnDeadMVar where
649 showsPrec _ BlockedOnDeadMVar = showString "thread blocked indefinitely"
651 blockedOnDeadMVar :: SomeException -- for the RTS
652 blockedOnDeadMVar = toException BlockedOnDeadMVar
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
661 instance Exception BlockedIndefinitely
663 instance Show BlockedIndefinitely where
664 showsPrec _ BlockedIndefinitely = showString "thread blocked indefinitely"
666 blockedIndefinitely :: SomeException -- for the RTS
667 blockedIndefinitely = toException BlockedIndefinitely
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
676 instance Exception Deadlock
678 instance Show Deadlock where
679 showsPrec _ Deadlock = showString "<<deadlock>>"
683 -- |Exceptions generated by 'assert'. The @String@ gives information
684 -- about the source location of the assertion.
685 data AssertionFailed = AssertionFailed String
688 instance Exception AssertionFailed
690 instance Show AssertionFailed where
691 showsPrec _ (AssertionFailed err) = showString err
695 -- |Asynchronous exceptions.
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
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:
708 -- * It is undefined which thread receives this exception.
710 -- * GHC currently does not throw 'HeapOverflow' exceptions.
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
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)
722 instance Exception AsyncException
724 -- | Exceptions generated by array operations
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)
734 instance Exception ArrayException
736 stackOverflow, heapOverflow :: SomeException -- for the RTS
737 stackOverflow = toException StackOverflow
738 heapOverflow = toException HeapOverflow
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"
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
751 showsPrec _ (UndefinedElement s)
752 = showString "undefined array element"
753 . (if not (null s) then showString ": " . showString s
756 -- -----------------------------------------------------------------------------
759 -- We need it here because it is used in ExitException in the
760 -- Exception datatype (above).
763 = ExitSuccess -- ^ indicates successful termination;
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)
771 instance Exception ExitCode
773 ioException :: IOException -> IO a
774 ioException err = throwIO err
776 -- | Raise an 'IOError' in the 'IO' monad.
777 ioError :: IOError -> IO a
778 ioError = ioException
780 -- ---------------------------------------------------------------------------
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'.
788 -- In Haskell 98, this is an opaque type.
789 type IOError = IOException
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
797 ioe_handle :: Maybe Handle, -- the handle used by the action flagging
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.
807 instance Exception IOException
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
813 -- | An abstract type that contains a value for each variant of 'IOError'.
825 | UnsatisfiedConstraints
832 | UnsupportedOperation
837 instance Eq IOErrorType where
838 x == y = getTag x ==# getTag y
840 instance Show IOErrorType where
844 AlreadyExists -> "already exists"
845 NoSuchThing -> "does not exist"
846 ResourceBusy -> "resource busy"
847 ResourceExhausted -> "resource exhausted"
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"
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:
868 -- > instance Monad IO where
870 -- > fail s = ioError (userError s)
872 userError :: String -> IOError
873 userError str = IOError Nothing UserError "" str Nothing Nothing
875 -- ---------------------------------------------------------------------------
878 instance Show IOException where
879 showsPrec p (IOError hdl iot loc s _ fn) =
881 Nothing -> case hdl of
883 Just h -> showsPrec p h . showString ": "
884 Just name -> showString name . showString ": ") .
887 _ -> showString loc . showString ": ") .
891 _ -> showString " (" . showString s . showString ")")
893 -- -----------------------------------------------------------------------------
896 data IOMode = ReadMode | WriteMode | AppendMode | ReadWriteMode
897 deriving (Eq, Ord, Ix, Enum, Read, Show)
900 %*********************************************************
902 \subsection{Primitive catch and throwIO}
904 %*********************************************************
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...).
913 catch# :: IO a -> (b -> IO a) -> IO a
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).
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')
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)
929 -- | A variant of 'throw' that can only be used within the 'IO' monad.
931 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
932 -- two functions are subtly different:
934 -- > throw e `seq` x ===> throw e
935 -- > throwIO e `seq` x ===> x
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'
944 throwIO :: Exception e => e -> IO a
945 throwIO e = IO (raiseIO# (toException e))
949 %*********************************************************
951 \subsection{Controlling asynchronous exception delivery}
953 %*********************************************************
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
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
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
979 block (IO io) = IO $ blockAsyncExceptions# io
980 unblock (IO io) = IO $ unblockAsyncExceptions# io
982 -- | returns True if asynchronous exceptions are blocked in the
985 blocked = IO $ \s -> case asyncExceptionsBlocked# s of
986 (# s', i #) -> (# s', i /=# 0# #)
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
995 -- > evaluate x `seq` y ==> y
996 -- > evaluate x `catch` f ==> (return $! x) `catch` f
997 -- > evaluate x >>= f ==> (return $! x) >>= f
999 -- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
1000 -- same as @(return $! x)@. A correct definition is
1002 -- > evaluate x = (return $! x) >>= return
1004 evaluate :: a -> IO a
1005 evaluate a = IO $ \s -> case a `seq` () of () -> (# s, a #)
1007 -- a `seq` (# s, a #)
1008 -- because we can't have an unboxed tuple as a function argument
1012 assertError :: Addr# -> Bool -> a -> a
1013 assertError str predicate v
1015 | otherwise = throw (AssertionFailed (untangle str "Assertion failed"))
1018 (untangle coded message) expects "coded" to be of the form
1021 location message details
1023 untangle :: Addr# -> String -> String
1024 untangle coded message
1031 coded_str = unpackCStringUtf8# coded
1034 = case (span not_bar coded_str) of { (loc, rest) ->
1036 ('|':det) -> (loc, ' ' : det)
1039 not_bar c = c /= '|'