docs: "state transformer" -> "state monad" / "ST" (whichever is meant)
[ghc.git] / libraries / base / GHC / IO.hs
1 {-# LANGUAGE Unsafe #-}
2 {-# LANGUAGE NoImplicitPrelude
3 , BangPatterns
4 , RankNTypes
5 , MagicHash
6 , ScopedTypeVariables
7 , UnboxedTuples
8 #-}
9 {-# OPTIONS_GHC -funbox-strict-fields #-}
10 {-# OPTIONS_HADDOCK hide #-}
11
12 -----------------------------------------------------------------------------
13 -- |
14 -- Module : GHC.IO
15 -- Copyright : (c) The University of Glasgow 1994-2002
16 -- License : see libraries/base/LICENSE
17 --
18 -- Maintainer : cvs-ghc@haskell.org
19 -- Stability : internal
20 -- Portability : non-portable (GHC Extensions)
21 --
22 -- Definitions for the 'IO' monad and its friends.
23 --
24 -----------------------------------------------------------------------------
25
26 module GHC.IO (
27 IO(..), unIO, failIO, liftIO, mplusIO,
28 unsafePerformIO, unsafeInterleaveIO,
29 unsafeDupablePerformIO, unsafeDupableInterleaveIO,
30 noDuplicate,
31
32 -- To and from from ST
33 stToIO, ioToST, unsafeIOToST, unsafeSTToIO,
34
35 FilePath,
36
37 catch, catchException, catchAny, throwIO,
38 mask, mask_, uninterruptibleMask, uninterruptibleMask_,
39 MaskingState(..), getMaskingState,
40 unsafeUnmask, interruptible,
41 onException, bracket, finally, evaluate
42 ) where
43
44 import GHC.Base
45 import GHC.ST
46 import GHC.Exception
47 import GHC.Show
48 import GHC.IO.Unsafe
49
50 import {-# SOURCE #-} GHC.IO.Exception ( userError, IOError )
51
52 -- ---------------------------------------------------------------------------
53 -- The IO Monad
54
55 {-
56 The IO Monad is just an instance of the ST monad, where the state thread
57 is the real world. We use the exception mechanism (in GHC.Exception) to
58 implement IO exceptions.
59
60 NOTE: The IO representation is deeply wired in to various parts of the
61 system. The following list may or may not be exhaustive:
62
63 Compiler - types of various primitives in PrimOp.hs
64
65 RTS - forceIO (StgStartup.cmm)
66 - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast
67 (Exception.cmm)
68 - raiseAsync (RaiseAsync.c)
69
70 Prelude - GHC.IO.hs, and several other places including
71 GHC.Exception.hs.
72
73 Libraries - parts of hslibs/lang.
74
75 --SDM
76 -}
77
78 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
79 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
80
81 failIO :: String -> IO a
82 failIO s = IO (raiseIO# (toException (userError s)))
83
84 -- ---------------------------------------------------------------------------
85 -- Coercions between IO and ST
86
87 -- | Embed a strict state thread in an 'IO'
88 -- action. The 'RealWorld' parameter indicates that the internal state
89 -- used by the 'ST' computation is a special one supplied by the 'IO'
90 -- monad, and thus distinct from those used by invocations of 'runST'.
91 stToIO :: ST RealWorld a -> IO a
92 stToIO (ST m) = IO m
93
94 -- | Convert an 'IO' action into an 'ST' action. The type of the result
95 -- is constrained to use a 'RealWorld' state thread, and therefore the
96 -- result cannot be passed to 'runST'.
97 ioToST :: IO a -> ST RealWorld a
98 ioToST (IO m) = (ST m)
99
100 -- | Convert an 'IO' action to an 'ST' action.
101 -- This relies on 'IO' and 'ST' having the same representation modulo the
102 -- constraint on the state thread type parameter.
103 unsafeIOToST :: IO a -> ST s a
104 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
105
106 -- | Convert an 'ST' action to an 'IO' action.
107 -- This relies on 'IO' and 'ST' having the same representation modulo the
108 -- constraint on the state thread type parameter.
109 --
110 -- For an example demonstrating why this is unsafe, see
111 -- https://mail.haskell.org/pipermail/haskell-cafe/2009-April/060719.html
112 unsafeSTToIO :: ST s a -> IO a
113 unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
114
115 -- -----------------------------------------------------------------------------
116 -- | File and directory names are values of type 'String', whose precise
117 -- meaning is operating system dependent. Files can be opened, yielding a
118 -- handle which can then be used to operate on the contents of that file.
119
120 type FilePath = String
121
122 -- -----------------------------------------------------------------------------
123 -- Primitive catch and throwIO
124
125 {-
126 catchException/catch used to handle the passing around of the state to the
127 action and the handler. This turned out to be a bad idea - it meant
128 that we had to wrap both arguments in thunks so they could be entered
129 as normal (remember IO returns an unboxed pair...).
130
131 Now catch# has type
132
133 catch# :: IO a -> (b -> IO a) -> IO a
134
135 (well almost; the compiler doesn't know about the IO newtype so we
136 have to work around that in the definition of catch below).
137 -}
138
139 -- | Catch an exception in the 'IO' monad.
140 --
141 -- Note that this function is /strict/ in the action. That is,
142 -- @catchException undefined b == _|_@. See #exceptions_and_strictness#
143 -- for details.
144 catchException :: Exception e => IO a -> (e -> IO a) -> IO a
145 catchException !io handler = catch io handler
146
147 -- | This is the simplest of the exception-catching functions. It
148 -- takes a single argument, runs it, and if an exception is raised
149 -- the \"handler\" is executed, with the value of the exception passed as an
150 -- argument. Otherwise, the result is returned as normal. For example:
151 --
152 -- > catch (readFile f)
153 -- > (\e -> do let err = show (e :: IOException)
154 -- > hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err)
155 -- > return "")
156 --
157 -- Note that we have to give a type signature to @e@, or the program
158 -- will not typecheck as the type is ambiguous. While it is possible
159 -- to catch exceptions of any type, see the section \"Catching all
160 -- exceptions\" (in "Control.Exception") for an explanation of the problems with doing so.
161 --
162 -- For catching exceptions in pure (non-'IO') expressions, see the
163 -- function 'evaluate'.
164 --
165 -- Note that due to Haskell\'s unspecified evaluation order, an
166 -- expression may throw one of several possible exceptions: consider
167 -- the expression @(error \"urk\") + (1 \`div\` 0)@. Does
168 -- the expression throw
169 -- @ErrorCall \"urk\"@, or @DivideByZero@?
170 --
171 -- The answer is \"it might throw either\"; the choice is
172 -- non-deterministic. If you are catching any type of exception then you
173 -- might catch either. If you are calling @catch@ with type
174 -- @IO Int -> (ArithException -> IO Int) -> IO Int@ then the handler may
175 -- get run with @DivideByZero@ as an argument, or an @ErrorCall \"urk\"@
176 -- exception may be propogated further up. If you call it again, you
177 -- might get a the opposite behaviour. This is ok, because 'catch' is an
178 -- 'IO' computation.
179 --
180 catch :: Exception e
181 => IO a -- ^ The computation to run
182 -> (e -> IO a) -- ^ Handler to invoke if an exception is raised
183 -> IO a
184 -- See #exceptions_and_strictness#.
185 catch (IO io) handler = IO $ catch# io handler'
186 where handler' e = case fromException e of
187 Just e' -> unIO (handler e')
188 Nothing -> raiseIO# e
189
190
191 -- | Catch any 'Exception' type in the 'IO' monad.
192 --
193 -- Note that this function is /strict/ in the action. That is,
194 -- @catchAny undefined b == _|_@. See #exceptions_and_strictness# for
195 -- details.
196 catchAny :: IO a -> (forall e . Exception e => e -> IO a) -> IO a
197 catchAny !(IO io) handler = IO $ catch# io handler'
198 where handler' (SomeException e) = unIO (handler e)
199
200 -- Using catchException here means that if `m` throws an
201 -- 'IOError' /as an imprecise exception/, we will not catch
202 -- it. No one should really be doing that anyway.
203 mplusIO :: IO a -> IO a -> IO a
204 mplusIO m n = m `catchException` \ (_ :: IOError) -> n
205
206 -- | A variant of 'throw' that can only be used within the 'IO' monad.
207 --
208 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
209 -- two functions are subtly different:
210 --
211 -- > throw e `seq` x ===> throw e
212 -- > throwIO e `seq` x ===> x
213 --
214 -- The first example will cause the exception @e@ to be raised,
215 -- whereas the second one won\'t. In fact, 'throwIO' will only cause
216 -- an exception to be raised when it is used within the 'IO' monad.
217 -- The 'throwIO' variant should be used in preference to 'throw' to
218 -- raise an exception within the 'IO' monad because it guarantees
219 -- ordering with respect to other 'IO' operations, whereas 'throw'
220 -- does not.
221 throwIO :: Exception e => e -> IO a
222 throwIO e = IO (raiseIO# (toException e))
223
224 -- -----------------------------------------------------------------------------
225 -- Controlling asynchronous exception delivery
226
227 -- Applying 'block' to a computation will
228 -- execute that computation with asynchronous exceptions
229 -- /blocked/. That is, any thread which
230 -- attempts to raise an exception in the current thread with 'Control.Exception.throwTo' will be
231 -- blocked until asynchronous exceptions are unblocked again. There\'s
232 -- no need to worry about re-enabling asynchronous exceptions; that is
233 -- done automatically on exiting the scope of
234 -- 'block'.
235 --
236 -- Threads created by 'Control.Concurrent.forkIO' inherit the blocked
237 -- state from the parent; that is, to start a thread in blocked mode,
238 -- use @block $ forkIO ...@. This is particularly useful if you need to
239 -- establish an exception handler in the forked thread before any
240 -- asynchronous exceptions are received.
241 block :: IO a -> IO a
242 block (IO io) = IO $ maskAsyncExceptions# io
243
244 -- To re-enable asynchronous exceptions inside the scope of
245 -- 'block', 'unblock' can be
246 -- used. It scopes in exactly the same way, so on exit from
247 -- 'unblock' asynchronous exception delivery will
248 -- be disabled again.
249 unblock :: IO a -> IO a
250 unblock = unsafeUnmask
251
252 unsafeUnmask :: IO a -> IO a
253 unsafeUnmask (IO io) = IO $ unmaskAsyncExceptions# io
254
255 -- | Allow asynchronous exceptions to be raised even inside 'mask', making
256 -- the operation interruptible (see the discussion of "Interruptible operations"
257 -- in 'Control.Exception').
258 --
259 -- When called outside 'mask', or inside 'uninterruptibleMask', this
260 -- function has no effect.
261 --
262 -- @since 4.9.0.0
263 interruptible :: IO a -> IO a
264 interruptible act = do
265 st <- getMaskingState
266 case st of
267 Unmasked -> act
268 MaskedInterruptible -> unsafeUnmask act
269 MaskedUninterruptible -> act
270
271 blockUninterruptible :: IO a -> IO a
272 blockUninterruptible (IO io) = IO $ maskUninterruptible# io
273
274 -- | Describes the behaviour of a thread when an asynchronous
275 -- exception is received.
276 data MaskingState
277 = Unmasked -- ^ asynchronous exceptions are unmasked (the normal state)
278 | MaskedInterruptible
279 -- ^ the state during 'mask': asynchronous exceptions are masked, but blocking operations may still be interrupted
280 | MaskedUninterruptible
281 -- ^ the state during 'uninterruptibleMask': asynchronous exceptions are masked, and blocking operations may not be interrupted
282 deriving ( Eq -- ^ @since 4.3.0.0
283 , Show -- ^ @since 4.3.0.0
284 )
285
286 -- | Returns the 'MaskingState' for the current thread.
287 getMaskingState :: IO MaskingState
288 getMaskingState = IO $ \s ->
289 case getMaskingState# s of
290 (# s', i #) -> (# s', case i of
291 0# -> Unmasked
292 1# -> MaskedUninterruptible
293 _ -> MaskedInterruptible #)
294
295 onException :: IO a -> IO b -> IO a
296 onException io what = io `catchException` \e -> do _ <- what
297 throwIO (e :: SomeException)
298
299 -- | Executes an IO computation with asynchronous
300 -- exceptions /masked/. That is, any thread which attempts to raise
301 -- an exception in the current thread with 'Control.Exception.throwTo'
302 -- will be blocked until asynchronous exceptions are unmasked again.
303 --
304 -- The argument passed to 'mask' is a function that takes as its
305 -- argument another function, which can be used to restore the
306 -- prevailing masking state within the context of the masked
307 -- computation. For example, a common way to use 'mask' is to protect
308 -- the acquisition of a resource:
309 --
310 -- > mask $ \restore -> do
311 -- > x <- acquire
312 -- > restore (do_something_with x) `onException` release
313 -- > release
314 --
315 -- This code guarantees that @acquire@ is paired with @release@, by masking
316 -- asynchronous exceptions for the critical parts. (Rather than write
317 -- this code yourself, it would be better to use
318 -- 'Control.Exception.bracket' which abstracts the general pattern).
319 --
320 -- Note that the @restore@ action passed to the argument to 'mask'
321 -- does not necessarily unmask asynchronous exceptions, it just
322 -- restores the masking state to that of the enclosing context. Thus
323 -- if asynchronous exceptions are already masked, 'mask' cannot be used
324 -- to unmask exceptions again. This is so that if you call a library function
325 -- with exceptions masked, you can be sure that the library call will not be
326 -- able to unmask exceptions again. If you are writing library code and need
327 -- to use asynchronous exceptions, the only way is to create a new thread;
328 -- see 'Control.Concurrent.forkIOWithUnmask'.
329 --
330 -- Asynchronous exceptions may still be received while in the masked
331 -- state if the masked thread /blocks/ in certain ways; see
332 -- "Control.Exception#interruptible".
333 --
334 -- Threads created by 'Control.Concurrent.forkIO' inherit the
335 -- 'MaskingState' from the parent; that is, to start a thread in the
336 -- 'MaskedInterruptible' state,
337 -- use @mask_ $ forkIO ...@. This is particularly useful if you need
338 -- to establish an exception handler in the forked thread before any
339 -- asynchronous exceptions are received. To create a new thread in
340 -- an unmasked state use 'Control.Concurrent.forkIOWithUnmask'.
341 --
342 mask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
343
344 -- | Like 'mask', but does not pass a @restore@ action to the argument.
345 mask_ :: IO a -> IO a
346
347 -- | Like 'mask', but the masked computation is not interruptible (see
348 -- "Control.Exception#interruptible"). THIS SHOULD BE USED WITH
349 -- GREAT CARE, because if a thread executing in 'uninterruptibleMask'
350 -- blocks for any reason, then the thread (and possibly the program,
351 -- if this is the main thread) will be unresponsive and unkillable.
352 -- This function should only be necessary if you need to mask
353 -- exceptions around an interruptible operation, and you can guarantee
354 -- that the interruptible operation will only block for a short period
355 -- of time.
356 --
357 uninterruptibleMask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
358
359 -- | Like 'uninterruptibleMask', but does not pass a @restore@ action
360 -- to the argument.
361 uninterruptibleMask_ :: IO a -> IO a
362
363 mask_ io = mask $ \_ -> io
364
365 mask io = do
366 b <- getMaskingState
367 case b of
368 Unmasked -> block $ io unblock
369 MaskedInterruptible -> io block
370 MaskedUninterruptible -> io blockUninterruptible
371
372 uninterruptibleMask_ io = uninterruptibleMask $ \_ -> io
373
374 uninterruptibleMask io = do
375 b <- getMaskingState
376 case b of
377 Unmasked -> blockUninterruptible $ io unblock
378 MaskedInterruptible -> blockUninterruptible $ io block
379 MaskedUninterruptible -> io blockUninterruptible
380
381 bracket
382 :: IO a -- ^ computation to run first (\"acquire resource\")
383 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
384 -> (a -> IO c) -- ^ computation to run in-between
385 -> IO c -- returns the value from the in-between computation
386 bracket before after thing =
387 mask $ \restore -> do
388 a <- before
389 r <- restore (thing a) `onException` after a
390 _ <- after a
391 return r
392
393 finally :: IO a -- ^ computation to run first
394 -> IO b -- ^ computation to run afterward (even if an exception
395 -- was raised)
396 -> IO a -- returns the value from the first computation
397 a `finally` sequel =
398 mask $ \restore -> do
399 r <- restore a `onException` sequel
400 _ <- sequel
401 return r
402
403 -- | Evaluate the argument to weak head normal form.
404 --
405 -- 'evaluate' is typically used to uncover any exceptions that a lazy value
406 -- may contain, and possibly handle them.
407 --
408 -- 'evaluate' only evaluates to /weak head normal form/. If deeper
409 -- evaluation is needed, the @force@ function from @Control.DeepSeq@
410 -- may be handy:
411 --
412 -- > evaluate $ force x
413 --
414 -- There is a subtle difference between @'evaluate' x@ and @'return' '$!' x@,
415 -- analogous to the difference between 'throwIO' and 'throw'. If the lazy
416 -- value @x@ throws an exception, @'return' '$!' x@ will fail to return an
417 -- 'IO' action and will throw an exception instead. @'evaluate' x@, on the
418 -- other hand, always produces an 'IO' action; that action will throw an
419 -- exception upon /execution/ iff @x@ throws an exception upon /evaluation/.
420 --
421 -- The practical implication of this difference is that due to the
422 -- /imprecise exceptions/ semantics,
423 --
424 -- > (return $! error "foo") >> error "bar"
425 --
426 -- may throw either @"foo"@ or @"bar"@, depending on the optimizations
427 -- performed by the compiler. On the other hand,
428 --
429 -- > evaluate (error "foo") >> error "bar"
430 --
431 -- is guaranteed to throw @"foo"@.
432 --
433 -- The rule of thumb is to use 'evaluate' to force or handle exceptions in
434 -- lazy values. If, on the other hand, you are forcing a lazy value for
435 -- efficiency reasons only and do not care about exceptions, you may
436 -- use @'return' '$!' x@.
437 evaluate :: a -> IO a
438 evaluate a = IO $ \s -> seq# a s -- NB. see #2273, #5129
439
440 {- $exceptions_and_strictness
441
442 Laziness can interact with @catch@-like operations in non-obvious ways (see,
443 e.g. GHC Trac #11555 and #13330). For instance, consider these subtly-different
444 examples:
445
446 > test1 = Control.Exception.catch (error "uh oh") (\(_ :: SomeException) -> putStrLn "it failed")
447 >
448 > test2 = GHC.IO.catchException (error "uh oh") (\(_ :: SomeException) -> putStrLn "it failed")
449
450 While @test1@ will print "it failed", @test2@ will print "uh oh".
451
452 When using 'catchException', exceptions thrown while evaluating the
453 action-to-be-executed will not be caught; only exceptions thrown during
454 execution of the action will be handled by the exception handler.
455
456 Since this strictness is a small optimization and may lead to surprising
457 results, all of the @catch@ and @handle@ variants offered by "Control.Exception"
458 use 'catch' rather than 'catchException'.
459 -}