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, catch, catchAny, catchException,
54 import GHC.Arr -- to derive Ix class
55 import GHC.Enum -- to derive Enum class
58 -- import GHC.Num -- To get fromInteger etc, needed because of -XNoImplicitPrelude
59 import Data.Maybe ( Maybe(..) )
63 import Foreign.C.Types (CInt)
64 import GHC.Exception hiding (Exception)
65 import qualified GHC.Exception as Exc
68 import {-# SOURCE #-} Data.Typeable ( showsTypeRep )
69 import {-# SOURCE #-} Data.Dynamic ( Dynamic, dynTypeRep )
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, a #) -> 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 ReadHandle = True
476 isReadableHandleType ReadWriteHandle = True
477 isReadableHandleType _ = False
479 isWritableHandleType AppendHandle = True
480 isWritableHandleType WriteHandle = True
481 isWritableHandleType ReadWriteHandle = True
482 isWritableHandleType _ = False
484 isReadWriteHandleType ReadWriteHandle{} = True
485 isReadWriteHandleType _ = False
487 -- | File and directory names are values of type 'String', whose precise
488 -- meaning is operating system dependent. Files can be opened, yielding a
489 -- handle which can then be used to operate on the contents of that file.
491 type FilePath = String
493 -- ---------------------------------------------------------------------------
496 -- | Three kinds of buffering are supported: line-buffering,
497 -- block-buffering or no-buffering. These modes have the following
498 -- effects. For output, items are written out, or /flushed/,
499 -- from the internal buffer according to the buffer mode:
501 -- * /line-buffering/: the entire output buffer is flushed
502 -- whenever a newline is output, the buffer overflows,
503 -- a 'System.IO.hFlush' is issued, or the handle is closed.
505 -- * /block-buffering/: the entire buffer is written out whenever it
506 -- overflows, a 'System.IO.hFlush' is issued, or the handle is closed.
508 -- * /no-buffering/: output is written immediately, and never stored
511 -- An implementation is free to flush the buffer more frequently,
512 -- but not less frequently, than specified above.
513 -- The output buffer is emptied as soon as it has been written out.
515 -- Similarly, input occurs according to the buffer mode for the handle:
517 -- * /line-buffering/: when the buffer for the handle is not empty,
518 -- the next item is obtained from the buffer; otherwise, when the
519 -- buffer is empty, characters up to and including the next newline
520 -- character are read into the buffer. No characters are available
521 -- until the newline character is available or the buffer is full.
523 -- * /block-buffering/: when the buffer for the handle becomes empty,
524 -- the next block of data is read into the buffer.
526 -- * /no-buffering/: the next input item is read and returned.
527 -- The 'System.IO.hLookAhead' operation implies that even a no-buffered
528 -- handle may require a one-character buffer.
530 -- The default buffering mode when a handle is opened is
531 -- implementation-dependent and may depend on the file system object
532 -- which is attached to that handle.
533 -- For most implementations, physical files will normally be block-buffered
534 -- and terminals will normally be line-buffered.
537 = NoBuffering -- ^ buffering is disabled if possible.
539 -- ^ line-buffering should be enabled if possible.
540 | BlockBuffering (Maybe Int)
541 -- ^ block-buffering should be enabled if possible.
542 -- The size of the buffer is @n@ items if the argument
543 -- is 'Just' @n@ and is otherwise implementation-dependent.
544 deriving (Eq, Ord, Read, Show)
546 -- ---------------------------------------------------------------------------
549 -- |A mutable variable in the 'IO' monad
550 newtype IORef a = IORef (STRef RealWorld a)
552 -- explicit instance because Haddock can't figure out a derived one
553 instance Eq (IORef a) where
554 IORef x == IORef y = x == y
556 -- |Build a new 'IORef'
557 newIORef :: a -> IO (IORef a)
558 newIORef v = stToIO (newSTRef v) >>= \ var -> return (IORef var)
560 -- |Read the value of an 'IORef'
561 readIORef :: IORef a -> IO a
562 readIORef (IORef var) = stToIO (readSTRef var)
564 -- |Write a new value into an 'IORef'
565 writeIORef :: IORef a -> a -> IO ()
566 writeIORef (IORef var) v = stToIO (writeSTRef var v)
568 -- ---------------------------------------------------------------------------
569 -- | An 'IOArray' is a mutable, boxed, non-strict array in the 'IO' monad.
570 -- The type arguments are as follows:
572 -- * @i@: the index type of the array (should be an instance of 'Ix')
574 -- * @e@: the element type of the array.
578 newtype IOArray i e = IOArray (STArray RealWorld i e)
580 -- explicit instance because Haddock can't figure out a derived one
581 instance Eq (IOArray i e) where
582 IOArray x == IOArray y = x == y
584 -- |Build a new 'IOArray'
585 newIOArray :: Ix i => (i,i) -> e -> IO (IOArray i e)
586 {-# INLINE newIOArray #-}
587 newIOArray lu init = stToIO $ do {marr <- newSTArray lu init; return (IOArray marr)}
589 -- | Read a value from an 'IOArray'
590 unsafeReadIOArray :: Ix i => IOArray i e -> Int -> IO e
591 {-# INLINE unsafeReadIOArray #-}
592 unsafeReadIOArray (IOArray marr) i = stToIO (unsafeReadSTArray marr i)
594 -- | Write a new value into an 'IOArray'
595 unsafeWriteIOArray :: Ix i => IOArray i e -> Int -> e -> IO ()
596 {-# INLINE unsafeWriteIOArray #-}
597 unsafeWriteIOArray (IOArray marr) i e = stToIO (unsafeWriteSTArray marr i e)
599 -- | Read a value from an 'IOArray'
600 readIOArray :: Ix i => IOArray i e -> i -> IO e
601 readIOArray (IOArray marr) i = stToIO (readSTArray marr i)
603 -- | Write a new value into an 'IOArray'
604 writeIOArray :: Ix i => IOArray i e -> i -> e -> IO ()
605 writeIOArray (IOArray marr) i e = stToIO (writeSTArray marr i e)
608 -- ---------------------------------------------------------------------------
609 -- Show instance for Handles
611 -- handle types are 'show'n when printing error msgs, so
612 -- we provide a more user-friendly Show instance for it
613 -- than the derived one.
615 instance Show HandleType where
618 ClosedHandle -> showString "closed"
619 SemiClosedHandle -> showString "semi-closed"
620 ReadHandle -> showString "readable"
621 WriteHandle -> showString "writable"
622 AppendHandle -> showString "writable (append)"
623 ReadWriteHandle -> showString "read-writable"
625 instance Show Handle where
626 showsPrec p (FileHandle file _) = showHandle file
627 showsPrec p (DuplexHandle file _ _) = showHandle file
629 showHandle file = showString "{handle: " . showString file . showString "}"
631 -- ------------------------------------------------------------------------
632 -- Exception datatype and operations
634 -- |The type of exceptions. Every kind of system-generated exception
635 -- has a constructor in the 'Exception' type, and values of other
636 -- types may be injected into 'Exception' by coercing them to
637 -- 'Data.Dynamic.Dynamic' (see the section on Dynamic Exceptions:
638 -- "Control.Exception\#DynamicExceptions").
640 = ArithException ArithException
641 -- ^Exceptions raised by arithmetic
642 -- operations. (NOTE: GHC currently does not throw
643 -- 'ArithException's except for 'DivideByZero').
644 | ArrayException ArrayException
645 -- ^Exceptions raised by array-related
646 -- operations. (NOTE: GHC currently does not throw
647 -- 'ArrayException's).
648 | AssertionFailed String
649 -- ^This exception is thrown by the
650 -- 'assert' operation when the condition
651 -- fails. The 'String' argument contains the
652 -- location of the assertion in the source program.
653 | AsyncException AsyncException
654 -- ^Asynchronous exceptions (see section on Asynchronous Exceptions: "Control.Exception\#AsynchronousExceptions").
656 -- ^The current thread was executing a call to
657 -- 'Control.Concurrent.MVar.takeMVar' that could never return,
658 -- because there are no other references to this 'MVar'.
659 | BlockedIndefinitely
660 -- ^The current thread was waiting to retry an atomic memory transaction
661 -- that could never become possible to complete because there are no other
662 -- threads referring to any of the TVars involved.
664 -- ^The runtime detected an attempt to nest one STM transaction
665 -- inside another one, presumably due to the use of
666 -- 'unsafePeformIO' with 'atomically'.
668 -- ^There are no runnable threads, so the program is
669 -- deadlocked. The 'Deadlock' exception is
670 -- raised in the main thread only (see also: "Control.Concurrent").
671 | DynException Dynamic
672 -- ^Dynamically typed exceptions (see section on Dynamic Exceptions: "Control.Exception\#DynamicExceptions").
674 -- ^The 'ErrorCall' exception is thrown by 'error'. The 'String'
675 -- argument of 'ErrorCall' is the string passed to 'error' when it was
677 | ExitException ExitCode
678 -- ^The 'ExitException' exception is thrown by 'System.Exit.exitWith' (and
679 -- 'System.Exit.exitFailure'). The 'ExitCode' argument is the value passed
680 -- to 'System.Exit.exitWith'. An unhandled 'ExitException' exception in the
681 -- main thread will cause the program to be terminated with the given
683 | IOException IOException
684 -- ^These are the standard IO exceptions generated by
685 -- Haskell\'s @IO@ operations. See also "System.IO.Error".
686 | NoMethodError String
687 -- ^An attempt was made to invoke a class method which has
688 -- no definition in this instance, and there was no default
689 -- definition given in the class declaration. GHC issues a
690 -- warning when you compile an instance which has missing
693 -- ^The current thread is stuck in an infinite loop. This
694 -- exception may or may not be thrown when the program is
696 | PatternMatchFail String
697 -- ^A pattern matching failure. The 'String' argument should contain a
698 -- descriptive message including the function name, source file
701 -- ^An attempt was made to evaluate a field of a record
702 -- for which no value was given at construction time. The
703 -- 'String' argument gives the location of the
704 -- record construction in the source program.
706 -- ^A field selection was attempted on a constructor that
707 -- doesn\'t have the requested field. This can happen with
708 -- multi-constructor records when one or more fields are
709 -- missing from some of the constructors. The
710 -- 'String' argument gives the location of the
711 -- record selection in the source program.
713 -- ^An attempt was made to update a field in a record,
714 -- where the record doesn\'t have the requested field. This can
715 -- only occur with multi-constructor records, when one or more
716 -- fields are missing from some of the constructors. The
717 -- 'String' argument gives the location of the
718 -- record update in the source program.
720 nonTermination :: SomeException
721 nonTermination = toException NonTermination
723 -- For now at least, make the monolithic Exception type an instance of
724 -- the Exception class
725 instance Exc.Exception Exception
727 -- |The type of arithmetic exceptions
737 -- |Asynchronous exceptions
740 -- ^The current thread\'s stack exceeded its limit.
741 -- Since an exception has been raised, the thread\'s stack
742 -- will certainly be below its limit again, but the
743 -- programmer should take remedial action
746 -- ^The program\'s heap is reaching its limit, and
747 -- the program should take action to reduce the amount of
748 -- live data it has. Notes:
750 -- * It is undefined which thread receives this exception.
752 -- * GHC currently does not throw 'HeapOverflow' exceptions.
754 -- ^This exception is raised by another thread
755 -- calling 'Control.Concurrent.killThread', or by the system
756 -- if it needs to terminate the thread for some
759 -- ^This exception is raised by default in the main thread of
760 -- the program when the user requests to terminate the program
761 -- via the usual mechanism(s) (e.g. Control-C in the console).
764 -- | Exceptions generated by array operations
766 = IndexOutOfBounds String
767 -- ^An attempt was made to index an array outside
768 -- its declared bounds.
769 | UndefinedElement String
770 -- ^An attempt was made to evaluate an element of an
771 -- array that had not been initialized.
774 stackOverflow, heapOverflow :: Exception -- for the RTS
775 stackOverflow = AsyncException StackOverflow
776 heapOverflow = AsyncException HeapOverflow
778 instance Show ArithException where
779 showsPrec _ Overflow = showString "arithmetic overflow"
780 showsPrec _ Underflow = showString "arithmetic underflow"
781 showsPrec _ LossOfPrecision = showString "loss of precision"
782 showsPrec _ DivideByZero = showString "divide by zero"
783 showsPrec _ Denormal = showString "denormal"
785 instance Show AsyncException where
786 showsPrec _ StackOverflow = showString "stack overflow"
787 showsPrec _ HeapOverflow = showString "heap overflow"
788 showsPrec _ ThreadKilled = showString "thread killed"
790 instance Show ArrayException where
791 showsPrec _ (IndexOutOfBounds s)
792 = showString "array index out of range"
793 . (if not (null s) then showString ": " . showString s
795 showsPrec _ (UndefinedElement s)
796 = showString "undefined array element"
797 . (if not (null s) then showString ": " . showString s
800 instance Show Exception where
801 showsPrec _ (IOException err) = shows err
802 showsPrec _ (ArithException err) = shows err
803 showsPrec _ (ArrayException err) = shows err
804 showsPrec _ (ErrorCall err) = showString err
805 showsPrec _ (ExitException err) = showString "exit: " . shows err
806 showsPrec _ (NoMethodError err) = showString err
807 showsPrec _ (PatternMatchFail err) = showString err
808 showsPrec _ (RecSelError err) = showString err
809 showsPrec _ (RecConError err) = showString err
810 showsPrec _ (RecUpdError err) = showString err
811 showsPrec _ (AssertionFailed err) = showString err
812 showsPrec _ (DynException err) = showString "exception :: " . showsTypeRep (dynTypeRep err)
813 showsPrec _ (AsyncException e) = shows e
814 showsPrec _ (BlockedOnDeadMVar) = showString "thread blocked indefinitely"
815 showsPrec _ (BlockedIndefinitely) = showString "thread blocked indefinitely"
816 showsPrec _ (NestedAtomically) = showString "Control.Concurrent.STM.atomically was nested"
817 showsPrec _ (NonTermination) = showString "<<loop>>"
818 showsPrec _ (Deadlock) = showString "<<deadlock>>"
820 instance Eq Exception where
821 IOException e1 == IOException e2 = e1 == e2
822 ArithException e1 == ArithException e2 = e1 == e2
823 ArrayException e1 == ArrayException e2 = e1 == e2
824 ErrorCall e1 == ErrorCall e2 = e1 == e2
825 ExitException e1 == ExitException e2 = e1 == e2
826 NoMethodError e1 == NoMethodError e2 = e1 == e2
827 PatternMatchFail e1 == PatternMatchFail e2 = e1 == e2
828 RecSelError e1 == RecSelError e2 = e1 == e2
829 RecConError e1 == RecConError e2 = e1 == e2
830 RecUpdError e1 == RecUpdError e2 = e1 == e2
831 AssertionFailed e1 == AssertionFailed e2 = e1 == e2
832 DynException _ == DynException _ = False -- incomparable
833 AsyncException e1 == AsyncException e2 = e1 == e2
834 BlockedOnDeadMVar == BlockedOnDeadMVar = True
835 NonTermination == NonTermination = True
836 NestedAtomically == NestedAtomically = True
837 Deadlock == Deadlock = True
840 -- -----------------------------------------------------------------------------
843 -- We need it here because it is used in ExitException in the
844 -- Exception datatype (above).
847 = ExitSuccess -- ^ indicates successful termination;
849 -- ^ indicates program failure with an exit code.
850 -- The exact interpretation of the code is
851 -- operating-system dependent. In particular, some values
852 -- may be prohibited (e.g. 0 on a POSIX-compliant system).
853 deriving (Eq, Ord, Read, Show)
855 ioException :: IOException -> IO a
856 ioException err = throwIO (IOException err)
858 -- | Raise an 'IOError' in the 'IO' monad.
859 ioError :: IOError -> IO a
860 ioError = ioException
862 -- ---------------------------------------------------------------------------
865 -- | The Haskell 98 type for exceptions in the 'IO' monad.
866 -- Any I\/O operation may raise an 'IOError' instead of returning a result.
867 -- For a more general type of exception, including also those that arise
868 -- in pure code, see 'Control.Exception.Exception'.
870 -- In Haskell 98, this is an opaque type.
871 type IOError = IOException
873 -- |Exceptions that occur in the @IO@ monad.
874 -- An @IOException@ records a more specific error type, a descriptive
875 -- string and maybe the handle that was used when the error was
879 ioe_handle :: Maybe Handle, -- the handle used by the action flagging
881 ioe_type :: IOErrorType, -- what it was.
882 ioe_location :: String, -- location.
883 ioe_description :: String, -- error type specific information.
884 ioe_filename :: Maybe FilePath -- filename the error is related to.
887 instance Eq IOException where
888 (IOError h1 e1 loc1 str1 fn1) == (IOError h2 e2 loc2 str2 fn2) =
889 e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && fn1==fn2
891 -- | An abstract type that contains a value for each variant of 'IOError'.
903 | UnsatisfiedConstraints
910 | UnsupportedOperation
914 | DynIOError Dynamic -- cheap&cheerful extensible IO error type.
916 instance Eq IOErrorType where
919 DynIOError{} -> False -- from a strictness POV, compatible with a derived Eq inst?
920 _ -> getTag x ==# getTag y
922 instance Show IOErrorType where
926 AlreadyExists -> "already exists"
927 NoSuchThing -> "does not exist"
928 ResourceBusy -> "resource busy"
929 ResourceExhausted -> "resource exhausted"
931 IllegalOperation -> "illegal operation"
932 PermissionDenied -> "permission denied"
933 UserError -> "user error"
934 HardwareFault -> "hardware fault"
935 InappropriateType -> "inappropriate type"
936 Interrupted -> "interrupted"
937 InvalidArgument -> "invalid argument"
938 OtherError -> "failed"
939 ProtocolError -> "protocol error"
940 ResourceVanished -> "resource vanished"
941 SystemError -> "system error"
942 TimeExpired -> "timeout"
943 UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise!
944 UnsupportedOperation -> "unsupported operation"
945 DynIOError{} -> "unknown IO error"
947 -- | Construct an 'IOError' value with a string describing the error.
948 -- The 'fail' method of the 'IO' instance of the 'Monad' class raises a
949 -- 'userError', thus:
951 -- > instance Monad IO where
953 -- > fail s = ioError (userError s)
955 userError :: String -> IOError
956 userError str = IOError Nothing UserError "" str Nothing
958 -- ---------------------------------------------------------------------------
961 instance Show IOException where
962 showsPrec p (IOError hdl iot loc s fn) =
964 Nothing -> case hdl of
966 Just h -> showsPrec p h . showString ": "
967 Just name -> showString name . showString ": ") .
970 _ -> showString loc . showString ": ") .
974 _ -> showString " (" . showString s . showString ")")
976 -- -----------------------------------------------------------------------------
979 data IOMode = ReadMode | WriteMode | AppendMode | ReadWriteMode
980 deriving (Eq, Ord, Ix, Enum, Read, Show)
983 %*********************************************************
985 \subsection{Primitive catch and throwIO}
987 %*********************************************************
989 catchException used to handle the passing around of the state to the
990 action and the handler. This turned out to be a bad idea - it meant
991 that we had to wrap both arguments in thunks so they could be entered
992 as normal (remember IO returns an unboxed pair...).
996 catch# :: IO a -> (b -> IO a) -> IO a
998 (well almost; the compiler doesn't know about the IO newtype so we
999 have to work around that in the definition of catchException below).
1002 catchException :: Exception e => IO a -> (e -> IO a) -> IO a
1003 catchException (IO io) handler = IO $ catch# io handler'
1004 where handler' e = case fromException e of
1005 Just e' -> unIO (handler e')
1008 catchAny :: IO a -> (forall e . Exception e => e -> IO a) -> IO a
1009 catchAny (IO io) handler = IO $ catch# io handler'
1010 where handler' (SomeException e) = unIO (handler e)
1012 -- | A variant of 'throw' that can be used within the 'IO' monad.
1014 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
1015 -- two functions are subtly different:
1017 -- > throw e `seq` x ===> throw e
1018 -- > throwIO e `seq` x ===> x
1020 -- The first example will cause the exception @e@ to be raised,
1021 -- whereas the second one won\'t. In fact, 'throwIO' will only cause
1022 -- an exception to be raised when it is used within the 'IO' monad.
1023 -- The 'throwIO' variant should be used in preference to 'throw' to
1024 -- raise an exception within the 'IO' monad because it guarantees
1025 -- ordering with respect to other 'IO' operations, whereas 'throw'
1027 throwIO :: Exception e => e -> IO a
1028 throwIO e = IO (raiseIO# (toException e))
1032 %*********************************************************
1034 \subsection{Controlling asynchronous exception delivery}
1036 %*********************************************************
1039 -- | Applying 'block' to a computation will
1040 -- execute that computation with asynchronous exceptions
1041 -- /blocked/. That is, any thread which
1042 -- attempts to raise an exception in the current thread with 'Control.Exception.throwTo' will be
1043 -- blocked until asynchronous exceptions are enabled again. There\'s
1044 -- no need to worry about re-enabling asynchronous exceptions; that is
1045 -- done automatically on exiting the scope of
1048 -- Threads created by 'Control.Concurrent.forkIO' inherit the blocked
1049 -- state from the parent; that is, to start a thread in blocked mode,
1050 -- use @block $ forkIO ...@. This is particularly useful if you need to
1051 -- establish an exception handler in the forked thread before any
1052 -- asynchronous exceptions are received.
1053 block :: IO a -> IO a
1055 -- | To re-enable asynchronous exceptions inside the scope of
1056 -- 'block', 'unblock' can be
1057 -- used. It scopes in exactly the same way, so on exit from
1058 -- 'unblock' asynchronous exception delivery will
1059 -- be disabled again.
1060 unblock :: IO a -> IO a
1062 block (IO io) = IO $ blockAsyncExceptions# io
1063 unblock (IO io) = IO $ unblockAsyncExceptions# io
1067 -- | Forces its argument to be evaluated when the resultant 'IO' action
1068 -- is executed. It can be used to order evaluation with respect to
1069 -- other 'IO' operations; its semantics are given by
1071 -- > evaluate x `seq` y ==> y
1072 -- > evaluate x `catch` f ==> (return $! x) `catch` f
1073 -- > evaluate x >>= f ==> (return $! x) >>= f
1075 -- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
1076 -- same as @(return $! x)@. A correct definition is
1078 -- > evaluate x = (return $! x) >>= return
1080 evaluate :: a -> IO a
1081 evaluate a = IO $ \s -> case a `seq` () of () -> (# s, a #)
1083 -- a `seq` (# s, a #)
1084 -- because we can't have an unboxed tuple as a function argument