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