345b68dd16920e4850c8f452008c65675d4e68ce
[packages/base.git] / 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 -- Module : GHC.IO
13 -- Copyright : (c) The University of Glasgow 1994-2002
14 -- License : see libraries/base/LICENSE
15 --
16 -- Maintainer : cvs-ghc@haskell.org
17 -- Stability : internal
18 -- Portability : non-portable (GHC Extensions)
19 --
20 -- Definitions for the 'IO' monad and its friends.
21 --
22 -----------------------------------------------------------------------------
23
24 -- #hide
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 block, unblock, blocked, 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.
174 -}
175 {-# NOINLINE unsafeDupablePerformIO #-}
176 unsafeDupablePerformIO :: IO a -> a
177 unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
178
179 -- Why do we NOINLINE unsafeDupablePerformIO? See the comment with
180 -- GHC.ST.runST. Essentially the issue is that the IO computation
181 -- inside unsafePerformIO must be atomic: it must either all run, or
182 -- not at all. If we let the compiler see the application of the IO
183 -- to realWorld#, it might float out part of the IO.
184
185 -- Why is there a call to 'lazy' in unsafeDupablePerformIO?
186 -- If we don't have it, the demand analyser discovers the following strictness
187 -- for unsafeDupablePerformIO: C(U(AV))
188 -- But then consider
189 -- unsafeDupablePerformIO (\s -> let r = f x in
190 -- case writeIORef v r s of (# s1, _ #) ->
191 -- (# s1, r #)
192 -- The strictness analyser will find that the binding for r is strict,
193 -- (becuase of uPIO's strictness sig), and so it'll evaluate it before
194 -- doing the writeIORef. This actually makes tests/lib/should_run/memo002
195 -- get a deadlock!
196 --
197 -- Solution: don't expose the strictness of unsafeDupablePerformIO,
198 -- by hiding it with 'lazy'
199
200 {-|
201 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
202 When passed a value of type @IO a@, the 'IO' will only be performed
203 when the value of the @a@ is demanded. This is used to implement lazy
204 file reading, see 'System.IO.hGetContents'.
205 -}
206 {-# INLINE unsafeInterleaveIO #-}
207 unsafeInterleaveIO :: IO a -> IO a
208 unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)
209
210 -- We believe that INLINE on unsafeInterleaveIO is safe, because the
211 -- state from this IO thread is passed explicitly to the interleaved
212 -- IO, so it cannot be floated out and shared.
213
214 {-# INLINE unsafeDupableInterleaveIO #-}
215 unsafeDupableInterleaveIO :: IO a -> IO a
216 unsafeDupableInterleaveIO (IO m)
217 = IO ( \ s -> let
218 r = case m s of (# _, res #) -> res
219 in
220 (# s, r #))
221
222 {-|
223 Ensures that the suspensions under evaluation by the current thread
224 are unique; that is, the current thread is not evaluating anything
225 that is also under evaluation by another thread that has also executed
226 'noDuplicate'.
227
228 This operation is used in the definition of 'unsafePerformIO' to
229 prevent the IO action from being executed multiple times, which is usually
230 undesirable.
231 -}
232 noDuplicate :: IO ()
233 noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)
234
235 -- -----------------------------------------------------------------------------
236 -- | File and directory names are values of type 'String', whose precise
237 -- meaning is operating system dependent. Files can be opened, yielding a
238 -- handle which can then be used to operate on the contents of that file.
239
240 type FilePath = String
241
242 -- -----------------------------------------------------------------------------
243 -- Primitive catch and throwIO
244
245 {-
246 catchException used to handle the passing around of the state to the
247 action and the handler. This turned out to be a bad idea - it meant
248 that we had to wrap both arguments in thunks so they could be entered
249 as normal (remember IO returns an unboxed pair...).
250
251 Now catch# has type
252
253 catch# :: IO a -> (b -> IO a) -> IO a
254
255 (well almost; the compiler doesn't know about the IO newtype so we
256 have to work around that in the definition of catchException below).
257 -}
258
259 catchException :: Exception e => IO a -> (e -> IO a) -> IO a
260 catchException (IO io) handler = IO $ catch# io handler'
261 where handler' e = case fromException e of
262 Just e' -> unIO (handler e')
263 Nothing -> raiseIO# e
264
265 catchAny :: IO a -> (forall e . Exception e => e -> IO a) -> IO a
266 catchAny (IO io) handler = IO $ catch# io handler'
267 where handler' (SomeException e) = unIO (handler e)
268
269 -- | A variant of 'throw' that can only be used within the 'IO' monad.
270 --
271 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
272 -- two functions are subtly different:
273 --
274 -- > throw e `seq` x ===> throw e
275 -- > throwIO e `seq` x ===> x
276 --
277 -- The first example will cause the exception @e@ to be raised,
278 -- whereas the second one won\'t. In fact, 'throwIO' will only cause
279 -- an exception to be raised when it is used within the 'IO' monad.
280 -- The 'throwIO' variant should be used in preference to 'throw' to
281 -- raise an exception within the 'IO' monad because it guarantees
282 -- ordering with respect to other 'IO' operations, whereas 'throw'
283 -- does not.
284 throwIO :: Exception e => e -> IO a
285 throwIO e = IO (raiseIO# (toException e))
286
287 -- -----------------------------------------------------------------------------
288 -- Controlling asynchronous exception delivery
289
290 {-# DEPRECATED block "use Control.Exception.mask instead" #-}
291 -- | Note: this function is deprecated, please use 'mask' instead.
292 --
293 -- Applying 'block' to a computation will
294 -- execute that computation with asynchronous exceptions
295 -- /blocked/. That is, any thread which
296 -- attempts to raise an exception in the current thread with 'Control.Exception.throwTo' will be
297 -- blocked until asynchronous exceptions are unblocked again. There\'s
298 -- no need to worry about re-enabling asynchronous exceptions; that is
299 -- done automatically on exiting the scope of
300 -- 'block'.
301 --
302 -- Threads created by 'Control.Concurrent.forkIO' inherit the blocked
303 -- state from the parent; that is, to start a thread in blocked mode,
304 -- use @block $ forkIO ...@. This is particularly useful if you need to
305 -- establish an exception handler in the forked thread before any
306 -- asynchronous exceptions are received.
307 block :: IO a -> IO a
308 block (IO io) = IO $ maskAsyncExceptions# io
309
310 {-# DEPRECATED unblock "use Control.Exception.mask instead" #-}
311 -- | Note: this function is deprecated, please use 'mask' instead.
312 --
313 -- To re-enable asynchronous exceptions inside the scope of
314 -- 'block', 'unblock' can be
315 -- used. It scopes in exactly the same way, so on exit from
316 -- 'unblock' asynchronous exception delivery will
317 -- be disabled again.
318 unblock :: IO a -> IO a
319 unblock = unsafeUnmask
320
321 unsafeUnmask :: IO a -> IO a
322 unsafeUnmask (IO io) = IO $ unmaskAsyncExceptions# io
323
324 blockUninterruptible :: IO a -> IO a
325 blockUninterruptible (IO io) = IO $ maskUninterruptible# io
326
327 -- | Describes the behaviour of a thread when an asynchronous
328 -- exception is received.
329 data MaskingState
330 = Unmasked -- ^ asynchronous exceptions are unmasked (the normal state)
331 | MaskedInterruptible
332 -- ^ the state during 'mask': asynchronous exceptions are masked, but blocking operations may still be interrupted
333 | MaskedUninterruptible
334 -- ^ the state during 'uninterruptibleMask': asynchronous exceptions are masked, and blocking operations may not be interrupted
335 deriving (Eq,Show)
336
337 -- | Returns the 'MaskingState' for the current thread.
338 getMaskingState :: IO MaskingState
339 getMaskingState = IO $ \s ->
340 case getMaskingState# s of
341 (# s', i #) -> (# s', case i of
342 0# -> Unmasked
343 1# -> MaskedUninterruptible
344 _ -> MaskedInterruptible #)
345
346 {-# DEPRECATED blocked "use Control.Exception.getMaskingState instead" #-}
347 -- | returns True if asynchronous exceptions are blocked in the
348 -- current thread.
349 blocked :: IO Bool
350 blocked = fmap (/= Unmasked) getMaskingState
351
352 onException :: IO a -> IO b -> IO a
353 onException io what = io `catchException` \e -> do _ <- what
354 throwIO (e :: SomeException)
355
356 -- | Executes an IO computation with asynchronous
357 -- exceptions /masked/. That is, any thread which attempts to raise
358 -- an exception in the current thread with 'Control.Exception.throwTo'
359 -- will be blocked until asynchronous exceptions are unmasked again.
360 --
361 -- The argument passed to 'mask' is a function that takes as its
362 -- argument another function, which can be used to restore the
363 -- prevailing masking state within the context of the masked
364 -- computation. For example, a common way to use 'mask' is to protect
365 -- the acquisition of a resource:
366 --
367 -- > mask $ \restore -> do
368 -- > x <- acquire
369 -- > restore (do_something_with x) `onException` release
370 -- > release
371 --
372 -- This code guarantees that @acquire@ is paired with @release@, by masking
373 -- asynchronous exceptions for the critical parts. (Rather than write
374 -- this code yourself, it would be better to use
375 -- 'Control.Exception.bracket' which abstracts the general pattern).
376 --
377 -- Note that the @restore@ action passed to the argument to 'mask'
378 -- does not necessarily unmask asynchronous exceptions, it just
379 -- restores the masking state to that of the enclosing context. Thus
380 -- if asynchronous exceptions are already masked, 'mask' cannot be used
381 -- to unmask exceptions again. This is so that if you call a library function
382 -- with exceptions masked, you can be sure that the library call will not be
383 -- able to unmask exceptions again. If you are writing library code and need
384 -- to use asynchronous exceptions, the only way is to create a new thread;
385 -- see 'Control.Concurrent.forkIOWithUnmask'.
386 --
387 -- Asynchronous exceptions may still be received while in the masked
388 -- state if the masked thread /blocks/ in certain ways; see
389 -- "Control.Exception#interruptible".
390 --
391 -- Threads created by 'Control.Concurrent.forkIO' inherit the masked
392 -- state from the parent; that is, to start a thread in blocked mode,
393 -- use @mask_ $ forkIO ...@. This is particularly useful if you need
394 -- to establish an exception handler in the forked thread before any
395 -- asynchronous exceptions are received. To create a a new thread in
396 -- an unmasked state use 'Control.Concurrent.forkIOUnmasked'.
397 --
398 mask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
399
400 -- | Like 'mask', but does not pass a @restore@ action to the argument.
401 mask_ :: IO a -> IO a
402
403 -- | Like 'mask', but the masked computation is not interruptible (see
404 -- "Control.Exception#interruptible"). THIS SHOULD BE USED WITH
405 -- GREAT CARE, because if a thread executing in 'uninterruptibleMask'
406 -- blocks for any reason, then the thread (and possibly the program,
407 -- if this is the main thread) will be unresponsive and unkillable.
408 -- This function should only be necessary if you need to mask
409 -- exceptions around an interruptible operation, and you can guarantee
410 -- that the interruptible operation will only block for a short period
411 -- of time.
412 --
413 uninterruptibleMask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
414
415 -- | Like 'uninterruptibleMask', but does not pass a @restore@ action
416 -- to the argument.
417 uninterruptibleMask_ :: IO a -> IO a
418
419 mask_ io = mask $ \_ -> io
420
421 mask io = do
422 b <- getMaskingState
423 case b of
424 Unmasked -> block $ io unblock
425 _ -> io id
426
427 uninterruptibleMask_ io = uninterruptibleMask $ \_ -> io
428
429 uninterruptibleMask io = do
430 b <- getMaskingState
431 case b of
432 Unmasked -> blockUninterruptible $ io unblock
433 MaskedInterruptible -> blockUninterruptible $ io block
434 MaskedUninterruptible -> io id
435
436 bracket
437 :: IO a -- ^ computation to run first (\"acquire resource\")
438 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
439 -> (a -> IO c) -- ^ computation to run in-between
440 -> IO c -- returns the value from the in-between computation
441 bracket before after thing =
442 mask $ \restore -> do
443 a <- before
444 r <- restore (thing a) `onException` after a
445 _ <- after a
446 return r
447
448 finally :: IO a -- ^ computation to run first
449 -> IO b -- ^ computation to run afterward (even if an exception
450 -- was raised)
451 -> IO a -- returns the value from the first computation
452 a `finally` sequel =
453 mask $ \restore -> do
454 r <- restore a `onException` sequel
455 _ <- sequel
456 return r
457
458 -- | Forces its argument to be evaluated to weak head normal form when
459 -- the resultant 'IO' action is executed. It can be used to order
460 -- evaluation with respect to other 'IO' operations; its semantics are
461 -- given by
462 --
463 -- > evaluate x `seq` y ==> y
464 -- > evaluate x `catch` f ==> (return $! x) `catch` f
465 -- > evaluate x >>= f ==> (return $! x) >>= f
466 --
467 -- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
468 -- same as @(return $! x)@. A correct definition is
469 --
470 -- > evaluate x = (return $! x) >>= return
471 --
472 evaluate :: a -> IO a
473 evaluate a = IO $ \s -> seq# a s -- NB. see #2273, #5129