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