608d2b11cbbdd29f1bef51cffacfe8ce7be7ef7d
[ghc-base.git] / GHC / IOBase.lhs
1 \begin{code}
2 {-# OPTIONS -fno-implicit-prelude #-}
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  GHC.IOBase
6 -- Copyright   :  (c) The University of Glasgow 1994-2002
7 -- License     :  see libraries/base/LICENSE
8 -- 
9 -- Maintainer  :  cvs-ghc@haskell.org
10 -- Stability   :  internal
11 -- Portability :  non-portable (GHC Extensions)
12 --
13 -- Definitions for the 'IO' monad and its friends.
14 --
15 -----------------------------------------------------------------------------
16
17 module GHC.IOBase where
18
19 import GHC.ST
20 import GHC.STRef
21 import GHC.Base
22 import GHC.Num  -- To get fromInteger etc, needed because of -fno-implicit-prelude
23 import Data.Maybe  ( Maybe(..) )
24 import GHC.Show
25 import GHC.List
26 import GHC.Read
27
28 #ifndef __HADDOCK__
29 import {-# SOURCE #-} Data.Dynamic
30 #endif
31
32 -- ---------------------------------------------------------------------------
33 -- The IO Monad
34
35 {-
36 The IO Monad is just an instance of the ST monad, where the state is
37 the real world.  We use the exception mechanism (in GHC.Exception) to
38 implement IO exceptions.
39
40 NOTE: The IO representation is deeply wired in to various parts of the
41 system.  The following list may or may not be exhaustive:
42
43 Compiler  - types of various primitives in PrimOp.lhs
44
45 RTS       - forceIO (StgMiscClosures.hc)
46           - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast 
47             (Exceptions.hc)
48           - raiseAsync (Schedule.c)
49
50 Prelude   - GHC.IOBase.lhs, and several other places including
51             GHC.Exception.lhs.
52
53 Libraries - parts of hslibs/lang.
54
55 --SDM
56 -}
57
58 newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #))
59
60 unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
61 unIO (IO a) = a
62
63 instance  Functor IO where
64    fmap f x = x >>= (return . f)
65
66 instance  Monad IO  where
67     {-# INLINE return #-}
68     {-# INLINE (>>)   #-}
69     {-# INLINE (>>=)  #-}
70     m >> k      =  m >>= \ _ -> k
71     return x    = returnIO x
72
73     m >>= k     = bindIO m k
74     fail s      = failIO s
75
76 failIO :: String -> IO a
77 failIO s = ioError (userError s)
78
79 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
80 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
81
82 bindIO :: IO a -> (a -> IO b) -> IO b
83 bindIO (IO m) k = IO ( \ s ->
84   case m s of 
85     (# new_s, a #) -> unIO (k a) new_s
86   )
87
88 thenIO :: IO a -> IO b -> IO b
89 thenIO (IO m) k = IO ( \ s ->
90   case m s of 
91     (# new_s, a #) -> unIO k new_s
92   )
93
94 returnIO :: a -> IO a
95 returnIO x = IO (\ s -> (# s, x #))
96
97 -- ---------------------------------------------------------------------------
98 -- Coercions between IO and ST
99
100 --stToIO        :: (forall s. ST s a) -> IO a
101 stToIO        :: ST RealWorld a -> IO a
102 stToIO (ST m) = IO m
103
104 ioToST        :: IO a -> ST RealWorld a
105 ioToST (IO m) = (ST m)
106
107 -- ---------------------------------------------------------------------------
108 -- Unsafe IO operations
109
110 {-|
111 This is the "back door" into the 'IO' monad, allowing
112 'IO' computation to be performed at any time.  For
113 this to be safe, the 'IO' computation should be
114 free of side effects and independent of its environment.
115
116 If the I\/O computation wrapped in 'unsafePerformIO'
117 performs side effects, then the relative order in which those side
118 effects take place (relative to the main I\/O trunk, or other calls to
119 'unsafePerformIO') is indeterminate.  
120
121 However, it is less well known that
122 'unsafePerformIO' is not type safe.  For example:
123
124 >     test :: IORef [a]
125 >     test = unsafePerformIO $ newIORef []
126 >     
127 >     main = do
128 >             writeIORef test [42]
129 >             bang \<- readIORef test
130 >             print (bang :: [Char])
131
132 This program will core dump.  This problem with polymorphic references
133 is well known in the ML community, and does not arise with normal
134 monadic use of references.  There is no easy way to make it impossible
135 once you use 'unsafePerformIO'.  Indeed, it is
136 possible to write @coerce :: a -> b@ with the
137 help of 'unsafePerformIO'.  So be careful!
138 -}
139 {-# NOINLINE unsafePerformIO #-}
140 unsafePerformIO :: IO a -> a
141 unsafePerformIO (IO m) = case m realWorld# of (# _, r #)   -> r
142
143 {-|
144 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
145 When passed a value of type @IO a@, the 'IO' will only be performed
146 when the value of the @a@ is demanded.  This is used to implement lazy
147 file reading, see 'IO.hGetContents'.
148 -}
149 {-# NOINLINE unsafeInterleaveIO #-}
150 unsafeInterleaveIO :: IO a -> IO a
151 unsafeInterleaveIO (IO m)
152   = IO ( \ s -> let
153                    r = case m s of (# _, res #) -> res
154                 in
155                 (# s, r #))
156
157 -- ---------------------------------------------------------------------------
158 -- Handle type
159
160 data MVar a = MVar (MVar# RealWorld a)
161 {- ^
162 An 'MVar' (pronounced \"em-var\") is a synchronising variable, used
163 for communication between concurrent threads.  It can be thought of
164 as a a box, which may be empty or full.
165 -}
166
167 -- pull in Eq (Mvar a) too, to avoid GHC.Conc being an orphan-instance module
168 instance Eq (MVar a) where
169         (MVar mvar1#) == (MVar mvar2#) = sameMVar# mvar1# mvar2#
170
171 --  A Handle is represented by (a reference to) a record 
172 --  containing the state of the I/O port/device. We record
173 --  the following pieces of info:
174
175 --    * type (read,write,closed etc.)
176 --    * the underlying file descriptor
177 --    * buffering mode 
178 --    * buffer, and spare buffers
179 --    * user-friendly name (usually the
180 --      FilePath used when IO.openFile was called)
181
182 -- Note: when a Handle is garbage collected, we want to flush its buffer
183 -- and close the OS file handle, so as to free up a (precious) resource.
184
185 data Handle 
186   = FileHandle                          -- A normal handle to a file
187         !(MVar Handle__)
188
189   | DuplexHandle                        -- A handle to a read/write stream
190         !(MVar Handle__)                -- The read side
191         !(MVar Handle__)                -- The write side
192
193 -- NOTES:
194 --    * A 'FileHandle' is seekable.  A 'DuplexHandle' may or may not be
195 --      seekable.
196
197 instance Eq Handle where
198  (FileHandle h1)     == (FileHandle h2)     = h1 == h2
199  (DuplexHandle h1 _) == (DuplexHandle h2 _) = h1 == h2
200  _ == _ = False 
201
202 type FD = Int -- XXX ToDo: should be CInt
203
204 data Handle__
205   = Handle__ {
206       haFD          :: !FD,                  -- file descriptor
207       haType        :: HandleType,           -- type (read/write/append etc.)
208       haIsBin       :: Bool,                 -- binary mode?
209       haIsStream    :: Bool,                 -- is this a stream handle?
210       haBufferMode  :: BufferMode,           -- buffer contains read/write data?
211       haFilePath    :: FilePath,             -- file name, possibly
212       haBuffer      :: !(IORef Buffer),      -- the current buffer
213       haBuffers     :: !(IORef BufferList),  -- spare buffers
214       haOtherSide   :: Maybe (MVar Handle__) -- ptr to the write side of a 
215                                              -- duplex handle.
216     }
217
218 -- ---------------------------------------------------------------------------
219 -- Buffers
220
221 -- The buffer is represented by a mutable variable containing a
222 -- record, where the record contains the raw buffer and the start/end
223 -- points of the filled portion.  We use a mutable variable so that
224 -- the common operation of writing (or reading) some data from (to)
225 -- the buffer doesn't need to modify, and hence copy, the handle
226 -- itself, it just updates the buffer.  
227
228 -- There will be some allocation involved in a simple hPutChar in
229 -- order to create the new Buffer structure (below), but this is
230 -- relatively small, and this only has to be done once per write
231 -- operation.
232
233 -- The buffer contains its size - we could also get the size by
234 -- calling sizeOfMutableByteArray# on the raw buffer, but that tends
235 -- to be rounded up to the nearest Word.
236
237 type RawBuffer = MutableByteArray# RealWorld
238
239 -- INVARIANTS on a Buffer:
240 --
241 --   * A handle *always* has a buffer, even if it is only 1 character long
242 --     (an unbuffered handle needs a 1 character buffer in order to support
243 --      hLookAhead and hIsEOF).
244 --   * r <= w
245 --   * if r == w, then r == 0 && w == 0
246 --   * if state == WriteBuffer, then r == 0
247 --   * a write buffer is never full.  If an operation
248 --     fills up the buffer, it will always flush it before 
249 --     returning.
250 --   * a read buffer may be full as a result of hLookAhead.  In normal
251 --     operation, a read buffer always has at least one character of space.
252
253 data Buffer 
254   = Buffer {
255         bufBuf   :: RawBuffer,
256         bufRPtr  :: !Int,
257         bufWPtr  :: !Int,
258         bufSize  :: !Int,
259         bufState :: BufferState
260   }
261
262 data BufferState = ReadBuffer | WriteBuffer deriving (Eq)
263
264 -- we keep a few spare buffers around in a handle to avoid allocating
265 -- a new one for each hPutStr.  These buffers are *guaranteed* to be the
266 -- same size as the main buffer.
267 data BufferList 
268   = BufferListNil 
269   | BufferListCons RawBuffer BufferList
270
271
272 bufferIsWritable :: Buffer -> Bool
273 bufferIsWritable Buffer{ bufState=WriteBuffer } = True
274 bufferIsWritable _other = False
275
276 bufferEmpty :: Buffer -> Bool
277 bufferEmpty Buffer{ bufRPtr=r, bufWPtr=w } = r == w
278
279 -- only makes sense for a write buffer
280 bufferFull :: Buffer -> Bool
281 bufferFull b@Buffer{ bufWPtr=w } = w >= bufSize b
282
283 --  Internally, we classify handles as being one
284 --  of the following:
285
286 data HandleType
287  = ClosedHandle
288  | SemiClosedHandle
289  | ReadHandle
290  | WriteHandle
291  | AppendHandle
292  | ReadWriteHandle
293
294 isReadableHandleType ReadHandle         = True
295 isReadableHandleType ReadWriteHandle    = True
296 isReadableHandleType _                  = False
297
298 isWritableHandleType AppendHandle    = True
299 isWritableHandleType WriteHandle     = True
300 isWritableHandleType ReadWriteHandle = True
301 isWritableHandleType _               = False
302
303 -- File names are specified using @FilePath@, a OS-dependent
304 -- string that (hopefully, I guess) maps to an accessible file/object.
305
306 type FilePath = String
307
308 -- ---------------------------------------------------------------------------
309 -- Buffering modes
310
311 -- Three kinds of buffering are supported: line-buffering, 
312 -- block-buffering or no-buffering.  These modes have the following
313 -- effects. For output, items are written out from the internal
314 -- buffer according to the buffer mode:
315 --
316 -- o line-buffering  the entire output buffer is written
317 --   out whenever a newline is output, the output buffer overflows, 
318 --   a flush is issued, or the handle is closed.
319 --
320 -- o block-buffering the entire output buffer is written out whenever 
321 --   it overflows, a flush is issued, or the handle
322 --   is closed.
323 --
324 -- o no-buffering output is written immediately, and never stored
325 --   in the output buffer.
326 --
327 -- The output buffer is emptied as soon as it has been written out.
328
329 -- Similarly, input occurs according to the buffer mode for handle {\em hdl}.
330
331 -- o line-buffering when the input buffer for the handle is not empty,
332 --   the next item is obtained from the buffer;
333 --   otherwise, when the input buffer is empty,
334 --   characters up to and including the next newline
335 --   character are read into the buffer.  No characters
336 --   are available until the newline character is
337 --   available.
338 --
339 -- o block-buffering when the input buffer for the handle becomes empty,
340 --   the next block of data is read into this buffer.
341 --
342 -- o no-buffering the next input item is read and returned.
343
344 -- For most implementations, physical files will normally be block-buffered 
345 -- and terminals will normally be line-buffered. (the IO interface provides
346 -- operations for changing the default buffering of a handle tho.)
347
348 data BufferMode  
349  = NoBuffering | LineBuffering | BlockBuffering (Maybe Int)
350    deriving (Eq, Ord, Read, Show)
351
352 -- ---------------------------------------------------------------------------
353 -- IORefs
354
355 -- |A mutable variable in the 'IO' monad
356 newtype IORef a = IORef (STRef RealWorld a) deriving Eq
357
358 -- |Build a new 'IORef'
359 newIORef    :: a -> IO (IORef a)
360 newIORef v = stToIO (newSTRef v) >>= \ var -> return (IORef var)
361
362 -- |Read the value of an 'IORef'
363 readIORef   :: IORef a -> IO a
364 readIORef  (IORef var) = stToIO (readSTRef var)
365
366 -- |Write a new value into an 'IORef'
367 writeIORef  :: IORef a -> a -> IO ()
368 writeIORef (IORef var) v = stToIO (writeSTRef var v)
369
370 -- ---------------------------------------------------------------------------
371 -- Show instance for Handles
372
373 -- handle types are 'show'n when printing error msgs, so
374 -- we provide a more user-friendly Show instance for it
375 -- than the derived one.
376
377 instance Show HandleType where
378   showsPrec p t =
379     case t of
380       ClosedHandle      -> showString "closed"
381       SemiClosedHandle  -> showString "semi-closed"
382       ReadHandle        -> showString "readable"
383       WriteHandle       -> showString "writable"
384       AppendHandle      -> showString "writable (append)"
385       ReadWriteHandle   -> showString "read-writable"
386
387 instance Show Handle where 
388   showsPrec p (FileHandle   h)   = showHandle p h False
389   showsPrec p (DuplexHandle _ h) = showHandle p h True
390    
391 showHandle p h duplex =
392     let
393      -- (Big) SIGH: unfolded defn of takeMVar to avoid
394      -- an (oh-so) unfortunate module loop with GHC.Conc.
395      hdl_ = unsafePerformIO (IO $ \ s# ->
396              case h                 of { MVar h# ->
397              case takeMVar# h# s#   of { (# s2# , r #) -> 
398              case putMVar# h# r s2# of { s3# ->
399              (# s3#, r #) }}})
400
401      showType | duplex = showString "duplex (read-write)"
402               | otherwise = showsPrec p (haType hdl_)
403     in
404     showChar '{' . 
405     showHdl (haType hdl_) 
406             (showString "loc=" . showString (haFilePath hdl_) . showChar ',' .
407              showString "type=" . showType . showChar ',' .
408              showString "binary=" . showsPrec p (haIsBin hdl_) . showChar ',' .
409              showString "buffering=" . showBufMode (unsafePerformIO (readIORef (haBuffer hdl_))) (haBufferMode hdl_) . showString "}" )
410    where
411
412     showHdl :: HandleType -> ShowS -> ShowS
413     showHdl ht cont = 
414        case ht of
415         ClosedHandle  -> showsPrec p ht . showString "}"
416         _ -> cont
417        
418     showBufMode :: Buffer -> BufferMode -> ShowS
419     showBufMode buf bmo =
420       case bmo of
421         NoBuffering   -> showString "none"
422         LineBuffering -> showString "line"
423         BlockBuffering (Just n) -> showString "block " . showParen True (showsPrec p n)
424         BlockBuffering Nothing  -> showString "block " . showParen True (showsPrec p def)
425       where
426        def :: Int 
427        def = bufSize buf
428
429 -- ------------------------------------------------------------------------
430 -- Exception datatype and operations
431
432 data Exception
433   = IOException         IOException     -- IO exceptions
434   | ArithException      ArithException  -- Arithmetic exceptions
435   | ArrayException      ArrayException  -- Array-related exceptions
436   | ErrorCall           String          -- Calls to 'error'
437   | ExitException       ExitCode        -- Call to System.exitWith
438   | NoMethodError       String          -- A non-existent method was invoked
439   | PatternMatchFail    String          -- A pattern match / guard failure
440   | RecSelError         String          -- Selecting a non-existent field
441   | RecConError         String          -- Field missing in record construction
442   | RecUpdError         String          -- Record doesn't contain updated field
443   | AssertionFailed     String          -- Assertions
444   | DynException        Dynamic         -- Dynamic exceptions
445   | AsyncException      AsyncException  -- Externally generated errors
446   | BlockedOnDeadMVar                   -- Blocking on a dead MVar
447   | Deadlock                            -- no threads can run (raised in main thread)
448   | NonTermination
449
450 data ArithException
451   = Overflow
452   | Underflow
453   | LossOfPrecision
454   | DivideByZero
455   | Denormal
456   deriving (Eq, Ord)
457
458 data AsyncException
459   = StackOverflow
460   | HeapOverflow
461   | ThreadKilled
462   deriving (Eq, Ord)
463
464 data ArrayException
465   = IndexOutOfBounds    String          -- out-of-range array access
466   | UndefinedElement    String          -- evaluating an undefined element
467   deriving (Eq, Ord)
468
469 stackOverflow, heapOverflow :: Exception -- for the RTS
470 stackOverflow = AsyncException StackOverflow
471 heapOverflow  = AsyncException HeapOverflow
472
473 instance Show ArithException where
474   showsPrec _ Overflow        = showString "arithmetic overflow"
475   showsPrec _ Underflow       = showString "arithmetic underflow"
476   showsPrec _ LossOfPrecision = showString "loss of precision"
477   showsPrec _ DivideByZero    = showString "divide by zero"
478   showsPrec _ Denormal        = showString "denormal"
479
480 instance Show AsyncException where
481   showsPrec _ StackOverflow   = showString "stack overflow"
482   showsPrec _ HeapOverflow    = showString "heap overflow"
483   showsPrec _ ThreadKilled    = showString "thread killed"
484
485 instance Show ArrayException where
486   showsPrec _ (IndexOutOfBounds s)
487         = showString "array index out of range"
488         . (if not (null s) then showString ": " . showString s
489                            else id)
490   showsPrec _ (UndefinedElement s)
491         = showString "undefined array element"
492         . (if not (null s) then showString ": " . showString s
493                            else id)
494
495 instance Show Exception where
496   showsPrec _ (IOException err)          = shows err
497   showsPrec _ (ArithException err)       = shows err
498   showsPrec _ (ArrayException err)       = shows err
499   showsPrec _ (ErrorCall err)            = showString err
500   showsPrec _ (ExitException err)        = showString "exit: " . shows err
501   showsPrec _ (NoMethodError err)        = showString err
502   showsPrec _ (PatternMatchFail err)     = showString err
503   showsPrec _ (RecSelError err)          = showString err
504   showsPrec _ (RecConError err)          = showString err
505   showsPrec _ (RecUpdError err)          = showString err
506   showsPrec _ (AssertionFailed err)      = showString err
507   showsPrec _ (DynException _err)        = showString "unknown exception"
508   showsPrec _ (AsyncException e)         = shows e
509   showsPrec _ (BlockedOnDeadMVar)        = showString "thread blocked indefinitely"
510   showsPrec _ (NonTermination)           = showString "<<loop>>"
511   showsPrec _ (Deadlock)                 = showString "<<deadlock>>"
512
513 instance Eq Exception where
514   IOException e1      == IOException e2      = e1 == e2
515   ArithException e1   == ArithException e2   = e1 == e2
516   ArrayException e1   == ArrayException e2   = e1 == e2
517   ErrorCall e1        == ErrorCall e2        = e1 == e2
518   ExitException e1    == ExitException e2    = e1 == e2
519   NoMethodError e1    == NoMethodError e2    = e1 == e2
520   PatternMatchFail e1 == PatternMatchFail e2 = e1 == e2
521   RecSelError e1      == RecSelError e2      = e1 == e2
522   RecConError e1      == RecConError e2      = e1 == e2
523   RecUpdError e1      == RecUpdError e2      = e1 == e2
524   AssertionFailed e1  == AssertionFailed e2  = e1 == e2
525   DynException _      == DynException _      = False -- incomparable
526   AsyncException e1   == AsyncException e2   = e1 == e2
527   BlockedOnDeadMVar   == BlockedOnDeadMVar   = True
528   NonTermination      == NonTermination      = True
529   Deadlock            == Deadlock            = True
530
531 -- -----------------------------------------------------------------------------
532 -- The ExitCode type
533
534 -- The `ExitCode' type defines the exit codes that a program
535 -- can return.  `ExitSuccess' indicates successful termination;
536 -- and `ExitFailure code' indicates program failure
537 -- with value `code'.  The exact interpretation of `code'
538 -- is operating-system dependent.  In particular, some values of 
539 -- `code' may be prohibited (e.g. 0 on a POSIX-compliant system).
540
541 -- We need it here because it is used in ExitException in the
542 -- Exception datatype (above).
543
544 data ExitCode = ExitSuccess | ExitFailure Int 
545                 deriving (Eq, Ord, Read, Show)
546
547 -- --------------------------------------------------------------------------
548 -- Primitive throw
549
550 throw :: Exception -> a
551 throw exception = raise# exception
552
553 ioError         :: Exception -> IO a 
554 ioError err     =  IO $ \s -> throw err s
555
556 ioException     :: IOException -> IO a
557 ioException err =  IO $ \s -> throw (IOException err) s
558
559 -- ---------------------------------------------------------------------------
560 -- IOError type
561
562 -- A value @IOError@ encode errors occurred in the @IO@ monad.
563 -- An @IOError@ records a more specific error type, a descriptive
564 -- string and maybe the handle that was used when the error was
565 -- flagged.
566
567 type IOError = Exception
568
569 data IOException
570  = IOError {
571      ioe_handle   :: Maybe Handle,   -- the handle used by the action flagging 
572                                      -- the error.
573      ioe_type     :: IOErrorType,    -- what it was.
574      ioe_location :: String,         -- location.
575      ioe_descr    :: String,         -- error type specific information.
576      ioe_filename :: Maybe FilePath  -- filename the error is related to.
577    }
578
579 instance Eq IOException where
580   (IOError h1 e1 loc1 str1 fn1) == (IOError h2 e2 loc2 str2 fn2) = 
581     e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && fn1==fn2
582
583 data IOErrorType
584   -- Haskell 98:
585   = AlreadyExists
586   | NoSuchThing
587   | ResourceBusy
588   | ResourceExhausted
589   | EOF
590   | IllegalOperation
591   | PermissionDenied
592   | UserError
593   -- GHC only:
594   | UnsatisfiedConstraints
595   | SystemError
596   | ProtocolError
597   | OtherError
598   | InvalidArgument
599   | InappropriateType
600   | HardwareFault
601   | UnsupportedOperation
602   | TimeExpired
603   | ResourceVanished
604   | Interrupted
605   | DynIOError Dynamic -- cheap&cheerful extensible IO error type.
606
607 instance Eq IOErrorType where
608    x == y = 
609      case x of
610        DynIOError{} -> False -- from a strictness POV, compatible with a derived Eq inst?
611        _ -> getTag# x ==# getTag# y
612  
613 instance Show IOErrorType where
614   showsPrec _ e =
615     showString $
616     case e of
617       AlreadyExists     -> "already exists"
618       NoSuchThing       -> "does not exist"
619       ResourceBusy      -> "resource busy"
620       ResourceExhausted -> "resource exhausted"
621       EOF               -> "end of file"
622       IllegalOperation  -> "illegal operation"
623       PermissionDenied  -> "permission denied"
624       UserError         -> "user error"
625       HardwareFault     -> "hardware fault"
626       InappropriateType -> "inappropriate type"
627       Interrupted       -> "interrupted"
628       InvalidArgument   -> "invalid argument"
629       OtherError        -> "failed"
630       ProtocolError     -> "protocol error"
631       ResourceVanished  -> "resource vanished"
632       SystemError       -> "system error"
633       TimeExpired       -> "timeout"
634       UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise!
635       UnsupportedOperation -> "unsupported operation"
636       DynIOError{}      -> "unknown IO error"
637
638 userError       :: String  -> IOError
639 userError str   =  IOException (IOError Nothing UserError "" str Nothing)
640
641 -- ---------------------------------------------------------------------------
642 -- Showing IOErrors
643
644 instance Show IOException where
645     showsPrec p (IOError hdl iot loc s fn) =
646       showsPrec p iot .
647       (case loc of
648          "" -> id
649          _  -> showString "\nAction: " . showString loc) .
650       (case hdl of
651         Nothing -> id
652         Just h  -> showString "\nHandle: " . showsPrec p h) .
653       (case s of
654          "" -> id
655          _  -> showString "\nReason: " . showString s) .
656       (case fn of
657          Nothing -> id
658          Just name -> showString "\nFile: " . showString name)
659 \end{code}