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,
52 import GHC.Arr -- to derive Ix class
53 import GHC.Enum -- to derive Enum class
56 -- import GHC.Num -- To get fromInteger etc, needed because of -XNoImplicitPrelude
57 import Data.Maybe ( Maybe(..) )
61 import Foreign.C.Types (CInt)
62 import {-# SOURCE #-} GHC.Exception ( SomeException, toException, throwIO )
65 import {-# SOURCE #-} Data.Typeable ( showsTypeRep )
66 import {-# SOURCE #-} Data.Dynamic ( Dynamic, dynTypeRep )
69 -- ---------------------------------------------------------------------------
73 The IO Monad is just an instance of the ST monad, where the state is
74 the real world. We use the exception mechanism (in GHC.Exception) to
75 implement IO exceptions.
77 NOTE: The IO representation is deeply wired in to various parts of the
78 system. The following list may or may not be exhaustive:
80 Compiler - types of various primitives in PrimOp.lhs
82 RTS - forceIO (StgMiscClosures.hc)
83 - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast
85 - raiseAsync (Schedule.c)
87 Prelude - GHC.IOBase.lhs, and several other places including
90 Libraries - parts of hslibs/lang.
96 A value of type @'IO' a@ is a computation which, when performed,
97 does some I\/O before returning a value of type @a@.
99 There is really only one way to \"perform\" an I\/O action: bind it to
100 @Main.main@ in your program. When your program is run, the I\/O will
101 be performed. It isn't possible to perform I\/O from an arbitrary
102 function, unless that function is itself in the 'IO' monad and called
103 at some point, directly or indirectly, from @Main.main@.
105 'IO' is a monad, so 'IO' actions can be combined using either the do-notation
106 or the '>>' and '>>=' operations from the 'Monad' class.
108 newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #))
110 unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
113 instance Functor IO where
114 fmap f x = x >>= (return . f)
116 instance Monad IO where
117 {-# INLINE return #-}
120 m >> k = m >>= \ _ -> k
121 return x = returnIO x
126 failIO :: String -> IO a
127 failIO s = ioError (userError s)
129 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
130 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
132 bindIO :: IO a -> (a -> IO b) -> IO b
133 bindIO (IO m) k = IO ( \ s ->
135 (# new_s, a #) -> unIO (k a) new_s
138 thenIO :: IO a -> IO b -> IO b
139 thenIO (IO m) k = IO ( \ s ->
141 (# new_s, a #) -> unIO k new_s
144 returnIO :: a -> IO a
145 returnIO x = IO (\ s -> (# s, x #))
147 -- ---------------------------------------------------------------------------
148 -- Coercions between IO and ST
150 -- | A monad transformer embedding strict state transformers in the 'IO'
151 -- monad. The 'RealWorld' parameter indicates that the internal state
152 -- used by the 'ST' computation is a special one supplied by the 'IO'
153 -- monad, and thus distinct from those used by invocations of 'runST'.
154 stToIO :: ST RealWorld a -> IO a
157 ioToST :: IO a -> ST RealWorld a
158 ioToST (IO m) = (ST m)
160 -- This relies on IO and ST having the same representation modulo the
161 -- constraint on the type of the state
163 unsafeIOToST :: IO a -> ST s a
164 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
166 unsafeSTToIO :: ST s a -> IO a
167 unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
169 -- ---------------------------------------------------------------------------
170 -- Unsafe IO operations
173 This is the \"back door\" into the 'IO' monad, allowing
174 'IO' computation to be performed at any time. For
175 this to be safe, the 'IO' computation should be
176 free of side effects and independent of its environment.
178 If the I\/O computation wrapped in 'unsafePerformIO'
179 performs side effects, then the relative order in which those side
180 effects take place (relative to the main I\/O trunk, or other calls to
181 'unsafePerformIO') is indeterminate. You have to be careful when
182 writing and compiling modules that use 'unsafePerformIO':
184 * Use @{\-\# NOINLINE foo \#-\}@ as a pragma on any function @foo@
185 that calls 'unsafePerformIO'. If the call is inlined,
186 the I\/O may be performed more than once.
188 * Use the compiler flag @-fno-cse@ to prevent common sub-expression
189 elimination being performed on the module, which might combine
190 two side effects that were meant to be separate. A good example
191 is using multiple global variables (like @test@ in the example below).
193 * Make sure that the either you switch off let-floating, or that the
194 call to 'unsafePerformIO' cannot float outside a lambda. For example,
197 f x = unsafePerformIO (newIORef [])
199 you may get only one reference cell shared between all calls to @f@.
202 f x = unsafePerformIO (newIORef [x])
204 because now it can't float outside the lambda.
206 It is less well known that
207 'unsafePerformIO' is not type safe. For example:
210 > test = unsafePerformIO $ newIORef []
213 > writeIORef test [42]
214 > bang <- readIORef test
215 > print (bang :: [Char])
217 This program will core dump. This problem with polymorphic references
218 is well known in the ML community, and does not arise with normal
219 monadic use of references. There is no easy way to make it impossible
220 once you use 'unsafePerformIO'. Indeed, it is
221 possible to write @coerce :: a -> b@ with the
222 help of 'unsafePerformIO'. So be careful!
224 unsafePerformIO :: IO a -> a
225 unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)
228 This version of 'unsafePerformIO' is slightly more efficient,
229 because it omits the check that the IO is only being performed by a
230 single thread. Hence, when you write 'unsafeDupablePerformIO',
231 there is a possibility that the IO action may be performed multiple
232 times (on a multiprocessor), and you should therefore ensure that
233 it gives the same results each time.
235 {-# NOINLINE unsafeDupablePerformIO #-}
236 unsafeDupablePerformIO :: IO a -> a
237 unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
239 -- Why do we NOINLINE unsafeDupablePerformIO? See the comment with
240 -- GHC.ST.runST. Essentially the issue is that the IO computation
241 -- inside unsafePerformIO must be atomic: it must either all run, or
242 -- not at all. If we let the compiler see the application of the IO
243 -- to realWorld#, it might float out part of the IO.
245 -- Why is there a call to 'lazy' in unsafeDupablePerformIO?
246 -- If we don't have it, the demand analyser discovers the following strictness
247 -- for unsafeDupablePerformIO: C(U(AV))
249 -- unsafeDupablePerformIO (\s -> let r = f x in
250 -- case writeIORef v r s of (# s1, _ #) ->
252 -- The strictness analyser will find that the binding for r is strict,
253 -- (becuase of uPIO's strictness sig), and so it'll evaluate it before
254 -- doing the writeIORef. This actually makes tests/lib/should_run/memo002
257 -- Solution: don't expose the strictness of unsafeDupablePerformIO,
258 -- by hiding it with 'lazy'
261 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
262 When passed a value of type @IO a@, the 'IO' will only be performed
263 when the value of the @a@ is demanded. This is used to implement lazy
264 file reading, see 'System.IO.hGetContents'.
266 {-# INLINE unsafeInterleaveIO #-}
267 unsafeInterleaveIO :: IO a -> IO a
268 unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)
270 -- We believe that INLINE on unsafeInterleaveIO is safe, because the
271 -- state from this IO thread is passed explicitly to the interleaved
272 -- IO, so it cannot be floated out and shared.
274 {-# INLINE unsafeDupableInterleaveIO #-}
275 unsafeDupableInterleaveIO :: IO a -> IO a
276 unsafeDupableInterleaveIO (IO m)
278 r = case m s of (# _, res #) -> res
283 Ensures that the suspensions under evaluation by the current thread
284 are unique; that is, the current thread is not evaluating anything
285 that is also under evaluation by another thread that has also executed
288 This operation is used in the definition of 'unsafePerformIO' to
289 prevent the IO action from being executed multiple times, which is usually
293 noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)
295 -- ---------------------------------------------------------------------------
298 data MVar a = MVar (MVar# RealWorld a)
300 An 'MVar' (pronounced \"em-var\") is a synchronising variable, used
301 for communication between concurrent threads. It can be thought of
302 as a a box, which may be empty or full.
305 -- pull in Eq (Mvar a) too, to avoid GHC.Conc being an orphan-instance module
306 instance Eq (MVar a) where
307 (MVar mvar1#) == (MVar mvar2#) = sameMVar# mvar1# mvar2#
309 -- A Handle is represented by (a reference to) a record
310 -- containing the state of the I/O port/device. We record
311 -- the following pieces of info:
313 -- * type (read,write,closed etc.)
314 -- * the underlying file descriptor
316 -- * buffer, and spare buffers
317 -- * user-friendly name (usually the
318 -- FilePath used when IO.openFile was called)
320 -- Note: when a Handle is garbage collected, we want to flush its buffer
321 -- and close the OS file handle, so as to free up a (precious) resource.
323 -- | Haskell defines operations to read and write characters from and to files,
324 -- represented by values of type @Handle@. Each value of this type is a
325 -- /handle/: a record used by the Haskell run-time system to /manage/ I\/O
326 -- with file system objects. A handle has at least the following properties:
328 -- * whether it manages input or output or both;
330 -- * whether it is /open/, /closed/ or /semi-closed/;
332 -- * whether the object is seekable;
334 -- * whether buffering is disabled, or enabled on a line or block basis;
336 -- * a buffer (whose length may be zero).
338 -- Most handles will also have a current I\/O position indicating where the next
339 -- input or output operation will occur. A handle is /readable/ if it
340 -- manages only input or both input and output; likewise, it is /writable/ if
341 -- it manages only output or both input and output. A handle is /open/ when
343 -- Once it is closed it can no longer be used for either input or output,
344 -- though an implementation cannot re-use its storage while references
345 -- remain to it. Handles are in the 'Show' and 'Eq' classes. The string
346 -- produced by showing a handle is system dependent; it should include
347 -- enough information to identify the handle for debugging. A handle is
348 -- equal according to '==' only to itself; no attempt
349 -- is made to compare the internal state of different handles for equality.
351 -- GHC note: a 'Handle' will be automatically closed when the garbage
352 -- collector detects that it has become unreferenced by the program.
353 -- However, relying on this behaviour is not generally recommended:
354 -- the garbage collector is unpredictable. If possible, use explicit
355 -- an explicit 'hClose' to close 'Handle's when they are no longer
356 -- required. GHC does not currently attempt to free up file
357 -- descriptors when they have run out, it is your responsibility to
358 -- ensure that this doesn't happen.
361 = FileHandle -- A normal handle to a file
362 FilePath -- the file (invariant)
365 | DuplexHandle -- A handle to a read/write stream
366 FilePath -- file for a FIFO, otherwise some
367 -- descriptive string.
368 !(MVar Handle__) -- The read side
369 !(MVar Handle__) -- The write side
372 -- * A 'FileHandle' is seekable. A 'DuplexHandle' may or may not be
375 instance Eq Handle where
376 (FileHandle _ h1) == (FileHandle _ h2) = h1 == h2
377 (DuplexHandle _ h1 _) == (DuplexHandle _ h2 _) = h1 == h2
384 haFD :: !FD, -- file descriptor
385 haType :: HandleType, -- type (read/write/append etc.)
386 haIsBin :: Bool, -- binary mode?
387 haIsStream :: Bool, -- Windows : is this a socket?
388 -- Unix : is O_NONBLOCK set?
389 haBufferMode :: BufferMode, -- buffer contains read/write data?
390 haBuffer :: !(IORef Buffer), -- the current buffer
391 haBuffers :: !(IORef BufferList), -- spare buffers
392 haOtherSide :: Maybe (MVar Handle__) -- ptr to the write side of a
396 -- ---------------------------------------------------------------------------
399 -- The buffer is represented by a mutable variable containing a
400 -- record, where the record contains the raw buffer and the start/end
401 -- points of the filled portion. We use a mutable variable so that
402 -- the common operation of writing (or reading) some data from (to)
403 -- the buffer doesn't need to modify, and hence copy, the handle
404 -- itself, it just updates the buffer.
406 -- There will be some allocation involved in a simple hPutChar in
407 -- order to create the new Buffer structure (below), but this is
408 -- relatively small, and this only has to be done once per write
411 -- The buffer contains its size - we could also get the size by
412 -- calling sizeOfMutableByteArray# on the raw buffer, but that tends
413 -- to be rounded up to the nearest Word.
415 type RawBuffer = MutableByteArray# RealWorld
417 -- INVARIANTS on a Buffer:
419 -- * A handle *always* has a buffer, even if it is only 1 character long
420 -- (an unbuffered handle needs a 1 character buffer in order to support
421 -- hLookAhead and hIsEOF).
423 -- * if r == w, then r == 0 && w == 0
424 -- * if state == WriteBuffer, then r == 0
425 -- * a write buffer is never full. If an operation
426 -- fills up the buffer, it will always flush it before
428 -- * a read buffer may be full as a result of hLookAhead. In normal
429 -- operation, a read buffer always has at least one character of space.
437 bufState :: BufferState
440 data BufferState = ReadBuffer | WriteBuffer deriving (Eq)
442 -- we keep a few spare buffers around in a handle to avoid allocating
443 -- a new one for each hPutStr. These buffers are *guaranteed* to be the
444 -- same size as the main buffer.
447 | BufferListCons RawBuffer BufferList
450 bufferIsWritable :: Buffer -> Bool
451 bufferIsWritable Buffer{ bufState=WriteBuffer } = True
452 bufferIsWritable _other = False
454 bufferEmpty :: Buffer -> Bool
455 bufferEmpty Buffer{ bufRPtr=r, bufWPtr=w } = r == w
457 -- only makes sense for a write buffer
458 bufferFull :: Buffer -> Bool
459 bufferFull b@Buffer{ bufWPtr=w } = w >= bufSize b
461 -- Internally, we classify handles as being one
472 isReadableHandleType ReadHandle = True
473 isReadableHandleType ReadWriteHandle = True
474 isReadableHandleType _ = False
476 isWritableHandleType AppendHandle = True
477 isWritableHandleType WriteHandle = True
478 isWritableHandleType ReadWriteHandle = True
479 isWritableHandleType _ = False
481 isReadWriteHandleType ReadWriteHandle{} = True
482 isReadWriteHandleType _ = False
484 -- | File and directory names are values of type 'String', whose precise
485 -- meaning is operating system dependent. Files can be opened, yielding a
486 -- handle which can then be used to operate on the contents of that file.
488 type FilePath = String
490 -- ---------------------------------------------------------------------------
493 -- | Three kinds of buffering are supported: line-buffering,
494 -- block-buffering or no-buffering. These modes have the following
495 -- effects. For output, items are written out, or /flushed/,
496 -- from the internal buffer according to the buffer mode:
498 -- * /line-buffering/: the entire output buffer is flushed
499 -- whenever a newline is output, the buffer overflows,
500 -- a 'System.IO.hFlush' is issued, or the handle is closed.
502 -- * /block-buffering/: the entire buffer is written out whenever it
503 -- overflows, a 'System.IO.hFlush' is issued, or the handle is closed.
505 -- * /no-buffering/: output is written immediately, and never stored
508 -- An implementation is free to flush the buffer more frequently,
509 -- but not less frequently, than specified above.
510 -- The output buffer is emptied as soon as it has been written out.
512 -- Similarly, input occurs according to the buffer mode for the handle:
514 -- * /line-buffering/: when the buffer for the handle is not empty,
515 -- the next item is obtained from the buffer; otherwise, when the
516 -- buffer is empty, characters up to and including the next newline
517 -- character are read into the buffer. No characters are available
518 -- until the newline character is available or the buffer is full.
520 -- * /block-buffering/: when the buffer for the handle becomes empty,
521 -- the next block of data is read into the buffer.
523 -- * /no-buffering/: the next input item is read and returned.
524 -- The 'System.IO.hLookAhead' operation implies that even a no-buffered
525 -- handle may require a one-character buffer.
527 -- The default buffering mode when a handle is opened is
528 -- implementation-dependent and may depend on the file system object
529 -- which is attached to that handle.
530 -- For most implementations, physical files will normally be block-buffered
531 -- and terminals will normally be line-buffered.
534 = NoBuffering -- ^ buffering is disabled if possible.
536 -- ^ line-buffering should be enabled if possible.
537 | BlockBuffering (Maybe Int)
538 -- ^ block-buffering should be enabled if possible.
539 -- The size of the buffer is @n@ items if the argument
540 -- is 'Just' @n@ and is otherwise implementation-dependent.
541 deriving (Eq, Ord, Read, Show)
543 -- ---------------------------------------------------------------------------
546 -- |A mutable variable in the 'IO' monad
547 newtype IORef a = IORef (STRef RealWorld a)
549 -- explicit instance because Haddock can't figure out a derived one
550 instance Eq (IORef a) where
551 IORef x == IORef y = x == y
553 -- |Build a new 'IORef'
554 newIORef :: a -> IO (IORef a)
555 newIORef v = stToIO (newSTRef v) >>= \ var -> return (IORef var)
557 -- |Read the value of an 'IORef'
558 readIORef :: IORef a -> IO a
559 readIORef (IORef var) = stToIO (readSTRef var)
561 -- |Write a new value into an 'IORef'
562 writeIORef :: IORef a -> a -> IO ()
563 writeIORef (IORef var) v = stToIO (writeSTRef var v)
565 -- ---------------------------------------------------------------------------
566 -- | An 'IOArray' is a mutable, boxed, non-strict array in the 'IO' monad.
567 -- The type arguments are as follows:
569 -- * @i@: the index type of the array (should be an instance of 'Ix')
571 -- * @e@: the element type of the array.
575 newtype IOArray i e = IOArray (STArray RealWorld i e)
577 -- explicit instance because Haddock can't figure out a derived one
578 instance Eq (IOArray i e) where
579 IOArray x == IOArray y = x == y
581 -- |Build a new 'IOArray'
582 newIOArray :: Ix i => (i,i) -> e -> IO (IOArray i e)
583 {-# INLINE newIOArray #-}
584 newIOArray lu init = stToIO $ do {marr <- newSTArray lu init; return (IOArray marr)}
586 -- | Read a value from an 'IOArray'
587 unsafeReadIOArray :: Ix i => IOArray i e -> Int -> IO e
588 {-# INLINE unsafeReadIOArray #-}
589 unsafeReadIOArray (IOArray marr) i = stToIO (unsafeReadSTArray marr i)
591 -- | Write a new value into an 'IOArray'
592 unsafeWriteIOArray :: Ix i => IOArray i e -> Int -> e -> IO ()
593 {-# INLINE unsafeWriteIOArray #-}
594 unsafeWriteIOArray (IOArray marr) i e = stToIO (unsafeWriteSTArray marr i e)
596 -- | Read a value from an 'IOArray'
597 readIOArray :: Ix i => IOArray i e -> i -> IO e
598 readIOArray (IOArray marr) i = stToIO (readSTArray marr i)
600 -- | Write a new value into an 'IOArray'
601 writeIOArray :: Ix i => IOArray i e -> i -> e -> IO ()
602 writeIOArray (IOArray marr) i e = stToIO (writeSTArray marr i e)
605 -- ---------------------------------------------------------------------------
606 -- Show instance for Handles
608 -- handle types are 'show'n when printing error msgs, so
609 -- we provide a more user-friendly Show instance for it
610 -- than the derived one.
612 instance Show HandleType where
615 ClosedHandle -> showString "closed"
616 SemiClosedHandle -> showString "semi-closed"
617 ReadHandle -> showString "readable"
618 WriteHandle -> showString "writable"
619 AppendHandle -> showString "writable (append)"
620 ReadWriteHandle -> showString "read-writable"
622 instance Show Handle where
623 showsPrec p (FileHandle file _) = showHandle file
624 showsPrec p (DuplexHandle file _ _) = showHandle file
626 showHandle file = showString "{handle: " . showString file . showString "}"
628 -- ------------------------------------------------------------------------
629 -- Exception datatype and operations
631 -- |The type of exceptions. Every kind of system-generated exception
632 -- has a constructor in the 'Exception' type, and values of other
633 -- types may be injected into 'Exception' by coercing them to
634 -- 'Data.Dynamic.Dynamic' (see the section on Dynamic Exceptions:
635 -- "Control.Exception\#DynamicExceptions").
637 = ArithException ArithException
638 -- ^Exceptions raised by arithmetic
639 -- operations. (NOTE: GHC currently does not throw
640 -- 'ArithException's except for 'DivideByZero').
641 | ArrayException ArrayException
642 -- ^Exceptions raised by array-related
643 -- operations. (NOTE: GHC currently does not throw
644 -- 'ArrayException's).
645 | AssertionFailed String
646 -- ^This exception is thrown by the
647 -- 'assert' operation when the condition
648 -- fails. The 'String' argument contains the
649 -- location of the assertion in the source program.
650 | AsyncException AsyncException
651 -- ^Asynchronous exceptions (see section on Asynchronous Exceptions: "Control.Exception\#AsynchronousExceptions").
653 -- ^The current thread was executing a call to
654 -- 'Control.Concurrent.MVar.takeMVar' that could never return,
655 -- because there are no other references to this 'MVar'.
656 | BlockedIndefinitely
657 -- ^The current thread was waiting to retry an atomic memory transaction
658 -- that could never become possible to complete because there are no other
659 -- threads referring to any of the TVars involved.
661 -- ^The runtime detected an attempt to nest one STM transaction
662 -- inside another one, presumably due to the use of
663 -- 'unsafePeformIO' with 'atomically'.
665 -- ^There are no runnable threads, so the program is
666 -- deadlocked. The 'Deadlock' exception is
667 -- raised in the main thread only (see also: "Control.Concurrent").
668 | DynException Dynamic
669 -- ^Dynamically typed exceptions (see section on Dynamic Exceptions: "Control.Exception\#DynamicExceptions").
671 -- ^The 'ErrorCall' exception is thrown by 'error'. The 'String'
672 -- argument of 'ErrorCall' is the string passed to 'error' when it was
674 | ExitException ExitCode
675 -- ^The 'ExitException' exception is thrown by 'System.Exit.exitWith' (and
676 -- 'System.Exit.exitFailure'). The 'ExitCode' argument is the value passed
677 -- to 'System.Exit.exitWith'. An unhandled 'ExitException' exception in the
678 -- main thread will cause the program to be terminated with the given
680 | IOException IOException
681 -- ^These are the standard IO exceptions generated by
682 -- Haskell\'s @IO@ operations. See also "System.IO.Error".
683 | NoMethodError String
684 -- ^An attempt was made to invoke a class method which has
685 -- no definition in this instance, and there was no default
686 -- definition given in the class declaration. GHC issues a
687 -- warning when you compile an instance which has missing
690 -- ^The current thread is stuck in an infinite loop. This
691 -- exception may or may not be thrown when the program is
693 | PatternMatchFail String
694 -- ^A pattern matching failure. The 'String' argument should contain a
695 -- descriptive message including the function name, source file
698 -- ^An attempt was made to evaluate a field of a record
699 -- for which no value was given at construction time. The
700 -- 'String' argument gives the location of the
701 -- record construction in the source program.
703 -- ^A field selection was attempted on a constructor that
704 -- doesn\'t have the requested field. This can happen with
705 -- multi-constructor records when one or more fields are
706 -- missing from some of the constructors. The
707 -- 'String' argument gives the location of the
708 -- record selection in the source program.
710 -- ^An attempt was made to update a field in a record,
711 -- where the record doesn\'t have the requested field. This can
712 -- only occur with multi-constructor records, when one or more
713 -- fields are missing from some of the constructors. The
714 -- 'String' argument gives the location of the
715 -- record update in the source program.
717 nonTermination :: SomeException
718 nonTermination = toException NonTermination
720 -- |The type of arithmetic exceptions
730 -- |Asynchronous exceptions
733 -- ^The current thread\'s stack exceeded its limit.
734 -- Since an exception has been raised, the thread\'s stack
735 -- will certainly be below its limit again, but the
736 -- programmer should take remedial action
739 -- ^The program\'s heap is reaching its limit, and
740 -- the program should take action to reduce the amount of
741 -- live data it has. Notes:
743 -- * It is undefined which thread receives this exception.
745 -- * GHC currently does not throw 'HeapOverflow' exceptions.
747 -- ^This exception is raised by another thread
748 -- calling 'Control.Concurrent.killThread', or by the system
749 -- if it needs to terminate the thread for some
752 -- ^This exception is raised by default in the main thread of
753 -- the program when the user requests to terminate the program
754 -- via the usual mechanism(s) (e.g. Control-C in the console).
757 -- | Exceptions generated by array operations
759 = IndexOutOfBounds String
760 -- ^An attempt was made to index an array outside
761 -- its declared bounds.
762 | UndefinedElement String
763 -- ^An attempt was made to evaluate an element of an
764 -- array that had not been initialized.
767 stackOverflow, heapOverflow :: Exception -- for the RTS
768 stackOverflow = AsyncException StackOverflow
769 heapOverflow = AsyncException HeapOverflow
771 instance Show ArithException where
772 showsPrec _ Overflow = showString "arithmetic overflow"
773 showsPrec _ Underflow = showString "arithmetic underflow"
774 showsPrec _ LossOfPrecision = showString "loss of precision"
775 showsPrec _ DivideByZero = showString "divide by zero"
776 showsPrec _ Denormal = showString "denormal"
778 instance Show AsyncException where
779 showsPrec _ StackOverflow = showString "stack overflow"
780 showsPrec _ HeapOverflow = showString "heap overflow"
781 showsPrec _ ThreadKilled = showString "thread killed"
783 instance Show ArrayException where
784 showsPrec _ (IndexOutOfBounds s)
785 = showString "array index out of range"
786 . (if not (null s) then showString ": " . showString s
788 showsPrec _ (UndefinedElement s)
789 = showString "undefined array element"
790 . (if not (null s) then showString ": " . showString s
793 instance Show Exception where
794 showsPrec _ (IOException err) = shows err
795 showsPrec _ (ArithException err) = shows err
796 showsPrec _ (ArrayException err) = shows err
797 showsPrec _ (ErrorCall err) = showString err
798 showsPrec _ (ExitException err) = showString "exit: " . shows err
799 showsPrec _ (NoMethodError err) = showString err
800 showsPrec _ (PatternMatchFail err) = showString err
801 showsPrec _ (RecSelError err) = showString err
802 showsPrec _ (RecConError err) = showString err
803 showsPrec _ (RecUpdError err) = showString err
804 showsPrec _ (AssertionFailed err) = showString err
805 showsPrec _ (DynException err) = showString "exception :: " . showsTypeRep (dynTypeRep err)
806 showsPrec _ (AsyncException e) = shows e
807 showsPrec _ (BlockedOnDeadMVar) = showString "thread blocked indefinitely"
808 showsPrec _ (BlockedIndefinitely) = showString "thread blocked indefinitely"
809 showsPrec _ (NestedAtomically) = showString "Control.Concurrent.STM.atomically was nested"
810 showsPrec _ (NonTermination) = showString "<<loop>>"
811 showsPrec _ (Deadlock) = showString "<<deadlock>>"
813 instance Eq Exception where
814 IOException e1 == IOException e2 = e1 == e2
815 ArithException e1 == ArithException e2 = e1 == e2
816 ArrayException e1 == ArrayException e2 = e1 == e2
817 ErrorCall e1 == ErrorCall e2 = e1 == e2
818 ExitException e1 == ExitException e2 = e1 == e2
819 NoMethodError e1 == NoMethodError e2 = e1 == e2
820 PatternMatchFail e1 == PatternMatchFail e2 = e1 == e2
821 RecSelError e1 == RecSelError e2 = e1 == e2
822 RecConError e1 == RecConError e2 = e1 == e2
823 RecUpdError e1 == RecUpdError e2 = e1 == e2
824 AssertionFailed e1 == AssertionFailed e2 = e1 == e2
825 DynException _ == DynException _ = False -- incomparable
826 AsyncException e1 == AsyncException e2 = e1 == e2
827 BlockedOnDeadMVar == BlockedOnDeadMVar = True
828 NonTermination == NonTermination = True
829 NestedAtomically == NestedAtomically = True
830 Deadlock == Deadlock = True
833 -- -----------------------------------------------------------------------------
836 -- We need it here because it is used in ExitException in the
837 -- Exception datatype (above).
840 = ExitSuccess -- ^ indicates successful termination;
842 -- ^ indicates program failure with an exit code.
843 -- The exact interpretation of the code is
844 -- operating-system dependent. In particular, some values
845 -- may be prohibited (e.g. 0 on a POSIX-compliant system).
846 deriving (Eq, Ord, Read, Show)
848 ioException :: IOException -> IO a
849 ioException err = throwIO (IOException err)
851 -- | Raise an 'IOError' in the 'IO' monad.
852 ioError :: IOError -> IO a
853 ioError = ioException
855 -- ---------------------------------------------------------------------------
858 -- | The Haskell 98 type for exceptions in the 'IO' monad.
859 -- Any I\/O operation may raise an 'IOError' instead of returning a result.
860 -- For a more general type of exception, including also those that arise
861 -- in pure code, see 'Control.Exception.Exception'.
863 -- In Haskell 98, this is an opaque type.
864 type IOError = IOException
866 -- |Exceptions that occur in the @IO@ monad.
867 -- An @IOException@ records a more specific error type, a descriptive
868 -- string and maybe the handle that was used when the error was
872 ioe_handle :: Maybe Handle, -- the handle used by the action flagging
874 ioe_type :: IOErrorType, -- what it was.
875 ioe_location :: String, -- location.
876 ioe_description :: String, -- error type specific information.
877 ioe_filename :: Maybe FilePath -- filename the error is related to.
880 instance Eq IOException where
881 (IOError h1 e1 loc1 str1 fn1) == (IOError h2 e2 loc2 str2 fn2) =
882 e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && fn1==fn2
884 -- | An abstract type that contains a value for each variant of 'IOError'.
896 | UnsatisfiedConstraints
903 | UnsupportedOperation
907 | DynIOError Dynamic -- cheap&cheerful extensible IO error type.
909 instance Eq IOErrorType where
912 DynIOError{} -> False -- from a strictness POV, compatible with a derived Eq inst?
913 _ -> getTag x ==# getTag y
915 instance Show IOErrorType where
919 AlreadyExists -> "already exists"
920 NoSuchThing -> "does not exist"
921 ResourceBusy -> "resource busy"
922 ResourceExhausted -> "resource exhausted"
924 IllegalOperation -> "illegal operation"
925 PermissionDenied -> "permission denied"
926 UserError -> "user error"
927 HardwareFault -> "hardware fault"
928 InappropriateType -> "inappropriate type"
929 Interrupted -> "interrupted"
930 InvalidArgument -> "invalid argument"
931 OtherError -> "failed"
932 ProtocolError -> "protocol error"
933 ResourceVanished -> "resource vanished"
934 SystemError -> "system error"
935 TimeExpired -> "timeout"
936 UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise!
937 UnsupportedOperation -> "unsupported operation"
938 DynIOError{} -> "unknown IO error"
940 -- | Construct an 'IOError' value with a string describing the error.
941 -- The 'fail' method of the 'IO' instance of the 'Monad' class raises a
942 -- 'userError', thus:
944 -- > instance Monad IO where
946 -- > fail s = ioError (userError s)
948 userError :: String -> IOError
949 userError str = IOError Nothing UserError "" str Nothing
951 -- ---------------------------------------------------------------------------
954 instance Show IOException where
955 showsPrec p (IOError hdl iot loc s fn) =
957 Nothing -> case hdl of
959 Just h -> showsPrec p h . showString ": "
960 Just name -> showString name . showString ": ") .
963 _ -> showString loc . showString ": ") .
967 _ -> showString " (" . showString s . showString ")")
969 -- -----------------------------------------------------------------------------
972 data IOMode = ReadMode | WriteMode | AppendMode | ReadWriteMode
973 deriving (Eq, Ord, Ix, Enum, Read, Show)