e82b2bc3fc8226f7c193cd8c6937d944c4958ac5
[ghc-base.git] / GHC / IOBase.lhs
1 \begin{code}
2 {-# OPTIONS -fno-implicit-prelude #-}
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  GHC.IOBase
6 -- Copyright   :  (c) The University of Glasgow 1994-2002
7 -- License     :  see libraries/base/LICENSE
8 -- 
9 -- Maintainer  :  cvs-ghc@haskell.org
10 -- Stability   :  internal
11 -- Portability :  non-portable (GHC Extensions)
12 --
13 -- Definitions for the 'IO' monad and its friends.
14 --
15 -----------------------------------------------------------------------------
16
17 module GHC.IOBase where
18
19 import GHC.ST
20 import GHC.STRef
21 import GHC.Base
22 import GHC.Num  -- To get fromInteger etc, needed because of -fno-implicit-prelude
23 import Data.Maybe  ( Maybe(..) )
24 import GHC.Show
25 import GHC.List
26 import GHC.Read
27
28 #ifndef __HADDOCK__
29 import {-# SOURCE #-} Data.Dynamic
30 #endif
31
32 -- ---------------------------------------------------------------------------
33 -- The IO Monad
34
35 {-
36 The IO Monad is just an instance of the ST monad, where the state is
37 the real world.  We use the exception mechanism (in GHC.Exception) to
38 implement IO exceptions.
39
40 NOTE: The IO representation is deeply wired in to various parts of the
41 system.  The following list may or may not be exhaustive:
42
43 Compiler  - types of various primitives in PrimOp.lhs
44
45 RTS       - forceIO (StgMiscClosures.hc)
46           - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast 
47             (Exceptions.hc)
48           - raiseAsync (Schedule.c)
49
50 Prelude   - GHC.IOBase.lhs, and several other places including
51             GHC.Exception.lhs.
52
53 Libraries - parts of hslibs/lang.
54
55 --SDM
56 -}
57
58 newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #))
59
60 unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
61 unIO (IO a) = a
62
63 instance  Functor IO where
64    fmap f x = x >>= (return . f)
65
66 instance  Monad IO  where
67     {-# INLINE return #-}
68     {-# INLINE (>>)   #-}
69     {-# INLINE (>>=)  #-}
70     m >> k      =  m >>= \ _ -> k
71     return x    = returnIO x
72
73     m >>= k     = bindIO m k
74     fail s      = failIO s
75
76 failIO :: String -> IO a
77 failIO s = ioError (userError s)
78
79 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
80 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
81
82 bindIO :: IO a -> (a -> IO b) -> IO b
83 bindIO (IO m) k = IO ( \ s ->
84   case m s of 
85     (# new_s, a #) -> unIO (k a) new_s
86   )
87
88 thenIO :: IO a -> IO b -> IO b
89 thenIO (IO m) k = IO ( \ s ->
90   case m s of 
91     (# new_s, a #) -> unIO k new_s
92   )
93
94 returnIO :: a -> IO a
95 returnIO x = IO (\ s -> (# s, x #))
96
97 -- ---------------------------------------------------------------------------
98 -- Coercions between IO and ST
99
100 --stToIO        :: (forall s. ST s a) -> IO a
101 stToIO        :: ST RealWorld a -> IO a
102 stToIO (ST m) = IO m
103
104 ioToST        :: IO a -> ST RealWorld a
105 ioToST (IO m) = (ST m)
106
107 -- ---------------------------------------------------------------------------
108 -- Unsafe IO operations
109
110 {-# NOINLINE unsafePerformIO #-}
111 unsafePerformIO :: IO a -> a
112 unsafePerformIO (IO m) = case m realWorld# of (# _, r #)   -> r
113
114 {-# NOINLINE unsafeInterleaveIO #-}
115 unsafeInterleaveIO :: IO a -> IO a
116 unsafeInterleaveIO (IO m)
117   = IO ( \ s -> let
118                    r = case m s of (# _, res #) -> res
119                 in
120                 (# s, r #))
121
122 -- ---------------------------------------------------------------------------
123 -- Handle type
124
125 data MVar a = MVar (MVar# RealWorld a)
126 {- ^
127 An 'MVar' (pronounced \"em-var\") is a synchronising variable, used
128 for communication between concurrent threads.  It can be thought of
129 as a a box, which may be empty or full.
130 -}
131
132 -- pull in Eq (Mvar a) too, to avoid GHC.Conc being an orphan-instance module
133 instance Eq (MVar a) where
134         (MVar mvar1#) == (MVar mvar2#) = sameMVar# mvar1# mvar2#
135
136 --  A Handle is represented by (a reference to) a record 
137 --  containing the state of the I/O port/device. We record
138 --  the following pieces of info:
139
140 --    * type (read,write,closed etc.)
141 --    * the underlying file descriptor
142 --    * buffering mode 
143 --    * buffer, and spare buffers
144 --    * user-friendly name (usually the
145 --      FilePath used when IO.openFile was called)
146
147 -- Note: when a Handle is garbage collected, we want to flush its buffer
148 -- and close the OS file handle, so as to free up a (precious) resource.
149
150 data Handle 
151   = FileHandle                          -- A normal handle to a file
152         !(MVar Handle__)
153
154   | DuplexHandle                        -- A handle to a read/write stream
155         !(MVar Handle__)                -- The read side
156         !(MVar Handle__)                -- The write side
157
158 -- NOTES:
159 --    * A 'FileHandle' is seekable.  A 'DuplexHandle' may or may not be
160 --      seekable.
161
162 instance Eq Handle where
163  (FileHandle h1)     == (FileHandle h2)     = h1 == h2
164  (DuplexHandle h1 _) == (DuplexHandle h2 _) = h1 == h2
165  _ == _ = False 
166
167 type FD = Int -- XXX ToDo: should be CInt
168
169 data Handle__
170   = Handle__ {
171       haFD          :: !FD,                  -- file descriptor
172       haType        :: HandleType,           -- type (read/write/append etc.)
173       haIsBin       :: Bool,                 -- binary mode?
174       haIsStream    :: Bool,                 -- is this a stream handle?
175       haBufferMode  :: BufferMode,           -- buffer contains read/write data?
176       haFilePath    :: FilePath,             -- file name, possibly
177       haBuffer      :: !(IORef Buffer),      -- the current buffer
178       haBuffers     :: !(IORef BufferList),  -- spare buffers
179       haOtherSide   :: Maybe (MVar Handle__) -- ptr to the write side of a 
180                                              -- duplex handle.
181     }
182
183 -- ---------------------------------------------------------------------------
184 -- Buffers
185
186 -- The buffer is represented by a mutable variable containing a
187 -- record, where the record contains the raw buffer and the start/end
188 -- points of the filled portion.  We use a mutable variable so that
189 -- the common operation of writing (or reading) some data from (to)
190 -- the buffer doesn't need to modify, and hence copy, the handle
191 -- itself, it just updates the buffer.  
192
193 -- There will be some allocation involved in a simple hPutChar in
194 -- order to create the new Buffer structure (below), but this is
195 -- relatively small, and this only has to be done once per write
196 -- operation.
197
198 -- The buffer contains its size - we could also get the size by
199 -- calling sizeOfMutableByteArray# on the raw buffer, but that tends
200 -- to be rounded up to the nearest Word.
201
202 type RawBuffer = MutableByteArray# RealWorld
203
204 -- INVARIANTS on a Buffer:
205 --
206 --   * A handle *always* has a buffer, even if it is only 1 character long
207 --     (an unbuffered handle needs a 1 character buffer in order to support
208 --      hLookAhead and hIsEOF).
209 --   * r <= w
210 --   * if r == w, then r == 0 && w == 0
211 --   * if state == WriteBuffer, then r == 0
212 --   * a write buffer is never full.  If an operation
213 --     fills up the buffer, it will always flush it before 
214 --     returning.
215 --   * a read buffer may be full as a result of hLookAhead.  In normal
216 --     operation, a read buffer always has at least one character of space.
217
218 data Buffer 
219   = Buffer {
220         bufBuf   :: RawBuffer,
221         bufRPtr  :: !Int,
222         bufWPtr  :: !Int,
223         bufSize  :: !Int,
224         bufState :: BufferState
225   }
226
227 data BufferState = ReadBuffer | WriteBuffer deriving (Eq)
228
229 -- we keep a few spare buffers around in a handle to avoid allocating
230 -- a new one for each hPutStr.  These buffers are *guaranteed* to be the
231 -- same size as the main buffer.
232 data BufferList 
233   = BufferListNil 
234   | BufferListCons RawBuffer BufferList
235
236
237 bufferIsWritable :: Buffer -> Bool
238 bufferIsWritable Buffer{ bufState=WriteBuffer } = True
239 bufferIsWritable _other = False
240
241 bufferEmpty :: Buffer -> Bool
242 bufferEmpty Buffer{ bufRPtr=r, bufWPtr=w } = r == w
243
244 -- only makes sense for a write buffer
245 bufferFull :: Buffer -> Bool
246 bufferFull b@Buffer{ bufWPtr=w } = w >= bufSize b
247
248 --  Internally, we classify handles as being one
249 --  of the following:
250
251 data HandleType
252  = ClosedHandle
253  | SemiClosedHandle
254  | ReadHandle
255  | WriteHandle
256  | AppendHandle
257  | ReadWriteHandle
258
259 isReadableHandleType ReadHandle         = True
260 isReadableHandleType ReadWriteHandle    = True
261 isReadableHandleType _                  = False
262
263 isWritableHandleType AppendHandle    = True
264 isWritableHandleType WriteHandle     = True
265 isWritableHandleType ReadWriteHandle = True
266 isWritableHandleType _               = False
267
268 -- File names are specified using @FilePath@, a OS-dependent
269 -- string that (hopefully, I guess) maps to an accessible file/object.
270
271 type FilePath = String
272
273 -- ---------------------------------------------------------------------------
274 -- Buffering modes
275
276 -- Three kinds of buffering are supported: line-buffering, 
277 -- block-buffering or no-buffering.  These modes have the following
278 -- effects. For output, items are written out from the internal
279 -- buffer according to the buffer mode:
280 --
281 -- o line-buffering  the entire output buffer is written
282 --   out whenever a newline is output, the output buffer overflows, 
283 --   a flush is issued, or the handle is closed.
284 --
285 -- o block-buffering the entire output buffer is written out whenever 
286 --   it overflows, a flush is issued, or the handle
287 --   is closed.
288 --
289 -- o no-buffering output is written immediately, and never stored
290 --   in the output buffer.
291 --
292 -- The output buffer is emptied as soon as it has been written out.
293
294 -- Similarly, input occurs according to the buffer mode for handle {\em hdl}.
295
296 -- o line-buffering when the input buffer for the handle is not empty,
297 --   the next item is obtained from the buffer;
298 --   otherwise, when the input buffer is empty,
299 --   characters up to and including the next newline
300 --   character are read into the buffer.  No characters
301 --   are available until the newline character is
302 --   available.
303 --
304 -- o block-buffering when the input buffer for the handle becomes empty,
305 --   the next block of data is read into this buffer.
306 --
307 -- o no-buffering the next input item is read and returned.
308
309 -- For most implementations, physical files will normally be block-buffered 
310 -- and terminals will normally be line-buffered. (the IO interface provides
311 -- operations for changing the default buffering of a handle tho.)
312
313 data BufferMode  
314  = NoBuffering | LineBuffering | BlockBuffering (Maybe Int)
315    deriving (Eq, Ord, Read, Show)
316
317 -- ---------------------------------------------------------------------------
318 -- IORefs
319
320 -- |A mutable variable in the 'IO' monad
321 newtype IORef a = IORef (STRef RealWorld a) deriving Eq
322
323 -- |Build a new 'IORef'
324 newIORef    :: a -> IO (IORef a)
325 newIORef v = stToIO (newSTRef v) >>= \ var -> return (IORef var)
326
327 -- |Read the value of an 'IORef'
328 readIORef   :: IORef a -> IO a
329 readIORef  (IORef var) = stToIO (readSTRef var)
330
331 -- |Write a new value into an 'IORef'
332 writeIORef  :: IORef a -> a -> IO ()
333 writeIORef (IORef var) v = stToIO (writeSTRef var v)
334
335 -- ---------------------------------------------------------------------------
336 -- Show instance for Handles
337
338 -- handle types are 'show'n when printing error msgs, so
339 -- we provide a more user-friendly Show instance for it
340 -- than the derived one.
341
342 instance Show HandleType where
343   showsPrec p t =
344     case t of
345       ClosedHandle      -> showString "closed"
346       SemiClosedHandle  -> showString "semi-closed"
347       ReadHandle        -> showString "readable"
348       WriteHandle       -> showString "writable"
349       AppendHandle      -> showString "writable (append)"
350       ReadWriteHandle   -> showString "read-writable"
351
352 instance Show Handle where 
353   showsPrec p (FileHandle   h)   = showHandle p h False
354   showsPrec p (DuplexHandle _ h) = showHandle p h True
355    
356 showHandle p h duplex =
357     let
358      -- (Big) SIGH: unfolded defn of takeMVar to avoid
359      -- an (oh-so) unfortunate module loop with GHC.Conc.
360      hdl_ = unsafePerformIO (IO $ \ s# ->
361              case h                 of { MVar h# ->
362              case takeMVar# h# s#   of { (# s2# , r #) -> 
363              case putMVar# h# r s2# of { s3# ->
364              (# s3#, r #) }}})
365
366      showType | duplex = showString "duplex (read-write)"
367               | otherwise = showsPrec p (haType hdl_)
368     in
369     showChar '{' . 
370     showHdl (haType hdl_) 
371             (showString "loc=" . showString (haFilePath hdl_) . showChar ',' .
372              showString "type=" . showType . showChar ',' .
373              showString "binary=" . showsPrec p (haIsBin hdl_) . showChar ',' .
374              showString "buffering=" . showBufMode (unsafePerformIO (readIORef (haBuffer hdl_))) (haBufferMode hdl_) . showString "}" )
375    where
376
377     showHdl :: HandleType -> ShowS -> ShowS
378     showHdl ht cont = 
379        case ht of
380         ClosedHandle  -> showsPrec p ht . showString "}"
381         _ -> cont
382        
383     showBufMode :: Buffer -> BufferMode -> ShowS
384     showBufMode buf bmo =
385       case bmo of
386         NoBuffering   -> showString "none"
387         LineBuffering -> showString "line"
388         BlockBuffering (Just n) -> showString "block " . showParen True (showsPrec p n)
389         BlockBuffering Nothing  -> showString "block " . showParen True (showsPrec p def)
390       where
391        def :: Int 
392        def = bufSize buf
393
394 -- ------------------------------------------------------------------------
395 -- Exception datatype and operations
396
397 data Exception
398   = IOException         IOException     -- IO exceptions
399   | ArithException      ArithException  -- Arithmetic exceptions
400   | ArrayException      ArrayException  -- Array-related exceptions
401   | ErrorCall           String          -- Calls to 'error'
402   | ExitException       ExitCode        -- Call to System.exitWith
403   | NoMethodError       String          -- A non-existent method was invoked
404   | PatternMatchFail    String          -- A pattern match / guard failure
405   | RecSelError         String          -- Selecting a non-existent field
406   | RecConError         String          -- Field missing in record construction
407   | RecUpdError         String          -- Record doesn't contain updated field
408   | AssertionFailed     String          -- Assertions
409   | DynException        Dynamic         -- Dynamic exceptions
410   | AsyncException      AsyncException  -- Externally generated errors
411   | BlockedOnDeadMVar                   -- Blocking on a dead MVar
412   | Deadlock                            -- no threads can run (raised in main thread)
413   | NonTermination
414
415 data ArithException
416   = Overflow
417   | Underflow
418   | LossOfPrecision
419   | DivideByZero
420   | Denormal
421   deriving (Eq, Ord)
422
423 data AsyncException
424   = StackOverflow
425   | HeapOverflow
426   | ThreadKilled
427   deriving (Eq, Ord)
428
429 data ArrayException
430   = IndexOutOfBounds    String          -- out-of-range array access
431   | UndefinedElement    String          -- evaluating an undefined element
432   deriving (Eq, Ord)
433
434 stackOverflow, heapOverflow :: Exception -- for the RTS
435 stackOverflow = AsyncException StackOverflow
436 heapOverflow  = AsyncException HeapOverflow
437
438 instance Show ArithException where
439   showsPrec _ Overflow        = showString "arithmetic overflow"
440   showsPrec _ Underflow       = showString "arithmetic underflow"
441   showsPrec _ LossOfPrecision = showString "loss of precision"
442   showsPrec _ DivideByZero    = showString "divide by zero"
443   showsPrec _ Denormal        = showString "denormal"
444
445 instance Show AsyncException where
446   showsPrec _ StackOverflow   = showString "stack overflow"
447   showsPrec _ HeapOverflow    = showString "heap overflow"
448   showsPrec _ ThreadKilled    = showString "thread killed"
449
450 instance Show ArrayException where
451   showsPrec _ (IndexOutOfBounds s)
452         = showString "array index out of range"
453         . (if not (null s) then showString ": " . showString s
454                            else id)
455   showsPrec _ (UndefinedElement s)
456         = showString "undefined array element"
457         . (if not (null s) then showString ": " . showString s
458                            else id)
459
460 instance Show Exception where
461   showsPrec _ (IOException err)          = shows err
462   showsPrec _ (ArithException err)       = shows err
463   showsPrec _ (ArrayException err)       = shows err
464   showsPrec _ (ErrorCall err)            = showString err
465   showsPrec _ (ExitException err)        = showString "exit: " . shows err
466   showsPrec _ (NoMethodError err)        = showString err
467   showsPrec _ (PatternMatchFail err)     = showString err
468   showsPrec _ (RecSelError err)          = showString err
469   showsPrec _ (RecConError err)          = showString err
470   showsPrec _ (RecUpdError err)          = showString err
471   showsPrec _ (AssertionFailed err)      = showString err
472   showsPrec _ (DynException _err)        = showString "unknown exception"
473   showsPrec _ (AsyncException e)         = shows e
474   showsPrec _ (BlockedOnDeadMVar)        = showString "thread blocked indefinitely"
475   showsPrec _ (NonTermination)           = showString "<<loop>>"
476   showsPrec _ (Deadlock)                 = showString "<<deadlock>>"
477
478 instance Eq Exception where
479   IOException e1      == IOException e2      = e1 == e2
480   ArithException e1   == ArithException e2   = e1 == e2
481   ArrayException e1   == ArrayException e2   = e1 == e2
482   ErrorCall e1        == ErrorCall e2        = e1 == e2
483   ExitException e1    == ExitException e2    = e1 == e2
484   NoMethodError e1    == NoMethodError e2    = e1 == e2
485   PatternMatchFail e1 == PatternMatchFail e2 = e1 == e2
486   RecSelError e1      == RecSelError e2      = e1 == e2
487   RecConError e1      == RecConError e2      = e1 == e2
488   RecUpdError e1      == RecUpdError e2      = e1 == e2
489   AssertionFailed e1  == AssertionFailed e2  = e1 == e2
490   DynException _      == DynException _      = False -- incomparable
491   AsyncException e1   == AsyncException e2   = e1 == e2
492   BlockedOnDeadMVar   == BlockedOnDeadMVar   = True
493   NonTermination      == NonTermination      = True
494   Deadlock            == Deadlock            = True
495
496 -- -----------------------------------------------------------------------------
497 -- The ExitCode type
498
499 -- The `ExitCode' type defines the exit codes that a program
500 -- can return.  `ExitSuccess' indicates successful termination;
501 -- and `ExitFailure code' indicates program failure
502 -- with value `code'.  The exact interpretation of `code'
503 -- is operating-system dependent.  In particular, some values of 
504 -- `code' may be prohibited (e.g. 0 on a POSIX-compliant system).
505
506 -- We need it here because it is used in ExitException in the
507 -- Exception datatype (above).
508
509 data ExitCode = ExitSuccess | ExitFailure Int 
510                 deriving (Eq, Ord, Read, Show)
511
512 -- --------------------------------------------------------------------------
513 -- Primitive throw
514
515 throw :: Exception -> a
516 throw exception = raise# exception
517
518 ioError         :: Exception -> IO a 
519 ioError err     =  IO $ \s -> throw err s
520
521 ioException     :: IOException -> IO a
522 ioException err =  IO $ \s -> throw (IOException err) s
523
524 -- ---------------------------------------------------------------------------
525 -- IOError type
526
527 -- A value @IOError@ encode errors occurred in the @IO@ monad.
528 -- An @IOError@ records a more specific error type, a descriptive
529 -- string and maybe the handle that was used when the error was
530 -- flagged.
531
532 type IOError = Exception
533
534 data IOException
535  = IOError {
536      ioe_handle   :: Maybe Handle,   -- the handle used by the action flagging 
537                                      -- the error.
538      ioe_type     :: IOErrorType,    -- what it was.
539      ioe_location :: String,         -- location.
540      ioe_descr    :: String,         -- error type specific information.
541      ioe_filename :: Maybe FilePath  -- filename the error is related to.
542    }
543
544 instance Eq IOException where
545   (IOError h1 e1 loc1 str1 fn1) == (IOError h2 e2 loc2 str2 fn2) = 
546     e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && fn1==fn2
547
548 data IOErrorType
549   -- Haskell 98:
550   = AlreadyExists
551   | NoSuchThing
552   | ResourceBusy
553   | ResourceExhausted
554   | EOF
555   | IllegalOperation
556   | PermissionDenied
557   | UserError
558   -- GHC only:
559   | UnsatisfiedConstraints
560   | SystemError
561   | ProtocolError
562   | OtherError
563   | InvalidArgument
564   | InappropriateType
565   | HardwareFault
566   | UnsupportedOperation
567   | TimeExpired
568   | ResourceVanished
569   | Interrupted
570   | DynIOError Dynamic -- cheap&cheerful extensible IO error type.
571
572 instance Eq IOErrorType where
573    x == y = 
574      case x of
575        DynIOError{} -> False -- from a strictness POV, compatible with a derived Eq inst?
576        _ -> getTag# x ==# getTag# y
577  
578 instance Show IOErrorType where
579   showsPrec _ e =
580     showString $
581     case e of
582       AlreadyExists     -> "already exists"
583       NoSuchThing       -> "does not exist"
584       ResourceBusy      -> "resource busy"
585       ResourceExhausted -> "resource exhausted"
586       EOF               -> "end of file"
587       IllegalOperation  -> "illegal operation"
588       PermissionDenied  -> "permission denied"
589       UserError         -> "user error"
590       HardwareFault     -> "hardware fault"
591       InappropriateType -> "inappropriate type"
592       Interrupted       -> "interrupted"
593       InvalidArgument   -> "invalid argument"
594       OtherError        -> "failed"
595       ProtocolError     -> "protocol error"
596       ResourceVanished  -> "resource vanished"
597       SystemError       -> "system error"
598       TimeExpired       -> "timeout"
599       UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise!
600       UnsupportedOperation -> "unsupported operation"
601       DynIOError{}      -> "unknown IO error"
602
603 userError       :: String  -> IOError
604 userError str   =  IOException (IOError Nothing UserError "" str Nothing)
605
606 -- ---------------------------------------------------------------------------
607 -- Showing IOErrors
608
609 instance Show IOException where
610     showsPrec p (IOError hdl iot loc s fn) =
611       showsPrec p iot .
612       (case loc of
613          "" -> id
614          _  -> showString "\nAction: " . showString loc) .
615       (case hdl of
616         Nothing -> id
617         Just h  -> showString "\nHandle: " . showsPrec p h) .
618       (case s of
619          "" -> id
620          _  -> showString "\nReason: " . showString s) .
621       (case fn of
622          Nothing -> id
623          Just name -> showString "\nFile: " . showString name)
624 \end{code}