2 {-# OPTIONS_GHC -fno-implicit-prelude #-}
3 -----------------------------------------------------------------------------
6 -- Copyright : (c) The University of Glasgow 1994-2002
7 -- License : see libraries/base/LICENSE
9 -- Maintainer : cvs-ghc@haskell.org
10 -- Stability : internal
11 -- Portability : non-portable (GHC Extensions)
13 -- Definitions for the 'IO' monad and its friends.
15 -----------------------------------------------------------------------------
19 IO(..), unIO, failIO, liftIO, bindIO, thenIO, returnIO,
20 unsafePerformIO, unsafeInterleaveIO,
22 -- To and from from ST
23 stToIO, ioToST, unsafeIOToST, unsafeSTToIO,
26 IORef(..), newIORef, readIORef, writeIORef,
27 IOArray(..), newIOArray, readIOArray, writeIOArray, unsafeReadIOArray, unsafeWriteIOArray,
30 -- Handles, file descriptors,
32 Handle(..), Handle__(..), HandleType(..), IOMode(..), FD,
33 isReadableHandleType, isWritableHandleType, isReadWriteHandleType, showHandle,
36 Buffer(..), RawBuffer, BufferState(..), BufferList(..), BufferMode(..),
37 bufferIsWritable, bufferEmpty, bufferFull,
40 Exception(..), ArithException(..), AsyncException(..), ArrayException(..),
41 stackOverflow, heapOverflow, throw, throwIO, ioException,
42 IOError, IOException(..), IOErrorType(..), ioError, userError,
47 import GHC.Arr -- to derive Ix class
48 import GHC.Enum -- to derive Enum class
51 -- import GHC.Num -- To get fromInteger etc, needed because of -fno-implicit-prelude
52 import Data.Maybe ( Maybe(..) )
56 import Foreign.C.Types (CInt)
59 import {-# SOURCE #-} GHC.Dynamic
62 -- ---------------------------------------------------------------------------
66 The IO Monad is just an instance of the ST monad, where the state is
67 the real world. We use the exception mechanism (in GHC.Exception) to
68 implement IO exceptions.
70 NOTE: The IO representation is deeply wired in to various parts of the
71 system. The following list may or may not be exhaustive:
73 Compiler - types of various primitives in PrimOp.lhs
75 RTS - forceIO (StgMiscClosures.hc)
76 - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast
78 - raiseAsync (Schedule.c)
80 Prelude - GHC.IOBase.lhs, and several other places including
83 Libraries - parts of hslibs/lang.
89 A value of type @'IO' a@ is a computation which, when performed,
90 does some I\/O before returning a value of type @a@.
92 There is really only one way to \"perform\" an I\/O action: bind it to
93 @Main.main@ in your program. When your program is run, the I\/O will
94 be performed. It isn't possible to perform I\/O from an arbitrary
95 function, unless that function is itself in the 'IO' monad and called
96 at some point, directly or indirectly, from @Main.main@.
98 'IO' is a monad, so 'IO' actions can be combined using either the do-notation
99 or the '>>' and '>>=' operations from the 'Monad' class.
101 newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #))
103 unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
106 instance Functor IO where
107 fmap f x = x >>= (return . f)
109 instance Monad IO where
110 {-# INLINE return #-}
113 m >> k = m >>= \ _ -> k
114 return x = returnIO x
119 failIO :: String -> IO a
120 failIO s = ioError (userError s)
122 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
123 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
125 bindIO :: IO a -> (a -> IO b) -> IO b
126 bindIO (IO m) k = IO ( \ s ->
128 (# new_s, a #) -> unIO (k a) new_s
131 thenIO :: IO a -> IO b -> IO b
132 thenIO (IO m) k = IO ( \ s ->
134 (# new_s, a #) -> unIO k new_s
137 returnIO :: a -> IO a
138 returnIO x = IO (\ s -> (# s, x #))
140 -- ---------------------------------------------------------------------------
141 -- Coercions between IO and ST
143 -- | A monad transformer embedding strict state transformers in the 'IO'
144 -- monad. The 'RealWorld' parameter indicates that the internal state
145 -- used by the 'ST' computation is a special one supplied by the 'IO'
146 -- monad, and thus distinct from those used by invocations of 'runST'.
147 stToIO :: ST RealWorld a -> IO a
150 ioToST :: IO a -> ST RealWorld a
151 ioToST (IO m) = (ST m)
153 -- This relies on IO and ST having the same representation modulo the
154 -- constraint on the type of the state
156 unsafeIOToST :: IO a -> ST s a
157 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
159 unsafeSTToIO :: ST s a -> IO a
160 unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
162 -- ---------------------------------------------------------------------------
163 -- Unsafe IO operations
166 This is the \"back door\" into the 'IO' monad, allowing
167 'IO' computation to be performed at any time. For
168 this to be safe, the 'IO' computation should be
169 free of side effects and independent of its environment.
171 If the I\/O computation wrapped in 'unsafePerformIO'
172 performs side effects, then the relative order in which those side
173 effects take place (relative to the main I\/O trunk, or other calls to
174 'unsafePerformIO') is indeterminate. You have to be careful when
175 writing and compiling modules that use 'unsafePerformIO':
177 * Use @{\-\# NOINLINE foo \#-\}@ as a pragma on any function @foo@
178 that calls 'unsafePerformIO'. If the call is inlined,
179 the I\/O may be performed more than once.
181 * Use the compiler flag @-fno-cse@ to prevent common sub-expression
182 elimination being performed on the module, which might combine
183 two side effects that were meant to be separate. A good example
184 is using multiple global variables (like @test@ in the example below).
186 * Make sure that the either you switch off let-floating, or that the
187 call to 'unsafePerformIO' cannot float outside a lambda. For example,
190 f x = unsafePerformIO (newIORef [])
192 you may get only one reference cell shared between all calls to @f@.
195 f x = unsafePerformIO (newIORef [x])
197 because now it can't float outside the lambda.
199 It is less well known that
200 'unsafePerformIO' is not type safe. For example:
203 > test = unsafePerformIO $ newIORef []
206 > writeIORef test [42]
207 > bang <- readIORef test
208 > print (bang :: [Char])
210 This program will core dump. This problem with polymorphic references
211 is well known in the ML community, and does not arise with normal
212 monadic use of references. There is no easy way to make it impossible
213 once you use 'unsafePerformIO'. Indeed, it is
214 possible to write @coerce :: a -> b@ with the
215 help of 'unsafePerformIO'. So be careful!
217 {-# NOINLINE unsafePerformIO #-}
218 unsafePerformIO :: IO a -> a
219 unsafePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
221 -- Why do we NOINLINE unsafePerformIO? See the comment with
222 -- GHC.ST.runST. Essentially the issue is that the IO computation
223 -- inside unsafePerformIO must be atomic: it must either all run, or
224 -- not at all. If we let the compiler see the application of the IO
225 -- to realWorld#, it might float out part of the IO.
227 -- Why is there a call to 'lazy' in unsafePerformIO?
228 -- If we don't have it, the demand analyser discovers the following strictness
229 -- for unsafePerformIO: C(U(AV))
231 -- unsafePerformIO (\s -> let r = f x in
232 -- case writeIORef v r s of (# s1, _ #) ->
234 -- The strictness analyser will find that the binding for r is strict,
235 -- (becuase of uPIO's strictness sig), and so it'll evaluate it before
236 -- doing the writeIORef. This actually makes tests/lib/should_run/memo002
239 -- Solution: don't expose the strictness of unsafePerformIO,
240 -- by hiding it with 'lazy'
244 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
245 When passed a value of type @IO a@, the 'IO' will only be performed
246 when the value of the @a@ is demanded. This is used to implement lazy
247 file reading, see 'System.IO.hGetContents'.
249 {-# INLINE unsafeInterleaveIO #-}
250 unsafeInterleaveIO :: IO a -> IO a
251 unsafeInterleaveIO (IO m)
253 r = case m s of (# _, res #) -> res
257 -- We believe that INLINE on unsafeInterleaveIO is safe, because the
258 -- state from this IO thread is passed explicitly to the interleaved
259 -- IO, so it cannot be floated out and shared.
261 -- ---------------------------------------------------------------------------
264 data MVar a = MVar (MVar# RealWorld a)
266 An 'MVar' (pronounced \"em-var\") is a synchronising variable, used
267 for communication between concurrent threads. It can be thought of
268 as a a box, which may be empty or full.
271 -- pull in Eq (Mvar a) too, to avoid GHC.Conc being an orphan-instance module
272 instance Eq (MVar a) where
273 (MVar mvar1#) == (MVar mvar2#) = sameMVar# mvar1# mvar2#
275 -- A Handle is represented by (a reference to) a record
276 -- containing the state of the I/O port/device. We record
277 -- the following pieces of info:
279 -- * type (read,write,closed etc.)
280 -- * the underlying file descriptor
282 -- * buffer, and spare buffers
283 -- * user-friendly name (usually the
284 -- FilePath used when IO.openFile was called)
286 -- Note: when a Handle is garbage collected, we want to flush its buffer
287 -- and close the OS file handle, so as to free up a (precious) resource.
289 -- | Haskell defines operations to read and write characters from and to files,
290 -- represented by values of type @Handle@. Each value of this type is a
291 -- /handle/: a record used by the Haskell run-time system to /manage/ I\/O
292 -- with file system objects. A handle has at least the following properties:
294 -- * whether it manages input or output or both;
296 -- * whether it is /open/, /closed/ or /semi-closed/;
298 -- * whether the object is seekable;
300 -- * whether buffering is disabled, or enabled on a line or block basis;
302 -- * a buffer (whose length may be zero).
304 -- Most handles will also have a current I\/O position indicating where the next
305 -- input or output operation will occur. A handle is /readable/ if it
306 -- manages only input or both input and output; likewise, it is /writable/ if
307 -- it manages only output or both input and output. A handle is /open/ when
309 -- Once it is closed it can no longer be used for either input or output,
310 -- though an implementation cannot re-use its storage while references
311 -- remain to it. Handles are in the 'Show' and 'Eq' classes. The string
312 -- produced by showing a handle is system dependent; it should include
313 -- enough information to identify the handle for debugging. A handle is
314 -- equal according to '==' only to itself; no attempt
315 -- is made to compare the internal state of different handles for equality.
317 -- GHC note: a 'Handle' will be automatically closed when the garbage
318 -- collector detects that it has become unreferenced by the program.
319 -- However, relying on this behaviour is not generally recommended:
320 -- the garbage collector is unpredictable. If possible, use explicit
321 -- an explicit 'hClose' to close 'Handle's when they are no longer
322 -- required. GHC does not currently attempt to free up file
323 -- descriptors when they have run out, it is your responsibility to
324 -- ensure that this doesn't happen.
327 = FileHandle -- A normal handle to a file
328 FilePath -- the file (invariant)
331 | DuplexHandle -- A handle to a read/write stream
332 FilePath -- file for a FIFO, otherwise some
333 -- descriptive string.
334 !(MVar Handle__) -- The read side
335 !(MVar Handle__) -- The write side
338 -- * A 'FileHandle' is seekable. A 'DuplexHandle' may or may not be
341 instance Eq Handle where
342 (FileHandle _ h1) == (FileHandle _ h2) = h1 == h2
343 (DuplexHandle _ h1 _) == (DuplexHandle _ h2 _) = h1 == h2
350 haFD :: !FD, -- file descriptor
351 haType :: HandleType, -- type (read/write/append etc.)
352 haIsBin :: Bool, -- binary mode?
353 haIsStream :: Bool, -- is this a stream handle?
354 haBufferMode :: BufferMode, -- buffer contains read/write data?
355 haBuffer :: !(IORef Buffer), -- the current buffer
356 haBuffers :: !(IORef BufferList), -- spare buffers
357 haOtherSide :: Maybe (MVar Handle__) -- ptr to the write side of a
361 -- ---------------------------------------------------------------------------
364 -- The buffer is represented by a mutable variable containing a
365 -- record, where the record contains the raw buffer and the start/end
366 -- points of the filled portion. We use a mutable variable so that
367 -- the common operation of writing (or reading) some data from (to)
368 -- the buffer doesn't need to modify, and hence copy, the handle
369 -- itself, it just updates the buffer.
371 -- There will be some allocation involved in a simple hPutChar in
372 -- order to create the new Buffer structure (below), but this is
373 -- relatively small, and this only has to be done once per write
376 -- The buffer contains its size - we could also get the size by
377 -- calling sizeOfMutableByteArray# on the raw buffer, but that tends
378 -- to be rounded up to the nearest Word.
380 type RawBuffer = MutableByteArray# RealWorld
382 -- INVARIANTS on a Buffer:
384 -- * A handle *always* has a buffer, even if it is only 1 character long
385 -- (an unbuffered handle needs a 1 character buffer in order to support
386 -- hLookAhead and hIsEOF).
388 -- * if r == w, then r == 0 && w == 0
389 -- * if state == WriteBuffer, then r == 0
390 -- * a write buffer is never full. If an operation
391 -- fills up the buffer, it will always flush it before
393 -- * a read buffer may be full as a result of hLookAhead. In normal
394 -- operation, a read buffer always has at least one character of space.
402 bufState :: BufferState
405 data BufferState = ReadBuffer | WriteBuffer deriving (Eq)
407 -- we keep a few spare buffers around in a handle to avoid allocating
408 -- a new one for each hPutStr. These buffers are *guaranteed* to be the
409 -- same size as the main buffer.
412 | BufferListCons RawBuffer BufferList
415 bufferIsWritable :: Buffer -> Bool
416 bufferIsWritable Buffer{ bufState=WriteBuffer } = True
417 bufferIsWritable _other = False
419 bufferEmpty :: Buffer -> Bool
420 bufferEmpty Buffer{ bufRPtr=r, bufWPtr=w } = r == w
422 -- only makes sense for a write buffer
423 bufferFull :: Buffer -> Bool
424 bufferFull b@Buffer{ bufWPtr=w } = w >= bufSize b
426 -- Internally, we classify handles as being one
437 isReadableHandleType ReadHandle = True
438 isReadableHandleType ReadWriteHandle = True
439 isReadableHandleType _ = False
441 isWritableHandleType AppendHandle = True
442 isWritableHandleType WriteHandle = True
443 isWritableHandleType ReadWriteHandle = True
444 isWritableHandleType _ = False
446 isReadWriteHandleType ReadWriteHandle{} = True
447 isReadWriteHandleType _ = False
449 -- | File and directory names are values of type 'String', whose precise
450 -- meaning is operating system dependent. Files can be opened, yielding a
451 -- handle which can then be used to operate on the contents of that file.
453 type FilePath = String
455 -- ---------------------------------------------------------------------------
458 -- | Three kinds of buffering are supported: line-buffering,
459 -- block-buffering or no-buffering. These modes have the following
460 -- effects. For output, items are written out, or /flushed/,
461 -- from the internal buffer according to the buffer mode:
463 -- * /line-buffering/: the entire output buffer is flushed
464 -- whenever a newline is output, the buffer overflows,
465 -- a 'System.IO.hFlush' is issued, or the handle is closed.
467 -- * /block-buffering/: the entire buffer is written out whenever it
468 -- overflows, a 'System.IO.hFlush' is issued, or the handle is closed.
470 -- * /no-buffering/: output is written immediately, and never stored
473 -- An implementation is free to flush the buffer more frequently,
474 -- but not less frequently, than specified above.
475 -- The output buffer is emptied as soon as it has been written out.
477 -- Similarly, input occurs according to the buffer mode for the handle:
479 -- * /line-buffering/: when the buffer for the handle is not empty,
480 -- the next item is obtained from the buffer; otherwise, when the
481 -- buffer is empty, characters up to and including the next newline
482 -- character are read into the buffer. No characters are available
483 -- until the newline character is available or the buffer is full.
485 -- * /block-buffering/: when the buffer for the handle becomes empty,
486 -- the next block of data is read into the buffer.
488 -- * /no-buffering/: the next input item is read and returned.
489 -- The 'System.IO.hLookAhead' operation implies that even a no-buffered
490 -- handle may require a one-character buffer.
492 -- The default buffering mode when a handle is opened is
493 -- implementation-dependent and may depend on the file system object
494 -- which is attached to that handle.
495 -- For most implementations, physical files will normally be block-buffered
496 -- and terminals will normally be line-buffered.
499 = NoBuffering -- ^ buffering is disabled if possible.
501 -- ^ line-buffering should be enabled if possible.
502 | BlockBuffering (Maybe Int)
503 -- ^ block-buffering should be enabled if possible.
504 -- The size of the buffer is @n@ items if the argument
505 -- is 'Just' @n@ and is otherwise implementation-dependent.
506 deriving (Eq, Ord, Read, Show)
508 -- ---------------------------------------------------------------------------
511 -- |A mutable variable in the 'IO' monad
512 newtype IORef a = IORef (STRef RealWorld a)
514 -- explicit instance because Haddock can't figure out a derived one
515 instance Eq (IORef a) where
516 IORef x == IORef y = x == y
518 -- |Build a new 'IORef'
519 newIORef :: a -> IO (IORef a)
520 newIORef v = stToIO (newSTRef v) >>= \ var -> return (IORef var)
522 -- |Read the value of an 'IORef'
523 readIORef :: IORef a -> IO a
524 readIORef (IORef var) = stToIO (readSTRef var)
526 -- |Write a new value into an 'IORef'
527 writeIORef :: IORef a -> a -> IO ()
528 writeIORef (IORef var) v = stToIO (writeSTRef var v)
530 -- ---------------------------------------------------------------------------
531 -- | An 'IOArray' is a mutable, boxed, non-strict array in the 'IO' monad.
532 -- The type arguments are as follows:
534 -- * @i@: the index type of the array (should be an instance of 'Ix')
536 -- * @e@: the element type of the array.
540 newtype IOArray i e = IOArray (STArray RealWorld i e)
542 -- explicit instance because Haddock can't figure out a derived one
543 instance Eq (IOArray i e) where
544 IOArray x == IOArray y = x == y
546 -- |Build a new 'IOArray'
547 newIOArray :: Ix i => (i,i) -> e -> IO (IOArray i e)
548 {-# INLINE newIOArray #-}
549 newIOArray lu init = stToIO $ do {marr <- newSTArray lu init; return (IOArray marr)}
551 -- | Read a value from an 'IOArray'
552 unsafeReadIOArray :: Ix i => IOArray i e -> Int -> IO e
553 {-# INLINE unsafeReadIOArray #-}
554 unsafeReadIOArray (IOArray marr) i = stToIO (unsafeReadSTArray marr i)
556 -- | Write a new value into an 'IOArray'
557 unsafeWriteIOArray :: Ix i => IOArray i e -> Int -> e -> IO ()
558 {-# INLINE unsafeWriteIOArray #-}
559 unsafeWriteIOArray (IOArray marr) i e = stToIO (unsafeWriteSTArray marr i e)
561 -- | Read a value from an 'IOArray'
562 readIOArray :: Ix i => IOArray i e -> i -> IO e
563 readIOArray (IOArray marr) i = stToIO (readSTArray marr i)
565 -- | Write a new value into an 'IOArray'
566 writeIOArray :: Ix i => IOArray i e -> i -> e -> IO ()
567 writeIOArray (IOArray marr) i e = stToIO (writeSTArray marr i e)
570 -- ---------------------------------------------------------------------------
571 -- Show instance for Handles
573 -- handle types are 'show'n when printing error msgs, so
574 -- we provide a more user-friendly Show instance for it
575 -- than the derived one.
577 instance Show HandleType where
580 ClosedHandle -> showString "closed"
581 SemiClosedHandle -> showString "semi-closed"
582 ReadHandle -> showString "readable"
583 WriteHandle -> showString "writable"
584 AppendHandle -> showString "writable (append)"
585 ReadWriteHandle -> showString "read-writable"
587 instance Show Handle where
588 showsPrec p (FileHandle file _) = showHandle file
589 showsPrec p (DuplexHandle file _ _) = showHandle file
591 showHandle file = showString "{handle: " . showString file . showString "}"
593 -- ------------------------------------------------------------------------
594 -- Exception datatype and operations
596 -- |The type of exceptions. Every kind of system-generated exception
597 -- has a constructor in the 'Exception' type, and values of other
598 -- types may be injected into 'Exception' by coercing them to
599 -- 'Data.Dynamic.Dynamic' (see the section on Dynamic Exceptions:
600 -- "Control.Exception\#DynamicExceptions").
602 = ArithException ArithException
603 -- ^Exceptions raised by arithmetic
604 -- operations. (NOTE: GHC currently does not throw
605 -- 'ArithException's except for 'DivideByZero').
606 | ArrayException ArrayException
607 -- ^Exceptions raised by array-related
608 -- operations. (NOTE: GHC currently does not throw
609 -- 'ArrayException's).
610 | AssertionFailed String
611 -- ^This exception is thrown by the
612 -- 'assert' operation when the condition
613 -- fails. The 'String' argument contains the
614 -- location of the assertion in the source program.
615 | AsyncException AsyncException
616 -- ^Asynchronous exceptions (see section on Asynchronous Exceptions: "Control.Exception\#AsynchronousExceptions").
618 -- ^The current thread was executing a call to
619 -- 'Control.Concurrent.MVar.takeMVar' that could never return,
620 -- because there are no other references to this 'MVar'.
621 | BlockedIndefinitely
622 -- ^The current thread was waiting to retry an atomic memory transaction
623 -- that could never become possible to complete because there are no other
624 -- threads referring to any of teh TVars involved.
626 -- ^The runtime detected an attempt to nest one STM transaction
627 -- inside another one, presumably due to the use of
628 -- 'unsafePeformIO' with 'atomically'.
630 -- ^There are no runnable threads, so the program is
631 -- deadlocked. The 'Deadlock' exception is
632 -- raised in the main thread only (see also: "Control.Concurrent").
633 | DynException Dynamic
634 -- ^Dynamically typed exceptions (see section on Dynamic Exceptions: "Control.Exception\#DynamicExceptions").
636 -- ^The 'ErrorCall' exception is thrown by 'error'. The 'String'
637 -- argument of 'ErrorCall' is the string passed to 'error' when it was
639 | ExitException ExitCode
640 -- ^The 'ExitException' exception is thrown by 'System.Exit.exitWith' (and
641 -- 'System.Exit.exitFailure'). The 'ExitCode' argument is the value passed
642 -- to 'System.Exit.exitWith'. An unhandled 'ExitException' exception in the
643 -- main thread will cause the program to be terminated with the given
645 | IOException IOException
646 -- ^These are the standard IO exceptions generated by
647 -- Haskell\'s @IO@ operations. See also "System.IO.Error".
648 | NoMethodError String
649 -- ^An attempt was made to invoke a class method which has
650 -- no definition in this instance, and there was no default
651 -- definition given in the class declaration. GHC issues a
652 -- warning when you compile an instance which has missing
655 -- ^The current thread is stuck in an infinite loop. This
656 -- exception may or may not be thrown when the program is
658 | PatternMatchFail String
659 -- ^A pattern matching failure. The 'String' argument should contain a
660 -- descriptive message including the function name, source file
663 -- ^An attempt was made to evaluate a field of a record
664 -- for which no value was given at construction time. The
665 -- 'String' argument gives the location of the
666 -- record construction in the source program.
668 -- ^A field selection was attempted on a constructor that
669 -- doesn\'t have the requested field. This can happen with
670 -- multi-constructor records when one or more fields are
671 -- missing from some of the constructors. The
672 -- 'String' argument gives the location of the
673 -- record selection in the source program.
675 -- ^An attempt was made to update a field in a record,
676 -- where the record doesn\'t have the requested field. This can
677 -- only occur with multi-constructor records, when one or more
678 -- fields are missing from some of the constructors. The
679 -- 'String' argument gives the location of the
680 -- record update in the source program.
682 -- |The type of arithmetic exceptions
692 -- |Asynchronous exceptions
695 -- ^The current thread\'s stack exceeded its limit.
696 -- Since an exception has been raised, the thread\'s stack
697 -- will certainly be below its limit again, but the
698 -- programmer should take remedial action
701 -- ^The program\'s heap is reaching its limit, and
702 -- the program should take action to reduce the amount of
703 -- live data it has. Notes:
705 -- * It is undefined which thread receives this exception.
707 -- * GHC currently does not throw 'HeapOverflow' exceptions.
709 -- ^This exception is raised by another thread
710 -- calling 'Control.Concurrent.killThread', or by the system
711 -- if it needs to terminate the thread for some
715 -- | Exceptions generated by array operations
717 = IndexOutOfBounds String
718 -- ^An attempt was made to index an array outside
719 -- its declared bounds.
720 | UndefinedElement String
721 -- ^An attempt was made to evaluate an element of an
722 -- array that had not been initialized.
725 stackOverflow, heapOverflow :: Exception -- for the RTS
726 stackOverflow = AsyncException StackOverflow
727 heapOverflow = AsyncException HeapOverflow
729 instance Show ArithException where
730 showsPrec _ Overflow = showString "arithmetic overflow"
731 showsPrec _ Underflow = showString "arithmetic underflow"
732 showsPrec _ LossOfPrecision = showString "loss of precision"
733 showsPrec _ DivideByZero = showString "divide by zero"
734 showsPrec _ Denormal = showString "denormal"
736 instance Show AsyncException where
737 showsPrec _ StackOverflow = showString "stack overflow"
738 showsPrec _ HeapOverflow = showString "heap overflow"
739 showsPrec _ ThreadKilled = showString "thread killed"
741 instance Show ArrayException where
742 showsPrec _ (IndexOutOfBounds s)
743 = showString "array index out of range"
744 . (if not (null s) then showString ": " . showString s
746 showsPrec _ (UndefinedElement s)
747 = showString "undefined array element"
748 . (if not (null s) then showString ": " . showString s
751 instance Show Exception where
752 showsPrec _ (IOException err) = shows err
753 showsPrec _ (ArithException err) = shows err
754 showsPrec _ (ArrayException err) = shows err
755 showsPrec _ (ErrorCall err) = showString err
756 showsPrec _ (ExitException err) = showString "exit: " . shows err
757 showsPrec _ (NoMethodError err) = showString err
758 showsPrec _ (PatternMatchFail err) = showString err
759 showsPrec _ (RecSelError err) = showString err
760 showsPrec _ (RecConError err) = showString err
761 showsPrec _ (RecUpdError err) = showString err
762 showsPrec _ (AssertionFailed err) = showString err
763 showsPrec _ (DynException err) = showString "exception :: " . showsTypeRep (dynTypeRep err)
764 showsPrec _ (AsyncException e) = shows e
765 showsPrec _ (BlockedOnDeadMVar) = showString "thread blocked indefinitely"
766 showsPrec _ (BlockedIndefinitely) = showString "thread blocked indefinitely"
767 showsPrec _ (NestedAtomically) = showString "Control.Concurrent.STM.atomically was nested"
768 showsPrec _ (NonTermination) = showString "<<loop>>"
769 showsPrec _ (Deadlock) = showString "<<deadlock>>"
771 instance Eq Exception where
772 IOException e1 == IOException e2 = e1 == e2
773 ArithException e1 == ArithException e2 = e1 == e2
774 ArrayException e1 == ArrayException e2 = e1 == e2
775 ErrorCall e1 == ErrorCall e2 = e1 == e2
776 ExitException e1 == ExitException e2 = e1 == e2
777 NoMethodError e1 == NoMethodError e2 = e1 == e2
778 PatternMatchFail e1 == PatternMatchFail e2 = e1 == e2
779 RecSelError e1 == RecSelError e2 = e1 == e2
780 RecConError e1 == RecConError e2 = e1 == e2
781 RecUpdError e1 == RecUpdError e2 = e1 == e2
782 AssertionFailed e1 == AssertionFailed e2 = e1 == e2
783 DynException _ == DynException _ = False -- incomparable
784 AsyncException e1 == AsyncException e2 = e1 == e2
785 BlockedOnDeadMVar == BlockedOnDeadMVar = True
786 NonTermination == NonTermination = True
787 NestedAtomically == NestedAtomically = True
788 Deadlock == Deadlock = True
791 -- -----------------------------------------------------------------------------
794 -- We need it here because it is used in ExitException in the
795 -- Exception datatype (above).
798 = ExitSuccess -- ^ indicates successful termination;
800 -- ^ indicates program failure with an exit code.
801 -- The exact interpretation of the code is
802 -- operating-system dependent. In particular, some values
803 -- may be prohibited (e.g. 0 on a POSIX-compliant system).
804 deriving (Eq, Ord, Read, Show)
806 -- --------------------------------------------------------------------------
809 -- | Throw an exception. Exceptions may be thrown from purely
810 -- functional code, but may only be caught within the 'IO' monad.
811 throw :: Exception -> a
812 throw exception = raise# exception
814 -- | A variant of 'throw' that can be used within the 'IO' monad.
816 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
817 -- two functions are subtly different:
819 -- > throw e `seq` x ===> throw e
820 -- > throwIO e `seq` x ===> x
822 -- The first example will cause the exception @e@ to be raised,
823 -- whereas the second one won\'t. In fact, 'throwIO' will only cause
824 -- an exception to be raised when it is used within the 'IO' monad.
825 -- The 'throwIO' variant should be used in preference to 'throw' to
826 -- raise an exception within the 'IO' monad because it guarantees
827 -- ordering with respect to other 'IO' operations, whereas 'throw'
829 throwIO :: Exception -> IO a
830 throwIO err = IO $ raiseIO# err
832 ioException :: IOException -> IO a
833 ioException err = IO $ raiseIO# (IOException err)
835 -- | Raise an 'IOError' in the 'IO' monad.
836 ioError :: IOError -> IO a
837 ioError = ioException
839 -- ---------------------------------------------------------------------------
842 -- | The Haskell 98 type for exceptions in the 'IO' monad.
843 -- Any I\/O operation may raise an 'IOError' instead of returning a result.
844 -- For a more general type of exception, including also those that arise
845 -- in pure code, see 'Control.Exception.Exception'.
847 -- In Haskell 98, this is an opaque type.
848 type IOError = IOException
850 -- |Exceptions that occur in the @IO@ monad.
851 -- An @IOException@ records a more specific error type, a descriptive
852 -- string and maybe the handle that was used when the error was
856 ioe_handle :: Maybe Handle, -- the handle used by the action flagging
858 ioe_type :: IOErrorType, -- what it was.
859 ioe_location :: String, -- location.
860 ioe_description :: String, -- error type specific information.
861 ioe_filename :: Maybe FilePath -- filename the error is related to.
864 instance Eq IOException where
865 (IOError h1 e1 loc1 str1 fn1) == (IOError h2 e2 loc2 str2 fn2) =
866 e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && fn1==fn2
868 -- | An abstract type that contains a value for each variant of 'IOError'.
880 | UnsatisfiedConstraints
887 | UnsupportedOperation
891 | DynIOError Dynamic -- cheap&cheerful extensible IO error type.
893 instance Eq IOErrorType where
896 DynIOError{} -> False -- from a strictness POV, compatible with a derived Eq inst?
897 _ -> getTag x ==# getTag y
899 instance Show IOErrorType where
903 AlreadyExists -> "already exists"
904 NoSuchThing -> "does not exist"
905 ResourceBusy -> "resource busy"
906 ResourceExhausted -> "resource exhausted"
908 IllegalOperation -> "illegal operation"
909 PermissionDenied -> "permission denied"
910 UserError -> "user error"
911 HardwareFault -> "hardware fault"
912 InappropriateType -> "inappropriate type"
913 Interrupted -> "interrupted"
914 InvalidArgument -> "invalid argument"
915 OtherError -> "failed"
916 ProtocolError -> "protocol error"
917 ResourceVanished -> "resource vanished"
918 SystemError -> "system error"
919 TimeExpired -> "timeout"
920 UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise!
921 UnsupportedOperation -> "unsupported operation"
922 DynIOError{} -> "unknown IO error"
924 -- | Construct an 'IOError' value with a string describing the error.
925 -- The 'fail' method of the 'IO' instance of the 'Monad' class raises a
926 -- 'userError', thus:
928 -- > instance Monad IO where
930 -- > fail s = ioError (userError s)
932 userError :: String -> IOError
933 userError str = IOError Nothing UserError "" str Nothing
935 -- ---------------------------------------------------------------------------
938 instance Show IOException where
939 showsPrec p (IOError hdl iot loc s fn) =
941 Nothing -> case hdl of
943 Just h -> showsPrec p h . showString ": "
944 Just name -> showString name . showString ": ") .
947 _ -> showString loc . showString ": ") .
951 _ -> showString " (" . showString s . showString ")")
953 -- -----------------------------------------------------------------------------
956 data IOMode = ReadMode | WriteMode | AppendMode | ReadWriteMode
957 deriving (Eq, Ord, Ix, Enum, Read, Show)