2 {-# OPTIONS -fno-implicit-prelude #-}
3 -----------------------------------------------------------------------------
6 -- Copyright : (c) The University of Glasgow 1994-2002
7 -- License : see libraries/base/LICENSE
9 -- Maintainer : cvs-ghc@haskell.org
10 -- Stability : internal
11 -- Portability : non-portable (GHC Extensions)
13 -- Definitions for the 'IO' monad and its friends.
15 -----------------------------------------------------------------------------
17 module GHC.IOBase where
22 import GHC.Num -- To get fromInteger etc, needed because of -fno-implicit-prelude
23 import Data.Maybe ( Maybe(..) )
27 import {-# SOURCE #-} Data.Dynamic
29 -- ---------------------------------------------------------------------------
33 The IO Monad is just an instance of the ST monad, where the state is
34 the real world. We use the exception mechanism (in GHC.Exception) to
35 implement IO exceptions.
37 NOTE: The IO representation is deeply wired in to various parts of the
38 system. The following list may or may not be exhaustive:
40 Compiler - types of various primitives in PrimOp.lhs
42 RTS - forceIO (StgMiscClosures.hc)
43 - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast
45 - raiseAsync (Schedule.c)
47 Prelude - GHC.IOBase.lhs, and several other places including
50 Libraries - parts of hslibs/lang.
55 newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #))
57 unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
60 instance Functor IO where
61 fmap f x = x >>= (return . f)
63 instance Monad IO where
67 m >> k = m >>= \ _ -> k
73 failIO :: String -> IO a
74 failIO s = ioError (userError s)
76 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
77 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
79 bindIO :: IO a -> (a -> IO b) -> IO b
80 bindIO (IO m) k = IO ( \ s ->
82 (# new_s, a #) -> unIO (k a) new_s
85 thenIO :: IO a -> IO b -> IO b
86 thenIO (IO m) k = IO ( \ s ->
88 (# new_s, a #) -> unIO k new_s
92 returnIO x = IO (\ s -> (# s, x #))
94 -- ---------------------------------------------------------------------------
95 -- Coercions between IO and ST
97 --stToIO :: (forall s. ST s a) -> IO a
98 stToIO :: ST RealWorld a -> IO a
101 ioToST :: IO a -> ST RealWorld a
102 ioToST (IO m) = (ST m)
104 -- ---------------------------------------------------------------------------
105 -- Unsafe IO operations
107 {-# NOINLINE unsafePerformIO #-}
108 unsafePerformIO :: IO a -> a
109 unsafePerformIO (IO m) = case m realWorld# of (# _, r #) -> r
111 {-# NOINLINE unsafeInterleaveIO #-}
112 unsafeInterleaveIO :: IO a -> IO a
113 unsafeInterleaveIO (IO m)
115 r = case m s of (# _, res #) -> res
119 -- ---------------------------------------------------------------------------
122 data MVar a = MVar (MVar# RealWorld a)
124 -- pull in Eq (Mvar a) too, to avoid GHC.Conc being an orphan-instance module
125 instance Eq (MVar a) where
126 (MVar mvar1#) == (MVar mvar2#) = sameMVar# mvar1# mvar2#
128 -- A Handle is represented by (a reference to) a record
129 -- containing the state of the I/O port/device. We record
130 -- the following pieces of info:
132 -- * type (read,write,closed etc.)
133 -- * the underlying file descriptor
135 -- * buffer, and spare buffers
136 -- * user-friendly name (usually the
137 -- FilePath used when IO.openFile was called)
139 -- Note: when a Handle is garbage collected, we want to flush its buffer
140 -- and close the OS file handle, so as to free up a (precious) resource.
143 = FileHandle -- A normal handle to a file
146 | DuplexHandle -- A handle to a read/write stream
147 !(MVar Handle__) -- The read side
148 !(MVar Handle__) -- The write side
151 -- * A 'FileHandle' is seekable. A 'DuplexHandle' may or may not be
154 instance Eq Handle where
155 (FileHandle h1) == (FileHandle h2) = h1 == h2
156 (DuplexHandle h1 _) == (DuplexHandle h2 _) = h1 == h2
159 type FD = Int -- XXX ToDo: should be CInt
163 haFD :: !FD, -- file descriptor
164 haType :: HandleType, -- type (read/write/append etc.)
165 haIsBin :: Bool, -- binary mode?
166 haIsStream :: Bool, -- is this a stream handle?
167 haBufferMode :: BufferMode, -- buffer contains read/write data?
168 haFilePath :: FilePath, -- file name, possibly
169 haBuffer :: !(IORef Buffer), -- the current buffer
170 haBuffers :: !(IORef BufferList), -- spare buffers
171 haOtherSide :: Maybe (MVar Handle__) -- ptr to the write side of a
175 -- ---------------------------------------------------------------------------
178 -- The buffer is represented by a mutable variable containing a
179 -- record, where the record contains the raw buffer and the start/end
180 -- points of the filled portion. We use a mutable variable so that
181 -- the common operation of writing (or reading) some data from (to)
182 -- the buffer doesn't need to modify, and hence copy, the handle
183 -- itself, it just updates the buffer.
185 -- There will be some allocation involved in a simple hPutChar in
186 -- order to create the new Buffer structure (below), but this is
187 -- relatively small, and this only has to be done once per write
190 -- The buffer contains its size - we could also get the size by
191 -- calling sizeOfMutableByteArray# on the raw buffer, but that tends
192 -- to be rounded up to the nearest Word.
194 type RawBuffer = MutableByteArray# RealWorld
196 -- INVARIANTS on a Buffer:
198 -- * A handle *always* has a buffer, even if it is only 1 character long
199 -- (an unbuffered handle needs a 1 character buffer in order to support
200 -- hLookAhead and hIsEOF).
202 -- * if r == w, then r == 0 && w == 0
203 -- * if state == WriteBuffer, then r == 0
204 -- * a write buffer is never full. If an operation
205 -- fills up the buffer, it will always flush it before
207 -- * a read buffer may be full as a result of hLookAhead. In normal
208 -- operation, a read buffer always has at least one character of space.
216 bufState :: BufferState
219 data BufferState = ReadBuffer | WriteBuffer deriving (Eq)
221 -- we keep a few spare buffers around in a handle to avoid allocating
222 -- a new one for each hPutStr. These buffers are *guaranteed* to be the
223 -- same size as the main buffer.
226 | BufferListCons RawBuffer BufferList
229 bufferIsWritable :: Buffer -> Bool
230 bufferIsWritable Buffer{ bufState=WriteBuffer } = True
231 bufferIsWritable _other = False
233 bufferEmpty :: Buffer -> Bool
234 bufferEmpty Buffer{ bufRPtr=r, bufWPtr=w } = r == w
236 -- only makes sense for a write buffer
237 bufferFull :: Buffer -> Bool
238 bufferFull b@Buffer{ bufWPtr=w } = w >= bufSize b
240 -- Internally, we classify handles as being one
251 isReadableHandleType ReadHandle = True
252 isReadableHandleType ReadWriteHandle = True
253 isReadableHandleType _ = False
255 isWritableHandleType AppendHandle = True
256 isWritableHandleType WriteHandle = True
257 isWritableHandleType ReadWriteHandle = True
258 isWritableHandleType _ = False
260 -- File names are specified using @FilePath@, a OS-dependent
261 -- string that (hopefully, I guess) maps to an accessible file/object.
263 type FilePath = String
265 -- ---------------------------------------------------------------------------
268 -- Three kinds of buffering are supported: line-buffering,
269 -- block-buffering or no-buffering. These modes have the following
270 -- effects. For output, items are written out from the internal
271 -- buffer according to the buffer mode:
273 -- * line-buffering the entire output buffer is written
274 -- out whenever a newline is output, the output buffer overflows,
275 -- a flush is issued, or the handle is closed.
277 -- * block-buffering the entire output buffer is written out whenever
278 -- it overflows, a flush is issued, or the handle
281 -- * no-buffering output is written immediately, and never stored
282 -- in the output buffer.
284 -- The output buffer is emptied as soon as it has been written out.
286 -- Similarly, input occurs according to the buffer mode for handle {\em hdl}.
288 -- * line-buffering when the input buffer for the handle is not empty,
289 -- the next item is obtained from the buffer;
290 -- otherwise, when the input buffer is empty,
291 -- characters up to and including the next newline
292 -- character are read into the buffer. No characters
293 -- are available until the newline character is
296 -- * block-buffering when the input buffer for the handle becomes empty,
297 -- the next block of data is read into this buffer.
299 -- * no-buffering the next input item is read and returned.
301 -- For most implementations, physical files will normally be block-buffered
302 -- and terminals will normally be line-buffered. (the IO interface provides
303 -- operations for changing the default buffering of a handle tho.)
306 = NoBuffering | LineBuffering | BlockBuffering (Maybe Int)
307 deriving (Eq, Ord, Read, Show)
309 -- ---------------------------------------------------------------------------
312 newtype IORef a = IORef (STRef RealWorld a) deriving Eq
314 newIORef :: a -> IO (IORef a)
315 newIORef v = stToIO (newSTRef v) >>= \ var -> return (IORef var)
317 readIORef :: IORef a -> IO a
318 readIORef (IORef var) = stToIO (readSTRef var)
320 writeIORef :: IORef a -> a -> IO ()
321 writeIORef (IORef var) v = stToIO (writeSTRef var v)
323 -- ---------------------------------------------------------------------------
324 -- Show instance for Handles
326 -- handle types are 'show'n when printing error msgs, so
327 -- we provide a more user-friendly Show instance for it
328 -- than the derived one.
330 instance Show HandleType where
333 ClosedHandle -> showString "closed"
334 SemiClosedHandle -> showString "semi-closed"
335 ReadHandle -> showString "readable"
336 WriteHandle -> showString "writable"
337 AppendHandle -> showString "writable (append)"
338 ReadWriteHandle -> showString "read-writable"
340 instance Show Handle where
341 showsPrec p (FileHandle h) = showHandle p h False
342 showsPrec p (DuplexHandle _ h) = showHandle p h True
344 showHandle p h duplex =
346 -- (Big) SIGH: unfolded defn of takeMVar to avoid
347 -- an (oh-so) unfortunate module loop with GHC.Conc.
348 hdl_ = unsafePerformIO (IO $ \ s# ->
349 case h of { MVar h# ->
350 case takeMVar# h# s# of { (# s2# , r #) ->
351 case putMVar# h# r s2# of { s3# ->
354 showType | duplex = showString "duplex (read-write)"
355 | otherwise = showsPrec p (haType hdl_)
358 showHdl (haType hdl_)
359 (showString "loc=" . showString (haFilePath hdl_) . showChar ',' .
360 showString "type=" . showType . showChar ',' .
361 showString "binary=" . showsPrec p (haIsBin hdl_) . showChar ',' .
362 showString "buffering=" . showBufMode (unsafePerformIO (readIORef (haBuffer hdl_))) (haBufferMode hdl_) . showString "}" )
365 showHdl :: HandleType -> ShowS -> ShowS
368 ClosedHandle -> showsPrec p ht . showString "}"
371 showBufMode :: Buffer -> BufferMode -> ShowS
372 showBufMode buf bmo =
374 NoBuffering -> showString "none"
375 LineBuffering -> showString "line"
376 BlockBuffering (Just n) -> showString "block " . showParen True (showsPrec p n)
377 BlockBuffering Nothing -> showString "block " . showParen True (showsPrec p def)
382 -- ------------------------------------------------------------------------
383 -- Exception datatype and operations
386 = IOException IOException -- IO exceptions
387 | ArithException ArithException -- Arithmetic exceptions
388 | ArrayException ArrayException -- Array-related exceptions
389 | ErrorCall String -- Calls to 'error'
390 | ExitException ExitCode -- Call to System.exitWith
391 | NoMethodError String -- A non-existent method was invoked
392 | PatternMatchFail String -- A pattern match / guard failure
393 | RecSelError String -- Selecting a non-existent field
394 | RecConError String -- Field missing in record construction
395 | RecUpdError String -- Record doesn't contain updated field
396 | AssertionFailed String -- Assertions
397 | DynException Dynamic -- Dynamic exceptions
398 | AsyncException AsyncException -- Externally generated errors
399 | BlockedOnDeadMVar -- Blocking on a dead MVar
400 | Deadlock -- no threads can run (raised in main thread)
418 = IndexOutOfBounds String -- out-of-range array access
419 | UndefinedElement String -- evaluating an undefined element
422 stackOverflow, heapOverflow :: Exception -- for the RTS
423 stackOverflow = AsyncException StackOverflow
424 heapOverflow = AsyncException HeapOverflow
426 instance Show ArithException where
427 showsPrec _ Overflow = showString "arithmetic overflow"
428 showsPrec _ Underflow = showString "arithmetic underflow"
429 showsPrec _ LossOfPrecision = showString "loss of precision"
430 showsPrec _ DivideByZero = showString "divide by zero"
431 showsPrec _ Denormal = showString "denormal"
433 instance Show AsyncException where
434 showsPrec _ StackOverflow = showString "stack overflow"
435 showsPrec _ HeapOverflow = showString "heap overflow"
436 showsPrec _ ThreadKilled = showString "thread killed"
438 instance Show ArrayException where
439 showsPrec _ (IndexOutOfBounds s)
440 = showString "array index out of range"
441 . (if not (null s) then showString ": " . showString s
443 showsPrec _ (UndefinedElement s)
444 = showString "undefined array element"
445 . (if not (null s) then showString ": " . showString s
448 instance Show Exception where
449 showsPrec _ (IOException err) = shows err
450 showsPrec _ (ArithException err) = shows err
451 showsPrec _ (ArrayException err) = shows err
452 showsPrec _ (ErrorCall err) = showString err
453 showsPrec _ (ExitException err) = showString "exit: " . shows err
454 showsPrec _ (NoMethodError err) = showString err
455 showsPrec _ (PatternMatchFail err) = showString err
456 showsPrec _ (RecSelError err) = showString err
457 showsPrec _ (RecConError err) = showString err
458 showsPrec _ (RecUpdError err) = showString err
459 showsPrec _ (AssertionFailed err) = showString err
460 showsPrec _ (DynException _err) = showString "unknown exception"
461 showsPrec _ (AsyncException e) = shows e
462 showsPrec _ (BlockedOnDeadMVar) = showString "thread blocked indefinitely"
463 showsPrec _ (NonTermination) = showString "<<loop>>"
464 showsPrec _ (Deadlock) = showString "<<deadlock>>"
466 instance Eq Exception where
467 IOException e1 == IOException e2 = e1 == e2
468 ArithException e1 == ArithException e2 = e1 == e2
469 ArrayException e1 == ArrayException e2 = e1 == e2
470 ErrorCall e1 == ErrorCall e2 = e1 == e2
471 ExitException e1 == ExitException e2 = e1 == e2
472 NoMethodError e1 == NoMethodError e2 = e1 == e2
473 PatternMatchFail e1 == PatternMatchFail e2 = e1 == e2
474 RecSelError e1 == RecSelError e2 = e1 == e2
475 RecConError e1 == RecConError e2 = e1 == e2
476 RecUpdError e1 == RecUpdError e2 = e1 == e2
477 AssertionFailed e1 == AssertionFailed e2 = e1 == e2
478 DynException _ == DynException _ = False -- incomparable
479 AsyncException e1 == AsyncException e2 = e1 == e2
480 BlockedOnDeadMVar == BlockedOnDeadMVar = True
481 NonTermination == NonTermination = True
482 Deadlock == Deadlock = True
484 -- -----------------------------------------------------------------------------
487 -- The `ExitCode' type defines the exit codes that a program
488 -- can return. `ExitSuccess' indicates successful termination;
489 -- and `ExitFailure code' indicates program failure
490 -- with value `code'. The exact interpretation of `code'
491 -- is operating-system dependent. In particular, some values of
492 -- `code' may be prohibited (e.g. 0 on a POSIX-compliant system).
494 -- We need it here because it is used in ExitException in the
495 -- Exception datatype (above).
497 data ExitCode = ExitSuccess | ExitFailure Int
498 deriving (Eq, Ord, Read, Show)
500 -- --------------------------------------------------------------------------
503 throw :: Exception -> a
504 throw exception = raise# exception
506 ioError :: Exception -> IO a
507 ioError err = IO $ \s -> throw err s
509 ioException :: IOException -> IO a
510 ioException err = IO $ \s -> throw (IOException err) s
512 -- ---------------------------------------------------------------------------
515 -- A value @IOError@ encode errors occurred in the @IO@ monad.
516 -- An @IOError@ records a more specific error type, a descriptive
517 -- string and maybe the handle that was used when the error was
520 type IOError = Exception
524 ioe_handle :: Maybe Handle, -- the handle used by the action flagging
526 ioe_type :: IOErrorType, -- what it was.
527 ioe_location :: String, -- location.
528 ioe_descr :: String, -- error type specific information.
529 ioe_filename :: Maybe FilePath -- filename the error is related to.
532 instance Eq IOException where
533 (IOError h1 e1 loc1 str1 fn1) == (IOError h2 e2 loc2 str2 fn2) =
534 e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && fn1==fn2
547 | UnsatisfiedConstraints
554 | UnsupportedOperation
558 | DynIOError Dynamic -- cheap&cheerful extensible IO error type.
560 instance Eq IOErrorType where
563 DynIOError{} -> False -- from a strictness POV, compatible with a derived Eq inst?
564 _ -> getTag# x ==# getTag# y
566 instance Show IOErrorType where
570 AlreadyExists -> "already exists"
571 NoSuchThing -> "does not exist"
572 ResourceBusy -> "resource busy"
573 ResourceExhausted -> "resource exhausted"
575 IllegalOperation -> "illegal operation"
576 PermissionDenied -> "permission denied"
577 UserError -> "user error"
578 HardwareFault -> "hardware fault"
579 InappropriateType -> "inappropriate type"
580 Interrupted -> "interrupted"
581 InvalidArgument -> "invalid argument"
582 OtherError -> "failed"
583 ProtocolError -> "protocol error"
584 ResourceVanished -> "resource vanished"
585 SystemError -> "system error"
586 TimeExpired -> "timeout"
587 UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise!
588 UnsupportedOperation -> "unsupported operation"
589 DynIOError{} -> "unknown IO error"
591 userError :: String -> IOError
592 userError str = IOException (IOError Nothing UserError "" str Nothing)
594 -- ---------------------------------------------------------------------------
597 instance Show IOException where
598 showsPrec p (IOError hdl iot loc s fn) =
602 _ -> showString "\nAction: " . showString loc) .
605 Just h -> showString "\nHandle: " . showsPrec p h) .
608 _ -> showString "\nReason: " . showString s) .
611 Just name -> showString "\nFile: " . showString name)