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, unsafeWriteIOArray,
33 -- Handles, file descriptors,
35 Handle(..), Handle__(..), HandleType(..), IOMode(..), FD,
36 isReadableHandleType, isWritableHandleType, isReadWriteHandleType, showHandle,
39 Buffer(..), RawBuffer, BufferState(..), BufferList(..), BufferMode(..),
40 bufferIsWritable, bufferEmpty, bufferFull,
43 Exception(..), ArithException(..), AsyncException(..), ArrayException(..),
44 stackOverflow, heapOverflow, ioException,
45 IOError, IOException(..), IOErrorType(..), ioError, userError,
47 throwIO, block, unblock, blocked, catchAny, catchException,
49 ErrorCall(..), AssertionFailed(..), assertError, untangle,
50 BlockedOnDeadMVar(..), BlockedIndefinitely(..), Deadlock(..),
51 blockedOnDeadMVar, blockedIndefinitely
55 import GHC.Arr -- to derive Ix class
56 import GHC.Enum -- to derive Enum class
59 -- import GHC.Num -- To get fromInteger etc, needed because of -XNoImplicitPrelude
60 import Data.Maybe ( Maybe(..) )
64 import Foreign.C.Types (CInt)
68 import {-# SOURCE #-} Data.Typeable ( Typeable )
71 -- ---------------------------------------------------------------------------
75 The IO Monad is just an instance of the ST monad, where the state is
76 the real world. We use the exception mechanism (in GHC.Exception) to
77 implement IO exceptions.
79 NOTE: The IO representation is deeply wired in to various parts of the
80 system. The following list may or may not be exhaustive:
82 Compiler - types of various primitives in PrimOp.lhs
84 RTS - forceIO (StgMiscClosures.hc)
85 - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast
87 - raiseAsync (Schedule.c)
89 Prelude - GHC.IOBase.lhs, and several other places including
92 Libraries - parts of hslibs/lang.
98 A value of type @'IO' a@ is a computation which, when performed,
99 does some I\/O before returning a value of type @a@.
101 There is really only one way to \"perform\" an I\/O action: bind it to
102 @Main.main@ in your program. When your program is run, the I\/O will
103 be performed. It isn't possible to perform I\/O from an arbitrary
104 function, unless that function is itself in the 'IO' monad and called
105 at some point, directly or indirectly, from @Main.main@.
107 'IO' is a monad, so 'IO' actions can be combined using either the do-notation
108 or the '>>' and '>>=' operations from the 'Monad' class.
110 newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #))
112 unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
115 instance Functor IO where
116 fmap f x = x >>= (return . f)
118 instance Monad IO where
119 {-# INLINE return #-}
122 m >> k = m >>= \ _ -> k
123 return x = returnIO x
128 failIO :: String -> IO a
129 failIO s = ioError (userError s)
131 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
132 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
134 bindIO :: IO a -> (a -> IO b) -> IO b
135 bindIO (IO m) k = IO ( \ s ->
137 (# new_s, a #) -> unIO (k a) new_s
140 thenIO :: IO a -> IO b -> IO b
141 thenIO (IO m) k = IO ( \ s ->
143 (# new_s, _ #) -> unIO k new_s
146 returnIO :: a -> IO a
147 returnIO x = IO (\ s -> (# s, x #))
149 -- ---------------------------------------------------------------------------
150 -- Coercions between IO and ST
152 -- | A monad transformer embedding strict state transformers in the 'IO'
153 -- monad. The 'RealWorld' parameter indicates that the internal state
154 -- used by the 'ST' computation is a special one supplied by the 'IO'
155 -- monad, and thus distinct from those used by invocations of 'runST'.
156 stToIO :: ST RealWorld a -> IO a
159 ioToST :: IO a -> ST RealWorld a
160 ioToST (IO m) = (ST m)
162 -- This relies on IO and ST having the same representation modulo the
163 -- constraint on the type of the state
165 unsafeIOToST :: IO a -> ST s a
166 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
168 unsafeSTToIO :: ST s a -> IO a
169 unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
171 -- ---------------------------------------------------------------------------
172 -- Unsafe IO operations
175 This is the \"back door\" into the 'IO' monad, allowing
176 'IO' computation to be performed at any time. For
177 this to be safe, the 'IO' computation should be
178 free of side effects and independent of its environment.
180 If the I\/O computation wrapped in 'unsafePerformIO'
181 performs side effects, then the relative order in which those side
182 effects take place (relative to the main I\/O trunk, or other calls to
183 'unsafePerformIO') is indeterminate. You have to be careful when
184 writing and compiling modules that use 'unsafePerformIO':
186 * Use @{\-\# NOINLINE foo \#-\}@ as a pragma on any function @foo@
187 that calls 'unsafePerformIO'. If the call is inlined,
188 the I\/O may be performed more than once.
190 * Use the compiler flag @-fno-cse@ to prevent common sub-expression
191 elimination being performed on the module, which might combine
192 two side effects that were meant to be separate. A good example
193 is using multiple global variables (like @test@ in the example below).
195 * Make sure that the either you switch off let-floating, or that the
196 call to 'unsafePerformIO' cannot float outside a lambda. For example,
199 f x = unsafePerformIO (newIORef [])
201 you may get only one reference cell shared between all calls to @f@.
204 f x = unsafePerformIO (newIORef [x])
206 because now it can't float outside the lambda.
208 It is less well known that
209 'unsafePerformIO' is not type safe. For example:
212 > test = unsafePerformIO $ newIORef []
215 > writeIORef test [42]
216 > bang <- readIORef test
217 > print (bang :: [Char])
219 This program will core dump. This problem with polymorphic references
220 is well known in the ML community, and does not arise with normal
221 monadic use of references. There is no easy way to make it impossible
222 once you use 'unsafePerformIO'. Indeed, it is
223 possible to write @coerce :: a -> b@ with the
224 help of 'unsafePerformIO'. So be careful!
226 unsafePerformIO :: IO a -> a
227 unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)
230 This version of 'unsafePerformIO' is slightly more efficient,
231 because it omits the check that the IO is only being performed by a
232 single thread. Hence, when you write 'unsafeDupablePerformIO',
233 there is a possibility that the IO action may be performed multiple
234 times (on a multiprocessor), and you should therefore ensure that
235 it gives the same results each time.
237 {-# NOINLINE unsafeDupablePerformIO #-}
238 unsafeDupablePerformIO :: IO a -> a
239 unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
241 -- Why do we NOINLINE unsafeDupablePerformIO? See the comment with
242 -- GHC.ST.runST. Essentially the issue is that the IO computation
243 -- inside unsafePerformIO must be atomic: it must either all run, or
244 -- not at all. If we let the compiler see the application of the IO
245 -- to realWorld#, it might float out part of the IO.
247 -- Why is there a call to 'lazy' in unsafeDupablePerformIO?
248 -- If we don't have it, the demand analyser discovers the following strictness
249 -- for unsafeDupablePerformIO: C(U(AV))
251 -- unsafeDupablePerformIO (\s -> let r = f x in
252 -- case writeIORef v r s of (# s1, _ #) ->
254 -- The strictness analyser will find that the binding for r is strict,
255 -- (becuase of uPIO's strictness sig), and so it'll evaluate it before
256 -- doing the writeIORef. This actually makes tests/lib/should_run/memo002
259 -- Solution: don't expose the strictness of unsafeDupablePerformIO,
260 -- by hiding it with 'lazy'
263 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
264 When passed a value of type @IO a@, the 'IO' will only be performed
265 when the value of the @a@ is demanded. This is used to implement lazy
266 file reading, see 'System.IO.hGetContents'.
268 {-# INLINE unsafeInterleaveIO #-}
269 unsafeInterleaveIO :: IO a -> IO a
270 unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)
272 -- We believe that INLINE on unsafeInterleaveIO is safe, because the
273 -- state from this IO thread is passed explicitly to the interleaved
274 -- IO, so it cannot be floated out and shared.
276 {-# INLINE unsafeDupableInterleaveIO #-}
277 unsafeDupableInterleaveIO :: IO a -> IO a
278 unsafeDupableInterleaveIO (IO m)
280 r = case m s of (# _, res #) -> res
285 Ensures that the suspensions under evaluation by the current thread
286 are unique; that is, the current thread is not evaluating anything
287 that is also under evaluation by another thread that has also executed
290 This operation is used in the definition of 'unsafePerformIO' to
291 prevent the IO action from being executed multiple times, which is usually
295 noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)
297 -- ---------------------------------------------------------------------------
300 data MVar a = MVar (MVar# RealWorld a)
302 An 'MVar' (pronounced \"em-var\") is a synchronising variable, used
303 for communication between concurrent threads. It can be thought of
304 as a a box, which may be empty or full.
307 -- pull in Eq (Mvar a) too, to avoid GHC.Conc being an orphan-instance module
308 instance Eq (MVar a) where
309 (MVar mvar1#) == (MVar mvar2#) = sameMVar# mvar1# mvar2#
311 -- A Handle is represented by (a reference to) a record
312 -- containing the state of the I/O port/device. We record
313 -- the following pieces of info:
315 -- * type (read,write,closed etc.)
316 -- * the underlying file descriptor
318 -- * buffer, and spare buffers
319 -- * user-friendly name (usually the
320 -- FilePath used when IO.openFile was called)
322 -- Note: when a Handle is garbage collected, we want to flush its buffer
323 -- and close the OS file handle, so as to free up a (precious) resource.
325 -- | Haskell defines operations to read and write characters from and to files,
326 -- represented by values of type @Handle@. Each value of this type is a
327 -- /handle/: a record used by the Haskell run-time system to /manage/ I\/O
328 -- with file system objects. A handle has at least the following properties:
330 -- * whether it manages input or output or both;
332 -- * whether it is /open/, /closed/ or /semi-closed/;
334 -- * whether the object is seekable;
336 -- * whether buffering is disabled, or enabled on a line or block basis;
338 -- * a buffer (whose length may be zero).
340 -- Most handles will also have a current I\/O position indicating where the next
341 -- input or output operation will occur. A handle is /readable/ if it
342 -- manages only input or both input and output; likewise, it is /writable/ if
343 -- it manages only output or both input and output. A handle is /open/ when
345 -- Once it is closed it can no longer be used for either input or output,
346 -- though an implementation cannot re-use its storage while references
347 -- remain to it. Handles are in the 'Show' and 'Eq' classes. The string
348 -- produced by showing a handle is system dependent; it should include
349 -- enough information to identify the handle for debugging. A handle is
350 -- equal according to '==' only to itself; no attempt
351 -- is made to compare the internal state of different handles for equality.
353 -- GHC note: a 'Handle' will be automatically closed when the garbage
354 -- collector detects that it has become unreferenced by the program.
355 -- However, relying on this behaviour is not generally recommended:
356 -- the garbage collector is unpredictable. If possible, use explicit
357 -- an explicit 'hClose' to close 'Handle's when they are no longer
358 -- required. GHC does not currently attempt to free up file
359 -- descriptors when they have run out, it is your responsibility to
360 -- ensure that this doesn't happen.
363 = FileHandle -- A normal handle to a file
364 FilePath -- the file (invariant)
367 | DuplexHandle -- A handle to a read/write stream
368 FilePath -- file for a FIFO, otherwise some
369 -- descriptive string.
370 !(MVar Handle__) -- The read side
371 !(MVar Handle__) -- The write side
374 -- * A 'FileHandle' is seekable. A 'DuplexHandle' may or may not be
377 instance Eq Handle where
378 (FileHandle _ h1) == (FileHandle _ h2) = h1 == h2
379 (DuplexHandle _ h1 _) == (DuplexHandle _ h2 _) = h1 == h2
386 haFD :: !FD, -- file descriptor
387 haType :: HandleType, -- type (read/write/append etc.)
388 haIsBin :: Bool, -- binary mode?
389 haIsStream :: Bool, -- Windows : is this a socket?
390 -- Unix : is O_NONBLOCK set?
391 haBufferMode :: BufferMode, -- buffer contains read/write data?
392 haBuffer :: !(IORef Buffer), -- the current buffer
393 haBuffers :: !(IORef BufferList), -- spare buffers
394 haOtherSide :: Maybe (MVar Handle__) -- ptr to the write side of a
398 -- ---------------------------------------------------------------------------
401 -- The buffer is represented by a mutable variable containing a
402 -- record, where the record contains the raw buffer and the start/end
403 -- points of the filled portion. We use a mutable variable so that
404 -- the common operation of writing (or reading) some data from (to)
405 -- the buffer doesn't need to modify, and hence copy, the handle
406 -- itself, it just updates the buffer.
408 -- There will be some allocation involved in a simple hPutChar in
409 -- order to create the new Buffer structure (below), but this is
410 -- relatively small, and this only has to be done once per write
413 -- The buffer contains its size - we could also get the size by
414 -- calling sizeOfMutableByteArray# on the raw buffer, but that tends
415 -- to be rounded up to the nearest Word.
417 type RawBuffer = MutableByteArray# RealWorld
419 -- INVARIANTS on a Buffer:
421 -- * A handle *always* has a buffer, even if it is only 1 character long
422 -- (an unbuffered handle needs a 1 character buffer in order to support
423 -- hLookAhead and hIsEOF).
425 -- * if r == w, then r == 0 && w == 0
426 -- * if state == WriteBuffer, then r == 0
427 -- * a write buffer is never full. If an operation
428 -- fills up the buffer, it will always flush it before
430 -- * a read buffer may be full as a result of hLookAhead. In normal
431 -- operation, a read buffer always has at least one character of space.
439 bufState :: BufferState
442 data BufferState = ReadBuffer | WriteBuffer deriving (Eq)
444 -- we keep a few spare buffers around in a handle to avoid allocating
445 -- a new one for each hPutStr. These buffers are *guaranteed* to be the
446 -- same size as the main buffer.
449 | BufferListCons RawBuffer BufferList
452 bufferIsWritable :: Buffer -> Bool
453 bufferIsWritable Buffer{ bufState=WriteBuffer } = True
454 bufferIsWritable _other = False
456 bufferEmpty :: Buffer -> Bool
457 bufferEmpty Buffer{ bufRPtr=r, bufWPtr=w } = r == w
459 -- only makes sense for a write buffer
460 bufferFull :: Buffer -> Bool
461 bufferFull b@Buffer{ bufWPtr=w } = w >= bufSize b
463 -- Internally, we classify handles as being one
474 isReadableHandleType :: HandleType -> Bool
475 isReadableHandleType ReadHandle = True
476 isReadableHandleType ReadWriteHandle = True
477 isReadableHandleType _ = False
479 isWritableHandleType :: HandleType -> Bool
480 isWritableHandleType AppendHandle = True
481 isWritableHandleType WriteHandle = True
482 isWritableHandleType ReadWriteHandle = True
483 isWritableHandleType _ = False
485 isReadWriteHandleType :: HandleType -> Bool
486 isReadWriteHandleType ReadWriteHandle{} = True
487 isReadWriteHandleType _ = False
489 -- | File and directory names are values of type 'String', whose precise
490 -- meaning is operating system dependent. Files can be opened, yielding a
491 -- handle which can then be used to operate on the contents of that file.
493 type FilePath = String
495 -- ---------------------------------------------------------------------------
498 -- | Three kinds of buffering are supported: line-buffering,
499 -- block-buffering or no-buffering. These modes have the following
500 -- effects. For output, items are written out, or /flushed/,
501 -- from the internal buffer according to the buffer mode:
503 -- * /line-buffering/: the entire output buffer is flushed
504 -- whenever a newline is output, the buffer overflows,
505 -- a 'System.IO.hFlush' is issued, or the handle is closed.
507 -- * /block-buffering/: the entire buffer is written out whenever it
508 -- overflows, a 'System.IO.hFlush' is issued, or the handle is closed.
510 -- * /no-buffering/: output is written immediately, and never stored
513 -- An implementation is free to flush the buffer more frequently,
514 -- but not less frequently, than specified above.
515 -- The output buffer is emptied as soon as it has been written out.
517 -- Similarly, input occurs according to the buffer mode for the handle:
519 -- * /line-buffering/: when the buffer for the handle is not empty,
520 -- the next item is obtained from the buffer; otherwise, when the
521 -- buffer is empty, characters up to and including the next newline
522 -- character are read into the buffer. No characters are available
523 -- until the newline character is available or the buffer is full.
525 -- * /block-buffering/: when the buffer for the handle becomes empty,
526 -- the next block of data is read into the buffer.
528 -- * /no-buffering/: the next input item is read and returned.
529 -- The 'System.IO.hLookAhead' operation implies that even a no-buffered
530 -- handle may require a one-character buffer.
532 -- The default buffering mode when a handle is opened is
533 -- implementation-dependent and may depend on the file system object
534 -- which is attached to that handle.
535 -- For most implementations, physical files will normally be block-buffered
536 -- and terminals will normally be line-buffered.
539 = NoBuffering -- ^ buffering is disabled if possible.
541 -- ^ line-buffering should be enabled if possible.
542 | BlockBuffering (Maybe Int)
543 -- ^ block-buffering should be enabled if possible.
544 -- The size of the buffer is @n@ items if the argument
545 -- is 'Just' @n@ and is otherwise implementation-dependent.
546 deriving (Eq, Ord, Read, Show)
548 -- ---------------------------------------------------------------------------
551 -- |A mutable variable in the 'IO' monad
552 newtype IORef a = IORef (STRef RealWorld a)
554 -- explicit instance because Haddock can't figure out a derived one
555 instance Eq (IORef a) where
556 IORef x == IORef y = x == y
558 -- |Build a new 'IORef'
559 newIORef :: a -> IO (IORef a)
560 newIORef v = stToIO (newSTRef v) >>= \ var -> return (IORef var)
562 -- |Read the value of an 'IORef'
563 readIORef :: IORef a -> IO a
564 readIORef (IORef var) = stToIO (readSTRef var)
566 -- |Write a new value into an 'IORef'
567 writeIORef :: IORef a -> a -> IO ()
568 writeIORef (IORef var) v = stToIO (writeSTRef var v)
570 -- ---------------------------------------------------------------------------
571 -- | An 'IOArray' is a mutable, boxed, non-strict array in the 'IO' monad.
572 -- The type arguments are as follows:
574 -- * @i@: the index type of the array (should be an instance of 'Ix')
576 -- * @e@: the element type of the array.
580 newtype IOArray i e = IOArray (STArray RealWorld i e)
582 -- explicit instance because Haddock can't figure out a derived one
583 instance Eq (IOArray i e) where
584 IOArray x == IOArray y = x == y
586 -- |Build a new 'IOArray'
587 newIOArray :: Ix i => (i,i) -> e -> IO (IOArray i e)
588 {-# INLINE newIOArray #-}
589 newIOArray lu initial = stToIO $ do {marr <- newSTArray lu initial; return (IOArray marr)}
591 -- | Read a value from an 'IOArray'
592 unsafeReadIOArray :: Ix i => IOArray i e -> Int -> IO e
593 {-# INLINE unsafeReadIOArray #-}
594 unsafeReadIOArray (IOArray marr) i = stToIO (unsafeReadSTArray marr i)
596 -- | Write a new value into an 'IOArray'
597 unsafeWriteIOArray :: Ix i => IOArray i e -> Int -> e -> IO ()
598 {-# INLINE unsafeWriteIOArray #-}
599 unsafeWriteIOArray (IOArray marr) i e = stToIO (unsafeWriteSTArray marr i e)
601 -- | Read a value from an 'IOArray'
602 readIOArray :: Ix i => IOArray i e -> i -> IO e
603 readIOArray (IOArray marr) i = stToIO (readSTArray marr i)
605 -- | Write a new value into an 'IOArray'
606 writeIOArray :: Ix i => IOArray i e -> i -> e -> IO ()
607 writeIOArray (IOArray marr) i e = stToIO (writeSTArray marr i e)
610 -- ---------------------------------------------------------------------------
611 -- Show instance for Handles
613 -- handle types are 'show'n when printing error msgs, so
614 -- we provide a more user-friendly Show instance for it
615 -- than the derived one.
617 instance Show HandleType where
620 ClosedHandle -> showString "closed"
621 SemiClosedHandle -> showString "semi-closed"
622 ReadHandle -> showString "readable"
623 WriteHandle -> showString "writable"
624 AppendHandle -> showString "writable (append)"
625 ReadWriteHandle -> showString "read-writable"
627 instance Show Handle where
628 showsPrec _ (FileHandle file _) = showHandle file
629 showsPrec _ (DuplexHandle file _ _) = showHandle file
631 showHandle :: FilePath -> String -> String
632 showHandle file = showString "{handle: " . showString file . showString "}"
634 -- ------------------------------------------------------------------------
635 -- Exception datatypes and operations
637 data BlockedOnDeadMVar = BlockedOnDeadMVar
640 instance Exception BlockedOnDeadMVar
642 instance Show BlockedOnDeadMVar where
643 showsPrec _ BlockedOnDeadMVar = showString "thread blocked indefinitely"
645 blockedOnDeadMVar :: SomeException -- for the RTS
646 blockedOnDeadMVar = toException BlockedOnDeadMVar
650 data BlockedIndefinitely = BlockedIndefinitely
653 instance Exception BlockedIndefinitely
655 instance Show BlockedIndefinitely where
656 showsPrec _ BlockedIndefinitely = showString "thread blocked indefinitely"
658 blockedIndefinitely :: SomeException -- for the RTS
659 blockedIndefinitely = toException BlockedIndefinitely
663 data Deadlock = Deadlock
666 instance Exception Deadlock
668 instance Show Deadlock where
669 showsPrec _ Deadlock = showString "<<deadlock>>"
673 data AssertionFailed = AssertionFailed String
676 instance Exception AssertionFailed
678 instance Show AssertionFailed where
679 showsPrec _ (AssertionFailed err) = showString err
683 -- |Asynchronous exceptions
686 -- ^The current thread\'s stack exceeded its limit.
687 -- Since an exception has been raised, the thread\'s stack
688 -- will certainly be below its limit again, but the
689 -- programmer should take remedial action
692 -- ^The program\'s heap is reaching its limit, and
693 -- the program should take action to reduce the amount of
694 -- live data it has. Notes:
696 -- * It is undefined which thread receives this exception.
698 -- * GHC currently does not throw 'HeapOverflow' exceptions.
700 -- ^This exception is raised by another thread
701 -- calling 'Control.Concurrent.killThread', or by the system
702 -- if it needs to terminate the thread for some
705 -- ^This exception is raised by default in the main thread of
706 -- the program when the user requests to terminate the program
707 -- via the usual mechanism(s) (e.g. Control-C in the console).
708 deriving (Eq, Ord, Typeable)
710 instance Exception AsyncException
712 -- | Exceptions generated by array operations
714 = IndexOutOfBounds String
715 -- ^An attempt was made to index an array outside
716 -- its declared bounds.
717 | UndefinedElement String
718 -- ^An attempt was made to evaluate an element of an
719 -- array that had not been initialized.
720 deriving (Eq, Ord, Typeable)
722 instance Exception ArrayException
724 stackOverflow, heapOverflow :: SomeException -- for the RTS
725 stackOverflow = toException StackOverflow
726 heapOverflow = toException HeapOverflow
728 instance Show AsyncException where
729 showsPrec _ StackOverflow = showString "stack overflow"
730 showsPrec _ HeapOverflow = showString "heap overflow"
731 showsPrec _ ThreadKilled = showString "thread killed"
732 showsPrec _ UserInterrupt = showString "user interrupt"
734 instance Show ArrayException where
735 showsPrec _ (IndexOutOfBounds s)
736 = showString "array index out of range"
737 . (if not (null s) then showString ": " . showString s
739 showsPrec _ (UndefinedElement s)
740 = showString "undefined array element"
741 . (if not (null s) then showString ": " . showString s
744 -- -----------------------------------------------------------------------------
747 -- We need it here because it is used in ExitException in the
748 -- Exception datatype (above).
751 = ExitSuccess -- ^ indicates successful termination;
753 -- ^ indicates program failure with an exit code.
754 -- The exact interpretation of the code is
755 -- operating-system dependent. In particular, some values
756 -- may be prohibited (e.g. 0 on a POSIX-compliant system).
757 deriving (Eq, Ord, Read, Show, Typeable)
759 instance Exception ExitCode
761 ioException :: IOException -> IO a
762 ioException err = throwIO err
764 -- | Raise an 'IOError' in the 'IO' monad.
765 ioError :: IOError -> IO a
766 ioError = ioException
768 -- ---------------------------------------------------------------------------
771 -- | The Haskell 98 type for exceptions in the 'IO' monad.
772 -- Any I\/O operation may raise an 'IOError' instead of returning a result.
773 -- For a more general type of exception, including also those that arise
774 -- in pure code, see 'Control.Exception.Exception'.
776 -- In Haskell 98, this is an opaque type.
777 type IOError = IOException
779 -- |Exceptions that occur in the @IO@ monad.
780 -- An @IOException@ records a more specific error type, a descriptive
781 -- string and maybe the handle that was used when the error was
785 ioe_handle :: Maybe Handle, -- the handle used by the action flagging
787 ioe_type :: IOErrorType, -- what it was.
788 ioe_location :: String, -- location.
789 ioe_description :: String, -- error type specific information.
790 ioe_errno :: Maybe CInt, -- errno leading to this error, if any.
791 ioe_filename :: Maybe FilePath -- filename the error is related to.
795 instance Exception IOException
797 instance Eq IOException where
798 (IOError h1 e1 loc1 str1 en1 fn1) == (IOError h2 e2 loc2 str2 en2 fn2) =
799 e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && en1==en2 && fn1==fn2
801 -- | An abstract type that contains a value for each variant of 'IOError'.
813 | UnsatisfiedConstraints
820 | UnsupportedOperation
825 instance Eq IOErrorType where
826 x == y = getTag x ==# getTag y
828 instance Show IOErrorType where
832 AlreadyExists -> "already exists"
833 NoSuchThing -> "does not exist"
834 ResourceBusy -> "resource busy"
835 ResourceExhausted -> "resource exhausted"
837 IllegalOperation -> "illegal operation"
838 PermissionDenied -> "permission denied"
839 UserError -> "user error"
840 HardwareFault -> "hardware fault"
841 InappropriateType -> "inappropriate type"
842 Interrupted -> "interrupted"
843 InvalidArgument -> "invalid argument"
844 OtherError -> "failed"
845 ProtocolError -> "protocol error"
846 ResourceVanished -> "resource vanished"
847 SystemError -> "system error"
848 TimeExpired -> "timeout"
849 UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise!
850 UnsupportedOperation -> "unsupported operation"
852 -- | Construct an 'IOError' value with a string describing the error.
853 -- The 'fail' method of the 'IO' instance of the 'Monad' class raises a
854 -- 'userError', thus:
856 -- > instance Monad IO where
858 -- > fail s = ioError (userError s)
860 userError :: String -> IOError
861 userError str = IOError Nothing UserError "" str Nothing Nothing
863 -- ---------------------------------------------------------------------------
866 instance Show IOException where
867 showsPrec p (IOError hdl iot loc s _ fn) =
869 Nothing -> case hdl of
871 Just h -> showsPrec p h . showString ": "
872 Just name -> showString name . showString ": ") .
875 _ -> showString loc . showString ": ") .
879 _ -> showString " (" . showString s . showString ")")
881 -- -----------------------------------------------------------------------------
884 data IOMode = ReadMode | WriteMode | AppendMode | ReadWriteMode
885 deriving (Eq, Ord, Ix, Enum, Read, Show)
888 %*********************************************************
890 \subsection{Primitive catch and throwIO}
892 %*********************************************************
894 catchException used to handle the passing around of the state to the
895 action and the handler. This turned out to be a bad idea - it meant
896 that we had to wrap both arguments in thunks so they could be entered
897 as normal (remember IO returns an unboxed pair...).
901 catch# :: IO a -> (b -> IO a) -> IO a
903 (well almost; the compiler doesn't know about the IO newtype so we
904 have to work around that in the definition of catchException below).
907 catchException :: Exception e => IO a -> (e -> IO a) -> IO a
908 catchException (IO io) handler = IO $ catch# io handler'
909 where handler' e = case fromException e of
910 Just e' -> unIO (handler e')
913 catchAny :: IO a -> (forall e . Exception e => e -> IO a) -> IO a
914 catchAny (IO io) handler = IO $ catch# io handler'
915 where handler' (SomeException e) = unIO (handler e)
917 -- | A variant of 'throw' that can be used within the 'IO' monad.
919 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
920 -- two functions are subtly different:
922 -- > throw e `seq` x ===> throw e
923 -- > throwIO e `seq` x ===> x
925 -- The first example will cause the exception @e@ to be raised,
926 -- whereas the second one won\'t. In fact, 'throwIO' will only cause
927 -- an exception to be raised when it is used within the 'IO' monad.
928 -- The 'throwIO' variant should be used in preference to 'throw' to
929 -- raise an exception within the 'IO' monad because it guarantees
930 -- ordering with respect to other 'IO' operations, whereas 'throw'
932 throwIO :: Exception e => e -> IO a
933 throwIO e = IO (raiseIO# (toException e))
937 %*********************************************************
939 \subsection{Controlling asynchronous exception delivery}
941 %*********************************************************
944 -- | Applying 'block' to a computation will
945 -- execute that computation with asynchronous exceptions
946 -- /blocked/. That is, any thread which
947 -- attempts to raise an exception in the current thread with 'Control.Exception.throwTo' will be
948 -- blocked until asynchronous exceptions are enabled again. There\'s
949 -- no need to worry about re-enabling asynchronous exceptions; that is
950 -- done automatically on exiting the scope of
953 -- Threads created by 'Control.Concurrent.forkIO' inherit the blocked
954 -- state from the parent; that is, to start a thread in blocked mode,
955 -- use @block $ forkIO ...@. This is particularly useful if you need to
956 -- establish an exception handler in the forked thread before any
957 -- asynchronous exceptions are received.
958 block :: IO a -> IO a
960 -- | To re-enable asynchronous exceptions inside the scope of
961 -- 'block', 'unblock' can be
962 -- used. It scopes in exactly the same way, so on exit from
963 -- 'unblock' asynchronous exception delivery will
964 -- be disabled again.
965 unblock :: IO a -> IO a
967 block (IO io) = IO $ blockAsyncExceptions# io
968 unblock (IO io) = IO $ unblockAsyncExceptions# io
970 -- | returns True if asynchronous exceptions are blocked in the
973 blocked = IO $ \s -> case asyncExceptionsBlocked# s of
974 (# s', i #) -> (# s', i /=# 0# #)
978 -- | Forces its argument to be evaluated when the resultant 'IO' action
979 -- is executed. It can be used to order evaluation with respect to
980 -- other 'IO' operations; its semantics are given by
982 -- > evaluate x `seq` y ==> y
983 -- > evaluate x `catch` f ==> (return $! x) `catch` f
984 -- > evaluate x >>= f ==> (return $! x) >>= f
986 -- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
987 -- same as @(return $! x)@. A correct definition is
989 -- > evaluate x = (return $! x) >>= return
991 evaluate :: a -> IO a
992 evaluate a = IO $ \s -> case a `seq` () of () -> (# s, a #)
994 -- a `seq` (# s, a #)
995 -- because we can't have an unboxed tuple as a function argument
999 assertError :: Addr# -> Bool -> a -> a
1000 assertError str predicate v
1002 | otherwise = throw (AssertionFailed (untangle str "Assertion failed"))
1005 (untangle coded message) expects "coded" to be of the form
1008 location message details
1010 untangle :: Addr# -> String -> String
1011 untangle coded message
1018 coded_str = unpackCStringUtf8# coded
1021 = case (span not_bar coded_str) of { (loc, rest) ->
1023 ('|':det) -> (loc, ' ' : det)
1026 not_bar c = c /= '|'