testsuite: Skip T17414 on Linux
[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 not-home #-}
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, 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 mkUserError
43 ) where
44
45 import GHC.Base
46 import GHC.ST
47 import GHC.Exception
48 import GHC.Show
49 import GHC.IO.Unsafe
50
51 import {-# SOURCE #-} GHC.IO.Exception ( userError, IOError )
52
53 -- ---------------------------------------------------------------------------
54 -- The IO Monad
55
56 {-
57 The IO Monad is just an instance of the ST monad, where the state thread
58 is the real world. We use the exception mechanism (in GHC.Exception) to
59 implement IO exceptions.
60
61 NOTE: The IO representation is deeply wired in to various parts of the
62 system. The following list may or may not be exhaustive:
63
64 Compiler - types of various primitives in PrimOp.hs
65
66 RTS - forceIO (StgStartup.cmm)
67 - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast
68 (Exception.cmm)
69 - raiseAsync (RaiseAsync.c)
70
71 Prelude - GHC.IO.hs, and several other places including
72 GHC.Exception.hs.
73
74 Libraries - parts of hslibs/lang.
75
76 --SDM
77 -}
78
79 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
80 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
81
82 -- ---------------------------------------------------------------------------
83 -- Coercions between IO and ST
84
85 -- | Embed a strict state thread in an 'IO'
86 -- action. 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 -- | Convert an 'IO' action into an 'ST' action. The type of the result
93 -- is constrained to use a 'RealWorld' state thread, and therefore the
94 -- result cannot be passed to 'runST'.
95 ioToST :: IO a -> ST RealWorld a
96 ioToST (IO m) = (ST m)
97
98 -- | Convert an 'IO' action to an 'ST' action.
99 -- This relies on 'IO' and 'ST' having the same representation modulo the
100 -- constraint on the state thread type parameter.
101 unsafeIOToST :: IO a -> ST s a
102 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
103
104 -- | Convert an 'ST' action to an 'IO' action.
105 -- This relies on 'IO' and 'ST' having the same representation modulo the
106 -- constraint on the state thread type parameter.
107 --
108 -- For an example demonstrating why this is unsafe, see
109 -- https://mail.haskell.org/pipermail/haskell-cafe/2009-April/060719.html
110 unsafeSTToIO :: ST s a -> IO a
111 unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
112
113 -- -----------------------------------------------------------------------------
114 -- | File and directory names are values of type 'String', whose precise
115 -- meaning is operating system dependent. Files can be opened, yielding a
116 -- handle which can then be used to operate on the contents of that file.
117
118 type FilePath = String
119
120 -- -----------------------------------------------------------------------------
121 -- Primitive catch and throwIO
122
123 {-
124 catchException/catch used to handle the passing around of the state to the
125 action and the handler. This turned out to be a bad idea - it meant
126 that we had to wrap both arguments in thunks so they could be entered
127 as normal (remember IO returns an unboxed pair...).
128
129 Now catch# has type
130
131 catch# :: IO a -> (b -> IO a) -> IO a
132
133 (well almost; the compiler doesn't know about the IO newtype so we
134 have to work around that in the definition of catch below).
135 -}
136
137 -- | Catch an exception in the 'IO' monad.
138 --
139 -- Note that this function is /strict/ in the action. That is,
140 -- @catchException undefined b == _|_@. See #exceptions_and_strictness#
141 -- for details.
142 catchException :: Exception e => IO a -> (e -> IO a) -> IO a
143 catchException !io handler = catch io handler
144
145 -- | This is the simplest of the exception-catching functions. It
146 -- takes a single argument, runs it, and if an exception is raised
147 -- the \"handler\" is executed, with the value of the exception passed as an
148 -- argument. Otherwise, the result is returned as normal. For example:
149 --
150 -- > catch (readFile f)
151 -- > (\e -> do let err = show (e :: IOException)
152 -- > hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err)
153 -- > return "")
154 --
155 -- Note that we have to give a type signature to @e@, or the program
156 -- will not typecheck as the type is ambiguous. While it is possible
157 -- to catch exceptions of any type, see the section \"Catching all
158 -- exceptions\" (in "Control.Exception") for an explanation of the problems with doing so.
159 --
160 -- For catching exceptions in pure (non-'IO') expressions, see the
161 -- function 'evaluate'.
162 --
163 -- Note that due to Haskell\'s unspecified evaluation order, an
164 -- expression may throw one of several possible exceptions: consider
165 -- the expression @(error \"urk\") + (1 \`div\` 0)@. Does
166 -- the expression throw
167 -- @ErrorCall \"urk\"@, or @DivideByZero@?
168 --
169 -- The answer is \"it might throw either\"; the choice is
170 -- non-deterministic. If you are catching any type of exception then you
171 -- might catch either. If you are calling @catch@ with type
172 -- @IO Int -> (ArithException -> IO Int) -> IO Int@ then the handler may
173 -- get run with @DivideByZero@ as an argument, or an @ErrorCall \"urk\"@
174 -- exception may be propogated further up. If you call it again, you
175 -- might get a the opposite behaviour. This is ok, because 'catch' is an
176 -- 'IO' computation.
177 --
178 catch :: Exception e
179 => IO a -- ^ The computation to run
180 -> (e -> IO a) -- ^ Handler to invoke if an exception is raised
181 -> IO a
182 -- See #exceptions_and_strictness#.
183 catch (IO io) handler = IO $ catch# io handler'
184 where handler' e = case fromException e of
185 Just e' -> unIO (handler e')
186 Nothing -> raiseIO# e
187
188
189 -- | Catch any 'Exception' type in the 'IO' monad.
190 --
191 -- Note that this function is /strict/ in the action. That is,
192 -- @catchAny undefined b == _|_@. See #exceptions_and_strictness# for
193 -- details.
194 catchAny :: IO a -> (forall e . Exception e => e -> IO a) -> IO a
195 catchAny !(IO io) handler = IO $ catch# io handler'
196 where handler' (SomeException e) = unIO (handler e)
197
198 -- Using catchException here means that if `m` throws an
199 -- 'IOError' /as an imprecise exception/, we will not catch
200 -- it. No one should really be doing that anyway.
201 mplusIO :: IO a -> IO a -> IO a
202 mplusIO m n = m `catchException` \ (_ :: IOError) -> n
203
204 -- | A variant of 'throw' that can only be used within the 'IO' monad.
205 --
206 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
207 -- two functions are subtly different:
208 --
209 -- > throw e `seq` x ===> throw e
210 -- > throwIO e `seq` x ===> x
211 --
212 -- The first example will cause the exception @e@ to be raised,
213 -- whereas the second one won\'t. In fact, 'throwIO' will only cause
214 -- an exception to be raised when it is used within the 'IO' monad.
215 -- The 'throwIO' variant should be used in preference to 'throw' to
216 -- raise an exception within the 'IO' monad because it guarantees
217 -- ordering with respect to other 'IO' operations, whereas 'throw'
218 -- does not.
219 throwIO :: Exception e => e -> IO a
220 throwIO e = IO (raiseIO# (toException e))
221
222 -- -----------------------------------------------------------------------------
223 -- Controlling asynchronous exception delivery
224
225 -- Applying 'block' to a computation will
226 -- execute that computation with asynchronous exceptions
227 -- /blocked/. That is, any thread which
228 -- attempts to raise an exception in the current thread with 'Control.Exception.throwTo' will be
229 -- blocked until asynchronous exceptions are unblocked again. There\'s
230 -- no need to worry about re-enabling asynchronous exceptions; that is
231 -- done automatically on exiting the scope of
232 -- 'block'.
233 --
234 -- Threads created by 'Control.Concurrent.forkIO' inherit the blocked
235 -- state from the parent; that is, to start a thread in blocked mode,
236 -- use @block $ forkIO ...@. This is particularly useful if you need to
237 -- establish an exception handler in the forked thread before any
238 -- asynchronous exceptions are received.
239 block :: IO a -> IO a
240 block (IO io) = IO $ maskAsyncExceptions# io
241
242 -- To re-enable asynchronous exceptions inside the scope of
243 -- 'block', 'unblock' can be
244 -- used. It scopes in exactly the same way, so on exit from
245 -- 'unblock' asynchronous exception delivery will
246 -- be disabled again.
247 unblock :: IO a -> IO a
248 unblock = unsafeUnmask
249
250 unsafeUnmask :: IO a -> IO a
251 unsafeUnmask (IO io) = IO $ unmaskAsyncExceptions# io
252
253 -- | Allow asynchronous exceptions to be raised even inside 'mask', making
254 -- the operation interruptible (see the discussion of "Interruptible operations"
255 -- in 'Control.Exception').
256 --
257 -- When called outside 'mask', or inside 'uninterruptibleMask', this
258 -- function has no effect.
259 --
260 -- @since 4.9.0.0
261 interruptible :: IO a -> IO a
262 interruptible act = do
263 st <- getMaskingState
264 case st of
265 Unmasked -> act
266 MaskedInterruptible -> unsafeUnmask act
267 MaskedUninterruptible -> act
268
269 blockUninterruptible :: IO a -> IO a
270 blockUninterruptible (IO io) = IO $ maskUninterruptible# io
271
272 -- | Describes the behaviour of a thread when an asynchronous
273 -- exception is received.
274 data MaskingState
275 = Unmasked -- ^ asynchronous exceptions are unmasked (the normal state)
276 | MaskedInterruptible
277 -- ^ the state during 'mask': asynchronous exceptions are masked, but blocking operations may still be interrupted
278 | MaskedUninterruptible
279 -- ^ the state during 'uninterruptibleMask': asynchronous exceptions are masked, and blocking operations may not be interrupted
280 deriving ( Eq -- ^ @since 4.3.0.0
281 , Show -- ^ @since 4.3.0.0
282 )
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 #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 -}
458
459 -- For SOURCE import by GHC.Base to define failIO.
460 mkUserError :: [Char] -> SomeException
461 mkUserError str = toException (userError str)