Move `Maybe`-typedef into GHC.Base
[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
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 blockUninterruptible :: IO a -> IO a
345 blockUninterruptible (IO io) = IO $ maskUninterruptible# io
346
347 -- | Describes the behaviour of a thread when an asynchronous
348 -- exception is received.
349 data MaskingState
350 = Unmasked -- ^ asynchronous exceptions are unmasked (the normal state)
351 | MaskedInterruptible
352 -- ^ the state during 'mask': asynchronous exceptions are masked, but blocking operations may still be interrupted
353 | MaskedUninterruptible
354 -- ^ the state during 'uninterruptibleMask': asynchronous exceptions are masked, and blocking operations may not be interrupted
355 deriving (Eq,Show)
356
357 -- | Returns the 'MaskingState' for the current thread.
358 getMaskingState :: IO MaskingState
359 getMaskingState = IO $ \s ->
360 case getMaskingState# s of
361 (# s', i #) -> (# s', case i of
362 0# -> Unmasked
363 1# -> MaskedUninterruptible
364 _ -> MaskedInterruptible #)
365
366 onException :: IO a -> IO b -> IO a
367 onException io what = io `catchException` \e -> do _ <- what
368 throwIO (e :: SomeException)
369
370 -- | Executes an IO computation with asynchronous
371 -- exceptions /masked/. That is, any thread which attempts to raise
372 -- an exception in the current thread with 'Control.Exception.throwTo'
373 -- will be blocked until asynchronous exceptions are unmasked again.
374 --
375 -- The argument passed to 'mask' is a function that takes as its
376 -- argument another function, which can be used to restore the
377 -- prevailing masking state within the context of the masked
378 -- computation. For example, a common way to use 'mask' is to protect
379 -- the acquisition of a resource:
380 --
381 -- > mask $ \restore -> do
382 -- > x <- acquire
383 -- > restore (do_something_with x) `onException` release
384 -- > release
385 --
386 -- This code guarantees that @acquire@ is paired with @release@, by masking
387 -- asynchronous exceptions for the critical parts. (Rather than write
388 -- this code yourself, it would be better to use
389 -- 'Control.Exception.bracket' which abstracts the general pattern).
390 --
391 -- Note that the @restore@ action passed to the argument to 'mask'
392 -- does not necessarily unmask asynchronous exceptions, it just
393 -- restores the masking state to that of the enclosing context. Thus
394 -- if asynchronous exceptions are already masked, 'mask' cannot be used
395 -- to unmask exceptions again. This is so that if you call a library function
396 -- with exceptions masked, you can be sure that the library call will not be
397 -- able to unmask exceptions again. If you are writing library code and need
398 -- to use asynchronous exceptions, the only way is to create a new thread;
399 -- see 'Control.Concurrent.forkIOWithUnmask'.
400 --
401 -- Asynchronous exceptions may still be received while in the masked
402 -- state if the masked thread /blocks/ in certain ways; see
403 -- "Control.Exception#interruptible".
404 --
405 -- Threads created by 'Control.Concurrent.forkIO' inherit the masked
406 -- state from the parent; that is, to start a thread in blocked mode,
407 -- use @mask_ $ forkIO ...@. This is particularly useful if you need
408 -- to establish an exception handler in the forked thread before any
409 -- asynchronous exceptions are received. To create a a new thread in
410 -- an unmasked state use 'Control.Concurrent.forkIOUnmasked'.
411 --
412 mask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
413
414 -- | Like 'mask', but does not pass a @restore@ action to the argument.
415 mask_ :: IO a -> IO a
416
417 -- | Like 'mask', but the masked computation is not interruptible (see
418 -- "Control.Exception#interruptible"). THIS SHOULD BE USED WITH
419 -- GREAT CARE, because if a thread executing in 'uninterruptibleMask'
420 -- blocks for any reason, then the thread (and possibly the program,
421 -- if this is the main thread) will be unresponsive and unkillable.
422 -- This function should only be necessary if you need to mask
423 -- exceptions around an interruptible operation, and you can guarantee
424 -- that the interruptible operation will only block for a short period
425 -- of time.
426 --
427 uninterruptibleMask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
428
429 -- | Like 'uninterruptibleMask', but does not pass a @restore@ action
430 -- to the argument.
431 uninterruptibleMask_ :: IO a -> IO a
432
433 mask_ io = mask $ \_ -> io
434
435 mask io = do
436 b <- getMaskingState
437 case b of
438 Unmasked -> block $ io unblock
439 _ -> io id
440
441 uninterruptibleMask_ io = uninterruptibleMask $ \_ -> io
442
443 uninterruptibleMask io = do
444 b <- getMaskingState
445 case b of
446 Unmasked -> blockUninterruptible $ io unblock
447 MaskedInterruptible -> blockUninterruptible $ io block
448 MaskedUninterruptible -> io id
449
450 bracket
451 :: IO a -- ^ computation to run first (\"acquire resource\")
452 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
453 -> (a -> IO c) -- ^ computation to run in-between
454 -> IO c -- returns the value from the in-between computation
455 bracket before after thing =
456 mask $ \restore -> do
457 a <- before
458 r <- restore (thing a) `onException` after a
459 _ <- after a
460 return r
461
462 finally :: IO a -- ^ computation to run first
463 -> IO b -- ^ computation to run afterward (even if an exception
464 -- was raised)
465 -> IO a -- returns the value from the first computation
466 a `finally` sequel =
467 mask $ \restore -> do
468 r <- restore a `onException` sequel
469 _ <- sequel
470 return r
471
472 -- | Forces its argument to be evaluated to weak head normal form when
473 -- the resultant 'IO' action is executed. It can be used to order
474 -- evaluation with respect to other 'IO' operations; its semantics are
475 -- given by
476 --
477 -- > evaluate x `seq` y ==> y
478 -- > evaluate x `catch` f ==> (return $! x) `catch` f
479 -- > evaluate x >>= f ==> (return $! x) >>= f
480 --
481 -- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
482 -- same as @(return $! x)@. A correct definition is
483 --
484 -- > evaluate x = (return $! x) >>= return
485 --
486 evaluate :: a -> IO a
487 evaluate a = IO $ \s -> seq# a s -- NB. see #2273, #5129
488