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(..) )
29 import {-# SOURCE #-} Data.Dynamic
32 -- ---------------------------------------------------------------------------
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.
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:
43 Compiler - types of various primitives in PrimOp.lhs
45 RTS - forceIO (StgMiscClosures.hc)
46 - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast
48 - raiseAsync (Schedule.c)
50 Prelude - GHC.IOBase.lhs, and several other places including
53 Libraries - parts of hslibs/lang.
58 newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #))
60 unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
63 instance Functor IO where
64 fmap f x = x >>= (return . f)
66 instance Monad IO where
70 m >> k = m >>= \ _ -> k
76 failIO :: String -> IO a
77 failIO s = ioError (userError s)
79 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
80 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
82 bindIO :: IO a -> (a -> IO b) -> IO b
83 bindIO (IO m) k = IO ( \ s ->
85 (# new_s, a #) -> unIO (k a) new_s
88 thenIO :: IO a -> IO b -> IO b
89 thenIO (IO m) k = IO ( \ s ->
91 (# new_s, a #) -> unIO k new_s
95 returnIO x = IO (\ s -> (# s, x #))
97 -- ---------------------------------------------------------------------------
98 -- Coercions between IO and ST
100 --stToIO :: (forall s. ST s a) -> IO a
101 stToIO :: ST RealWorld a -> IO a
104 ioToST :: IO a -> ST RealWorld a
105 ioToST (IO m) = (ST m)
107 -- ---------------------------------------------------------------------------
108 -- Unsafe IO operations
111 This is the "back door" into the 'IO' monad, allowing
112 'IO' computation to be performed at any time. For
113 this to be safe, the 'IO' computation should be
114 free of side effects and independent of its environment.
116 If the I\/O computation wrapped in 'unsafePerformIO'
117 performs side effects, then the relative order in which those side
118 effects take place (relative to the main I\/O trunk, or other calls to
119 'unsafePerformIO') is indeterminate.
121 However, it is less well known that
122 'unsafePerformIO' is not type safe. For example:
125 > test = unsafePerformIO $ newIORef []
128 > writeIORef test [42]
129 > bang \<- readIORef test
130 > print (bang :: [Char])
132 This program will core dump. This problem with polymorphic references
133 is well known in the ML community, and does not arise with normal
134 monadic use of references. There is no easy way to make it impossible
135 once you use 'unsafePerformIO'. Indeed, it is
136 possible to write @coerce :: a -> b@ with the
137 help of 'unsafePerformIO'. So be careful!
139 {-# NOINLINE unsafePerformIO #-}
140 unsafePerformIO :: IO a -> a
141 unsafePerformIO (IO m) = case m realWorld# of (# _, r #) -> r
144 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
145 When passed a value of type @IO a@, the 'IO' will only be performed
146 when the value of the @a@ is demanded. This is used to implement lazy
147 file reading, see 'IO.hGetContents'.
149 {-# NOINLINE unsafeInterleaveIO #-}
150 unsafeInterleaveIO :: IO a -> IO a
151 unsafeInterleaveIO (IO m)
153 r = case m s of (# _, res #) -> res
157 -- ---------------------------------------------------------------------------
160 data MVar a = MVar (MVar# RealWorld a)
162 An 'MVar' (pronounced \"em-var\") is a synchronising variable, used
163 for communication between concurrent threads. It can be thought of
164 as a a box, which may be empty or full.
167 -- pull in Eq (Mvar a) too, to avoid GHC.Conc being an orphan-instance module
168 instance Eq (MVar a) where
169 (MVar mvar1#) == (MVar mvar2#) = sameMVar# mvar1# mvar2#
171 -- A Handle is represented by (a reference to) a record
172 -- containing the state of the I/O port/device. We record
173 -- the following pieces of info:
175 -- * type (read,write,closed etc.)
176 -- * the underlying file descriptor
178 -- * buffer, and spare buffers
179 -- * user-friendly name (usually the
180 -- FilePath used when IO.openFile was called)
182 -- Note: when a Handle is garbage collected, we want to flush its buffer
183 -- and close the OS file handle, so as to free up a (precious) resource.
186 = FileHandle -- A normal handle to a file
189 | DuplexHandle -- A handle to a read/write stream
190 !(MVar Handle__) -- The read side
191 !(MVar Handle__) -- The write side
194 -- * A 'FileHandle' is seekable. A 'DuplexHandle' may or may not be
197 instance Eq Handle where
198 (FileHandle h1) == (FileHandle h2) = h1 == h2
199 (DuplexHandle h1 _) == (DuplexHandle h2 _) = h1 == h2
202 type FD = Int -- XXX ToDo: should be CInt
206 haFD :: !FD, -- file descriptor
207 haType :: HandleType, -- type (read/write/append etc.)
208 haIsBin :: Bool, -- binary mode?
209 haIsStream :: Bool, -- is this a stream handle?
210 haBufferMode :: BufferMode, -- buffer contains read/write data?
211 haFilePath :: FilePath, -- file name, possibly
212 haBuffer :: !(IORef Buffer), -- the current buffer
213 haBuffers :: !(IORef BufferList), -- spare buffers
214 haOtherSide :: Maybe (MVar Handle__) -- ptr to the write side of a
218 -- ---------------------------------------------------------------------------
221 -- The buffer is represented by a mutable variable containing a
222 -- record, where the record contains the raw buffer and the start/end
223 -- points of the filled portion. We use a mutable variable so that
224 -- the common operation of writing (or reading) some data from (to)
225 -- the buffer doesn't need to modify, and hence copy, the handle
226 -- itself, it just updates the buffer.
228 -- There will be some allocation involved in a simple hPutChar in
229 -- order to create the new Buffer structure (below), but this is
230 -- relatively small, and this only has to be done once per write
233 -- The buffer contains its size - we could also get the size by
234 -- calling sizeOfMutableByteArray# on the raw buffer, but that tends
235 -- to be rounded up to the nearest Word.
237 type RawBuffer = MutableByteArray# RealWorld
239 -- INVARIANTS on a Buffer:
241 -- * A handle *always* has a buffer, even if it is only 1 character long
242 -- (an unbuffered handle needs a 1 character buffer in order to support
243 -- hLookAhead and hIsEOF).
245 -- * if r == w, then r == 0 && w == 0
246 -- * if state == WriteBuffer, then r == 0
247 -- * a write buffer is never full. If an operation
248 -- fills up the buffer, it will always flush it before
250 -- * a read buffer may be full as a result of hLookAhead. In normal
251 -- operation, a read buffer always has at least one character of space.
259 bufState :: BufferState
262 data BufferState = ReadBuffer | WriteBuffer deriving (Eq)
264 -- we keep a few spare buffers around in a handle to avoid allocating
265 -- a new one for each hPutStr. These buffers are *guaranteed* to be the
266 -- same size as the main buffer.
269 | BufferListCons RawBuffer BufferList
272 bufferIsWritable :: Buffer -> Bool
273 bufferIsWritable Buffer{ bufState=WriteBuffer } = True
274 bufferIsWritable _other = False
276 bufferEmpty :: Buffer -> Bool
277 bufferEmpty Buffer{ bufRPtr=r, bufWPtr=w } = r == w
279 -- only makes sense for a write buffer
280 bufferFull :: Buffer -> Bool
281 bufferFull b@Buffer{ bufWPtr=w } = w >= bufSize b
283 -- Internally, we classify handles as being one
294 isReadableHandleType ReadHandle = True
295 isReadableHandleType ReadWriteHandle = True
296 isReadableHandleType _ = False
298 isWritableHandleType AppendHandle = True
299 isWritableHandleType WriteHandle = True
300 isWritableHandleType ReadWriteHandle = True
301 isWritableHandleType _ = False
303 -- File names are specified using @FilePath@, a OS-dependent
304 -- string that (hopefully, I guess) maps to an accessible file/object.
306 type FilePath = String
308 -- ---------------------------------------------------------------------------
311 -- Three kinds of buffering are supported: line-buffering,
312 -- block-buffering or no-buffering. These modes have the following
313 -- effects. For output, items are written out from the internal
314 -- buffer according to the buffer mode:
316 -- o line-buffering the entire output buffer is written
317 -- out whenever a newline is output, the output buffer overflows,
318 -- a flush is issued, or the handle is closed.
320 -- o block-buffering the entire output buffer is written out whenever
321 -- it overflows, a flush is issued, or the handle
324 -- o no-buffering output is written immediately, and never stored
325 -- in the output buffer.
327 -- The output buffer is emptied as soon as it has been written out.
329 -- Similarly, input occurs according to the buffer mode for handle {\em hdl}.
331 -- o line-buffering when the input buffer for the handle is not empty,
332 -- the next item is obtained from the buffer;
333 -- otherwise, when the input buffer is empty,
334 -- characters up to and including the next newline
335 -- character are read into the buffer. No characters
336 -- are available until the newline character is
339 -- o block-buffering when the input buffer for the handle becomes empty,
340 -- the next block of data is read into this buffer.
342 -- o no-buffering the next input item is read and returned.
344 -- For most implementations, physical files will normally be block-buffered
345 -- and terminals will normally be line-buffered. (the IO interface provides
346 -- operations for changing the default buffering of a handle tho.)
349 = NoBuffering | LineBuffering | BlockBuffering (Maybe Int)
350 deriving (Eq, Ord, Read, Show)
352 -- ---------------------------------------------------------------------------
355 -- |A mutable variable in the 'IO' monad
356 newtype IORef a = IORef (STRef RealWorld a) deriving Eq
358 -- |Build a new 'IORef'
359 newIORef :: a -> IO (IORef a)
360 newIORef v = stToIO (newSTRef v) >>= \ var -> return (IORef var)
362 -- |Read the value of an 'IORef'
363 readIORef :: IORef a -> IO a
364 readIORef (IORef var) = stToIO (readSTRef var)
366 -- |Write a new value into an 'IORef'
367 writeIORef :: IORef a -> a -> IO ()
368 writeIORef (IORef var) v = stToIO (writeSTRef var v)
370 -- ---------------------------------------------------------------------------
371 -- Show instance for Handles
373 -- handle types are 'show'n when printing error msgs, so
374 -- we provide a more user-friendly Show instance for it
375 -- than the derived one.
377 instance Show HandleType where
380 ClosedHandle -> showString "closed"
381 SemiClosedHandle -> showString "semi-closed"
382 ReadHandle -> showString "readable"
383 WriteHandle -> showString "writable"
384 AppendHandle -> showString "writable (append)"
385 ReadWriteHandle -> showString "read-writable"
387 instance Show Handle where
388 showsPrec p (FileHandle h) = showHandle p h False
389 showsPrec p (DuplexHandle _ h) = showHandle p h True
391 showHandle p h duplex =
393 -- (Big) SIGH: unfolded defn of takeMVar to avoid
394 -- an (oh-so) unfortunate module loop with GHC.Conc.
395 hdl_ = unsafePerformIO (IO $ \ s# ->
396 case h of { MVar h# ->
397 case takeMVar# h# s# of { (# s2# , r #) ->
398 case putMVar# h# r s2# of { s3# ->
401 showType | duplex = showString "duplex (read-write)"
402 | otherwise = showsPrec p (haType hdl_)
405 showHdl (haType hdl_)
406 (showString "loc=" . showString (haFilePath hdl_) . showChar ',' .
407 showString "type=" . showType . showChar ',' .
408 showString "binary=" . showsPrec p (haIsBin hdl_) . showChar ',' .
409 showString "buffering=" . showBufMode (unsafePerformIO (readIORef (haBuffer hdl_))) (haBufferMode hdl_) . showString "}" )
412 showHdl :: HandleType -> ShowS -> ShowS
415 ClosedHandle -> showsPrec p ht . showString "}"
418 showBufMode :: Buffer -> BufferMode -> ShowS
419 showBufMode buf bmo =
421 NoBuffering -> showString "none"
422 LineBuffering -> showString "line"
423 BlockBuffering (Just n) -> showString "block " . showParen True (showsPrec p n)
424 BlockBuffering Nothing -> showString "block " . showParen True (showsPrec p def)
429 -- ------------------------------------------------------------------------
430 -- Exception datatype and operations
432 -- |The type of exceptions. Every kind of system-generated exception
433 -- has a constructor in the 'Exception' type, and values of other
434 -- types may be injected into 'Exception' by coercing them to
435 -- 'Dynamic' (see the section on Dynamic Exceptions).
437 -- For backwards compatibility with Haskell 98, 'IOError' is a type synonym
440 = ArithException ArithException
441 -- ^Exceptions raised by arithmetic
442 -- operations. (NOTE: GHC currently does not throw
443 -- 'ArithException's).
444 | ArrayException ArrayException
445 -- ^Exceptions raised by array-related
446 -- operations. (NOTE: GHC currently does not throw
447 -- 'ArrayException's).
448 | AssertionFailed String
449 -- ^This exception is thrown by the
450 -- 'assert' operation when the condition
451 -- fails. The 'String' argument contains the
452 -- location of the assertion in the source program.
453 | AsyncException AsyncException
454 -- ^Asynchronous exceptions (see section on Asynchronous Exceptions).
456 -- ^The current thread was executing a call to
457 -- 'takeMVar' that could never return, because there are no other
458 -- references to this 'MVar'.
460 -- ^There are no runnable threads, so the program is
461 -- deadlocked. The 'Deadlock' exception is
462 -- raised in the main thread only (see also: "Control.Concurrent").
463 | DynException Dynamic
464 -- ^Dynamically typed exceptions (see section on Dynamic Exceptions).
466 -- ^The 'ErrorCall' exception is thrown by 'error'. The 'String'
467 -- argument of 'ErrorCall' is the string passed to 'error' when it was
469 | ExitException ExitCode
470 -- ^The 'ExitException' exception is thrown by 'System.exitWith' (and
471 -- 'System.exitFailure'). The 'ExitCode' argument is the value passed
472 -- to 'System.exitWith'. An unhandled 'ExitException' exception in the
473 -- main thread will cause the program to be terminated with the given
475 | IOException IOException
476 -- ^These are the standard IO exceptions generated by
477 -- Haskell\'s @IO@ operations. See also "System.IO.Error".
478 | NoMethodError String
479 -- ^An attempt was made to invoke a class method which has
480 -- no definition in this instance, and there was no default
481 -- definition given in the class declaration. GHC issues a
482 -- warning when you compile an instance which has missing
485 -- ^The current thread is stuck in an infinite loop. This
486 -- exception may or may not be thrown when the program is
488 | PatternMatchFail String
489 -- ^A pattern matching failure. The 'String' argument should contain a
490 -- descriptive message including the function name, source file
493 -- ^An attempt was made to evaluate a field of a record
494 -- for which no value was given at construction time. The
495 -- 'String' argument gives the location of the
496 -- record construction in the source program.
498 -- ^A field selection was attempted on a constructor that
499 -- doesn\'t have the requested field. This can happen with
500 -- multi-constructor records when one or more fields are
501 -- missing from some of the constructors. The
502 -- 'String' argument gives the location of the
503 -- record selection in the source program.
505 -- ^An attempt was made to update a field in a record,
506 -- where the record doesn\'t have the requested field. This can
507 -- only occur with multi-constructor records, when one or more
508 -- fields are missing from some of the constructors. The
509 -- 'String' argument gives the location of the
510 -- record update in the source program.
512 -- |The type of arithmetic exceptions
522 -- |Asynchronous exceptions
525 -- ^The current thread\'s stack exceeded its limit.
526 -- Since an exception has been raised, the thread\'s stack
527 -- will certainly be below its limit again, but the
528 -- programmer should take remedial action
531 -- ^The program\'s heap is reaching its limit, and
532 -- the program should take action to reduce the amount of
533 -- live data it has. Notes:
535 -- * It is undefined which thread receives this exception.
537 -- * GHC currently does not throw 'HeapOverflow' exceptions.
539 -- ^This exception is raised by another thread
540 -- calling 'killThread', or by the system
541 -- if it needs to terminate the thread for some
545 -- | Exceptions generated by array operations
547 = IndexOutOfBounds String
548 -- ^An attempt was made to index an array outside
549 -- its declared bounds.
550 | UndefinedElement String
551 -- ^An attempt was made to evaluate an element of an
552 -- array that had not been initialized.
555 stackOverflow, heapOverflow :: Exception -- for the RTS
556 stackOverflow = AsyncException StackOverflow
557 heapOverflow = AsyncException HeapOverflow
559 instance Show ArithException where
560 showsPrec _ Overflow = showString "arithmetic overflow"
561 showsPrec _ Underflow = showString "arithmetic underflow"
562 showsPrec _ LossOfPrecision = showString "loss of precision"
563 showsPrec _ DivideByZero = showString "divide by zero"
564 showsPrec _ Denormal = showString "denormal"
566 instance Show AsyncException where
567 showsPrec _ StackOverflow = showString "stack overflow"
568 showsPrec _ HeapOverflow = showString "heap overflow"
569 showsPrec _ ThreadKilled = showString "thread killed"
571 instance Show ArrayException where
572 showsPrec _ (IndexOutOfBounds s)
573 = showString "array index out of range"
574 . (if not (null s) then showString ": " . showString s
576 showsPrec _ (UndefinedElement s)
577 = showString "undefined array element"
578 . (if not (null s) then showString ": " . showString s
581 instance Show Exception where
582 showsPrec _ (IOException err) = shows err
583 showsPrec _ (ArithException err) = shows err
584 showsPrec _ (ArrayException err) = shows err
585 showsPrec _ (ErrorCall err) = showString err
586 showsPrec _ (ExitException err) = showString "exit: " . shows err
587 showsPrec _ (NoMethodError err) = showString err
588 showsPrec _ (PatternMatchFail err) = showString err
589 showsPrec _ (RecSelError err) = showString err
590 showsPrec _ (RecConError err) = showString err
591 showsPrec _ (RecUpdError err) = showString err
592 showsPrec _ (AssertionFailed err) = showString err
593 showsPrec _ (DynException _err) = showString "unknown exception"
594 showsPrec _ (AsyncException e) = shows e
595 showsPrec _ (BlockedOnDeadMVar) = showString "thread blocked indefinitely"
596 showsPrec _ (NonTermination) = showString "<<loop>>"
597 showsPrec _ (Deadlock) = showString "<<deadlock>>"
599 instance Eq Exception where
600 IOException e1 == IOException e2 = e1 == e2
601 ArithException e1 == ArithException e2 = e1 == e2
602 ArrayException e1 == ArrayException e2 = e1 == e2
603 ErrorCall e1 == ErrorCall e2 = e1 == e2
604 ExitException e1 == ExitException e2 = e1 == e2
605 NoMethodError e1 == NoMethodError e2 = e1 == e2
606 PatternMatchFail e1 == PatternMatchFail e2 = e1 == e2
607 RecSelError e1 == RecSelError e2 = e1 == e2
608 RecConError e1 == RecConError e2 = e1 == e2
609 RecUpdError e1 == RecUpdError e2 = e1 == e2
610 AssertionFailed e1 == AssertionFailed e2 = e1 == e2
611 DynException _ == DynException _ = False -- incomparable
612 AsyncException e1 == AsyncException e2 = e1 == e2
613 BlockedOnDeadMVar == BlockedOnDeadMVar = True
614 NonTermination == NonTermination = True
615 Deadlock == Deadlock = True
617 -- -----------------------------------------------------------------------------
620 -- The `ExitCode' type defines the exit codes that a program
621 -- can return. `ExitSuccess' indicates successful termination;
622 -- and `ExitFailure code' indicates program failure
623 -- with value `code'. The exact interpretation of `code'
624 -- is operating-system dependent. In particular, some values of
625 -- `code' may be prohibited (e.g. 0 on a POSIX-compliant system).
627 -- We need it here because it is used in ExitException in the
628 -- Exception datatype (above).
630 data ExitCode = ExitSuccess | ExitFailure Int
631 deriving (Eq, Ord, Read, Show)
633 -- --------------------------------------------------------------------------
636 -- | Throw an exception. Exceptions may be thrown from purely
637 -- functional code, but may only be caught within the 'IO' monad.
638 throw :: Exception -> a
639 throw exception = raise# exception
641 -- | A variant of 'throw' that can be used within the 'IO' monad.
643 -- Although 'ioError' has a type that is an instance of the type of 'throw', the
644 -- two functions are subtly different:
646 -- > throw e `seq` return () ===> throw e
647 -- > ioError e `seq` return () ===> return ()
649 -- The first example will cause the exception @e@ to be raised,
650 -- whereas the second one won\'t. In fact, 'ioError' will only cause
651 -- an exception to be raised when it is used within the 'IO' monad.
652 -- The 'ioError' variant should be used in preference to 'throw' to
653 -- raise an exception within the 'IO' monad because it guarantees
654 -- ordering with respect to other 'IO' operations, whereas 'throw'
656 ioError :: Exception -> IO a
657 ioError err = IO $ \s -> throw err s
659 ioException :: IOException -> IO a
660 ioException err = IO $ \s -> throw (IOException err) s
662 -- ---------------------------------------------------------------------------
665 -- A value @IOError@ encode errors occurred in the @IO@ monad.
666 -- An @IOError@ records a more specific error type, a descriptive
667 -- string and maybe the handle that was used when the error was
670 type IOError = Exception
674 ioe_handle :: Maybe Handle, -- the handle used by the action flagging
676 ioe_type :: IOErrorType, -- what it was.
677 ioe_location :: String, -- location.
678 ioe_descr :: String, -- error type specific information.
679 ioe_filename :: Maybe FilePath -- filename the error is related to.
682 instance Eq IOException where
683 (IOError h1 e1 loc1 str1 fn1) == (IOError h2 e2 loc2 str2 fn2) =
684 e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && fn1==fn2
697 | UnsatisfiedConstraints
704 | UnsupportedOperation
708 | DynIOError Dynamic -- cheap&cheerful extensible IO error type.
710 instance Eq IOErrorType where
713 DynIOError{} -> False -- from a strictness POV, compatible with a derived Eq inst?
714 _ -> getTag# x ==# getTag# y
716 instance Show IOErrorType where
720 AlreadyExists -> "already exists"
721 NoSuchThing -> "does not exist"
722 ResourceBusy -> "resource busy"
723 ResourceExhausted -> "resource exhausted"
725 IllegalOperation -> "illegal operation"
726 PermissionDenied -> "permission denied"
727 UserError -> "user error"
728 HardwareFault -> "hardware fault"
729 InappropriateType -> "inappropriate type"
730 Interrupted -> "interrupted"
731 InvalidArgument -> "invalid argument"
732 OtherError -> "failed"
733 ProtocolError -> "protocol error"
734 ResourceVanished -> "resource vanished"
735 SystemError -> "system error"
736 TimeExpired -> "timeout"
737 UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise!
738 UnsupportedOperation -> "unsupported operation"
739 DynIOError{} -> "unknown IO error"
741 userError :: String -> IOError
742 userError str = IOException (IOError Nothing UserError "" str Nothing)
744 -- ---------------------------------------------------------------------------
747 instance Show IOException where
748 showsPrec p (IOError hdl iot loc s fn) =
752 _ -> showString "\nAction: " . showString loc) .
755 Just h -> showString "\nHandle: " . showsPrec p h) .
758 _ -> showString "\nReason: " . showString s) .
761 Just name -> showString "\nFile: " . showString name)