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