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,
21 unsafeDupablePerformIO, unsafeDupableInterleaveIO,
24 -- To and from from ST
25 stToIO, ioToST, unsafeIOToST, unsafeSTToIO,
28 IORef(..), newIORef, readIORef, writeIORef,
29 IOArray(..), newIOArray, readIOArray, writeIOArray, unsafeReadIOArray, unsafeWriteIOArray,
32 -- Handles, file descriptors,
34 Handle(..), Handle__(..), HandleType(..), IOMode(..), FD,
35 isReadableHandleType, isWritableHandleType, isReadWriteHandleType, showHandle,
38 Buffer(..), RawBuffer, BufferState(..), BufferList(..), BufferMode(..),
39 bufferIsWritable, bufferEmpty, bufferFull,
42 Exception(..), ArithException(..), AsyncException(..), ArrayException(..),
43 stackOverflow, heapOverflow, throw, throwIO, ioException,
44 IOError, IOException(..), IOErrorType(..), ioError, userError,
49 import GHC.Arr -- to derive Ix class
50 import GHC.Enum -- to derive Enum class
53 -- import GHC.Num -- To get fromInteger etc, needed because of -fno-implicit-prelude
54 import Data.Maybe ( Maybe(..) )
58 import Foreign.C.Types (CInt)
61 import {-# SOURCE #-} GHC.Dynamic
64 -- ---------------------------------------------------------------------------
68 The IO Monad is just an instance of the ST monad, where the state is
69 the real world. We use the exception mechanism (in GHC.Exception) to
70 implement IO exceptions.
72 NOTE: The IO representation is deeply wired in to various parts of the
73 system. The following list may or may not be exhaustive:
75 Compiler - types of various primitives in PrimOp.lhs
77 RTS - forceIO (StgMiscClosures.hc)
78 - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast
80 - raiseAsync (Schedule.c)
82 Prelude - GHC.IOBase.lhs, and several other places including
85 Libraries - parts of hslibs/lang.
91 A value of type @'IO' a@ is a computation which, when performed,
92 does some I\/O before returning a value of type @a@.
94 There is really only one way to \"perform\" an I\/O action: bind it to
95 @Main.main@ in your program. When your program is run, the I\/O will
96 be performed. It isn't possible to perform I\/O from an arbitrary
97 function, unless that function is itself in the 'IO' monad and called
98 at some point, directly or indirectly, from @Main.main@.
100 'IO' is a monad, so 'IO' actions can be combined using either the do-notation
101 or the '>>' and '>>=' operations from the 'Monad' class.
103 newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #))
105 unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
108 instance Functor IO where
109 fmap f x = x >>= (return . f)
111 instance Monad IO where
112 {-# INLINE return #-}
115 m >> k = m >>= \ _ -> k
116 return x = returnIO x
121 failIO :: String -> IO a
122 failIO s = ioError (userError s)
124 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
125 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
127 bindIO :: IO a -> (a -> IO b) -> IO b
128 bindIO (IO m) k = IO ( \ s ->
130 (# new_s, a #) -> unIO (k a) new_s
133 thenIO :: IO a -> IO b -> IO b
134 thenIO (IO m) k = IO ( \ s ->
136 (# new_s, a #) -> unIO k new_s
139 returnIO :: a -> IO a
140 returnIO x = IO (\ s -> (# s, x #))
142 -- ---------------------------------------------------------------------------
143 -- Coercions between IO and ST
145 -- | A monad transformer embedding strict state transformers in the 'IO'
146 -- monad. The 'RealWorld' parameter indicates that the internal state
147 -- used by the 'ST' computation is a special one supplied by the 'IO'
148 -- monad, and thus distinct from those used by invocations of 'runST'.
149 stToIO :: ST RealWorld a -> IO a
152 ioToST :: IO a -> ST RealWorld a
153 ioToST (IO m) = (ST m)
155 -- This relies on IO and ST having the same representation modulo the
156 -- constraint on the type of the state
158 unsafeIOToST :: IO a -> ST s a
159 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
161 unsafeSTToIO :: ST s a -> IO a
162 unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
164 -- ---------------------------------------------------------------------------
165 -- Unsafe IO operations
168 This is the \"back door\" into the 'IO' monad, allowing
169 'IO' computation to be performed at any time. For
170 this to be safe, the 'IO' computation should be
171 free of side effects and independent of its environment.
173 If the I\/O computation wrapped in 'unsafePerformIO'
174 performs side effects, then the relative order in which those side
175 effects take place (relative to the main I\/O trunk, or other calls to
176 'unsafePerformIO') is indeterminate. You have to be careful when
177 writing and compiling modules that use 'unsafePerformIO':
179 * Use @{\-\# NOINLINE foo \#-\}@ as a pragma on any function @foo@
180 that calls 'unsafePerformIO'. If the call is inlined,
181 the I\/O may be performed more than once.
183 * Use the compiler flag @-fno-cse@ to prevent common sub-expression
184 elimination being performed on the module, which might combine
185 two side effects that were meant to be separate. A good example
186 is using multiple global variables (like @test@ in the example below).
188 * Make sure that the either you switch off let-floating, or that the
189 call to 'unsafePerformIO' cannot float outside a lambda. For example,
192 f x = unsafePerformIO (newIORef [])
194 you may get only one reference cell shared between all calls to @f@.
197 f x = unsafePerformIO (newIORef [x])
199 because now it can't float outside the lambda.
201 It is less well known that
202 'unsafePerformIO' is not type safe. For example:
205 > test = unsafePerformIO $ newIORef []
208 > writeIORef test [42]
209 > bang <- readIORef test
210 > print (bang :: [Char])
212 This program will core dump. This problem with polymorphic references
213 is well known in the ML community, and does not arise with normal
214 monadic use of references. There is no easy way to make it impossible
215 once you use 'unsafePerformIO'. Indeed, it is
216 possible to write @coerce :: a -> b@ with the
217 help of 'unsafePerformIO'. So be careful!
219 unsafePerformIO :: IO a -> a
220 unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)
223 This version of 'unsafePerformIO' is slightly more efficient,
224 because it omits the check that the IO is only being performed by a
225 single thread. Hence, when you write 'unsafeDupablePerformIO',
226 there is a possibility that the IO action may be performed multiple
227 times (on a multiprocessor), and you should therefore ensure that
228 it gives the same results each time.
230 {-# NOINLINE unsafeDupablePerformIO #-}
231 unsafeDupablePerformIO :: IO a -> a
232 unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
234 -- Why do we NOINLINE unsafeDupablePerformIO? See the comment with
235 -- GHC.ST.runST. Essentially the issue is that the IO computation
236 -- inside unsafePerformIO must be atomic: it must either all run, or
237 -- not at all. If we let the compiler see the application of the IO
238 -- to realWorld#, it might float out part of the IO.
240 -- Why is there a call to 'lazy' in unsafeDupablePerformIO?
241 -- If we don't have it, the demand analyser discovers the following strictness
242 -- for unsafeDupablePerformIO: C(U(AV))
244 -- unsafeDupablePerformIO (\s -> let r = f x in
245 -- case writeIORef v r s of (# s1, _ #) ->
247 -- The strictness analyser will find that the binding for r is strict,
248 -- (becuase of uPIO's strictness sig), and so it'll evaluate it before
249 -- doing the writeIORef. This actually makes tests/lib/should_run/memo002
252 -- Solution: don't expose the strictness of unsafeDupablePerformIO,
253 -- by hiding it with 'lazy'
256 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
257 When passed a value of type @IO a@, the 'IO' will only be performed
258 when the value of the @a@ is demanded. This is used to implement lazy
259 file reading, see 'System.IO.hGetContents'.
261 {-# INLINE unsafeInterleaveIO #-}
262 unsafeInterleaveIO :: IO a -> IO a
263 unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)
265 -- We believe that INLINE on unsafeInterleaveIO is safe, because the
266 -- state from this IO thread is passed explicitly to the interleaved
267 -- IO, so it cannot be floated out and shared.
269 {-# INLINE unsafeDupableInterleaveIO #-}
270 unsafeDupableInterleaveIO :: IO a -> IO a
271 unsafeDupableInterleaveIO (IO m)
273 r = case m s of (# _, res #) -> res
278 Ensures that the suspensions under evaluation by the current thread
279 are unique; that is, the current thread is not evaluating anything
280 that is also under evaluation by another thread that has also executed
283 This operation is used in the definition of 'unsafePerformIO' to
284 prevent the IO action from being executed multiple times, which is usually
288 noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)
290 -- ---------------------------------------------------------------------------
293 data MVar a = MVar (MVar# RealWorld a)
295 An 'MVar' (pronounced \"em-var\") is a synchronising variable, used
296 for communication between concurrent threads. It can be thought of
297 as a a box, which may be empty or full.
300 -- pull in Eq (Mvar a) too, to avoid GHC.Conc being an orphan-instance module
301 instance Eq (MVar a) where
302 (MVar mvar1#) == (MVar mvar2#) = sameMVar# mvar1# mvar2#
304 -- A Handle is represented by (a reference to) a record
305 -- containing the state of the I/O port/device. We record
306 -- the following pieces of info:
308 -- * type (read,write,closed etc.)
309 -- * the underlying file descriptor
311 -- * buffer, and spare buffers
312 -- * user-friendly name (usually the
313 -- FilePath used when IO.openFile was called)
315 -- Note: when a Handle is garbage collected, we want to flush its buffer
316 -- and close the OS file handle, so as to free up a (precious) resource.
318 -- | Haskell defines operations to read and write characters from and to files,
319 -- represented by values of type @Handle@. Each value of this type is a
320 -- /handle/: a record used by the Haskell run-time system to /manage/ I\/O
321 -- with file system objects. A handle has at least the following properties:
323 -- * whether it manages input or output or both;
325 -- * whether it is /open/, /closed/ or /semi-closed/;
327 -- * whether the object is seekable;
329 -- * whether buffering is disabled, or enabled on a line or block basis;
331 -- * a buffer (whose length may be zero).
333 -- Most handles will also have a current I\/O position indicating where the next
334 -- input or output operation will occur. A handle is /readable/ if it
335 -- manages only input or both input and output; likewise, it is /writable/ if
336 -- it manages only output or both input and output. A handle is /open/ when
338 -- Once it is closed it can no longer be used for either input or output,
339 -- though an implementation cannot re-use its storage while references
340 -- remain to it. Handles are in the 'Show' and 'Eq' classes. The string
341 -- produced by showing a handle is system dependent; it should include
342 -- enough information to identify the handle for debugging. A handle is
343 -- equal according to '==' only to itself; no attempt
344 -- is made to compare the internal state of different handles for equality.
346 -- GHC note: a 'Handle' will be automatically closed when the garbage
347 -- collector detects that it has become unreferenced by the program.
348 -- However, relying on this behaviour is not generally recommended:
349 -- the garbage collector is unpredictable. If possible, use explicit
350 -- an explicit 'hClose' to close 'Handle's when they are no longer
351 -- required. GHC does not currently attempt to free up file
352 -- descriptors when they have run out, it is your responsibility to
353 -- ensure that this doesn't happen.
356 = FileHandle -- A normal handle to a file
357 FilePath -- the file (invariant)
360 | DuplexHandle -- A handle to a read/write stream
361 FilePath -- file for a FIFO, otherwise some
362 -- descriptive string.
363 !(MVar Handle__) -- The read side
364 !(MVar Handle__) -- The write side
367 -- * A 'FileHandle' is seekable. A 'DuplexHandle' may or may not be
370 instance Eq Handle where
371 (FileHandle _ h1) == (FileHandle _ h2) = h1 == h2
372 (DuplexHandle _ h1 _) == (DuplexHandle _ h2 _) = h1 == h2
379 haFD :: !FD, -- file descriptor
380 haType :: HandleType, -- type (read/write/append etc.)
381 haIsBin :: Bool, -- binary mode?
382 haIsStream :: Bool, -- is this a stream handle?
383 haBufferMode :: BufferMode, -- buffer contains read/write data?
384 haBuffer :: !(IORef Buffer), -- the current buffer
385 haBuffers :: !(IORef BufferList), -- spare buffers
386 haOtherSide :: Maybe (MVar Handle__) -- ptr to the write side of a
390 -- ---------------------------------------------------------------------------
393 -- The buffer is represented by a mutable variable containing a
394 -- record, where the record contains the raw buffer and the start/end
395 -- points of the filled portion. We use a mutable variable so that
396 -- the common operation of writing (or reading) some data from (to)
397 -- the buffer doesn't need to modify, and hence copy, the handle
398 -- itself, it just updates the buffer.
400 -- There will be some allocation involved in a simple hPutChar in
401 -- order to create the new Buffer structure (below), but this is
402 -- relatively small, and this only has to be done once per write
405 -- The buffer contains its size - we could also get the size by
406 -- calling sizeOfMutableByteArray# on the raw buffer, but that tends
407 -- to be rounded up to the nearest Word.
409 type RawBuffer = MutableByteArray# RealWorld
411 -- INVARIANTS on a Buffer:
413 -- * A handle *always* has a buffer, even if it is only 1 character long
414 -- (an unbuffered handle needs a 1 character buffer in order to support
415 -- hLookAhead and hIsEOF).
417 -- * if r == w, then r == 0 && w == 0
418 -- * if state == WriteBuffer, then r == 0
419 -- * a write buffer is never full. If an operation
420 -- fills up the buffer, it will always flush it before
422 -- * a read buffer may be full as a result of hLookAhead. In normal
423 -- operation, a read buffer always has at least one character of space.
431 bufState :: BufferState
434 data BufferState = ReadBuffer | WriteBuffer deriving (Eq)
436 -- we keep a few spare buffers around in a handle to avoid allocating
437 -- a new one for each hPutStr. These buffers are *guaranteed* to be the
438 -- same size as the main buffer.
441 | BufferListCons RawBuffer BufferList
444 bufferIsWritable :: Buffer -> Bool
445 bufferIsWritable Buffer{ bufState=WriteBuffer } = True
446 bufferIsWritable _other = False
448 bufferEmpty :: Buffer -> Bool
449 bufferEmpty Buffer{ bufRPtr=r, bufWPtr=w } = r == w
451 -- only makes sense for a write buffer
452 bufferFull :: Buffer -> Bool
453 bufferFull b@Buffer{ bufWPtr=w } = w >= bufSize b
455 -- Internally, we classify handles as being one
466 isReadableHandleType ReadHandle = True
467 isReadableHandleType ReadWriteHandle = True
468 isReadableHandleType _ = False
470 isWritableHandleType AppendHandle = True
471 isWritableHandleType WriteHandle = True
472 isWritableHandleType ReadWriteHandle = True
473 isWritableHandleType _ = False
475 isReadWriteHandleType ReadWriteHandle{} = True
476 isReadWriteHandleType _ = False
478 -- | File and directory names are values of type 'String', whose precise
479 -- meaning is operating system dependent. Files can be opened, yielding a
480 -- handle which can then be used to operate on the contents of that file.
482 type FilePath = String
484 -- ---------------------------------------------------------------------------
487 -- | Three kinds of buffering are supported: line-buffering,
488 -- block-buffering or no-buffering. These modes have the following
489 -- effects. For output, items are written out, or /flushed/,
490 -- from the internal buffer according to the buffer mode:
492 -- * /line-buffering/: the entire output buffer is flushed
493 -- whenever a newline is output, the buffer overflows,
494 -- a 'System.IO.hFlush' is issued, or the handle is closed.
496 -- * /block-buffering/: the entire buffer is written out whenever it
497 -- overflows, a 'System.IO.hFlush' is issued, or the handle is closed.
499 -- * /no-buffering/: output is written immediately, and never stored
502 -- An implementation is free to flush the buffer more frequently,
503 -- but not less frequently, than specified above.
504 -- The output buffer is emptied as soon as it has been written out.
506 -- Similarly, input occurs according to the buffer mode for the handle:
508 -- * /line-buffering/: when the buffer for the handle is not empty,
509 -- the next item is obtained from the buffer; otherwise, when the
510 -- buffer is empty, characters up to and including the next newline
511 -- character are read into the buffer. No characters are available
512 -- until the newline character is available or the buffer is full.
514 -- * /block-buffering/: when the buffer for the handle becomes empty,
515 -- the next block of data is read into the buffer.
517 -- * /no-buffering/: the next input item is read and returned.
518 -- The 'System.IO.hLookAhead' operation implies that even a no-buffered
519 -- handle may require a one-character buffer.
521 -- The default buffering mode when a handle is opened is
522 -- implementation-dependent and may depend on the file system object
523 -- which is attached to that handle.
524 -- For most implementations, physical files will normally be block-buffered
525 -- and terminals will normally be line-buffered.
528 = NoBuffering -- ^ buffering is disabled if possible.
530 -- ^ line-buffering should be enabled if possible.
531 | BlockBuffering (Maybe Int)
532 -- ^ block-buffering should be enabled if possible.
533 -- The size of the buffer is @n@ items if the argument
534 -- is 'Just' @n@ and is otherwise implementation-dependent.
535 deriving (Eq, Ord, Read, Show)
537 -- ---------------------------------------------------------------------------
540 -- |A mutable variable in the 'IO' monad
541 newtype IORef a = IORef (STRef RealWorld a)
543 -- explicit instance because Haddock can't figure out a derived one
544 instance Eq (IORef a) where
545 IORef x == IORef y = x == y
547 -- |Build a new 'IORef'
548 newIORef :: a -> IO (IORef a)
549 newIORef v = stToIO (newSTRef v) >>= \ var -> return (IORef var)
551 -- |Read the value of an 'IORef'
552 readIORef :: IORef a -> IO a
553 readIORef (IORef var) = stToIO (readSTRef var)
555 -- |Write a new value into an 'IORef'
556 writeIORef :: IORef a -> a -> IO ()
557 writeIORef (IORef var) v = stToIO (writeSTRef var v)
559 -- ---------------------------------------------------------------------------
560 -- | An 'IOArray' is a mutable, boxed, non-strict array in the 'IO' monad.
561 -- The type arguments are as follows:
563 -- * @i@: the index type of the array (should be an instance of 'Ix')
565 -- * @e@: the element type of the array.
569 newtype IOArray i e = IOArray (STArray RealWorld i e)
571 -- explicit instance because Haddock can't figure out a derived one
572 instance Eq (IOArray i e) where
573 IOArray x == IOArray y = x == y
575 -- |Build a new 'IOArray'
576 newIOArray :: Ix i => (i,i) -> e -> IO (IOArray i e)
577 {-# INLINE newIOArray #-}
578 newIOArray lu init = stToIO $ do {marr <- newSTArray lu init; return (IOArray marr)}
580 -- | Read a value from an 'IOArray'
581 unsafeReadIOArray :: Ix i => IOArray i e -> Int -> IO e
582 {-# INLINE unsafeReadIOArray #-}
583 unsafeReadIOArray (IOArray marr) i = stToIO (unsafeReadSTArray marr i)
585 -- | Write a new value into an 'IOArray'
586 unsafeWriteIOArray :: Ix i => IOArray i e -> Int -> e -> IO ()
587 {-# INLINE unsafeWriteIOArray #-}
588 unsafeWriteIOArray (IOArray marr) i e = stToIO (unsafeWriteSTArray marr i e)
590 -- | Read a value from an 'IOArray'
591 readIOArray :: Ix i => IOArray i e -> i -> IO e
592 readIOArray (IOArray marr) i = stToIO (readSTArray marr i)
594 -- | Write a new value into an 'IOArray'
595 writeIOArray :: Ix i => IOArray i e -> i -> e -> IO ()
596 writeIOArray (IOArray marr) i e = stToIO (writeSTArray marr i e)
599 -- ---------------------------------------------------------------------------
600 -- Show instance for Handles
602 -- handle types are 'show'n when printing error msgs, so
603 -- we provide a more user-friendly Show instance for it
604 -- than the derived one.
606 instance Show HandleType where
609 ClosedHandle -> showString "closed"
610 SemiClosedHandle -> showString "semi-closed"
611 ReadHandle -> showString "readable"
612 WriteHandle -> showString "writable"
613 AppendHandle -> showString "writable (append)"
614 ReadWriteHandle -> showString "read-writable"
616 instance Show Handle where
617 showsPrec p (FileHandle file _) = showHandle file
618 showsPrec p (DuplexHandle file _ _) = showHandle file
620 showHandle file = showString "{handle: " . showString file . showString "}"
622 -- ------------------------------------------------------------------------
623 -- Exception datatype and operations
625 -- |The type of exceptions. Every kind of system-generated exception
626 -- has a constructor in the 'Exception' type, and values of other
627 -- types may be injected into 'Exception' by coercing them to
628 -- 'Data.Dynamic.Dynamic' (see the section on Dynamic Exceptions:
629 -- "Control.Exception\#DynamicExceptions").
631 = ArithException ArithException
632 -- ^Exceptions raised by arithmetic
633 -- operations. (NOTE: GHC currently does not throw
634 -- 'ArithException's except for 'DivideByZero').
635 | ArrayException ArrayException
636 -- ^Exceptions raised by array-related
637 -- operations. (NOTE: GHC currently does not throw
638 -- 'ArrayException's).
639 | AssertionFailed String
640 -- ^This exception is thrown by the
641 -- 'assert' operation when the condition
642 -- fails. The 'String' argument contains the
643 -- location of the assertion in the source program.
644 | AsyncException AsyncException
645 -- ^Asynchronous exceptions (see section on Asynchronous Exceptions: "Control.Exception\#AsynchronousExceptions").
647 -- ^The current thread was executing a call to
648 -- 'Control.Concurrent.MVar.takeMVar' that could never return,
649 -- because there are no other references to this 'MVar'.
650 | BlockedIndefinitely
651 -- ^The current thread was waiting to retry an atomic memory transaction
652 -- that could never become possible to complete because there are no other
653 -- threads referring to any of teh TVars involved.
655 -- ^The runtime detected an attempt to nest one STM transaction
656 -- inside another one, presumably due to the use of
657 -- 'unsafePeformIO' with 'atomically'.
659 -- ^There are no runnable threads, so the program is
660 -- deadlocked. The 'Deadlock' exception is
661 -- raised in the main thread only (see also: "Control.Concurrent").
662 | DynException Dynamic
663 -- ^Dynamically typed exceptions (see section on Dynamic Exceptions: "Control.Exception\#DynamicExceptions").
665 -- ^The 'ErrorCall' exception is thrown by 'error'. The 'String'
666 -- argument of 'ErrorCall' is the string passed to 'error' when it was
668 | ExitException ExitCode
669 -- ^The 'ExitException' exception is thrown by 'System.Exit.exitWith' (and
670 -- 'System.Exit.exitFailure'). The 'ExitCode' argument is the value passed
671 -- to 'System.Exit.exitWith'. An unhandled 'ExitException' exception in the
672 -- main thread will cause the program to be terminated with the given
674 | IOException IOException
675 -- ^These are the standard IO exceptions generated by
676 -- Haskell\'s @IO@ operations. See also "System.IO.Error".
677 | NoMethodError String
678 -- ^An attempt was made to invoke a class method which has
679 -- no definition in this instance, and there was no default
680 -- definition given in the class declaration. GHC issues a
681 -- warning when you compile an instance which has missing
684 -- ^The current thread is stuck in an infinite loop. This
685 -- exception may or may not be thrown when the program is
687 | PatternMatchFail String
688 -- ^A pattern matching failure. The 'String' argument should contain a
689 -- descriptive message including the function name, source file
692 -- ^An attempt was made to evaluate a field of a record
693 -- for which no value was given at construction time. The
694 -- 'String' argument gives the location of the
695 -- record construction in the source program.
697 -- ^A field selection was attempted on a constructor that
698 -- doesn\'t have the requested field. This can happen with
699 -- multi-constructor records when one or more fields are
700 -- missing from some of the constructors. The
701 -- 'String' argument gives the location of the
702 -- record selection in the source program.
704 -- ^An attempt was made to update a field in a record,
705 -- where the record doesn\'t have the requested field. This can
706 -- only occur with multi-constructor records, when one or more
707 -- fields are missing from some of the constructors. The
708 -- 'String' argument gives the location of the
709 -- record update in the source program.
711 -- |The type of arithmetic exceptions
721 -- |Asynchronous exceptions
724 -- ^The current thread\'s stack exceeded its limit.
725 -- Since an exception has been raised, the thread\'s stack
726 -- will certainly be below its limit again, but the
727 -- programmer should take remedial action
730 -- ^The program\'s heap is reaching its limit, and
731 -- the program should take action to reduce the amount of
732 -- live data it has. Notes:
734 -- * It is undefined which thread receives this exception.
736 -- * GHC currently does not throw 'HeapOverflow' exceptions.
738 -- ^This exception is raised by another thread
739 -- calling 'Control.Concurrent.killThread', or by the system
740 -- if it needs to terminate the thread for some
744 -- | Exceptions generated by array operations
746 = IndexOutOfBounds String
747 -- ^An attempt was made to index an array outside
748 -- its declared bounds.
749 | UndefinedElement String
750 -- ^An attempt was made to evaluate an element of an
751 -- array that had not been initialized.
754 stackOverflow, heapOverflow :: Exception -- for the RTS
755 stackOverflow = AsyncException StackOverflow
756 heapOverflow = AsyncException HeapOverflow
758 instance Show ArithException where
759 showsPrec _ Overflow = showString "arithmetic overflow"
760 showsPrec _ Underflow = showString "arithmetic underflow"
761 showsPrec _ LossOfPrecision = showString "loss of precision"
762 showsPrec _ DivideByZero = showString "divide by zero"
763 showsPrec _ Denormal = showString "denormal"
765 instance Show AsyncException where
766 showsPrec _ StackOverflow = showString "stack overflow"
767 showsPrec _ HeapOverflow = showString "heap overflow"
768 showsPrec _ ThreadKilled = showString "thread killed"
770 instance Show ArrayException where
771 showsPrec _ (IndexOutOfBounds s)
772 = showString "array index out of range"
773 . (if not (null s) then showString ": " . showString s
775 showsPrec _ (UndefinedElement s)
776 = showString "undefined array element"
777 . (if not (null s) then showString ": " . showString s
780 instance Show Exception where
781 showsPrec _ (IOException err) = shows err
782 showsPrec _ (ArithException err) = shows err
783 showsPrec _ (ArrayException err) = shows err
784 showsPrec _ (ErrorCall err) = showString err
785 showsPrec _ (ExitException err) = showString "exit: " . shows err
786 showsPrec _ (NoMethodError err) = showString err
787 showsPrec _ (PatternMatchFail err) = showString err
788 showsPrec _ (RecSelError err) = showString err
789 showsPrec _ (RecConError err) = showString err
790 showsPrec _ (RecUpdError err) = showString err
791 showsPrec _ (AssertionFailed err) = showString err
792 showsPrec _ (DynException err) = showString "exception :: " . showsTypeRep (dynTypeRep err)
793 showsPrec _ (AsyncException e) = shows e
794 showsPrec _ (BlockedOnDeadMVar) = showString "thread blocked indefinitely"
795 showsPrec _ (BlockedIndefinitely) = showString "thread blocked indefinitely"
796 showsPrec _ (NestedAtomically) = showString "Control.Concurrent.STM.atomically was nested"
797 showsPrec _ (NonTermination) = showString "<<loop>>"
798 showsPrec _ (Deadlock) = showString "<<deadlock>>"
800 instance Eq Exception where
801 IOException e1 == IOException e2 = e1 == e2
802 ArithException e1 == ArithException e2 = e1 == e2
803 ArrayException e1 == ArrayException e2 = e1 == e2
804 ErrorCall e1 == ErrorCall e2 = e1 == e2
805 ExitException e1 == ExitException e2 = e1 == e2
806 NoMethodError e1 == NoMethodError e2 = e1 == e2
807 PatternMatchFail e1 == PatternMatchFail e2 = e1 == e2
808 RecSelError e1 == RecSelError e2 = e1 == e2
809 RecConError e1 == RecConError e2 = e1 == e2
810 RecUpdError e1 == RecUpdError e2 = e1 == e2
811 AssertionFailed e1 == AssertionFailed e2 = e1 == e2
812 DynException _ == DynException _ = False -- incomparable
813 AsyncException e1 == AsyncException e2 = e1 == e2
814 BlockedOnDeadMVar == BlockedOnDeadMVar = True
815 NonTermination == NonTermination = True
816 NestedAtomically == NestedAtomically = True
817 Deadlock == Deadlock = True
820 -- -----------------------------------------------------------------------------
823 -- We need it here because it is used in ExitException in the
824 -- Exception datatype (above).
827 = ExitSuccess -- ^ indicates successful termination;
829 -- ^ indicates program failure with an exit code.
830 -- The exact interpretation of the code is
831 -- operating-system dependent. In particular, some values
832 -- may be prohibited (e.g. 0 on a POSIX-compliant system).
833 deriving (Eq, Ord, Read, Show)
835 -- --------------------------------------------------------------------------
838 -- | Throw an exception. Exceptions may be thrown from purely
839 -- functional code, but may only be caught within the 'IO' monad.
840 throw :: Exception -> a
841 throw exception = raise# exception
843 -- | A variant of 'throw' that can be used within the 'IO' monad.
845 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
846 -- two functions are subtly different:
848 -- > throw e `seq` x ===> throw e
849 -- > throwIO e `seq` x ===> x
851 -- The first example will cause the exception @e@ to be raised,
852 -- whereas the second one won\'t. In fact, 'throwIO' will only cause
853 -- an exception to be raised when it is used within the 'IO' monad.
854 -- The 'throwIO' variant should be used in preference to 'throw' to
855 -- raise an exception within the 'IO' monad because it guarantees
856 -- ordering with respect to other 'IO' operations, whereas 'throw'
858 throwIO :: Exception -> IO a
859 throwIO err = IO $ raiseIO# err
861 ioException :: IOException -> IO a
862 ioException err = IO $ raiseIO# (IOException err)
864 -- | Raise an 'IOError' in the 'IO' monad.
865 ioError :: IOError -> IO a
866 ioError = ioException
868 -- ---------------------------------------------------------------------------
871 -- | The Haskell 98 type for exceptions in the 'IO' monad.
872 -- Any I\/O operation may raise an 'IOError' instead of returning a result.
873 -- For a more general type of exception, including also those that arise
874 -- in pure code, see 'Control.Exception.Exception'.
876 -- In Haskell 98, this is an opaque type.
877 type IOError = IOException
879 -- |Exceptions that occur in the @IO@ monad.
880 -- An @IOException@ records a more specific error type, a descriptive
881 -- string and maybe the handle that was used when the error was
885 ioe_handle :: Maybe Handle, -- the handle used by the action flagging
887 ioe_type :: IOErrorType, -- what it was.
888 ioe_location :: String, -- location.
889 ioe_description :: String, -- error type specific information.
890 ioe_filename :: Maybe FilePath -- filename the error is related to.
893 instance Eq IOException where
894 (IOError h1 e1 loc1 str1 fn1) == (IOError h2 e2 loc2 str2 fn2) =
895 e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && fn1==fn2
897 -- | An abstract type that contains a value for each variant of 'IOError'.
909 | UnsatisfiedConstraints
916 | UnsupportedOperation
920 | DynIOError Dynamic -- cheap&cheerful extensible IO error type.
922 instance Eq IOErrorType where
925 DynIOError{} -> False -- from a strictness POV, compatible with a derived Eq inst?
926 _ -> getTag x ==# getTag y
928 instance Show IOErrorType where
932 AlreadyExists -> "already exists"
933 NoSuchThing -> "does not exist"
934 ResourceBusy -> "resource busy"
935 ResourceExhausted -> "resource exhausted"
937 IllegalOperation -> "illegal operation"
938 PermissionDenied -> "permission denied"
939 UserError -> "user error"
940 HardwareFault -> "hardware fault"
941 InappropriateType -> "inappropriate type"
942 Interrupted -> "interrupted"
943 InvalidArgument -> "invalid argument"
944 OtherError -> "failed"
945 ProtocolError -> "protocol error"
946 ResourceVanished -> "resource vanished"
947 SystemError -> "system error"
948 TimeExpired -> "timeout"
949 UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise!
950 UnsupportedOperation -> "unsupported operation"
951 DynIOError{} -> "unknown IO error"
953 -- | Construct an 'IOError' value with a string describing the error.
954 -- The 'fail' method of the 'IO' instance of the 'Monad' class raises a
955 -- 'userError', thus:
957 -- > instance Monad IO where
959 -- > fail s = ioError (userError s)
961 userError :: String -> IOError
962 userError str = IOError Nothing UserError "" str Nothing
964 -- ---------------------------------------------------------------------------
967 instance Show IOException where
968 showsPrec p (IOError hdl iot loc s fn) =
970 Nothing -> case hdl of
972 Just h -> showsPrec p h . showString ": "
973 Just name -> showString name . showString ": ") .
976 _ -> showString loc . showString ": ") .
980 _ -> showString " (" . showString s . showString ")")
982 -- -----------------------------------------------------------------------------
985 data IOMode = ReadMode | WriteMode | AppendMode | ReadWriteMode
986 deriving (Eq, Ord, Ix, Enum, Read, Show)