base: Update `@since 4.8.2` annotations (re #11026)
[ghc.git] / libraries / base / GHC / IO.hs
1 {-# LANGUAGE Unsafe #-}
2 {-# LANGUAGE NoImplicitPrelude
3 , BangPatterns
4 , RankNTypes
5 , MagicHash
6 , UnboxedTuples
7 #-}
8 {-# OPTIONS_GHC -funbox-strict-fields #-}
9 {-# OPTIONS_HADDOCK hide #-}
10
11 -----------------------------------------------------------------------------
12 -- |
13 -- Module : GHC.IO
14 -- Copyright : (c) The University of Glasgow 1994-2002
15 -- License : see libraries/base/LICENSE
16 --
17 -- Maintainer : cvs-ghc@haskell.org
18 -- Stability : internal
19 -- Portability : non-portable (GHC Extensions)
20 --
21 -- Definitions for the 'IO' monad and its friends.
22 --
23 -----------------------------------------------------------------------------
24
25 module GHC.IO (
26 IO(..), unIO, failIO, liftIO,
27 unsafePerformIO, unsafeInterleaveIO,
28 unsafeDupablePerformIO, unsafeDupableInterleaveIO,
29 noDuplicate,
30
31 -- To and from from ST
32 stToIO, ioToST, unsafeIOToST, unsafeSTToIO,
33
34 FilePath,
35
36 catchException, catchAny, throwIO,
37 mask, mask_, uninterruptibleMask, uninterruptibleMask_,
38 MaskingState(..), getMaskingState,
39 unsafeUnmask, interruptible,
40 onException, bracket, finally, evaluate
41 ) where
42
43 import GHC.Base
44 import GHC.ST
45 import GHC.Exception
46 import GHC.Show
47
48 import {-# SOURCE #-} GHC.IO.Exception ( userError )
49
50 -- ---------------------------------------------------------------------------
51 -- The IO Monad
52
53 {-
54 The IO Monad is just an instance of the ST monad, where the state is
55 the real world. We use the exception mechanism (in GHC.Exception) to
56 implement IO exceptions.
57
58 NOTE: The IO representation is deeply wired in to various parts of the
59 system. The following list may or may not be exhaustive:
60
61 Compiler - types of various primitives in PrimOp.lhs
62
63 RTS - forceIO (StgMiscClosures.hc)
64 - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast
65 (Exceptions.hc)
66 - raiseAsync (Schedule.c)
67
68 Prelude - GHC.IO.lhs, and several other places including
69 GHC.Exception.lhs.
70
71 Libraries - parts of hslibs/lang.
72
73 --SDM
74 -}
75
76 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
77 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
78
79 failIO :: String -> IO a
80 failIO s = IO (raiseIO# (toException (userError s)))
81
82 -- ---------------------------------------------------------------------------
83 -- Coercions between IO and ST
84
85 -- | A monad transformer embedding strict state transformers in the 'IO'
86 -- monad. The 'RealWorld' parameter indicates that the internal state
87 -- used by the 'ST' computation is a special one supplied by the 'IO'
88 -- monad, and thus distinct from those used by invocations of 'runST'.
89 stToIO :: ST RealWorld a -> IO a
90 stToIO (ST m) = IO m
91
92 ioToST :: IO a -> ST RealWorld a
93 ioToST (IO m) = (ST m)
94
95 -- This relies on IO and ST having the same representation modulo the
96 -- constraint on the type of the state
97 --
98 unsafeIOToST :: IO a -> ST s a
99 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
100
101 unsafeSTToIO :: ST s a -> IO a
102 unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
103
104 -- ---------------------------------------------------------------------------
105 -- Unsafe IO operations
106
107 {-|
108 This is the \"back door\" into the 'IO' monad, allowing
109 'IO' computation to be performed at any time. For
110 this to be safe, the 'IO' computation should be
111 free of side effects and independent of its environment.
112
113 If the I\/O computation wrapped in 'unsafePerformIO' performs side
114 effects, then the relative order in which those side effects take
115 place (relative to the main I\/O trunk, or other calls to
116 'unsafePerformIO') is indeterminate. Furthermore, when using
117 'unsafePerformIO' to cause side-effects, you should take the following
118 precautions to ensure the side effects are performed as many times as
119 you expect them to be. Note that these precautions are necessary for
120 GHC, but may not be sufficient, and other compilers may require
121 different precautions:
122
123 * Use @{\-\# NOINLINE foo \#-\}@ as a pragma on any function @foo@
124 that calls 'unsafePerformIO'. If the call is inlined,
125 the I\/O may be performed more than once.
126
127 * Use the compiler flag @-fno-cse@ to prevent common sub-expression
128 elimination being performed on the module, which might combine
129 two side effects that were meant to be separate. A good example
130 is using multiple global variables (like @test@ in the example below).
131
132 * Make sure that the either you switch off let-floating (@-fno-full-laziness@), or that the
133 call to 'unsafePerformIO' cannot float outside a lambda. For example,
134 if you say:
135 @
136 f x = unsafePerformIO (newIORef [])
137 @
138 you may get only one reference cell shared between all calls to @f@.
139 Better would be
140 @
141 f x = unsafePerformIO (newIORef [x])
142 @
143 because now it can't float outside the lambda.
144
145 It is less well known that
146 'unsafePerformIO' is not type safe. For example:
147
148 > test :: IORef [a]
149 > test = unsafePerformIO $ newIORef []
150 >
151 > main = do
152 > writeIORef test [42]
153 > bang <- readIORef test
154 > print (bang :: [Char])
155
156 This program will core dump. This problem with polymorphic references
157 is well known in the ML community, and does not arise with normal
158 monadic use of references. There is no easy way to make it impossible
159 once you use 'unsafePerformIO'. Indeed, it is
160 possible to write @coerce :: a -> b@ with the
161 help of 'unsafePerformIO'. So be careful!
162 -}
163 unsafePerformIO :: IO a -> a
164 unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)
165
166 {-|
167 This version of 'unsafePerformIO' is more efficient
168 because it omits the check that the IO is only being performed by a
169 single thread. Hence, when you use 'unsafeDupablePerformIO',
170 there is a possibility that the IO action may be performed multiple
171 times (on a multiprocessor), and you should therefore ensure that
172 it gives the same results each time. It may even happen that one
173 of the duplicated IO actions is only run partially, and then interrupted
174 in the middle without an exception being raised. Therefore, functions
175 like 'bracket' cannot be used safely within 'unsafeDupablePerformIO'.
176
177 @since 4.4.0.0
178 -}
179 {-# NOINLINE unsafeDupablePerformIO #-}
180 -- See Note [unsafeDupablePerformIO is NOINLINE]
181 unsafeDupablePerformIO :: IO a -> a
182 unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
183 -- See Note [unsafeDupablePerformIO has a lazy RHS]
184
185 -- Note [unsafeDupablePerformIO is NOINLINE]
186 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
187 -- Why do we NOINLINE unsafeDupablePerformIO? See the comment with
188 -- GHC.ST.runST. Essentially the issue is that the IO computation
189 -- inside unsafePerformIO must be atomic: it must either all run, or
190 -- not at all. If we let the compiler see the application of the IO
191 -- to realWorld#, it might float out part of the IO.
192
193 -- Note [unsafeDupablePerformIO has a lazy RHS]
194 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
195 -- Why is there a call to 'lazy' in unsafeDupablePerformIO?
196 -- If we don't have it, the demand analyser discovers the following strictness
197 -- for unsafeDupablePerformIO: C(U(AV))
198 -- But then consider
199 -- unsafeDupablePerformIO (\s -> let r = f x in
200 -- case writeIORef v r s of (# s1, _ #) ->
201 -- (# s1, r #) )
202 -- The strictness analyser will find that the binding for r is strict,
203 -- (because of uPIO's strictness sig), and so it'll evaluate it before
204 -- doing the writeIORef. This actually makes libraries/base/tests/memo002
205 -- get a deadlock, where we specifically wanted to write a lazy thunk
206 -- into the ref cell.
207 --
208 -- Solution: don't expose the strictness of unsafeDupablePerformIO,
209 -- by hiding it with 'lazy'
210 -- But see discussion in Trac #9390 (comment:33)
211
212 {-|
213 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
214 When passed a value of type @IO a@, the 'IO' will only be performed
215 when the value of the @a@ is demanded. This is used to implement lazy
216 file reading, see 'System.IO.hGetContents'.
217 -}
218 {-# INLINE unsafeInterleaveIO #-}
219 unsafeInterleaveIO :: IO a -> IO a
220 unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)
221
222 -- We used to believe that INLINE on unsafeInterleaveIO was safe,
223 -- because the state from this IO thread is passed explicitly to the
224 -- interleaved IO, so it cannot be floated out and shared.
225 --
226 -- HOWEVER, if the compiler figures out that r is used strictly here,
227 -- then it will eliminate the thunk and the side effects in m will no
228 -- longer be shared in the way the programmer was probably expecting,
229 -- but can be performed many times. In #5943, this broke our
230 -- definition of fixIO, which contains
231 --
232 -- ans <- unsafeInterleaveIO (takeMVar m)
233 --
234 -- after inlining, we lose the sharing of the takeMVar, so the second
235 -- time 'ans' was demanded we got a deadlock. We could fix this with
236 -- a readMVar, but it seems wrong for unsafeInterleaveIO to sometimes
237 -- share and sometimes not (plus it probably breaks the noDuplicate).
238 -- So now, we do not inline unsafeDupableInterleaveIO.
239
240 {-# NOINLINE unsafeDupableInterleaveIO #-}
241 unsafeDupableInterleaveIO :: IO a -> IO a
242 unsafeDupableInterleaveIO (IO m)
243 = IO ( \ s -> let
244 r = case m s of (# _, res #) -> res
245 in
246 (# s, r #))
247
248 {-|
249 Ensures that the suspensions under evaluation by the current thread
250 are unique; that is, the current thread is not evaluating anything
251 that is also under evaluation by another thread that has also executed
252 'noDuplicate'.
253
254 This operation is used in the definition of 'unsafePerformIO' to
255 prevent the IO action from being executed multiple times, which is usually
256 undesirable.
257 -}
258 noDuplicate :: IO ()
259 noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)
260
261 -- -----------------------------------------------------------------------------
262 -- | File and directory names are values of type 'String', whose precise
263 -- meaning is operating system dependent. Files can be opened, yielding a
264 -- handle which can then be used to operate on the contents of that file.
265
266 type FilePath = String
267
268 -- -----------------------------------------------------------------------------
269 -- Primitive catch and throwIO
270
271 {-
272 catchException used to handle the passing around of the state to the
273 action and the handler. This turned out to be a bad idea - it meant
274 that we had to wrap both arguments in thunks so they could be entered
275 as normal (remember IO returns an unboxed pair...).
276
277 Now catch# has type
278
279 catch# :: IO a -> (b -> IO a) -> IO a
280
281 (well almost; the compiler doesn't know about the IO newtype so we
282 have to work around that in the definition of catchException below).
283 -}
284
285 catchException :: Exception e => IO a -> (e -> IO a) -> IO a
286 catchException (IO io) handler = IO $ catch# io handler'
287 where handler' e = case fromException e of
288 Just e' -> unIO (handler e')
289 Nothing -> raiseIO# e
290
291 catchAny :: IO a -> (forall e . Exception e => e -> IO a) -> IO a
292 catchAny (IO io) handler = IO $ catch# io handler'
293 where handler' (SomeException e) = unIO (handler e)
294
295 -- | A variant of 'throw' that can only be used within the 'IO' monad.
296 --
297 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
298 -- two functions are subtly different:
299 --
300 -- > throw e `seq` x ===> throw e
301 -- > throwIO e `seq` x ===> x
302 --
303 -- The first example will cause the exception @e@ to be raised,
304 -- whereas the second one won\'t. In fact, 'throwIO' will only cause
305 -- an exception to be raised when it is used within the 'IO' monad.
306 -- The 'throwIO' variant should be used in preference to 'throw' to
307 -- raise an exception within the 'IO' monad because it guarantees
308 -- ordering with respect to other 'IO' operations, whereas 'throw'
309 -- does not.
310 throwIO :: Exception e => e -> IO a
311 throwIO e = IO (raiseIO# (toException e))
312
313 -- -----------------------------------------------------------------------------
314 -- Controlling asynchronous exception delivery
315
316 -- Applying 'block' to a computation will
317 -- execute that computation with asynchronous exceptions
318 -- /blocked/. That is, any thread which
319 -- attempts to raise an exception in the current thread with 'Control.Exception.throwTo' will be
320 -- blocked until asynchronous exceptions are unblocked again. There\'s
321 -- no need to worry about re-enabling asynchronous exceptions; that is
322 -- done automatically on exiting the scope of
323 -- 'block'.
324 --
325 -- Threads created by 'Control.Concurrent.forkIO' inherit the blocked
326 -- state from the parent; that is, to start a thread in blocked mode,
327 -- use @block $ forkIO ...@. This is particularly useful if you need to
328 -- establish an exception handler in the forked thread before any
329 -- asynchronous exceptions are received.
330 block :: IO a -> IO a
331 block (IO io) = IO $ maskAsyncExceptions# io
332
333 -- To re-enable asynchronous exceptions inside the scope of
334 -- 'block', 'unblock' can be
335 -- used. It scopes in exactly the same way, so on exit from
336 -- 'unblock' asynchronous exception delivery will
337 -- be disabled again.
338 unblock :: IO a -> IO a
339 unblock = unsafeUnmask
340
341 unsafeUnmask :: IO a -> IO a
342 unsafeUnmask (IO io) = IO $ unmaskAsyncExceptions# io
343
344 -- | Allow asynchronous exceptions to be raised even inside 'mask', making
345 -- the operation interruptible (see the discussion of "Interruptible operations"
346 -- in 'Control.Exception').
347 --
348 -- When called outside 'mask', or inside 'uninterruptibleMask', this
349 -- function has no effect.
350 --
351 -- @since 4.9.0.0
352 interruptible :: IO a -> IO a
353 interruptible act = do
354 st <- getMaskingState
355 case st of
356 Unmasked -> act
357 MaskedInterruptible -> unsafeUnmask act
358 MaskedUninterruptible -> act
359
360 blockUninterruptible :: IO a -> IO a
361 blockUninterruptible (IO io) = IO $ maskUninterruptible# io
362
363 -- | Describes the behaviour of a thread when an asynchronous
364 -- exception is received.
365 data MaskingState
366 = Unmasked -- ^ asynchronous exceptions are unmasked (the normal state)
367 | MaskedInterruptible
368 -- ^ the state during 'mask': asynchronous exceptions are masked, but blocking operations may still be interrupted
369 | MaskedUninterruptible
370 -- ^ the state during 'uninterruptibleMask': asynchronous exceptions are masked, and blocking operations may not be interrupted
371 deriving (Eq,Show)
372
373 -- | Returns the 'MaskingState' for the current thread.
374 getMaskingState :: IO MaskingState
375 getMaskingState = IO $ \s ->
376 case getMaskingState# s of
377 (# s', i #) -> (# s', case i of
378 0# -> Unmasked
379 1# -> MaskedUninterruptible
380 _ -> MaskedInterruptible #)
381
382 onException :: IO a -> IO b -> IO a
383 onException io what = io `catchException` \e -> do _ <- what
384 throwIO (e :: SomeException)
385
386 -- | Executes an IO computation with asynchronous
387 -- exceptions /masked/. That is, any thread which attempts to raise
388 -- an exception in the current thread with 'Control.Exception.throwTo'
389 -- will be blocked until asynchronous exceptions are unmasked again.
390 --
391 -- The argument passed to 'mask' is a function that takes as its
392 -- argument another function, which can be used to restore the
393 -- prevailing masking state within the context of the masked
394 -- computation. For example, a common way to use 'mask' is to protect
395 -- the acquisition of a resource:
396 --
397 -- > mask $ \restore -> do
398 -- > x <- acquire
399 -- > restore (do_something_with x) `onException` release
400 -- > release
401 --
402 -- This code guarantees that @acquire@ is paired with @release@, by masking
403 -- asynchronous exceptions for the critical parts. (Rather than write
404 -- this code yourself, it would be better to use
405 -- 'Control.Exception.bracket' which abstracts the general pattern).
406 --
407 -- Note that the @restore@ action passed to the argument to 'mask'
408 -- does not necessarily unmask asynchronous exceptions, it just
409 -- restores the masking state to that of the enclosing context. Thus
410 -- if asynchronous exceptions are already masked, 'mask' cannot be used
411 -- to unmask exceptions again. This is so that if you call a library function
412 -- with exceptions masked, you can be sure that the library call will not be
413 -- able to unmask exceptions again. If you are writing library code and need
414 -- to use asynchronous exceptions, the only way is to create a new thread;
415 -- see 'Control.Concurrent.forkIOWithUnmask'.
416 --
417 -- Asynchronous exceptions may still be received while in the masked
418 -- state if the masked thread /blocks/ in certain ways; see
419 -- "Control.Exception#interruptible".
420 --
421 -- Threads created by 'Control.Concurrent.forkIO' inherit the
422 -- 'MaskingState' from the parent; that is, to start a thread in the
423 -- 'MaskedInterruptible' state,
424 -- use @mask_ $ forkIO ...@. This is particularly useful if you need
425 -- to establish an exception handler in the forked thread before any
426 -- asynchronous exceptions are received. To create a a new thread in
427 -- an unmasked state use 'Control.Concurrent.forkIOUnmasked'.
428 --
429 mask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
430
431 -- | Like 'mask', but does not pass a @restore@ action to the argument.
432 mask_ :: IO a -> IO a
433
434 -- | Like 'mask', but the masked computation is not interruptible (see
435 -- "Control.Exception#interruptible"). THIS SHOULD BE USED WITH
436 -- GREAT CARE, because if a thread executing in 'uninterruptibleMask'
437 -- blocks for any reason, then the thread (and possibly the program,
438 -- if this is the main thread) will be unresponsive and unkillable.
439 -- This function should only be necessary if you need to mask
440 -- exceptions around an interruptible operation, and you can guarantee
441 -- that the interruptible operation will only block for a short period
442 -- of time.
443 --
444 uninterruptibleMask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
445
446 -- | Like 'uninterruptibleMask', but does not pass a @restore@ action
447 -- to the argument.
448 uninterruptibleMask_ :: IO a -> IO a
449
450 mask_ io = mask $ \_ -> io
451
452 mask io = do
453 b <- getMaskingState
454 case b of
455 Unmasked -> block $ io unblock
456 MaskedInterruptible -> io block
457 MaskedUninterruptible -> io blockUninterruptible
458
459 uninterruptibleMask_ io = uninterruptibleMask $ \_ -> io
460
461 uninterruptibleMask io = do
462 b <- getMaskingState
463 case b of
464 Unmasked -> blockUninterruptible $ io unblock
465 MaskedInterruptible -> blockUninterruptible $ io block
466 MaskedUninterruptible -> io blockUninterruptible
467
468 bracket
469 :: IO a -- ^ computation to run first (\"acquire resource\")
470 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
471 -> (a -> IO c) -- ^ computation to run in-between
472 -> IO c -- returns the value from the in-between computation
473 bracket before after thing =
474 mask $ \restore -> do
475 a <- before
476 r <- restore (thing a) `onException` after a
477 _ <- after a
478 return r
479
480 finally :: IO a -- ^ computation to run first
481 -> IO b -- ^ computation to run afterward (even if an exception
482 -- was raised)
483 -> IO a -- returns the value from the first computation
484 a `finally` sequel =
485 mask $ \restore -> do
486 r <- restore a `onException` sequel
487 _ <- sequel
488 return r
489
490 -- | Evaluate the argument to weak head normal form.
491 --
492 -- 'evaluate' is typically used to uncover any exceptions that a lazy value
493 -- may contain, and possibly handle them.
494 --
495 -- 'evaluate' only evaluates to /weak head normal form/. If deeper
496 -- evaluation is needed, the @force@ function from @Control.DeepSeq@
497 -- may be handy:
498 --
499 -- > evaluate $ force x
500 --
501 -- There is a subtle difference between @'evaluate' x@ and @'return' '$!' x@,
502 -- analogous to the difference between 'throwIO' and 'throw'. If the lazy
503 -- value @x@ throws an exception, @'return' '$!' x@ will fail to return an
504 -- 'IO' action and will throw an exception instead. @'evaluate' x@, on the
505 -- other hand, always produces an 'IO' action; that action will throw an
506 -- exception upon /execution/ iff @x@ throws an exception upon /evaluation/.
507 --
508 -- The practical implication of this difference is that due to the
509 -- /imprecise exceptions/ semantics,
510 --
511 -- > (return $! error "foo") >> error "bar"
512 --
513 -- may throw either @"foo"@ or @"bar"@, depending on the optimizations
514 -- performed by the compiler. On the other hand,
515 --
516 -- > evaluate (error "foo") >> error "bar"
517 --
518 -- is guaranteed to throw @"foo"@.
519 --
520 -- The rule of thumb is to use 'evaluate' to force or handle exceptions in
521 -- lazy values. If, on the other hand, you are forcing a lazy value for
522 -- efficiency reasons only and do not care about exceptions, you may
523 -- use @'return' '$!' x@.
524 evaluate :: a -> IO a
525 evaluate a = IO $ \s -> seq# a s -- NB. see #2273, #5129