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