1 {-# OPTIONS_GHC -funbox-strict-fields #-}
2 {-# LANGUAGE NoImplicitPrelude, BangPatterns, RankNTypes #-}
3 {-# OPTIONS_HADDOCK hide #-}
4 -----------------------------------------------------------------------------
7 -- Copyright : (c) The University of Glasgow 1994-2002
8 -- License : see libraries/base/LICENSE
10 -- Maintainer : cvs-ghc@haskell.org
11 -- Stability : internal
12 -- Portability : non-portable (GHC Extensions)
14 -- Definitions for the 'IO' monad and its friends.
16 -----------------------------------------------------------------------------
20 IO(..), unIO, failIO, liftIO,
21 unsafePerformIO, unsafeInterleaveIO,
22 unsafeDupablePerformIO, unsafeDupableInterleaveIO,
25 -- To and from from ST
26 stToIO, ioToST, unsafeIOToST, unsafeSTToIO,
30 catchException, catchAny, throwIO,
31 mask, mask_, uninterruptibleMask, uninterruptibleMask_,
32 MaskingState(..), getMaskingState,
33 block, unblock, blocked, unsafeUnmask,
34 onException, finally, evaluate
43 import {-# SOURCE #-} GHC.IO.Exception ( userError )
45 -- ---------------------------------------------------------------------------
49 The IO Monad is just an instance of the ST monad, where the state is
50 the real world. We use the exception mechanism (in GHC.Exception) to
51 implement IO exceptions.
53 NOTE: The IO representation is deeply wired in to various parts of the
54 system. The following list may or may not be exhaustive:
56 Compiler - types of various primitives in PrimOp.lhs
58 RTS - forceIO (StgMiscClosures.hc)
59 - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast
61 - raiseAsync (Schedule.c)
63 Prelude - GHC.IO.lhs, and several other places including
66 Libraries - parts of hslibs/lang.
71 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
72 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
74 failIO :: String -> IO a
75 failIO s = IO (raiseIO# (toException (userError s)))
77 -- ---------------------------------------------------------------------------
78 -- Coercions between IO and ST
80 -- | A monad transformer embedding strict state transformers in the 'IO'
81 -- monad. The 'RealWorld' parameter indicates that the internal state
82 -- used by the 'ST' computation is a special one supplied by the 'IO'
83 -- monad, and thus distinct from those used by invocations of 'runST'.
84 stToIO :: ST RealWorld a -> IO a
87 ioToST :: IO a -> ST RealWorld a
88 ioToST (IO m) = (ST m)
90 -- This relies on IO and ST having the same representation modulo the
91 -- constraint on the type of the state
93 unsafeIOToST :: IO a -> ST s a
94 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
96 unsafeSTToIO :: ST s a -> IO a
97 unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
99 -- ---------------------------------------------------------------------------
100 -- Unsafe IO operations
103 This is the \"back door\" into the 'IO' monad, allowing
104 'IO' computation to be performed at any time. For
105 this to be safe, the 'IO' computation should be
106 free of side effects and independent of its environment.
108 If the I\/O computation wrapped in 'unsafePerformIO' performs side
109 effects, then the relative order in which those side effects take
110 place (relative to the main I\/O trunk, or other calls to
111 'unsafePerformIO') is indeterminate. Furthermore, when using
112 'unsafePerformIO' to cause side-effects, you should take the following
113 precautions to ensure the side effects are performed as many times as
114 you expect them to be. Note that these precautions are necessary for
115 GHC, but may not be sufficient, and other compilers may require
116 different precautions:
118 * Use @{\-\# NOINLINE foo \#-\}@ as a pragma on any function @foo@
119 that calls 'unsafePerformIO'. If the call is inlined,
120 the I\/O may be performed more than once.
122 * Use the compiler flag @-fno-cse@ to prevent common sub-expression
123 elimination being performed on the module, which might combine
124 two side effects that were meant to be separate. A good example
125 is using multiple global variables (like @test@ in the example below).
127 * Make sure that the either you switch off let-floating (@-fno-full-laziness@), or that the
128 call to 'unsafePerformIO' cannot float outside a lambda. For example,
131 f x = unsafePerformIO (newIORef [])
133 you may get only one reference cell shared between all calls to @f@.
136 f x = unsafePerformIO (newIORef [x])
138 because now it can't float outside the lambda.
140 It is less well known that
141 'unsafePerformIO' is not type safe. For example:
144 > test = unsafePerformIO $ newIORef []
147 > writeIORef test [42]
148 > bang <- readIORef test
149 > print (bang :: [Char])
151 This program will core dump. This problem with polymorphic references
152 is well known in the ML community, and does not arise with normal
153 monadic use of references. There is no easy way to make it impossible
154 once you use 'unsafePerformIO'. Indeed, it is
155 possible to write @coerce :: a -> b@ with the
156 help of 'unsafePerformIO'. So be careful!
158 unsafePerformIO :: IO a -> a
159 unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)
162 This version of 'unsafePerformIO' is slightly more efficient,
163 because it omits the check that the IO is only being performed by a
164 single thread. Hence, when you write 'unsafeDupablePerformIO',
165 there is a possibility that the IO action may be performed multiple
166 times (on a multiprocessor), and you should therefore ensure that
167 it gives the same results each time.
169 {-# NOINLINE unsafeDupablePerformIO #-}
170 unsafeDupablePerformIO :: IO a -> a
171 unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
173 -- Why do we NOINLINE unsafeDupablePerformIO? See the comment with
174 -- GHC.ST.runST. Essentially the issue is that the IO computation
175 -- inside unsafePerformIO must be atomic: it must either all run, or
176 -- not at all. If we let the compiler see the application of the IO
177 -- to realWorld#, it might float out part of the IO.
179 -- Why is there a call to 'lazy' in unsafeDupablePerformIO?
180 -- If we don't have it, the demand analyser discovers the following strictness
181 -- for unsafeDupablePerformIO: C(U(AV))
183 -- unsafeDupablePerformIO (\s -> let r = f x in
184 -- case writeIORef v r s of (# s1, _ #) ->
186 -- The strictness analyser will find that the binding for r is strict,
187 -- (becuase of uPIO's strictness sig), and so it'll evaluate it before
188 -- doing the writeIORef. This actually makes tests/lib/should_run/memo002
191 -- Solution: don't expose the strictness of unsafeDupablePerformIO,
192 -- by hiding it with 'lazy'
195 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
196 When passed a value of type @IO a@, the 'IO' will only be performed
197 when the value of the @a@ is demanded. This is used to implement lazy
198 file reading, see 'System.IO.hGetContents'.
200 {-# INLINE unsafeInterleaveIO #-}
201 unsafeInterleaveIO :: IO a -> IO a
202 unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)
204 -- We believe that INLINE on unsafeInterleaveIO is safe, because the
205 -- state from this IO thread is passed explicitly to the interleaved
206 -- IO, so it cannot be floated out and shared.
208 {-# INLINE unsafeDupableInterleaveIO #-}
209 unsafeDupableInterleaveIO :: IO a -> IO a
210 unsafeDupableInterleaveIO (IO m)
212 r = case m s of (# _, res #) -> res
217 Ensures that the suspensions under evaluation by the current thread
218 are unique; that is, the current thread is not evaluating anything
219 that is also under evaluation by another thread that has also executed
222 This operation is used in the definition of 'unsafePerformIO' to
223 prevent the IO action from being executed multiple times, which is usually
227 noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)
229 -- -----------------------------------------------------------------------------
230 -- | File and directory names are values of type 'String', whose precise
231 -- meaning is operating system dependent. Files can be opened, yielding a
232 -- handle which can then be used to operate on the contents of that file.
234 type FilePath = String
236 -- -----------------------------------------------------------------------------
237 -- Primitive catch and throwIO
240 catchException used to handle the passing around of the state to the
241 action and the handler. This turned out to be a bad idea - it meant
242 that we had to wrap both arguments in thunks so they could be entered
243 as normal (remember IO returns an unboxed pair...).
247 catch# :: IO a -> (b -> IO a) -> IO a
249 (well almost; the compiler doesn't know about the IO newtype so we
250 have to work around that in the definition of catchException below).
253 catchException :: Exception e => IO a -> (e -> IO a) -> IO a
254 catchException (IO io) handler = IO $ catch# io handler'
255 where handler' e = case fromException e of
256 Just e' -> unIO (handler e')
257 Nothing -> raiseIO# e
259 catchAny :: IO a -> (forall e . Exception e => e -> IO a) -> IO a
260 catchAny (IO io) handler = IO $ catch# io handler'
261 where handler' (SomeException e) = unIO (handler e)
263 -- | A variant of 'throw' that can only be used within the 'IO' monad.
265 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
266 -- two functions are subtly different:
268 -- > throw e `seq` x ===> throw e
269 -- > throwIO e `seq` x ===> x
271 -- The first example will cause the exception @e@ to be raised,
272 -- whereas the second one won\'t. In fact, 'throwIO' will only cause
273 -- an exception to be raised when it is used within the 'IO' monad.
274 -- The 'throwIO' variant should be used in preference to 'throw' to
275 -- raise an exception within the 'IO' monad because it guarantees
276 -- ordering with respect to other 'IO' operations, whereas 'throw'
278 throwIO :: Exception e => e -> IO a
279 throwIO e = IO (raiseIO# (toException e))
281 -- -----------------------------------------------------------------------------
282 -- Controlling asynchronous exception delivery
284 {-# DEPRECATED block "use Control.Exception.mask instead" #-}
285 -- | Note: this function is deprecated, please use 'mask' instead.
287 -- Applying 'block' to a computation will
288 -- execute that computation with asynchronous exceptions
289 -- /blocked/. That is, any thread which
290 -- attempts to raise an exception in the current thread with 'Control.Exception.throwTo' will be
291 -- blocked until asynchronous exceptions are unblocked again. There\'s
292 -- no need to worry about re-enabling asynchronous exceptions; that is
293 -- done automatically on exiting the scope of
296 -- Threads created by 'Control.Concurrent.forkIO' inherit the blocked
297 -- state from the parent; that is, to start a thread in blocked mode,
298 -- use @block $ forkIO ...@. This is particularly useful if you need to
299 -- establish an exception handler in the forked thread before any
300 -- asynchronous exceptions are received.
301 block :: IO a -> IO a
302 block (IO io) = IO $ maskAsyncExceptions# io
304 {-# DEPRECATED unblock "use Control.Exception.mask instead" #-}
305 -- | Note: this function is deprecated, please use 'mask' instead.
307 -- To re-enable asynchronous exceptions inside the scope of
308 -- 'block', 'unblock' can be
309 -- used. It scopes in exactly the same way, so on exit from
310 -- 'unblock' asynchronous exception delivery will
311 -- be disabled again.
312 unblock :: IO a -> IO a
313 unblock = unsafeUnmask
315 unsafeUnmask :: IO a -> IO a
316 unsafeUnmask (IO io) = IO $ unmaskAsyncExceptions# io
318 blockUninterruptible :: IO a -> IO a
319 blockUninterruptible (IO io) = IO $ maskUninterruptible# io
321 -- | Describes the behaviour of a thread when an asynchronous
322 -- exception is received.
324 = Unmasked -- ^ asynchronous exceptions are unmasked (the normal state)
325 | MaskedInterruptible
326 -- ^ the state during 'mask': asynchronous exceptions are masked, but blocking operations may still be interrupted
327 | MaskedUninterruptible
328 -- ^ the state during 'uninterruptibleMask': asynchronous exceptions are masked, and blocking operations may not be interrupted
331 -- | Returns the 'MaskingState' for the current thread.
332 getMaskingState :: IO MaskingState
333 getMaskingState = IO $ \s ->
334 case getMaskingState# s of
335 (# s', i #) -> (# s', case i of
337 1# -> MaskedUninterruptible
338 _ -> MaskedInterruptible #)
340 -- | returns True if asynchronous exceptions are blocked in the
343 blocked = fmap (/= Unmasked) getMaskingState
345 onException :: IO a -> IO b -> IO a
346 onException io what = io `catchException` \e -> do _ <- what
347 throwIO (e :: SomeException)
349 -- | Executes an IO computation with asynchronous
350 -- exceptions /masked/. That is, any thread which attempts to raise
351 -- an exception in the current thread with 'Control.Exception.throwTo'
352 -- will be blocked until asynchronous exceptions are unmasked again.
354 -- The argument passed to 'mask' is a function that takes as its
355 -- argument another function, which can be used to restore the
356 -- prevailing masking state within the context of the masked
357 -- computation. For example, a common way to use 'mask' is to protect
358 -- the acquisition of a resource:
360 -- > mask $ \restore -> do
362 -- > restore (do_something_with x) `onException` release
365 -- This code guarantees that @acquire@ is paired with @release@, by masking
366 -- asynchronous exceptions for the critical parts. (Rather than write
367 -- this code yourself, it would be better to use
368 -- 'Control.Exception.bracket' which abstracts the general pattern).
370 -- Note that the @restore@ action passed to the argument to 'mask'
371 -- does not necessarily unmask asynchronous exceptions, it just
372 -- restores the masking state to that of the enclosing context. Thus
373 -- if asynchronous exceptions are already masked, 'mask' cannot be used
374 -- to unmask exceptions again. This is so that if you call a library function
375 -- with exceptions masked, you can be sure that the library call will not be
376 -- able to unmask exceptions again. If you are writing library code and need
377 -- to use asynchronous exceptions, the only way is to create a new thread;
378 -- see 'Control.Concurrent.forkIOUnmasked'.
380 -- Asynchronous exceptions may still be received while in the masked
381 -- state if the masked thread /blocks/ in certain ways; see
382 -- "Control.Exception#interruptible".
384 -- Threads created by 'Control.Concurrent.forkIO' inherit the masked
385 -- state from the parent; that is, to start a thread in blocked mode,
386 -- use @mask_ $ forkIO ...@. This is particularly useful if you need
387 -- to establish an exception handler in the forked thread before any
388 -- asynchronous exceptions are received. To create a a new thread in
389 -- an unmasked state use 'Control.Concurrent.forkIOUnmasked'.
391 mask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
393 -- | Like 'mask', but does not pass a @restore@ action to the argument.
394 mask_ :: IO a -> IO a
396 -- | Like 'mask', but the masked computation is not interruptible (see
397 -- "Control.Exception#interruptible"). THIS SHOULD BE USED WITH
398 -- GREAT CARE, because if a thread executing in 'uninterruptibleMask'
399 -- blocks for any reason, then the thread (and possibly the program,
400 -- if this is the main thread) will be unresponsive and unkillable.
401 -- This function should only be necessary if you need to mask
402 -- exceptions around an interruptible operation, and you can guarantee
403 -- that the interruptible operation will only block for a short period
406 uninterruptibleMask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
408 -- | Like 'uninterruptibleMask', but does not pass a @restore@ action
410 uninterruptibleMask_ :: IO a -> IO a
412 mask_ io = mask $ \_ -> io
417 Unmasked -> block $ io unblock
420 uninterruptibleMask_ io = uninterruptibleMask $ \_ -> io
422 uninterruptibleMask io = do
425 Unmasked -> blockUninterruptible $ io unblock
426 MaskedInterruptible -> blockUninterruptible $ io block
427 MaskedUninterruptible -> io id
429 finally :: IO a -- ^ computation to run first
430 -> IO b -- ^ computation to run afterward (even if an exception
432 -> IO a -- returns the value from the first computation
434 mask $ \restore -> do
435 r <- restore a `onException` sequel
439 -- | Forces its argument to be evaluated to weak head normal form when
440 -- the resultant 'IO' action is executed. It can be used to order
441 -- evaluation with respect to other 'IO' operations; its semantics are
444 -- > evaluate x `seq` y ==> y
445 -- > evaluate x `catch` f ==> (return $! x) `catch` f
446 -- > evaluate x >>= f ==> (return $! x) >>= f
448 -- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
449 -- same as @(return $! x)@. A correct definition is
451 -- > evaluate x = (return $! x) >>= return
453 evaluate :: a -> IO a
454 evaluate a = IO $ \s -> let !va = a in (# s, va #) -- NB. see #2273