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 --stToIO :: (forall s. ST s a) -> IO a
116 stToIO :: ST RealWorld a -> IO a
119 ioToST :: IO a -> ST RealWorld a
120 ioToST (IO m) = (ST m)
122 -- ---------------------------------------------------------------------------
123 -- Unsafe IO operations
126 This is the \"back door\" into the 'IO' monad, allowing
127 'IO' computation to be performed at any time. For
128 this to be safe, the 'IO' computation should be
129 free of side effects and independent of its environment.
131 If the I\/O computation wrapped in 'unsafePerformIO'
132 performs side effects, then the relative order in which those side
133 effects take place (relative to the main I\/O trunk, or other calls to
134 'unsafePerformIO') is indeterminate. You have to be careful when
135 writing and compiling modules that use 'unsafePerformIO':
137 * Use @{\-\# NOINLINE foo \#-\}@ as a pragma on any function @foo@
138 that calls 'unsafePerformIO'. If the call is inlined,
139 the I\/O may be performed more than once.
141 * Use the compiler flag @-fno-cse@ to prevent common sub-expression
142 elimination being performed on the module, which might combine
143 two side effects that were meant to be separate. A good example
144 is using multiple global variables (like @test@ in the example below).
146 * Make sure that the either you switch off let-floating, or that the
147 call to 'unsafePerformIO' cannot float outside a lambda. For example,
150 f x = unsafePerformIO (newIORef [])
152 you may get only one reference cell shared between all calls to @f@.
155 f x = unsafePerformIO (newIORef [x])
157 because now it can't float outside the lambda.
159 It is less well known that
160 'unsafePerformIO' is not type safe. For example:
163 > test = unsafePerformIO $ newIORef []
166 > writeIORef test [42]
167 > bang \<- readIORef test
168 > print (bang :: [Char])
170 This program will core dump. This problem with polymorphic references
171 is well known in the ML community, and does not arise with normal
172 monadic use of references. There is no easy way to make it impossible
173 once you use 'unsafePerformIO'. Indeed, it is
174 possible to write @coerce :: a -> b@ with the
175 help of 'unsafePerformIO'. So be careful!
177 {-# NOINLINE unsafePerformIO #-}
178 unsafePerformIO :: IO a -> a
179 unsafePerformIO (IO m) = case m realWorld# of (# _, r #) -> r
182 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
183 When passed a value of type @IO a@, the 'IO' will only be performed
184 when the value of the @a@ is demanded. This is used to implement lazy
185 file reading, see 'System.IO.hGetContents'.
187 {-# NOINLINE unsafeInterleaveIO #-}
188 unsafeInterleaveIO :: IO a -> IO a
189 unsafeInterleaveIO (IO m)
191 r = case m s of (# _, res #) -> res
195 -- ---------------------------------------------------------------------------
198 data MVar a = MVar (MVar# RealWorld a)
200 An 'MVar' (pronounced \"em-var\") is a synchronising variable, used
201 for communication between concurrent threads. It can be thought of
202 as a a box, which may be empty or full.
205 -- pull in Eq (Mvar a) too, to avoid GHC.Conc being an orphan-instance module
206 instance Eq (MVar a) where
207 (MVar mvar1#) == (MVar mvar2#) = sameMVar# mvar1# mvar2#
209 -- A Handle is represented by (a reference to) a record
210 -- containing the state of the I/O port/device. We record
211 -- the following pieces of info:
213 -- * type (read,write,closed etc.)
214 -- * the underlying file descriptor
216 -- * buffer, and spare buffers
217 -- * user-friendly name (usually the
218 -- FilePath used when IO.openFile was called)
220 -- Note: when a Handle is garbage collected, we want to flush its buffer
221 -- and close the OS file handle, so as to free up a (precious) resource.
224 = FileHandle -- A normal handle to a file
227 | DuplexHandle -- A handle to a read/write stream
228 !(MVar Handle__) -- The read side
229 !(MVar Handle__) -- The write side
232 -- * A 'FileHandle' is seekable. A 'DuplexHandle' may or may not be
235 instance Eq Handle where
236 (FileHandle h1) == (FileHandle h2) = h1 == h2
237 (DuplexHandle h1 _) == (DuplexHandle h2 _) = h1 == h2
240 type FD = Int -- XXX ToDo: should be CInt
244 haFD :: !FD, -- file descriptor
245 haType :: HandleType, -- type (read/write/append etc.)
246 haIsBin :: Bool, -- binary mode?
247 haIsStream :: Bool, -- is this a stream handle?
248 haBufferMode :: BufferMode, -- buffer contains read/write data?
249 haFilePath :: FilePath, -- file name, possibly
250 haBuffer :: !(IORef Buffer), -- the current buffer
251 haBuffers :: !(IORef BufferList), -- spare buffers
252 haOtherSide :: Maybe (MVar Handle__) -- ptr to the write side of a
256 -- ---------------------------------------------------------------------------
259 -- The buffer is represented by a mutable variable containing a
260 -- record, where the record contains the raw buffer and the start/end
261 -- points of the filled portion. We use a mutable variable so that
262 -- the common operation of writing (or reading) some data from (to)
263 -- the buffer doesn't need to modify, and hence copy, the handle
264 -- itself, it just updates the buffer.
266 -- There will be some allocation involved in a simple hPutChar in
267 -- order to create the new Buffer structure (below), but this is
268 -- relatively small, and this only has to be done once per write
271 -- The buffer contains its size - we could also get the size by
272 -- calling sizeOfMutableByteArray# on the raw buffer, but that tends
273 -- to be rounded up to the nearest Word.
275 type RawBuffer = MutableByteArray# RealWorld
277 -- INVARIANTS on a Buffer:
279 -- * A handle *always* has a buffer, even if it is only 1 character long
280 -- (an unbuffered handle needs a 1 character buffer in order to support
281 -- hLookAhead and hIsEOF).
283 -- * if r == w, then r == 0 && w == 0
284 -- * if state == WriteBuffer, then r == 0
285 -- * a write buffer is never full. If an operation
286 -- fills up the buffer, it will always flush it before
288 -- * a read buffer may be full as a result of hLookAhead. In normal
289 -- operation, a read buffer always has at least one character of space.
297 bufState :: BufferState
300 data BufferState = ReadBuffer | WriteBuffer deriving (Eq)
302 -- we keep a few spare buffers around in a handle to avoid allocating
303 -- a new one for each hPutStr. These buffers are *guaranteed* to be the
304 -- same size as the main buffer.
307 | BufferListCons RawBuffer BufferList
310 bufferIsWritable :: Buffer -> Bool
311 bufferIsWritable Buffer{ bufState=WriteBuffer } = True
312 bufferIsWritable _other = False
314 bufferEmpty :: Buffer -> Bool
315 bufferEmpty Buffer{ bufRPtr=r, bufWPtr=w } = r == w
317 -- only makes sense for a write buffer
318 bufferFull :: Buffer -> Bool
319 bufferFull b@Buffer{ bufWPtr=w } = w >= bufSize b
321 -- Internally, we classify handles as being one
332 isReadableHandleType ReadHandle = True
333 isReadableHandleType ReadWriteHandle = True
334 isReadableHandleType _ = False
336 isWritableHandleType AppendHandle = True
337 isWritableHandleType WriteHandle = True
338 isWritableHandleType ReadWriteHandle = True
339 isWritableHandleType _ = False
341 -- File names are specified using @FilePath@, a OS-dependent
342 -- string that (hopefully, I guess) maps to an accessible file/object.
344 type FilePath = String
346 -- ---------------------------------------------------------------------------
349 -- Three kinds of buffering are supported: line-buffering,
350 -- block-buffering or no-buffering. These modes have the following
351 -- effects. For output, items are written out from the internal
352 -- buffer according to the buffer mode:
354 -- o line-buffering the entire output buffer is written
355 -- out whenever a newline is output, the output buffer overflows,
356 -- a flush is issued, or the handle is closed.
358 -- o block-buffering the entire output buffer is written out whenever
359 -- it overflows, a flush is issued, or the handle
362 -- o no-buffering output is written immediately, and never stored
363 -- in the output buffer.
365 -- The output buffer is emptied as soon as it has been written out.
367 -- Similarly, input occurs according to the buffer mode for handle {\em hdl}.
369 -- o line-buffering when the input buffer for the handle is not empty,
370 -- the next item is obtained from the buffer;
371 -- otherwise, when the input buffer is empty,
372 -- characters up to and including the next newline
373 -- character are read into the buffer. No characters
374 -- are available until the newline character is
377 -- o block-buffering when the input buffer for the handle becomes empty,
378 -- the next block of data is read into this buffer.
380 -- o no-buffering the next input item is read and returned.
382 -- For most implementations, physical files will normally be block-buffered
383 -- and terminals will normally be line-buffered. (the IO interface provides
384 -- operations for changing the default buffering of a handle tho.)
387 = NoBuffering | LineBuffering | BlockBuffering (Maybe Int)
388 deriving (Eq, Ord, Read, Show)
390 -- ---------------------------------------------------------------------------
393 -- |A mutable variable in the 'IO' monad
394 newtype IORef a = IORef (STRef RealWorld a)
396 -- explicit instance because Haddock can't figure out a derived one
397 instance Eq (IORef a) where
398 IORef x == IORef y = x == y
400 -- |Build a new 'IORef'
401 newIORef :: a -> IO (IORef a)
402 newIORef v = stToIO (newSTRef v) >>= \ var -> return (IORef var)
404 -- |Read the value of an 'IORef'
405 readIORef :: IORef a -> IO a
406 readIORef (IORef var) = stToIO (readSTRef var)
408 -- |Write a new value into an 'IORef'
409 writeIORef :: IORef a -> a -> IO ()
410 writeIORef (IORef var) v = stToIO (writeSTRef var v)
412 -- ---------------------------------------------------------------------------
413 -- | An 'IOArray' is a mutable, boxed, non-strict array in the 'IO' monad.
414 -- The type arguments are as follows:
416 -- * @i@: the index type of the array (should be an instance of 'Ix')
418 -- * @e@: the element type of the array.
422 newtype IOArray i e = IOArray (STArray RealWorld i e)
424 -- explicit instance because Haddock can't figure out a derived one
425 instance Eq (IOArray i e) where
426 IOArray x == IOArray y = x == y
428 -- |Build a new 'IOArray'
429 newIOArray :: Ix i => (i,i) -> e -> IO (IOArray i e)
430 {-# INLINE newIOArray #-}
431 newIOArray lu init = stToIO $ do {marr <- newSTArray lu init; return (IOArray marr)}
433 -- | Read a value from an 'IOArray'
434 unsafeReadIOArray :: Ix i => IOArray i e -> Int -> IO e
435 {-# INLINE unsafeReadIOArray #-}
436 unsafeReadIOArray (IOArray marr) i = stToIO (unsafeReadSTArray marr i)
438 -- | Write a new value into an 'IOArray'
439 unsafeWriteIOArray :: Ix i => IOArray i e -> Int -> e -> IO ()
440 {-# INLINE unsafeWriteIOArray #-}
441 unsafeWriteIOArray (IOArray marr) i e = stToIO (unsafeWriteSTArray marr i e)
443 -- | Read a value from an 'IOArray'
444 readIOArray :: Ix i => IOArray i e -> i -> IO e
445 readIOArray (IOArray marr) i = stToIO (readSTArray marr i)
447 -- | Write a new value into an 'IOArray'
448 writeIOArray :: Ix i => IOArray i e -> i -> e -> IO ()
449 writeIOArray (IOArray marr) i e = stToIO (writeSTArray marr i e)
452 -- ---------------------------------------------------------------------------
453 -- Show instance for Handles
455 -- handle types are 'show'n when printing error msgs, so
456 -- we provide a more user-friendly Show instance for it
457 -- than the derived one.
459 instance Show HandleType where
462 ClosedHandle -> showString "closed"
463 SemiClosedHandle -> showString "semi-closed"
464 ReadHandle -> showString "readable"
465 WriteHandle -> showString "writable"
466 AppendHandle -> showString "writable (append)"
467 ReadWriteHandle -> showString "read-writable"
469 instance Show Handle where
470 showsPrec p (FileHandle h) = showHandle p h False
471 showsPrec p (DuplexHandle _ h) = showHandle p h True
473 showHandle p h duplex =
475 -- (Big) SIGH: unfolded defn of takeMVar to avoid
476 -- an (oh-so) unfortunate module loop with GHC.Conc.
477 hdl_ = unsafePerformIO (IO $ \ s# ->
478 case h of { MVar h# ->
479 case takeMVar# h# s# of { (# s2# , r #) ->
480 case putMVar# h# r s2# of { s3# ->
483 showType | duplex = showString "duplex (read-write)"
484 | otherwise = showsPrec p (haType hdl_)
487 showHdl (haType hdl_)
488 (showString "loc=" . showString (haFilePath hdl_) . showChar ',' .
489 showString "type=" . showType . showChar ',' .
490 showString "binary=" . showsPrec p (haIsBin hdl_) . showChar ',' .
491 showString "buffering=" . showBufMode (unsafePerformIO (readIORef (haBuffer hdl_))) (haBufferMode hdl_) . showString "}" )
494 showHdl :: HandleType -> ShowS -> ShowS
497 ClosedHandle -> showsPrec p ht . showString "}"
500 showBufMode :: Buffer -> BufferMode -> ShowS
501 showBufMode buf bmo =
503 NoBuffering -> showString "none"
504 LineBuffering -> showString "line"
505 BlockBuffering (Just n) -> showString "block " . showParen True (showsPrec p n)
506 BlockBuffering Nothing -> showString "block " . showParen True (showsPrec p def)
511 -- ------------------------------------------------------------------------
512 -- Exception datatype and operations
514 -- |The type of exceptions. Every kind of system-generated exception
515 -- has a constructor in the 'Exception' type, and values of other
516 -- types may be injected into 'Exception' by coercing them to
517 -- 'Dynamic' (see the section on Dynamic Exceptions: "Control.Exception\#DynamicExceptions").
519 = ArithException ArithException
520 -- ^Exceptions raised by arithmetic
521 -- operations. (NOTE: GHC currently does not throw
522 -- 'ArithException's except for 'DivideByZero').
523 | ArrayException ArrayException
524 -- ^Exceptions raised by array-related
525 -- operations. (NOTE: GHC currently does not throw
526 -- 'ArrayException's).
527 | AssertionFailed String
528 -- ^This exception is thrown by the
529 -- 'assert' operation when the condition
530 -- fails. The 'String' argument contains the
531 -- location of the assertion in the source program.
532 | AsyncException AsyncException
533 -- ^Asynchronous exceptions (see section on Asynchronous Exceptions: "Control.Exception\#AsynchronousExceptions").
535 -- ^The current thread was executing a call to
536 -- 'takeMVar' that could never return, because there are no other
537 -- references to this 'MVar'.
539 -- ^There are no runnable threads, so the program is
540 -- deadlocked. The 'Deadlock' exception is
541 -- raised in the main thread only (see also: "Control.Concurrent").
542 | DynException Dynamic
543 -- ^Dynamically typed exceptions (see section on Dynamic Exceptions: "Control.Exception\#DynamicExceptions").
545 -- ^The 'ErrorCall' exception is thrown by 'error'. The 'String'
546 -- argument of 'ErrorCall' is the string passed to 'error' when it was
548 | ExitException ExitCode
549 -- ^The 'ExitException' exception is thrown by 'System.exitWith' (and
550 -- 'System.exitFailure'). The 'ExitCode' argument is the value passed
551 -- to 'System.exitWith'. An unhandled 'ExitException' exception in the
552 -- main thread will cause the program to be terminated with the given
554 | IOException IOException
555 -- ^These are the standard IO exceptions generated by
556 -- Haskell\'s @IO@ operations. See also "System.IO.Error".
557 | NoMethodError String
558 -- ^An attempt was made to invoke a class method which has
559 -- no definition in this instance, and there was no default
560 -- definition given in the class declaration. GHC issues a
561 -- warning when you compile an instance which has missing
564 -- ^The current thread is stuck in an infinite loop. This
565 -- exception may or may not be thrown when the program is
567 | PatternMatchFail String
568 -- ^A pattern matching failure. The 'String' argument should contain a
569 -- descriptive message including the function name, source file
572 -- ^An attempt was made to evaluate a field of a record
573 -- for which no value was given at construction time. The
574 -- 'String' argument gives the location of the
575 -- record construction in the source program.
577 -- ^A field selection was attempted on a constructor that
578 -- doesn\'t have the requested field. This can happen with
579 -- multi-constructor records when one or more fields are
580 -- missing from some of the constructors. The
581 -- 'String' argument gives the location of the
582 -- record selection in the source program.
584 -- ^An attempt was made to update a field in a record,
585 -- where the record doesn\'t have the requested field. This can
586 -- only occur with multi-constructor records, when one or more
587 -- fields are missing from some of the constructors. The
588 -- 'String' argument gives the location of the
589 -- record update in the source program.
591 -- |The type of arithmetic exceptions
601 -- |Asynchronous exceptions
604 -- ^The current thread\'s stack exceeded its limit.
605 -- Since an exception has been raised, the thread\'s stack
606 -- will certainly be below its limit again, but the
607 -- programmer should take remedial action
610 -- ^The program\'s heap is reaching its limit, and
611 -- the program should take action to reduce the amount of
612 -- live data it has. Notes:
614 -- * It is undefined which thread receives this exception.
616 -- * GHC currently does not throw 'HeapOverflow' exceptions.
618 -- ^This exception is raised by another thread
619 -- calling 'killThread', or by the system
620 -- if it needs to terminate the thread for some
624 -- | Exceptions generated by array operations
626 = IndexOutOfBounds String
627 -- ^An attempt was made to index an array outside
628 -- its declared bounds.
629 | UndefinedElement String
630 -- ^An attempt was made to evaluate an element of an
631 -- array that had not been initialized.
634 stackOverflow, heapOverflow :: Exception -- for the RTS
635 stackOverflow = AsyncException StackOverflow
636 heapOverflow = AsyncException HeapOverflow
638 instance Show ArithException where
639 showsPrec _ Overflow = showString "arithmetic overflow"
640 showsPrec _ Underflow = showString "arithmetic underflow"
641 showsPrec _ LossOfPrecision = showString "loss of precision"
642 showsPrec _ DivideByZero = showString "divide by zero"
643 showsPrec _ Denormal = showString "denormal"
645 instance Show AsyncException where
646 showsPrec _ StackOverflow = showString "stack overflow"
647 showsPrec _ HeapOverflow = showString "heap overflow"
648 showsPrec _ ThreadKilled = showString "thread killed"
650 instance Show ArrayException where
651 showsPrec _ (IndexOutOfBounds s)
652 = showString "array index out of range"
653 . (if not (null s) then showString ": " . showString s
655 showsPrec _ (UndefinedElement s)
656 = showString "undefined array element"
657 . (if not (null s) then showString ": " . showString s
660 instance Show Exception where
661 showsPrec _ (IOException err) = shows err
662 showsPrec _ (ArithException err) = shows err
663 showsPrec _ (ArrayException err) = shows err
664 showsPrec _ (ErrorCall err) = showString err
665 showsPrec _ (ExitException err) = showString "exit: " . shows err
666 showsPrec _ (NoMethodError err) = showString err
667 showsPrec _ (PatternMatchFail err) = showString err
668 showsPrec _ (RecSelError err) = showString err
669 showsPrec _ (RecConError err) = showString err
670 showsPrec _ (RecUpdError err) = showString err
671 showsPrec _ (AssertionFailed err) = showString err
672 showsPrec _ (DynException _err) = showString "unknown exception"
673 showsPrec _ (AsyncException e) = shows e
674 showsPrec _ (BlockedOnDeadMVar) = showString "thread blocked indefinitely"
675 showsPrec _ (NonTermination) = showString "<<loop>>"
676 showsPrec _ (Deadlock) = showString "<<deadlock>>"
678 instance Eq Exception where
679 IOException e1 == IOException e2 = e1 == e2
680 ArithException e1 == ArithException e2 = e1 == e2
681 ArrayException e1 == ArrayException e2 = e1 == e2
682 ErrorCall e1 == ErrorCall e2 = e1 == e2
683 ExitException e1 == ExitException e2 = e1 == e2
684 NoMethodError e1 == NoMethodError e2 = e1 == e2
685 PatternMatchFail e1 == PatternMatchFail e2 = e1 == e2
686 RecSelError e1 == RecSelError e2 = e1 == e2
687 RecConError e1 == RecConError e2 = e1 == e2
688 RecUpdError e1 == RecUpdError e2 = e1 == e2
689 AssertionFailed e1 == AssertionFailed e2 = e1 == e2
690 DynException _ == DynException _ = False -- incomparable
691 AsyncException e1 == AsyncException e2 = e1 == e2
692 BlockedOnDeadMVar == BlockedOnDeadMVar = True
693 NonTermination == NonTermination = True
694 Deadlock == Deadlock = True
697 -- -----------------------------------------------------------------------------
700 -- The `ExitCode' type defines the exit codes that a program
701 -- can return. `ExitSuccess' indicates successful termination;
702 -- and `ExitFailure code' indicates program failure
703 -- with value `code'. The exact interpretation of `code'
704 -- is operating-system dependent. In particular, some values of
705 -- `code' may be prohibited (e.g. 0 on a POSIX-compliant system).
707 -- We need it here because it is used in ExitException in the
708 -- Exception datatype (above).
710 data ExitCode = ExitSuccess | ExitFailure Int
711 deriving (Eq, Ord, Read, Show)
713 -- --------------------------------------------------------------------------
716 -- | Throw an exception. Exceptions may be thrown from purely
717 -- functional code, but may only be caught within the 'IO' monad.
718 throw :: Exception -> a
719 throw exception = raise# exception
721 -- | A variant of 'throw' that can be used within the 'IO' monad.
723 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
724 -- two functions are subtly different:
726 -- > throw e `seq` return () ===> throw e
727 -- > throwIO e `seq` return () ===> return ()
729 -- The first example will cause the exception @e@ to be raised,
730 -- whereas the second one won\'t. In fact, 'throwIO' will only cause
731 -- an exception to be raised when it is used within the 'IO' monad.
732 -- The 'throwIO' variant should be used in preference to 'throw' to
733 -- raise an exception within the 'IO' monad because it guarantees
734 -- ordering with respect to other 'IO' operations, whereas 'throw'
736 throwIO :: Exception -> IO a
737 throwIO err = IO $ raiseIO# err
739 ioException :: IOException -> IO a
740 ioException err = IO $ raiseIO# (IOException err)
742 ioError :: IOError -> IO a
743 ioError = ioException
745 -- ---------------------------------------------------------------------------
748 -- | The Haskell 98 type for exceptions in the @IO@ monad.
749 -- In Haskell 98, this is an opaque type.
750 type IOError = IOException
752 -- |Exceptions that occur in the @IO@ monad.
753 -- An @IOException@ records a more specific error type, a descriptive
754 -- string and maybe the handle that was used when the error was
758 ioe_handle :: Maybe Handle, -- the handle used by the action flagging
760 ioe_type :: IOErrorType, -- what it was.
761 ioe_location :: String, -- location.
762 ioe_description :: String, -- error type specific information.
763 ioe_filename :: Maybe FilePath -- filename the error is related to.
766 instance Eq IOException where
767 (IOError h1 e1 loc1 str1 fn1) == (IOError h2 e2 loc2 str2 fn2) =
768 e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && fn1==fn2
781 | UnsatisfiedConstraints
788 | UnsupportedOperation
792 | DynIOError Dynamic -- cheap&cheerful extensible IO error type.
794 instance Eq IOErrorType where
797 DynIOError{} -> False -- from a strictness POV, compatible with a derived Eq inst?
798 _ -> getTag x ==# getTag y
800 instance Show IOErrorType where
804 AlreadyExists -> "already exists"
805 NoSuchThing -> "does not exist"
806 ResourceBusy -> "resource busy"
807 ResourceExhausted -> "resource exhausted"
809 IllegalOperation -> "illegal operation"
810 PermissionDenied -> "permission denied"
811 UserError -> "user error"
812 HardwareFault -> "hardware fault"
813 InappropriateType -> "inappropriate type"
814 Interrupted -> "interrupted"
815 InvalidArgument -> "invalid argument"
816 OtherError -> "failed"
817 ProtocolError -> "protocol error"
818 ResourceVanished -> "resource vanished"
819 SystemError -> "system error"
820 TimeExpired -> "timeout"
821 UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise!
822 UnsupportedOperation -> "unsupported operation"
823 DynIOError{} -> "unknown IO error"
825 userError :: String -> IOError
826 userError str = IOError Nothing UserError "" str Nothing
828 -- ---------------------------------------------------------------------------
831 instance Show IOException where
832 showsPrec p (IOError hdl iot loc s fn) =
836 _ -> showString "\nAction: " . showString loc) .
839 Just h -> showString "\nHandle: " . showsPrec p h) .
842 _ -> showString "\nReason: " . showString s) .
845 Just name -> showString "\nFile: " . showString name)
847 -- -----------------------------------------------------------------------------
850 data IOMode = ReadMode | WriteMode | AppendMode | ReadWriteMode
851 deriving (Eq, Ord, Ix, Enum, Read, Show)