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