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