Get rid of some stuttering in comments and docs
[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 is
57 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 transformer 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, and therefore the result cannot
96 -- 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 type of the state.
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 type of the state.
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,Show)
283
284 -- | Returns the 'MaskingState' for the current thread.
285 getMaskingState :: IO MaskingState
286 getMaskingState = IO $ \s ->
287 case getMaskingState# s of
288 (# s', i #) -> (# s', case i of
289 0# -> Unmasked
290 1# -> MaskedUninterruptible
291 _ -> MaskedInterruptible #)
292
293 onException :: IO a -> IO b -> IO a
294 onException io what = io `catchException` \e -> do _ <- what
295 throwIO (e :: SomeException)
296
297 -- | Executes an IO computation with asynchronous
298 -- exceptions /masked/. That is, any thread which attempts to raise
299 -- an exception in the current thread with 'Control.Exception.throwTo'
300 -- will be blocked until asynchronous exceptions are unmasked again.
301 --
302 -- The argument passed to 'mask' is a function that takes as its
303 -- argument another function, which can be used to restore the
304 -- prevailing masking state within the context of the masked
305 -- computation. For example, a common way to use 'mask' is to protect
306 -- the acquisition of a resource:
307 --
308 -- > mask $ \restore -> do
309 -- > x <- acquire
310 -- > restore (do_something_with x) `onException` release
311 -- > release
312 --
313 -- This code guarantees that @acquire@ is paired with @release@, by masking
314 -- asynchronous exceptions for the critical parts. (Rather than write
315 -- this code yourself, it would be better to use
316 -- 'Control.Exception.bracket' which abstracts the general pattern).
317 --
318 -- Note that the @restore@ action passed to the argument to 'mask'
319 -- does not necessarily unmask asynchronous exceptions, it just
320 -- restores the masking state to that of the enclosing context. Thus
321 -- if asynchronous exceptions are already masked, 'mask' cannot be used
322 -- to unmask exceptions again. This is so that if you call a library function
323 -- with exceptions masked, you can be sure that the library call will not be
324 -- able to unmask exceptions again. If you are writing library code and need
325 -- to use asynchronous exceptions, the only way is to create a new thread;
326 -- see 'Control.Concurrent.forkIOWithUnmask'.
327 --
328 -- Asynchronous exceptions may still be received while in the masked
329 -- state if the masked thread /blocks/ in certain ways; see
330 -- "Control.Exception#interruptible".
331 --
332 -- Threads created by 'Control.Concurrent.forkIO' inherit the
333 -- 'MaskingState' from the parent; that is, to start a thread in the
334 -- 'MaskedInterruptible' state,
335 -- use @mask_ $ forkIO ...@. This is particularly useful if you need
336 -- to establish an exception handler in the forked thread before any
337 -- asynchronous exceptions are received. To create a new thread in
338 -- an unmasked state use 'Control.Concurrent.forkIOWithUnmask'.
339 --
340 mask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
341
342 -- | Like 'mask', but does not pass a @restore@ action to the argument.
343 mask_ :: IO a -> IO a
344
345 -- | Like 'mask', but the masked computation is not interruptible (see
346 -- "Control.Exception#interruptible"). THIS SHOULD BE USED WITH
347 -- GREAT CARE, because if a thread executing in 'uninterruptibleMask'
348 -- blocks for any reason, then the thread (and possibly the program,
349 -- if this is the main thread) will be unresponsive and unkillable.
350 -- This function should only be necessary if you need to mask
351 -- exceptions around an interruptible operation, and you can guarantee
352 -- that the interruptible operation will only block for a short period
353 -- of time.
354 --
355 uninterruptibleMask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
356
357 -- | Like 'uninterruptibleMask', but does not pass a @restore@ action
358 -- to the argument.
359 uninterruptibleMask_ :: IO a -> IO a
360
361 mask_ io = mask $ \_ -> io
362
363 mask io = do
364 b <- getMaskingState
365 case b of
366 Unmasked -> block $ io unblock
367 MaskedInterruptible -> io block
368 MaskedUninterruptible -> io blockUninterruptible
369
370 uninterruptibleMask_ io = uninterruptibleMask $ \_ -> io
371
372 uninterruptibleMask io = do
373 b <- getMaskingState
374 case b of
375 Unmasked -> blockUninterruptible $ io unblock
376 MaskedInterruptible -> blockUninterruptible $ io block
377 MaskedUninterruptible -> io blockUninterruptible
378
379 bracket
380 :: IO a -- ^ computation to run first (\"acquire resource\")
381 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
382 -> (a -> IO c) -- ^ computation to run in-between
383 -> IO c -- returns the value from the in-between computation
384 bracket before after thing =
385 mask $ \restore -> do
386 a <- before
387 r <- restore (thing a) `onException` after a
388 _ <- after a
389 return r
390
391 finally :: IO a -- ^ computation to run first
392 -> IO b -- ^ computation to run afterward (even if an exception
393 -- was raised)
394 -> IO a -- returns the value from the first computation
395 a `finally` sequel =
396 mask $ \restore -> do
397 r <- restore a `onException` sequel
398 _ <- sequel
399 return r
400
401 -- | Evaluate the argument to weak head normal form.
402 --
403 -- 'evaluate' is typically used to uncover any exceptions that a lazy value
404 -- may contain, and possibly handle them.
405 --
406 -- 'evaluate' only evaluates to /weak head normal form/. If deeper
407 -- evaluation is needed, the @force@ function from @Control.DeepSeq@
408 -- may be handy:
409 --
410 -- > evaluate $ force x
411 --
412 -- There is a subtle difference between @'evaluate' x@ and @'return' '$!' x@,
413 -- analogous to the difference between 'throwIO' and 'throw'. If the lazy
414 -- value @x@ throws an exception, @'return' '$!' x@ will fail to return an
415 -- 'IO' action and will throw an exception instead. @'evaluate' x@, on the
416 -- other hand, always produces an 'IO' action; that action will throw an
417 -- exception upon /execution/ iff @x@ throws an exception upon /evaluation/.
418 --
419 -- The practical implication of this difference is that due to the
420 -- /imprecise exceptions/ semantics,
421 --
422 -- > (return $! error "foo") >> error "bar"
423 --
424 -- may throw either @"foo"@ or @"bar"@, depending on the optimizations
425 -- performed by the compiler. On the other hand,
426 --
427 -- > evaluate (error "foo") >> error "bar"
428 --
429 -- is guaranteed to throw @"foo"@.
430 --
431 -- The rule of thumb is to use 'evaluate' to force or handle exceptions in
432 -- lazy values. If, on the other hand, you are forcing a lazy value for
433 -- efficiency reasons only and do not care about exceptions, you may
434 -- use @'return' '$!' x@.
435 evaluate :: a -> IO a
436 evaluate a = IO $ \s -> seq# a s -- NB. see #2273, #5129
437
438 {- $exceptions_and_strictness
439
440 Laziness can interact with @catch@-like operations in non-obvious ways (see,
441 e.g. GHC Trac #11555 and #13330). For instance, consider these subtly-different
442 examples:
443
444 > test1 = Control.Exception.catch (error "uh oh") (\(_ :: SomeException) -> putStrLn "it failed")
445 >
446 > test2 = GHC.IO.catchException (error "uh oh") (\(_ :: SomeException) -> putStrLn "it failed")
447
448 While @test1@ will print "it failed", @test2@ will print "uh oh".
449
450 When using 'catchException', exceptions thrown while evaluating the
451 action-to-be-executed will not be caught; only exceptions thrown during
452 execution of the action will be handled by the exception handler.
453
454 Since this strictness is a small optimization and may lead to surprising
455 results, all of the @catch@ and @handle@ variants offered by "Control.Exception"
456 use 'catch' rather than 'catchException'.
457 -}