Fix comment (old filename '.lhs') in libraries/
[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, mplusIO,
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, interruptible,
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 GHC.IO.Unsafe
48
49 import {-# SOURCE #-} GHC.IO.Exception ( userError, IOError )
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.hs
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.hs, and several other places including
70 GHC.Exception.hs.
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 -- | File and directory names are values of type 'String', whose precise
107 -- meaning is operating system dependent. Files can be opened, yielding a
108 -- handle which can then be used to operate on the contents of that file.
109
110 type FilePath = String
111
112 -- -----------------------------------------------------------------------------
113 -- Primitive catch and throwIO
114
115 {-
116 catchException used to handle the passing around of the state to the
117 action and the handler. This turned out to be a bad idea - it meant
118 that we had to wrap both arguments in thunks so they could be entered
119 as normal (remember IO returns an unboxed pair...).
120
121 Now catch# has type
122
123 catch# :: IO a -> (b -> IO a) -> IO a
124
125 (well almost; the compiler doesn't know about the IO newtype so we
126 have to work around that in the definition of catchException below).
127 -}
128
129 -- | Catch an exception in the 'IO' monad.
130 --
131 -- Note that this function is /strict/ in the action. That is,
132 -- @catchException undefined b == _|_@. See #exceptions_and_strictness#
133 -- for details.
134 catchException :: Exception e => IO a -> (e -> IO a) -> IO a
135 catchException (IO io) handler = IO $ catch# io handler'
136 where handler' e = case fromException e of
137 Just e' -> unIO (handler e')
138 Nothing -> raiseIO# e
139
140 -- | Catch any 'Exception' type in the 'IO' monad.
141 --
142 -- Note that this function is /strict/ in the action. That is,
143 -- @catchException undefined b == _|_@. See #exceptions_and_strictness# for
144 -- details.
145 catchAny :: IO a -> (forall e . Exception e => e -> IO a) -> IO a
146 catchAny (IO io) handler = IO $ catch# io handler'
147 where handler' (SomeException e) = unIO (handler e)
148
149
150 mplusIO :: IO a -> IO a -> IO a
151 mplusIO m n = m `catchIOError` \ _ -> n
152 where catchIOError :: IO a -> (IOError -> IO a) -> IO a
153 catchIOError = catchException
154
155 -- | A variant of 'throw' that can only be used within the 'IO' monad.
156 --
157 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
158 -- two functions are subtly different:
159 --
160 -- > throw e `seq` x ===> throw e
161 -- > throwIO e `seq` x ===> x
162 --
163 -- The first example will cause the exception @e@ to be raised,
164 -- whereas the second one won\'t. In fact, 'throwIO' will only cause
165 -- an exception to be raised when it is used within the 'IO' monad.
166 -- The 'throwIO' variant should be used in preference to 'throw' to
167 -- raise an exception within the 'IO' monad because it guarantees
168 -- ordering with respect to other 'IO' operations, whereas 'throw'
169 -- does not.
170 throwIO :: Exception e => e -> IO a
171 throwIO e = IO (raiseIO# (toException e))
172
173 -- -----------------------------------------------------------------------------
174 -- Controlling asynchronous exception delivery
175
176 -- Applying 'block' to a computation will
177 -- execute that computation with asynchronous exceptions
178 -- /blocked/. That is, any thread which
179 -- attempts to raise an exception in the current thread with 'Control.Exception.throwTo' will be
180 -- blocked until asynchronous exceptions are unblocked again. There\'s
181 -- no need to worry about re-enabling asynchronous exceptions; that is
182 -- done automatically on exiting the scope of
183 -- 'block'.
184 --
185 -- Threads created by 'Control.Concurrent.forkIO' inherit the blocked
186 -- state from the parent; that is, to start a thread in blocked mode,
187 -- use @block $ forkIO ...@. This is particularly useful if you need to
188 -- establish an exception handler in the forked thread before any
189 -- asynchronous exceptions are received.
190 block :: IO a -> IO a
191 block (IO io) = IO $ maskAsyncExceptions# io
192
193 -- To re-enable asynchronous exceptions inside the scope of
194 -- 'block', 'unblock' can be
195 -- used. It scopes in exactly the same way, so on exit from
196 -- 'unblock' asynchronous exception delivery will
197 -- be disabled again.
198 unblock :: IO a -> IO a
199 unblock = unsafeUnmask
200
201 unsafeUnmask :: IO a -> IO a
202 unsafeUnmask (IO io) = IO $ unmaskAsyncExceptions# io
203
204 -- | Allow asynchronous exceptions to be raised even inside 'mask', making
205 -- the operation interruptible (see the discussion of "Interruptible operations"
206 -- in 'Control.Exception').
207 --
208 -- When called outside 'mask', or inside 'uninterruptibleMask', this
209 -- function has no effect.
210 --
211 -- @since 4.9.0.0
212 interruptible :: IO a -> IO a
213 interruptible act = do
214 st <- getMaskingState
215 case st of
216 Unmasked -> act
217 MaskedInterruptible -> unsafeUnmask act
218 MaskedUninterruptible -> act
219
220 blockUninterruptible :: IO a -> IO a
221 blockUninterruptible (IO io) = IO $ maskUninterruptible# io
222
223 -- | Describes the behaviour of a thread when an asynchronous
224 -- exception is received.
225 data MaskingState
226 = Unmasked -- ^ asynchronous exceptions are unmasked (the normal state)
227 | MaskedInterruptible
228 -- ^ the state during 'mask': asynchronous exceptions are masked, but blocking operations may still be interrupted
229 | MaskedUninterruptible
230 -- ^ the state during 'uninterruptibleMask': asynchronous exceptions are masked, and blocking operations may not be interrupted
231 deriving (Eq,Show)
232
233 -- | Returns the 'MaskingState' for the current thread.
234 getMaskingState :: IO MaskingState
235 getMaskingState = IO $ \s ->
236 case getMaskingState# s of
237 (# s', i #) -> (# s', case i of
238 0# -> Unmasked
239 1# -> MaskedUninterruptible
240 _ -> MaskedInterruptible #)
241
242 onException :: IO a -> IO b -> IO a
243 onException io what = io `catchException` \e -> do _ <- what
244 throwIO (e :: SomeException)
245
246 -- | Executes an IO computation with asynchronous
247 -- exceptions /masked/. That is, any thread which attempts to raise
248 -- an exception in the current thread with 'Control.Exception.throwTo'
249 -- will be blocked until asynchronous exceptions are unmasked again.
250 --
251 -- The argument passed to 'mask' is a function that takes as its
252 -- argument another function, which can be used to restore the
253 -- prevailing masking state within the context of the masked
254 -- computation. For example, a common way to use 'mask' is to protect
255 -- the acquisition of a resource:
256 --
257 -- > mask $ \restore -> do
258 -- > x <- acquire
259 -- > restore (do_something_with x) `onException` release
260 -- > release
261 --
262 -- This code guarantees that @acquire@ is paired with @release@, by masking
263 -- asynchronous exceptions for the critical parts. (Rather than write
264 -- this code yourself, it would be better to use
265 -- 'Control.Exception.bracket' which abstracts the general pattern).
266 --
267 -- Note that the @restore@ action passed to the argument to 'mask'
268 -- does not necessarily unmask asynchronous exceptions, it just
269 -- restores the masking state to that of the enclosing context. Thus
270 -- if asynchronous exceptions are already masked, 'mask' cannot be used
271 -- to unmask exceptions again. This is so that if you call a library function
272 -- with exceptions masked, you can be sure that the library call will not be
273 -- able to unmask exceptions again. If you are writing library code and need
274 -- to use asynchronous exceptions, the only way is to create a new thread;
275 -- see 'Control.Concurrent.forkIOWithUnmask'.
276 --
277 -- Asynchronous exceptions may still be received while in the masked
278 -- state if the masked thread /blocks/ in certain ways; see
279 -- "Control.Exception#interruptible".
280 --
281 -- Threads created by 'Control.Concurrent.forkIO' inherit the
282 -- 'MaskingState' from the parent; that is, to start a thread in the
283 -- 'MaskedInterruptible' state,
284 -- use @mask_ $ forkIO ...@. This is particularly useful if you need
285 -- to establish an exception handler in the forked thread before any
286 -- asynchronous exceptions are received. To create a a new thread in
287 -- an unmasked state use 'Control.Concurrent.forkIOUnmasked'.
288 --
289 mask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
290
291 -- | Like 'mask', but does not pass a @restore@ action to the argument.
292 mask_ :: IO a -> IO a
293
294 -- | Like 'mask', but the masked computation is not interruptible (see
295 -- "Control.Exception#interruptible"). THIS SHOULD BE USED WITH
296 -- GREAT CARE, because if a thread executing in 'uninterruptibleMask'
297 -- blocks for any reason, then the thread (and possibly the program,
298 -- if this is the main thread) will be unresponsive and unkillable.
299 -- This function should only be necessary if you need to mask
300 -- exceptions around an interruptible operation, and you can guarantee
301 -- that the interruptible operation will only block for a short period
302 -- of time.
303 --
304 uninterruptibleMask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
305
306 -- | Like 'uninterruptibleMask', but does not pass a @restore@ action
307 -- to the argument.
308 uninterruptibleMask_ :: IO a -> IO a
309
310 mask_ io = mask $ \_ -> io
311
312 mask io = do
313 b <- getMaskingState
314 case b of
315 Unmasked -> block $ io unblock
316 MaskedInterruptible -> io block
317 MaskedUninterruptible -> io blockUninterruptible
318
319 uninterruptibleMask_ io = uninterruptibleMask $ \_ -> io
320
321 uninterruptibleMask io = do
322 b <- getMaskingState
323 case b of
324 Unmasked -> blockUninterruptible $ io unblock
325 MaskedInterruptible -> blockUninterruptible $ io block
326 MaskedUninterruptible -> io blockUninterruptible
327
328 bracket
329 :: IO a -- ^ computation to run first (\"acquire resource\")
330 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
331 -> (a -> IO c) -- ^ computation to run in-between
332 -> IO c -- returns the value from the in-between computation
333 bracket before after thing =
334 mask $ \restore -> do
335 a <- before
336 r <- restore (thing a) `onException` after a
337 _ <- after a
338 return r
339
340 finally :: IO a -- ^ computation to run first
341 -> IO b -- ^ computation to run afterward (even if an exception
342 -- was raised)
343 -> IO a -- returns the value from the first computation
344 a `finally` sequel =
345 mask $ \restore -> do
346 r <- restore a `onException` sequel
347 _ <- sequel
348 return r
349
350 -- | Evaluate the argument to weak head normal form.
351 --
352 -- 'evaluate' is typically used to uncover any exceptions that a lazy value
353 -- may contain, and possibly handle them.
354 --
355 -- 'evaluate' only evaluates to /weak head normal form/. If deeper
356 -- evaluation is needed, the @force@ function from @Control.DeepSeq@
357 -- may be handy:
358 --
359 -- > evaluate $ force x
360 --
361 -- There is a subtle difference between @'evaluate' x@ and @'return' '$!' x@,
362 -- analogous to the difference between 'throwIO' and 'throw'. If the lazy
363 -- value @x@ throws an exception, @'return' '$!' x@ will fail to return an
364 -- 'IO' action and will throw an exception instead. @'evaluate' x@, on the
365 -- other hand, always produces an 'IO' action; that action will throw an
366 -- exception upon /execution/ iff @x@ throws an exception upon /evaluation/.
367 --
368 -- The practical implication of this difference is that due to the
369 -- /imprecise exceptions/ semantics,
370 --
371 -- > (return $! error "foo") >> error "bar"
372 --
373 -- may throw either @"foo"@ or @"bar"@, depending on the optimizations
374 -- performed by the compiler. On the other hand,
375 --
376 -- > evaluate (error "foo") >> error "bar"
377 --
378 -- is guaranteed to throw @"foo"@.
379 --
380 -- The rule of thumb is to use 'evaluate' to force or handle exceptions in
381 -- lazy values. If, on the other hand, you are forcing a lazy value for
382 -- efficiency reasons only and do not care about exceptions, you may
383 -- use @'return' '$!' x@.
384 evaluate :: a -> IO a
385 evaluate a = IO $ \s -> seq# a s -- NB. see #2273, #5129
386
387 {- $exceptions_and_strictness
388
389 Laziness can interact with @catch@-like operations in non-obvious ways (see,
390 e.g. GHC Trac #11555). For instance, consider these subtly-different examples,
391
392 > test1 = Control.Exception.catch (error "uh oh") (\(_ :: SomeException) -> putStrLn "it failed")
393 >
394 > test2 = GHC.IO.catchException (error "uh oh") (\(_ :: SomeException) -> putStrLn "it failed")
395
396 While the first case is always guaranteed to print "it failed", the behavior of
397 @test2@ may vary with optimization level.
398
399 The unspecified behavior of @test2@ is due to the fact that GHC may assume that
400 'catchException' (and the 'catch#' primitive operation which it is built upon)
401 is strict in its first argument. This assumption allows the compiler to better
402 optimize @catchException@ calls at the expense of deterministic behavior when
403 the action may be bottom.
404
405 Namely, the assumed strictness means that exceptions thrown while evaluating the
406 action-to-be-executed may not be caught; only exceptions thrown during execution
407 of the action will be handled by the exception handler.
408
409 Since this strictness is a small optimization and may lead to surprising
410 results, all of the @catch@ and @handle@ variants offered by "Control.Exception"
411 are lazy in their first argument. If you are certain that that the action to be
412 executed won't bottom in performance-sensitive code, you might consider using
413 'GHC.IO.catchException' or 'GHC.IO.catchAny' for a small speed-up.
414 -}