2 {-# OPTIONS -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 -----------------------------------------------------------------------------
17 module GHC.IOBase where
20 import GHC.Arr -- to derive Ix class
21 import GHC.Enum -- to derive Enum class
24 import GHC.Num -- To get fromInteger etc, needed because of -fno-implicit-prelude
25 import Data.Maybe ( Maybe(..) )
31 import {-# SOURCE #-} Data.Dynamic
34 -- ---------------------------------------------------------------------------
38 The IO Monad is just an instance of the ST monad, where the state is
39 the real world. We use the exception mechanism (in GHC.Exception) to
40 implement IO exceptions.
42 NOTE: The IO representation is deeply wired in to various parts of the
43 system. The following list may or may not be exhaustive:
45 Compiler - types of various primitives in PrimOp.lhs
47 RTS - forceIO (StgMiscClosures.hc)
48 - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast
50 - raiseAsync (Schedule.c)
52 Prelude - GHC.IOBase.lhs, and several other places including
55 Libraries - parts of hslibs/lang.
61 A value of type @'IO' a@ is a computation which, when performed,
62 does some I\/O before returning a value of type @a@.
64 There is really only one way to \"perform\" an I\/O action: bind it to
65 @Main.main@ in your program. When your program is run, the I\/O will
66 be performed. It isn't possible to perform I\/O from an arbitrary
67 function, unless that function is itself in the 'IO' monad and called
68 at some point, directly or indirectly, from @Main.main@.
70 'IO' is a monad, so 'IO' actions can be combined using either the do-notation
71 or the '>>' and '>>=' operations from the 'Monad' class.
73 newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #))
75 unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
78 instance Functor IO where
79 fmap f x = x >>= (return . f)
81 instance Monad IO where
85 m >> k = m >>= \ _ -> k
91 failIO :: String -> IO a
92 failIO s = ioError (userError s)
94 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
95 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
97 bindIO :: IO a -> (a -> IO b) -> IO b
98 bindIO (IO m) k = IO ( \ s ->
100 (# new_s, a #) -> unIO (k a) new_s
103 thenIO :: IO a -> IO b -> IO b
104 thenIO (IO m) k = IO ( \ s ->
106 (# new_s, a #) -> unIO k new_s
109 returnIO :: a -> IO a
110 returnIO x = IO (\ s -> (# s, x #))
112 -- ---------------------------------------------------------------------------
113 -- Coercions between IO and ST
115 -- | A monad transformer embedding strict state transformers in the 'IO'
116 -- monad. The 'RealWorld' parameter indicates that the internal state
117 -- used by the 'ST' computation is a special one supplied by the 'IO'
118 -- monad, and thus distinct from those used by invocations of 'runST'.
119 stToIO :: ST RealWorld a -> IO a
122 ioToST :: IO a -> ST RealWorld a
123 ioToST (IO m) = (ST m)
125 -- This relies on IO and ST having the same representation modulo the
126 -- constraint on the type of the state
128 unsafeIOToST :: IO a -> ST s a
129 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
131 -- ---------------------------------------------------------------------------
132 -- Unsafe IO operations
135 This is the \"back door\" into the 'IO' monad, allowing
136 'IO' computation to be performed at any time. For
137 this to be safe, the 'IO' computation should be
138 free of side effects and independent of its environment.
140 If the I\/O computation wrapped in 'unsafePerformIO'
141 performs side effects, then the relative order in which those side
142 effects take place (relative to the main I\/O trunk, or other calls to
143 'unsafePerformIO') is indeterminate. You have to be careful when
144 writing and compiling modules that use 'unsafePerformIO':
146 * Use @{\-\# NOINLINE foo \#-\}@ as a pragma on any function @foo@
147 that calls 'unsafePerformIO'. If the call is inlined,
148 the I\/O may be performed more than once.
150 * Use the compiler flag @-fno-cse@ to prevent common sub-expression
151 elimination being performed on the module, which might combine
152 two side effects that were meant to be separate. A good example
153 is using multiple global variables (like @test@ in the example below).
155 * Make sure that the either you switch off let-floating, or that the
156 call to 'unsafePerformIO' cannot float outside a lambda. For example,
159 f x = unsafePerformIO (newIORef [])
161 you may get only one reference cell shared between all calls to @f@.
164 f x = unsafePerformIO (newIORef [x])
166 because now it can't float outside the lambda.
168 It is less well known that
169 'unsafePerformIO' is not type safe. For example:
172 > test = unsafePerformIO $ newIORef []
175 > writeIORef test [42]
176 > bang <- readIORef test
177 > print (bang :: [Char])
179 This program will core dump. This problem with polymorphic references
180 is well known in the ML community, and does not arise with normal
181 monadic use of references. There is no easy way to make it impossible
182 once you use 'unsafePerformIO'. Indeed, it is
183 possible to write @coerce :: a -> b@ with the
184 help of 'unsafePerformIO'. So be careful!
186 {-# NOINLINE unsafePerformIO #-}
187 unsafePerformIO :: IO a -> a
188 unsafePerformIO (IO m) = case m realWorld# of (# _, r #) -> r
190 -- Why do we NOINLINE unsafePerformIO? See the comment with
191 -- GHC.ST.runST. Essentially the issue is that the IO computation
192 -- inside unsafePerformIO must be atomic: it must either all run, or
193 -- not at all. If we let the compiler see the application of the IO
194 -- to realWorld#, it might float out part of the IO.
197 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
198 When passed a value of type @IO a@, the 'IO' will only be performed
199 when the value of the @a@ is demanded. This is used to implement lazy
200 file reading, see 'System.IO.hGetContents'.
202 {-# INLINE unsafeInterleaveIO #-}
203 unsafeInterleaveIO :: IO a -> IO a
204 unsafeInterleaveIO (IO m)
206 r = case m s of (# _, res #) -> res
210 -- We believe that INLINE on unsafeInterleaveIO is safe, because the
211 -- state from this IO thread is passed explicitly to the interleaved
212 -- IO, so it cannot be floated out and shared.
214 -- ---------------------------------------------------------------------------
217 data MVar a = MVar (MVar# RealWorld a)
219 An 'MVar' (pronounced \"em-var\") is a synchronising variable, used
220 for communication between concurrent threads. It can be thought of
221 as a a box, which may be empty or full.
224 -- pull in Eq (Mvar a) too, to avoid GHC.Conc being an orphan-instance module
225 instance Eq (MVar a) where
226 (MVar mvar1#) == (MVar mvar2#) = sameMVar# mvar1# mvar2#
228 -- A Handle is represented by (a reference to) a record
229 -- containing the state of the I/O port/device. We record
230 -- the following pieces of info:
232 -- * type (read,write,closed etc.)
233 -- * the underlying file descriptor
235 -- * buffer, and spare buffers
236 -- * user-friendly name (usually the
237 -- FilePath used when IO.openFile was called)
239 -- Note: when a Handle is garbage collected, we want to flush its buffer
240 -- and close the OS file handle, so as to free up a (precious) resource.
242 -- | Haskell defines operations to read and write characters from and to files,
243 -- represented by values of type @Handle@. Each value of this type is a
244 -- /handle/: a record used by the Haskell run-time system to /manage/ I\/O
245 -- with file system objects. A handle has at least the following properties:
247 -- * whether it manages input or output or both;
249 -- * whether it is /open/, /closed/ or /semi-closed/;
251 -- * whether the object is seekable;
253 -- * whether buffering is disabled, or enabled on a line or block basis;
255 -- * a buffer (whose length may be zero).
257 -- Most handles will also have a current I\/O position indicating where the next
258 -- input or output operation will occur. A handle is /readable/ if it
259 -- manages only input or both input and output; likewise, it is /writable/ if
260 -- it manages only output or both input and output. A handle is /open/ when
262 -- Once it is closed it can no longer be used for either input or output,
263 -- though an implementation cannot re-use its storage while references
264 -- remain to it. Handles are in the 'Show' and 'Eq' classes. The string
265 -- produced by showing a handle is system dependent; it should include
266 -- enough information to identify the handle for debugging. A handle is
267 -- equal according to '==' only to itself; no attempt
268 -- is made to compare the internal state of different handles for equality.
271 = FileHandle -- A normal handle to a file
272 FilePath -- the file (invariant)
275 | DuplexHandle -- A handle to a read/write stream
276 FilePath -- file for a FIFO, otherwise some
277 -- descriptive string.
278 !(MVar Handle__) -- The read side
279 !(MVar Handle__) -- The write side
282 -- * A 'FileHandle' is seekable. A 'DuplexHandle' may or may not be
285 instance Eq Handle where
286 (FileHandle _ h1) == (FileHandle _ h2) = h1 == h2
287 (DuplexHandle _ h1 _) == (DuplexHandle _ h2 _) = h1 == h2
290 type FD = Int -- XXX ToDo: should be CInt
294 haFD :: !FD, -- file descriptor
295 haType :: HandleType, -- type (read/write/append etc.)
296 haIsBin :: Bool, -- binary mode?
297 haIsStream :: Bool, -- is this a stream handle?
298 haBufferMode :: BufferMode, -- buffer contains read/write data?
299 haBuffer :: !(IORef Buffer), -- the current buffer
300 haBuffers :: !(IORef BufferList), -- spare buffers
301 haOtherSide :: Maybe (MVar Handle__) -- ptr to the write side of a
305 -- ---------------------------------------------------------------------------
308 -- The buffer is represented by a mutable variable containing a
309 -- record, where the record contains the raw buffer and the start/end
310 -- points of the filled portion. We use a mutable variable so that
311 -- the common operation of writing (or reading) some data from (to)
312 -- the buffer doesn't need to modify, and hence copy, the handle
313 -- itself, it just updates the buffer.
315 -- There will be some allocation involved in a simple hPutChar in
316 -- order to create the new Buffer structure (below), but this is
317 -- relatively small, and this only has to be done once per write
320 -- The buffer contains its size - we could also get the size by
321 -- calling sizeOfMutableByteArray# on the raw buffer, but that tends
322 -- to be rounded up to the nearest Word.
324 type RawBuffer = MutableByteArray# RealWorld
326 -- INVARIANTS on a Buffer:
328 -- * A handle *always* has a buffer, even if it is only 1 character long
329 -- (an unbuffered handle needs a 1 character buffer in order to support
330 -- hLookAhead and hIsEOF).
332 -- * if r == w, then r == 0 && w == 0
333 -- * if state == WriteBuffer, then r == 0
334 -- * a write buffer is never full. If an operation
335 -- fills up the buffer, it will always flush it before
337 -- * a read buffer may be full as a result of hLookAhead. In normal
338 -- operation, a read buffer always has at least one character of space.
346 bufState :: BufferState
349 data BufferState = ReadBuffer | WriteBuffer deriving (Eq)
351 -- we keep a few spare buffers around in a handle to avoid allocating
352 -- a new one for each hPutStr. These buffers are *guaranteed* to be the
353 -- same size as the main buffer.
356 | BufferListCons RawBuffer BufferList
359 bufferIsWritable :: Buffer -> Bool
360 bufferIsWritable Buffer{ bufState=WriteBuffer } = True
361 bufferIsWritable _other = False
363 bufferEmpty :: Buffer -> Bool
364 bufferEmpty Buffer{ bufRPtr=r, bufWPtr=w } = r == w
366 -- only makes sense for a write buffer
367 bufferFull :: Buffer -> Bool
368 bufferFull b@Buffer{ bufWPtr=w } = w >= bufSize b
370 -- Internally, we classify handles as being one
381 isReadableHandleType ReadHandle = True
382 isReadableHandleType ReadWriteHandle = True
383 isReadableHandleType _ = False
385 isWritableHandleType AppendHandle = True
386 isWritableHandleType WriteHandle = True
387 isWritableHandleType ReadWriteHandle = True
388 isWritableHandleType _ = False
390 -- | File and directory names are values of type 'String', whose precise
391 -- meaning is operating system dependent. Files can be opened, yielding a
392 -- handle which can then be used to operate on the contents of that file.
394 type FilePath = String
396 -- ---------------------------------------------------------------------------
399 -- | Three kinds of buffering are supported: line-buffering,
400 -- block-buffering or no-buffering. These modes have the following
401 -- effects. For output, items are written out, or /flushed/,
402 -- from the internal buffer according to the buffer mode:
404 -- * /line-buffering/: the entire output buffer is flushed
405 -- whenever a newline is output, the buffer overflows,
406 -- a 'System.IO.hFlush' is issued, or the handle is closed.
408 -- * /block-buffering/: the entire buffer is written out whenever it
409 -- overflows, a 'System.IO.hFlush' is issued, or the handle is closed.
411 -- * /no-buffering/: output is written immediately, and never stored
414 -- An implementation is free to flush the buffer more frequently,
415 -- but not less frequently, than specified above.
416 -- The output buffer is emptied as soon as it has been written out.
418 -- Similarly, input occurs according to the buffer mode for the handle:
420 -- * /line-buffering/: when the buffer for the handle is not empty,
421 -- the next item is obtained from the buffer; otherwise, when the
422 -- buffer is empty, characters up to and including the next newline
423 -- character are read into the buffer. No characters are available
424 -- until the newline character is available or the buffer is full.
426 -- * /block-buffering/: when the buffer for the handle becomes empty,
427 -- the next block of data is read into the buffer.
429 -- * /no-buffering/: the next input item is read and returned.
430 -- The 'System.IO.hLookAhead' operation implies that even a no-buffered
431 -- handle may require a one-character buffer.
433 -- The default buffering mode when a handle is opened is
434 -- implementation-dependent and may depend on the file system object
435 -- which is attached to that handle.
436 -- For most implementations, physical files will normally be block-buffered
437 -- and terminals will normally be line-buffered.
440 = NoBuffering -- ^ buffering is disabled if possible.
442 -- ^ line-buffering should be enabled if possible.
443 | BlockBuffering (Maybe Int)
444 -- ^ block-buffering should be enabled if possible.
445 -- The size of the buffer is @n@ items if the argument
446 -- is 'Just' @n@ and is otherwise implementation-dependent.
447 deriving (Eq, Ord, Read, Show)
449 -- ---------------------------------------------------------------------------
452 -- |A mutable variable in the 'IO' monad
453 newtype IORef a = IORef (STRef RealWorld a)
455 -- explicit instance because Haddock can't figure out a derived one
456 instance Eq (IORef a) where
457 IORef x == IORef y = x == y
459 -- |Build a new 'IORef'
460 newIORef :: a -> IO (IORef a)
461 newIORef v = stToIO (newSTRef v) >>= \ var -> return (IORef var)
463 -- |Read the value of an 'IORef'
464 readIORef :: IORef a -> IO a
465 readIORef (IORef var) = stToIO (readSTRef var)
467 -- |Write a new value into an 'IORef'
468 writeIORef :: IORef a -> a -> IO ()
469 writeIORef (IORef var) v = stToIO (writeSTRef var v)
471 -- ---------------------------------------------------------------------------
472 -- | An 'IOArray' is a mutable, boxed, non-strict array in the 'IO' monad.
473 -- The type arguments are as follows:
475 -- * @i@: the index type of the array (should be an instance of 'Ix')
477 -- * @e@: the element type of the array.
481 newtype IOArray i e = IOArray (STArray RealWorld i e)
483 -- explicit instance because Haddock can't figure out a derived one
484 instance Eq (IOArray i e) where
485 IOArray x == IOArray y = x == y
487 -- |Build a new 'IOArray'
488 newIOArray :: Ix i => (i,i) -> e -> IO (IOArray i e)
489 {-# INLINE newIOArray #-}
490 newIOArray lu init = stToIO $ do {marr <- newSTArray lu init; return (IOArray marr)}
492 -- | Read a value from an 'IOArray'
493 unsafeReadIOArray :: Ix i => IOArray i e -> Int -> IO e
494 {-# INLINE unsafeReadIOArray #-}
495 unsafeReadIOArray (IOArray marr) i = stToIO (unsafeReadSTArray marr i)
497 -- | Write a new value into an 'IOArray'
498 unsafeWriteIOArray :: Ix i => IOArray i e -> Int -> e -> IO ()
499 {-# INLINE unsafeWriteIOArray #-}
500 unsafeWriteIOArray (IOArray marr) i e = stToIO (unsafeWriteSTArray marr i e)
502 -- | Read a value from an 'IOArray'
503 readIOArray :: Ix i => IOArray i e -> i -> IO e
504 readIOArray (IOArray marr) i = stToIO (readSTArray marr i)
506 -- | Write a new value into an 'IOArray'
507 writeIOArray :: Ix i => IOArray i e -> i -> e -> IO ()
508 writeIOArray (IOArray marr) i e = stToIO (writeSTArray marr i e)
511 -- ---------------------------------------------------------------------------
512 -- Show instance for Handles
514 -- handle types are 'show'n when printing error msgs, so
515 -- we provide a more user-friendly Show instance for it
516 -- than the derived one.
518 instance Show HandleType where
521 ClosedHandle -> showString "closed"
522 SemiClosedHandle -> showString "semi-closed"
523 ReadHandle -> showString "readable"
524 WriteHandle -> showString "writable"
525 AppendHandle -> showString "writable (append)"
526 ReadWriteHandle -> showString "read-writable"
528 instance Show Handle where
529 showsPrec p (FileHandle file _) = showHandle file
530 showsPrec p (DuplexHandle file _ _) = showHandle file
532 showHandle file = showString "{handle: " . showString file . showString "}"
534 -- ------------------------------------------------------------------------
535 -- Exception datatype and operations
537 -- |The type of exceptions. Every kind of system-generated exception
538 -- has a constructor in the 'Exception' type, and values of other
539 -- types may be injected into 'Exception' by coercing them to
540 -- 'Data.Dynamic.Dynamic' (see the section on Dynamic Exceptions:
541 -- "Control.Exception\#DynamicExceptions").
543 = ArithException ArithException
544 -- ^Exceptions raised by arithmetic
545 -- operations. (NOTE: GHC currently does not throw
546 -- 'ArithException's except for 'DivideByZero').
547 | ArrayException ArrayException
548 -- ^Exceptions raised by array-related
549 -- operations. (NOTE: GHC currently does not throw
550 -- 'ArrayException's).
551 | AssertionFailed String
552 -- ^This exception is thrown by the
553 -- 'assert' operation when the condition
554 -- fails. The 'String' argument contains the
555 -- location of the assertion in the source program.
556 | AsyncException AsyncException
557 -- ^Asynchronous exceptions (see section on Asynchronous Exceptions: "Control.Exception\#AsynchronousExceptions").
559 -- ^The current thread was executing a call to
560 -- 'Control.Concurrent.MVar.takeMVar' that could never return,
561 -- because there are no other references to this 'MVar'.
563 -- ^There are no runnable threads, so the program is
564 -- deadlocked. The 'Deadlock' exception is
565 -- raised in the main thread only (see also: "Control.Concurrent").
566 | DynException Dynamic
567 -- ^Dynamically typed exceptions (see section on Dynamic Exceptions: "Control.Exception\#DynamicExceptions").
569 -- ^The 'ErrorCall' exception is thrown by 'error'. The 'String'
570 -- argument of 'ErrorCall' is the string passed to 'error' when it was
572 | ExitException ExitCode
573 -- ^The 'ExitException' exception is thrown by 'System.Exit.exitWith' (and
574 -- 'System.Exit.exitFailure'). The 'ExitCode' argument is the value passed
575 -- to 'System.Exit.exitWith'. An unhandled 'ExitException' exception in the
576 -- main thread will cause the program to be terminated with the given
578 | IOException IOException
579 -- ^These are the standard IO exceptions generated by
580 -- Haskell\'s @IO@ operations. See also "System.IO.Error".
581 | NoMethodError String
582 -- ^An attempt was made to invoke a class method which has
583 -- no definition in this instance, and there was no default
584 -- definition given in the class declaration. GHC issues a
585 -- warning when you compile an instance which has missing
588 -- ^The current thread is stuck in an infinite loop. This
589 -- exception may or may not be thrown when the program is
591 | PatternMatchFail String
592 -- ^A pattern matching failure. The 'String' argument should contain a
593 -- descriptive message including the function name, source file
596 -- ^An attempt was made to evaluate a field of a record
597 -- for which no value was given at construction time. The
598 -- 'String' argument gives the location of the
599 -- record construction in the source program.
601 -- ^A field selection was attempted on a constructor that
602 -- doesn\'t have the requested field. This can happen with
603 -- multi-constructor records when one or more fields are
604 -- missing from some of the constructors. The
605 -- 'String' argument gives the location of the
606 -- record selection in the source program.
608 -- ^An attempt was made to update a field in a record,
609 -- where the record doesn\'t have the requested field. This can
610 -- only occur with multi-constructor records, when one or more
611 -- fields are missing from some of the constructors. The
612 -- 'String' argument gives the location of the
613 -- record update in the source program.
615 -- |The type of arithmetic exceptions
625 -- |Asynchronous exceptions
628 -- ^The current thread\'s stack exceeded its limit.
629 -- Since an exception has been raised, the thread\'s stack
630 -- will certainly be below its limit again, but the
631 -- programmer should take remedial action
634 -- ^The program\'s heap is reaching its limit, and
635 -- the program should take action to reduce the amount of
636 -- live data it has. Notes:
638 -- * It is undefined which thread receives this exception.
640 -- * GHC currently does not throw 'HeapOverflow' exceptions.
642 -- ^This exception is raised by another thread
643 -- calling 'Control.Concurrent.killThread', or by the system
644 -- if it needs to terminate the thread for some
648 -- | Exceptions generated by array operations
650 = IndexOutOfBounds String
651 -- ^An attempt was made to index an array outside
652 -- its declared bounds.
653 | UndefinedElement String
654 -- ^An attempt was made to evaluate an element of an
655 -- array that had not been initialized.
658 stackOverflow, heapOverflow :: Exception -- for the RTS
659 stackOverflow = AsyncException StackOverflow
660 heapOverflow = AsyncException HeapOverflow
662 instance Show ArithException where
663 showsPrec _ Overflow = showString "arithmetic overflow"
664 showsPrec _ Underflow = showString "arithmetic underflow"
665 showsPrec _ LossOfPrecision = showString "loss of precision"
666 showsPrec _ DivideByZero = showString "divide by zero"
667 showsPrec _ Denormal = showString "denormal"
669 instance Show AsyncException where
670 showsPrec _ StackOverflow = showString "stack overflow"
671 showsPrec _ HeapOverflow = showString "heap overflow"
672 showsPrec _ ThreadKilled = showString "thread killed"
674 instance Show ArrayException where
675 showsPrec _ (IndexOutOfBounds s)
676 = showString "array index out of range"
677 . (if not (null s) then showString ": " . showString s
679 showsPrec _ (UndefinedElement s)
680 = showString "undefined array element"
681 . (if not (null s) then showString ": " . showString s
684 instance Show Exception where
685 showsPrec _ (IOException err) = shows err
686 showsPrec _ (ArithException err) = shows err
687 showsPrec _ (ArrayException err) = shows err
688 showsPrec _ (ErrorCall err) = showString err
689 showsPrec _ (ExitException err) = showString "exit: " . shows err
690 showsPrec _ (NoMethodError err) = showString err
691 showsPrec _ (PatternMatchFail err) = showString err
692 showsPrec _ (RecSelError err) = showString err
693 showsPrec _ (RecConError err) = showString err
694 showsPrec _ (RecUpdError err) = showString err
695 showsPrec _ (AssertionFailed err) = showString err
696 showsPrec _ (DynException _err) = showString "unknown exception"
697 showsPrec _ (AsyncException e) = shows e
698 showsPrec _ (BlockedOnDeadMVar) = showString "thread blocked indefinitely"
699 showsPrec _ (NonTermination) = showString "<<loop>>"
700 showsPrec _ (Deadlock) = showString "<<deadlock>>"
702 instance Eq Exception where
703 IOException e1 == IOException e2 = e1 == e2
704 ArithException e1 == ArithException e2 = e1 == e2
705 ArrayException e1 == ArrayException e2 = e1 == e2
706 ErrorCall e1 == ErrorCall e2 = e1 == e2
707 ExitException e1 == ExitException e2 = e1 == e2
708 NoMethodError e1 == NoMethodError e2 = e1 == e2
709 PatternMatchFail e1 == PatternMatchFail e2 = e1 == e2
710 RecSelError e1 == RecSelError e2 = e1 == e2
711 RecConError e1 == RecConError e2 = e1 == e2
712 RecUpdError e1 == RecUpdError e2 = e1 == e2
713 AssertionFailed e1 == AssertionFailed e2 = e1 == e2
714 DynException _ == DynException _ = False -- incomparable
715 AsyncException e1 == AsyncException e2 = e1 == e2
716 BlockedOnDeadMVar == BlockedOnDeadMVar = True
717 NonTermination == NonTermination = True
718 Deadlock == Deadlock = True
721 -- -----------------------------------------------------------------------------
724 -- We need it here because it is used in ExitException in the
725 -- Exception datatype (above).
728 = ExitSuccess -- ^ indicates successful termination;
730 -- ^ indicates program failure with an exit code.
731 -- The exact interpretation of the code is
732 -- operating-system dependent. In particular, some values
733 -- may be prohibited (e.g. 0 on a POSIX-compliant system).
734 deriving (Eq, Ord, Read, Show)
736 -- --------------------------------------------------------------------------
739 -- | Throw an exception. Exceptions may be thrown from purely
740 -- functional code, but may only be caught within the 'IO' monad.
741 throw :: Exception -> a
742 throw exception = raise# exception
744 -- | A variant of 'throw' that can be used within the 'IO' monad.
746 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
747 -- two functions are subtly different:
749 -- > throw e `seq` return () ===> throw e
750 -- > throwIO e `seq` return () ===> return ()
752 -- The first example will cause the exception @e@ to be raised,
753 -- whereas the second one won\'t. In fact, 'throwIO' will only cause
754 -- an exception to be raised when it is used within the 'IO' monad.
755 -- The 'throwIO' variant should be used in preference to 'throw' to
756 -- raise an exception within the 'IO' monad because it guarantees
757 -- ordering with respect to other 'IO' operations, whereas 'throw'
759 throwIO :: Exception -> IO a
760 throwIO err = IO $ raiseIO# err
762 ioException :: IOException -> IO a
763 ioException err = IO $ raiseIO# (IOException err)
765 -- | Raise an 'IOError' in the 'IO' monad.
766 ioError :: IOError -> IO a
767 ioError = ioException
769 -- ---------------------------------------------------------------------------
772 -- | The Haskell 98 type for exceptions in the 'IO' monad.
773 -- Any I\/O operation may raise an 'IOError' instead of returning a result.
774 -- For a more general type of exception, including also those that arise
775 -- in pure code, see 'Control.Exception.Exception'.
777 -- In Haskell 98, this is an opaque type.
778 type IOError = IOException
780 -- |Exceptions that occur in the @IO@ monad.
781 -- An @IOException@ records a more specific error type, a descriptive
782 -- string and maybe the handle that was used when the error was
786 ioe_handle :: Maybe Handle, -- the handle used by the action flagging
788 ioe_type :: IOErrorType, -- what it was.
789 ioe_location :: String, -- location.
790 ioe_description :: String, -- error type specific information.
791 ioe_filename :: Maybe FilePath -- filename the error is related to.
794 instance Eq IOException where
795 (IOError h1 e1 loc1 str1 fn1) == (IOError h2 e2 loc2 str2 fn2) =
796 e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && fn1==fn2
798 -- | An abstract type that contains a value for each variant of 'IOError'.
810 | UnsatisfiedConstraints
817 | UnsupportedOperation
821 | DynIOError Dynamic -- cheap&cheerful extensible IO error type.
823 instance Eq IOErrorType where
826 DynIOError{} -> False -- from a strictness POV, compatible with a derived Eq inst?
827 _ -> getTag x ==# getTag y
829 instance Show IOErrorType where
833 AlreadyExists -> "already exists"
834 NoSuchThing -> "does not exist"
835 ResourceBusy -> "resource busy"
836 ResourceExhausted -> "resource exhausted"
838 IllegalOperation -> "illegal operation"
839 PermissionDenied -> "permission denied"
840 UserError -> "user error"
841 HardwareFault -> "hardware fault"
842 InappropriateType -> "inappropriate type"
843 Interrupted -> "interrupted"
844 InvalidArgument -> "invalid argument"
845 OtherError -> "failed"
846 ProtocolError -> "protocol error"
847 ResourceVanished -> "resource vanished"
848 SystemError -> "system error"
849 TimeExpired -> "timeout"
850 UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise!
851 UnsupportedOperation -> "unsupported operation"
852 DynIOError{} -> "unknown IO error"
854 -- | Construct an 'IOError' value with a string describing the error.
855 -- The 'fail' method of the 'IO' instance of the 'Monad' class raises a
856 -- 'userError', thus:
858 -- > instance Monad IO where
860 -- > fail s = ioError (userError s)
862 userError :: String -> IOError
863 userError str = IOError Nothing UserError "" str Nothing
865 -- ---------------------------------------------------------------------------
868 instance Show IOException where
869 showsPrec p (IOError hdl iot loc s fn) =
871 Nothing -> case hdl of
873 Just h -> showsPrec p h . showString ": "
874 Just name -> showString name . showString ": ") .
877 _ -> showString loc . showString ": ") .
881 _ -> showString " (" . showString s . showString ")")
883 -- -----------------------------------------------------------------------------
886 data IOMode = ReadMode | WriteMode | AppendMode | ReadWriteMode
887 deriving (Eq, Ord, Ix, Enum, Read, Show)