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':
136 * Use @{-# NOINLINE foo #-}@ as a pragma on any function @foo@
137 that calls 'unsafePerformIO'. If the call is inlined,
138 the I/O may be performed more than once.
140 * Use the compiler flag @-fno-cse@ to prevent common sub-expression
141 elimination being performed on the module, which might combine
142 two side effects that were meant to be separate. A good example
143 is using multiple global variables (like @test@ in the example below).
145 * Make sure that the either you switch off let-floating, or that the
146 call to 'unsafePerformIO' cannot float outside a lambda. For example,
149 f x = unsafePerformIO (newIORef [])
151 you may get only one reference cell shared between all calls to @f@.
154 f x = unsafePerformIO (newIORef [x])
156 because now it can't float outside the lambda.
158 It is less well known that
159 'unsafePerformIO' is not type safe. For example:
162 > test = unsafePerformIO $ newIORef []
165 > writeIORef test [42]
166 > bang \<- readIORef test
167 > print (bang :: [Char])
169 This program will core dump. This problem with polymorphic references
170 is well known in the ML community, and does not arise with normal
171 monadic use of references. There is no easy way to make it impossible
172 once you use 'unsafePerformIO'. Indeed, it is
173 possible to write @coerce :: a -> b@ with the
174 help of 'unsafePerformIO'. So be careful!
176 {-# NOINLINE unsafePerformIO #-}
177 unsafePerformIO :: IO a -> a
178 unsafePerformIO (IO m) = case m realWorld# of (# _, r #) -> r
181 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
182 When passed a value of type @IO a@, the 'IO' will only be performed
183 when the value of the @a@ is demanded. This is used to implement lazy
184 file reading, see 'IO.hGetContents'.
186 {-# NOINLINE unsafeInterleaveIO #-}
187 unsafeInterleaveIO :: IO a -> IO a
188 unsafeInterleaveIO (IO m)
190 r = case m s of (# _, res #) -> res
194 -- ---------------------------------------------------------------------------
197 data MVar a = MVar (MVar# RealWorld a)
199 An 'MVar' (pronounced \"em-var\") is a synchronising variable, used
200 for communication between concurrent threads. It can be thought of
201 as a a box, which may be empty or full.
204 -- pull in Eq (Mvar a) too, to avoid GHC.Conc being an orphan-instance module
205 instance Eq (MVar a) where
206 (MVar mvar1#) == (MVar mvar2#) = sameMVar# mvar1# mvar2#
208 -- A Handle is represented by (a reference to) a record
209 -- containing the state of the I/O port/device. We record
210 -- the following pieces of info:
212 -- * type (read,write,closed etc.)
213 -- * the underlying file descriptor
215 -- * buffer, and spare buffers
216 -- * user-friendly name (usually the
217 -- FilePath used when IO.openFile was called)
219 -- Note: when a Handle is garbage collected, we want to flush its buffer
220 -- and close the OS file handle, so as to free up a (precious) resource.
223 = FileHandle -- A normal handle to a file
226 | DuplexHandle -- A handle to a read/write stream
227 !(MVar Handle__) -- The read side
228 !(MVar Handle__) -- The write side
231 -- * A 'FileHandle' is seekable. A 'DuplexHandle' may or may not be
234 instance Eq Handle where
235 (FileHandle h1) == (FileHandle h2) = h1 == h2
236 (DuplexHandle h1 _) == (DuplexHandle h2 _) = h1 == h2
239 type FD = Int -- XXX ToDo: should be CInt
243 haFD :: !FD, -- file descriptor
244 haType :: HandleType, -- type (read/write/append etc.)
245 haIsBin :: Bool, -- binary mode?
246 haIsStream :: Bool, -- is this a stream handle?
247 haBufferMode :: BufferMode, -- buffer contains read/write data?
248 haFilePath :: FilePath, -- file name, possibly
249 haBuffer :: !(IORef Buffer), -- the current buffer
250 haBuffers :: !(IORef BufferList), -- spare buffers
251 haOtherSide :: Maybe (MVar Handle__) -- ptr to the write side of a
255 -- ---------------------------------------------------------------------------
258 -- The buffer is represented by a mutable variable containing a
259 -- record, where the record contains the raw buffer and the start/end
260 -- points of the filled portion. We use a mutable variable so that
261 -- the common operation of writing (or reading) some data from (to)
262 -- the buffer doesn't need to modify, and hence copy, the handle
263 -- itself, it just updates the buffer.
265 -- There will be some allocation involved in a simple hPutChar in
266 -- order to create the new Buffer structure (below), but this is
267 -- relatively small, and this only has to be done once per write
270 -- The buffer contains its size - we could also get the size by
271 -- calling sizeOfMutableByteArray# on the raw buffer, but that tends
272 -- to be rounded up to the nearest Word.
274 type RawBuffer = MutableByteArray# RealWorld
276 -- INVARIANTS on a Buffer:
278 -- * A handle *always* has a buffer, even if it is only 1 character long
279 -- (an unbuffered handle needs a 1 character buffer in order to support
280 -- hLookAhead and hIsEOF).
282 -- * if r == w, then r == 0 && w == 0
283 -- * if state == WriteBuffer, then r == 0
284 -- * a write buffer is never full. If an operation
285 -- fills up the buffer, it will always flush it before
287 -- * a read buffer may be full as a result of hLookAhead. In normal
288 -- operation, a read buffer always has at least one character of space.
296 bufState :: BufferState
299 data BufferState = ReadBuffer | WriteBuffer deriving (Eq)
301 -- we keep a few spare buffers around in a handle to avoid allocating
302 -- a new one for each hPutStr. These buffers are *guaranteed* to be the
303 -- same size as the main buffer.
306 | BufferListCons RawBuffer BufferList
309 bufferIsWritable :: Buffer -> Bool
310 bufferIsWritable Buffer{ bufState=WriteBuffer } = True
311 bufferIsWritable _other = False
313 bufferEmpty :: Buffer -> Bool
314 bufferEmpty Buffer{ bufRPtr=r, bufWPtr=w } = r == w
316 -- only makes sense for a write buffer
317 bufferFull :: Buffer -> Bool
318 bufferFull b@Buffer{ bufWPtr=w } = w >= bufSize b
320 -- Internally, we classify handles as being one
331 isReadableHandleType ReadHandle = True
332 isReadableHandleType ReadWriteHandle = True
333 isReadableHandleType _ = False
335 isWritableHandleType AppendHandle = True
336 isWritableHandleType WriteHandle = True
337 isWritableHandleType ReadWriteHandle = True
338 isWritableHandleType _ = False
340 -- File names are specified using @FilePath@, a OS-dependent
341 -- string that (hopefully, I guess) maps to an accessible file/object.
343 type FilePath = String
345 -- ---------------------------------------------------------------------------
348 -- Three kinds of buffering are supported: line-buffering,
349 -- block-buffering or no-buffering. These modes have the following
350 -- effects. For output, items are written out from the internal
351 -- buffer according to the buffer mode:
353 -- o line-buffering the entire output buffer is written
354 -- out whenever a newline is output, the output buffer overflows,
355 -- a flush is issued, or the handle is closed.
357 -- o block-buffering the entire output buffer is written out whenever
358 -- it overflows, a flush is issued, or the handle
361 -- o no-buffering output is written immediately, and never stored
362 -- in the output buffer.
364 -- The output buffer is emptied as soon as it has been written out.
366 -- Similarly, input occurs according to the buffer mode for handle {\em hdl}.
368 -- o line-buffering when the input buffer for the handle is not empty,
369 -- the next item is obtained from the buffer;
370 -- otherwise, when the input buffer is empty,
371 -- characters up to and including the next newline
372 -- character are read into the buffer. No characters
373 -- are available until the newline character is
376 -- o block-buffering when the input buffer for the handle becomes empty,
377 -- the next block of data is read into this buffer.
379 -- o no-buffering the next input item is read and returned.
381 -- For most implementations, physical files will normally be block-buffered
382 -- and terminals will normally be line-buffered. (the IO interface provides
383 -- operations for changing the default buffering of a handle tho.)
386 = NoBuffering | LineBuffering | BlockBuffering (Maybe Int)
387 deriving (Eq, Ord, Read, Show)
389 -- ---------------------------------------------------------------------------
392 -- |A mutable variable in the 'IO' monad
393 newtype IORef a = IORef (STRef RealWorld a) deriving Eq
395 -- |Build a new 'IORef'
396 newIORef :: a -> IO (IORef a)
397 newIORef v = stToIO (newSTRef v) >>= \ var -> return (IORef var)
399 -- |Read the value of an 'IORef'
400 readIORef :: IORef a -> IO a
401 readIORef (IORef var) = stToIO (readSTRef var)
403 -- |Write a new value into an 'IORef'
404 writeIORef :: IORef a -> a -> IO ()
405 writeIORef (IORef var) v = stToIO (writeSTRef var v)
407 -- ---------------------------------------------------------------------------
408 -- Show instance for Handles
410 -- handle types are 'show'n when printing error msgs, so
411 -- we provide a more user-friendly Show instance for it
412 -- than the derived one.
414 instance Show HandleType where
417 ClosedHandle -> showString "closed"
418 SemiClosedHandle -> showString "semi-closed"
419 ReadHandle -> showString "readable"
420 WriteHandle -> showString "writable"
421 AppendHandle -> showString "writable (append)"
422 ReadWriteHandle -> showString "read-writable"
424 instance Show Handle where
425 showsPrec p (FileHandle h) = showHandle p h False
426 showsPrec p (DuplexHandle _ h) = showHandle p h True
428 showHandle p h duplex =
430 -- (Big) SIGH: unfolded defn of takeMVar to avoid
431 -- an (oh-so) unfortunate module loop with GHC.Conc.
432 hdl_ = unsafePerformIO (IO $ \ s# ->
433 case h of { MVar h# ->
434 case takeMVar# h# s# of { (# s2# , r #) ->
435 case putMVar# h# r s2# of { s3# ->
438 showType | duplex = showString "duplex (read-write)"
439 | otherwise = showsPrec p (haType hdl_)
442 showHdl (haType hdl_)
443 (showString "loc=" . showString (haFilePath hdl_) . showChar ',' .
444 showString "type=" . showType . showChar ',' .
445 showString "binary=" . showsPrec p (haIsBin hdl_) . showChar ',' .
446 showString "buffering=" . showBufMode (unsafePerformIO (readIORef (haBuffer hdl_))) (haBufferMode hdl_) . showString "}" )
449 showHdl :: HandleType -> ShowS -> ShowS
452 ClosedHandle -> showsPrec p ht . showString "}"
455 showBufMode :: Buffer -> BufferMode -> ShowS
456 showBufMode buf bmo =
458 NoBuffering -> showString "none"
459 LineBuffering -> showString "line"
460 BlockBuffering (Just n) -> showString "block " . showParen True (showsPrec p n)
461 BlockBuffering Nothing -> showString "block " . showParen True (showsPrec p def)
466 -- ------------------------------------------------------------------------
467 -- Exception datatype and operations
469 -- |The type of exceptions. Every kind of system-generated exception
470 -- has a constructor in the 'Exception' type, and values of other
471 -- types may be injected into 'Exception' by coercing them to
472 -- 'Dynamic' (see the section on Dynamic Exceptions: "Control.Exception\#DynamicExceptions").
474 -- For backwards compatibility with Haskell 98, 'IOError' is a type synonym
477 = ArithException ArithException
478 -- ^Exceptions raised by arithmetic
479 -- operations. (NOTE: GHC currently does not throw
480 -- 'ArithException's).
481 | ArrayException ArrayException
482 -- ^Exceptions raised by array-related
483 -- operations. (NOTE: GHC currently does not throw
484 -- 'ArrayException's).
485 | AssertionFailed String
486 -- ^This exception is thrown by the
487 -- 'assert' operation when the condition
488 -- fails. The 'String' argument contains the
489 -- location of the assertion in the source program.
490 | AsyncException AsyncException
491 -- ^Asynchronous exceptions (see section on Asynchronous Exceptions: "Control.Exception\#AsynchronousExceptions").
493 -- ^The current thread was executing a call to
494 -- 'takeMVar' that could never return, because there are no other
495 -- references to this 'MVar'.
497 -- ^There are no runnable threads, so the program is
498 -- deadlocked. The 'Deadlock' exception is
499 -- raised in the main thread only (see also: "Control.Concurrent").
500 | DynException Dynamic
501 -- ^Dynamically typed exceptions (see section on Dynamic Exceptions: "Control.Exception\#DynamicExceptions").
503 -- ^The 'ErrorCall' exception is thrown by 'error'. The 'String'
504 -- argument of 'ErrorCall' is the string passed to 'error' when it was
506 | ExitException ExitCode
507 -- ^The 'ExitException' exception is thrown by 'System.exitWith' (and
508 -- 'System.exitFailure'). The 'ExitCode' argument is the value passed
509 -- to 'System.exitWith'. An unhandled 'ExitException' exception in the
510 -- main thread will cause the program to be terminated with the given
512 | IOException IOException
513 -- ^These are the standard IO exceptions generated by
514 -- Haskell\'s @IO@ operations. See also "System.IO.Error".
515 | NoMethodError String
516 -- ^An attempt was made to invoke a class method which has
517 -- no definition in this instance, and there was no default
518 -- definition given in the class declaration. GHC issues a
519 -- warning when you compile an instance which has missing
522 -- ^The current thread is stuck in an infinite loop. This
523 -- exception may or may not be thrown when the program is
525 | PatternMatchFail String
526 -- ^A pattern matching failure. The 'String' argument should contain a
527 -- descriptive message including the function name, source file
530 -- ^An attempt was made to evaluate a field of a record
531 -- for which no value was given at construction time. The
532 -- 'String' argument gives the location of the
533 -- record construction in the source program.
535 -- ^A field selection was attempted on a constructor that
536 -- doesn\'t have the requested field. This can happen with
537 -- multi-constructor records when one or more fields are
538 -- missing from some of the constructors. The
539 -- 'String' argument gives the location of the
540 -- record selection in the source program.
542 -- ^An attempt was made to update a field in a record,
543 -- where the record doesn\'t have the requested field. This can
544 -- only occur with multi-constructor records, when one or more
545 -- fields are missing from some of the constructors. The
546 -- 'String' argument gives the location of the
547 -- record update in the source program.
549 -- |The type of arithmetic exceptions
559 -- |Asynchronous exceptions
562 -- ^The current thread\'s stack exceeded its limit.
563 -- Since an exception has been raised, the thread\'s stack
564 -- will certainly be below its limit again, but the
565 -- programmer should take remedial action
568 -- ^The program\'s heap is reaching its limit, and
569 -- the program should take action to reduce the amount of
570 -- live data it has. Notes:
572 -- * It is undefined which thread receives this exception.
574 -- * GHC currently does not throw 'HeapOverflow' exceptions.
576 -- ^This exception is raised by another thread
577 -- calling 'killThread', or by the system
578 -- if it needs to terminate the thread for some
582 -- | Exceptions generated by array operations
584 = IndexOutOfBounds String
585 -- ^An attempt was made to index an array outside
586 -- its declared bounds.
587 | UndefinedElement String
588 -- ^An attempt was made to evaluate an element of an
589 -- array that had not been initialized.
592 stackOverflow, heapOverflow :: Exception -- for the RTS
593 stackOverflow = AsyncException StackOverflow
594 heapOverflow = AsyncException HeapOverflow
596 instance Show ArithException where
597 showsPrec _ Overflow = showString "arithmetic overflow"
598 showsPrec _ Underflow = showString "arithmetic underflow"
599 showsPrec _ LossOfPrecision = showString "loss of precision"
600 showsPrec _ DivideByZero = showString "divide by zero"
601 showsPrec _ Denormal = showString "denormal"
603 instance Show AsyncException where
604 showsPrec _ StackOverflow = showString "stack overflow"
605 showsPrec _ HeapOverflow = showString "heap overflow"
606 showsPrec _ ThreadKilled = showString "thread killed"
608 instance Show ArrayException where
609 showsPrec _ (IndexOutOfBounds s)
610 = showString "array index out of range"
611 . (if not (null s) then showString ": " . showString s
613 showsPrec _ (UndefinedElement s)
614 = showString "undefined array element"
615 . (if not (null s) then showString ": " . showString s
618 instance Show Exception where
619 showsPrec _ (IOException err) = shows err
620 showsPrec _ (ArithException err) = shows err
621 showsPrec _ (ArrayException err) = shows err
622 showsPrec _ (ErrorCall err) = showString err
623 showsPrec _ (ExitException err) = showString "exit: " . shows err
624 showsPrec _ (NoMethodError err) = showString err
625 showsPrec _ (PatternMatchFail err) = showString err
626 showsPrec _ (RecSelError err) = showString err
627 showsPrec _ (RecConError err) = showString err
628 showsPrec _ (RecUpdError err) = showString err
629 showsPrec _ (AssertionFailed err) = showString err
630 showsPrec _ (DynException _err) = showString "unknown exception"
631 showsPrec _ (AsyncException e) = shows e
632 showsPrec _ (BlockedOnDeadMVar) = showString "thread blocked indefinitely"
633 showsPrec _ (NonTermination) = showString "<<loop>>"
634 showsPrec _ (Deadlock) = showString "<<deadlock>>"
636 instance Eq Exception where
637 IOException e1 == IOException e2 = e1 == e2
638 ArithException e1 == ArithException e2 = e1 == e2
639 ArrayException e1 == ArrayException e2 = e1 == e2
640 ErrorCall e1 == ErrorCall e2 = e1 == e2
641 ExitException e1 == ExitException e2 = e1 == e2
642 NoMethodError e1 == NoMethodError e2 = e1 == e2
643 PatternMatchFail e1 == PatternMatchFail e2 = e1 == e2
644 RecSelError e1 == RecSelError e2 = e1 == e2
645 RecConError e1 == RecConError e2 = e1 == e2
646 RecUpdError e1 == RecUpdError e2 = e1 == e2
647 AssertionFailed e1 == AssertionFailed e2 = e1 == e2
648 DynException _ == DynException _ = False -- incomparable
649 AsyncException e1 == AsyncException e2 = e1 == e2
650 BlockedOnDeadMVar == BlockedOnDeadMVar = True
651 NonTermination == NonTermination = True
652 Deadlock == Deadlock = True
654 -- -----------------------------------------------------------------------------
657 -- The `ExitCode' type defines the exit codes that a program
658 -- can return. `ExitSuccess' indicates successful termination;
659 -- and `ExitFailure code' indicates program failure
660 -- with value `code'. The exact interpretation of `code'
661 -- is operating-system dependent. In particular, some values of
662 -- `code' may be prohibited (e.g. 0 on a POSIX-compliant system).
664 -- We need it here because it is used in ExitException in the
665 -- Exception datatype (above).
667 data ExitCode = ExitSuccess | ExitFailure Int
668 deriving (Eq, Ord, Read, Show)
670 -- --------------------------------------------------------------------------
673 -- | Throw an exception. Exceptions may be thrown from purely
674 -- functional code, but may only be caught within the 'IO' monad.
675 throw :: Exception -> a
676 throw exception = raise# exception
678 -- | A variant of 'throw' that can be used within the 'IO' monad.
680 -- Although 'ioError' has a type that is an instance of the type of 'throw', the
681 -- two functions are subtly different:
683 -- > throw e `seq` return () ===> throw e
684 -- > ioError e `seq` return () ===> return ()
686 -- The first example will cause the exception @e@ to be raised,
687 -- whereas the second one won\'t. In fact, 'ioError' will only cause
688 -- an exception to be raised when it is used within the 'IO' monad.
689 -- The 'ioError' variant should be used in preference to 'throw' to
690 -- raise an exception within the 'IO' monad because it guarantees
691 -- ordering with respect to other 'IO' operations, whereas 'throw'
693 ioError :: Exception -> IO a
694 ioError err = IO $ \s -> throw err s
696 ioException :: IOException -> IO a
697 ioException err = IO $ \s -> throw (IOException err) s
699 -- ---------------------------------------------------------------------------
702 -- A value @IOError@ encode errors occurred in the @IO@ monad.
703 -- An @IOError@ records a more specific error type, a descriptive
704 -- string and maybe the handle that was used when the error was
707 type IOError = Exception
711 ioe_handle :: Maybe Handle, -- the handle used by the action flagging
713 ioe_type :: IOErrorType, -- what it was.
714 ioe_location :: String, -- location.
715 ioe_descr :: String, -- error type specific information.
716 ioe_filename :: Maybe FilePath -- filename the error is related to.
719 instance Eq IOException where
720 (IOError h1 e1 loc1 str1 fn1) == (IOError h2 e2 loc2 str2 fn2) =
721 e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && fn1==fn2
734 | UnsatisfiedConstraints
741 | UnsupportedOperation
745 | DynIOError Dynamic -- cheap&cheerful extensible IO error type.
747 instance Eq IOErrorType where
750 DynIOError{} -> False -- from a strictness POV, compatible with a derived Eq inst?
751 _ -> getTag# x ==# getTag# y
753 instance Show IOErrorType where
757 AlreadyExists -> "already exists"
758 NoSuchThing -> "does not exist"
759 ResourceBusy -> "resource busy"
760 ResourceExhausted -> "resource exhausted"
762 IllegalOperation -> "illegal operation"
763 PermissionDenied -> "permission denied"
764 UserError -> "user error"
765 HardwareFault -> "hardware fault"
766 InappropriateType -> "inappropriate type"
767 Interrupted -> "interrupted"
768 InvalidArgument -> "invalid argument"
769 OtherError -> "failed"
770 ProtocolError -> "protocol error"
771 ResourceVanished -> "resource vanished"
772 SystemError -> "system error"
773 TimeExpired -> "timeout"
774 UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise!
775 UnsupportedOperation -> "unsupported operation"
776 DynIOError{} -> "unknown IO error"
778 userError :: String -> IOError
779 userError str = IOException (IOError Nothing UserError "" str Nothing)
781 -- ---------------------------------------------------------------------------
784 instance Show IOException where
785 showsPrec p (IOError hdl iot loc s fn) =
789 _ -> showString "\nAction: " . showString loc) .
792 Just h -> showString "\nHandle: " . showsPrec p h) .
795 _ -> showString "\nReason: " . showString s) .
798 Just name -> showString "\nFile: " . showString name)
800 -- -----------------------------------------------------------------------------
803 data IOMode = ReadMode | WriteMode | AppendMode | ReadWriteMode
804 deriving (Eq, Ord, Ix, Enum, Read, Show)