Make 'error' include the CCS call stack when profiled
[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.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 -- | 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 catchException :: Exception e => IO a -> (e -> IO a) -> IO a
130 catchException (IO io) handler = IO $ catch# io handler'
131 where handler' e = case fromException e of
132 Just e' -> unIO (handler e')
133 Nothing -> raiseIO# e
134
135 catchAny :: IO a -> (forall e . Exception e => e -> IO a) -> IO a
136 catchAny (IO io) handler = IO $ catch# io handler'
137 where handler' (SomeException e) = unIO (handler e)
138
139
140 mplusIO :: IO a -> IO a -> IO a
141 mplusIO m n = m `catchIOError` \ _ -> n
142 where catchIOError :: IO a -> (IOError -> IO a) -> IO a
143 catchIOError = catchException
144
145 -- | A variant of 'throw' that can only be used within the 'IO' monad.
146 --
147 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
148 -- two functions are subtly different:
149 --
150 -- > throw e `seq` x ===> throw e
151 -- > throwIO e `seq` x ===> x
152 --
153 -- The first example will cause the exception @e@ to be raised,
154 -- whereas the second one won\'t. In fact, 'throwIO' will only cause
155 -- an exception to be raised when it is used within the 'IO' monad.
156 -- The 'throwIO' variant should be used in preference to 'throw' to
157 -- raise an exception within the 'IO' monad because it guarantees
158 -- ordering with respect to other 'IO' operations, whereas 'throw'
159 -- does not.
160 throwIO :: Exception e => e -> IO a
161 throwIO e = IO (raiseIO# (toException e))
162
163 -- -----------------------------------------------------------------------------
164 -- Controlling asynchronous exception delivery
165
166 -- Applying 'block' to a computation will
167 -- execute that computation with asynchronous exceptions
168 -- /blocked/. That is, any thread which
169 -- attempts to raise an exception in the current thread with 'Control.Exception.throwTo' will be
170 -- blocked until asynchronous exceptions are unblocked again. There\'s
171 -- no need to worry about re-enabling asynchronous exceptions; that is
172 -- done automatically on exiting the scope of
173 -- 'block'.
174 --
175 -- Threads created by 'Control.Concurrent.forkIO' inherit the blocked
176 -- state from the parent; that is, to start a thread in blocked mode,
177 -- use @block $ forkIO ...@. This is particularly useful if you need to
178 -- establish an exception handler in the forked thread before any
179 -- asynchronous exceptions are received.
180 block :: IO a -> IO a
181 block (IO io) = IO $ maskAsyncExceptions# io
182
183 -- To re-enable asynchronous exceptions inside the scope of
184 -- 'block', 'unblock' can be
185 -- used. It scopes in exactly the same way, so on exit from
186 -- 'unblock' asynchronous exception delivery will
187 -- be disabled again.
188 unblock :: IO a -> IO a
189 unblock = unsafeUnmask
190
191 unsafeUnmask :: IO a -> IO a
192 unsafeUnmask (IO io) = IO $ unmaskAsyncExceptions# io
193
194 -- | Allow asynchronous exceptions to be raised even inside 'mask', making
195 -- the operation interruptible (see the discussion of "Interruptible operations"
196 -- in 'Control.Exception').
197 --
198 -- When called outside 'mask', or inside 'uninterruptibleMask', this
199 -- function has no effect.
200 --
201 -- @since 4.9.0.0
202 interruptible :: IO a -> IO a
203 interruptible act = do
204 st <- getMaskingState
205 case st of
206 Unmasked -> act
207 MaskedInterruptible -> unsafeUnmask act
208 MaskedUninterruptible -> act
209
210 blockUninterruptible :: IO a -> IO a
211 blockUninterruptible (IO io) = IO $ maskUninterruptible# io
212
213 -- | Describes the behaviour of a thread when an asynchronous
214 -- exception is received.
215 data MaskingState
216 = Unmasked -- ^ asynchronous exceptions are unmasked (the normal state)
217 | MaskedInterruptible
218 -- ^ the state during 'mask': asynchronous exceptions are masked, but blocking operations may still be interrupted
219 | MaskedUninterruptible
220 -- ^ the state during 'uninterruptibleMask': asynchronous exceptions are masked, and blocking operations may not be interrupted
221 deriving (Eq,Show)
222
223 -- | Returns the 'MaskingState' for the current thread.
224 getMaskingState :: IO MaskingState
225 getMaskingState = IO $ \s ->
226 case getMaskingState# s of
227 (# s', i #) -> (# s', case i of
228 0# -> Unmasked
229 1# -> MaskedUninterruptible
230 _ -> MaskedInterruptible #)
231
232 onException :: IO a -> IO b -> IO a
233 onException io what = io `catchException` \e -> do _ <- what
234 throwIO (e :: SomeException)
235
236 -- | Executes an IO computation with asynchronous
237 -- exceptions /masked/. That is, any thread which attempts to raise
238 -- an exception in the current thread with 'Control.Exception.throwTo'
239 -- will be blocked until asynchronous exceptions are unmasked again.
240 --
241 -- The argument passed to 'mask' is a function that takes as its
242 -- argument another function, which can be used to restore the
243 -- prevailing masking state within the context of the masked
244 -- computation. For example, a common way to use 'mask' is to protect
245 -- the acquisition of a resource:
246 --
247 -- > mask $ \restore -> do
248 -- > x <- acquire
249 -- > restore (do_something_with x) `onException` release
250 -- > release
251 --
252 -- This code guarantees that @acquire@ is paired with @release@, by masking
253 -- asynchronous exceptions for the critical parts. (Rather than write
254 -- this code yourself, it would be better to use
255 -- 'Control.Exception.bracket' which abstracts the general pattern).
256 --
257 -- Note that the @restore@ action passed to the argument to 'mask'
258 -- does not necessarily unmask asynchronous exceptions, it just
259 -- restores the masking state to that of the enclosing context. Thus
260 -- if asynchronous exceptions are already masked, 'mask' cannot be used
261 -- to unmask exceptions again. This is so that if you call a library function
262 -- with exceptions masked, you can be sure that the library call will not be
263 -- able to unmask exceptions again. If you are writing library code and need
264 -- to use asynchronous exceptions, the only way is to create a new thread;
265 -- see 'Control.Concurrent.forkIOWithUnmask'.
266 --
267 -- Asynchronous exceptions may still be received while in the masked
268 -- state if the masked thread /blocks/ in certain ways; see
269 -- "Control.Exception#interruptible".
270 --
271 -- Threads created by 'Control.Concurrent.forkIO' inherit the
272 -- 'MaskingState' from the parent; that is, to start a thread in the
273 -- 'MaskedInterruptible' state,
274 -- use @mask_ $ forkIO ...@. This is particularly useful if you need
275 -- to establish an exception handler in the forked thread before any
276 -- asynchronous exceptions are received. To create a a new thread in
277 -- an unmasked state use 'Control.Concurrent.forkIOUnmasked'.
278 --
279 mask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
280
281 -- | Like 'mask', but does not pass a @restore@ action to the argument.
282 mask_ :: IO a -> IO a
283
284 -- | Like 'mask', but the masked computation is not interruptible (see
285 -- "Control.Exception#interruptible"). THIS SHOULD BE USED WITH
286 -- GREAT CARE, because if a thread executing in 'uninterruptibleMask'
287 -- blocks for any reason, then the thread (and possibly the program,
288 -- if this is the main thread) will be unresponsive and unkillable.
289 -- This function should only be necessary if you need to mask
290 -- exceptions around an interruptible operation, and you can guarantee
291 -- that the interruptible operation will only block for a short period
292 -- of time.
293 --
294 uninterruptibleMask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
295
296 -- | Like 'uninterruptibleMask', but does not pass a @restore@ action
297 -- to the argument.
298 uninterruptibleMask_ :: IO a -> IO a
299
300 mask_ io = mask $ \_ -> io
301
302 mask io = do
303 b <- getMaskingState
304 case b of
305 Unmasked -> block $ io unblock
306 MaskedInterruptible -> io block
307 MaskedUninterruptible -> io blockUninterruptible
308
309 uninterruptibleMask_ io = uninterruptibleMask $ \_ -> io
310
311 uninterruptibleMask io = do
312 b <- getMaskingState
313 case b of
314 Unmasked -> blockUninterruptible $ io unblock
315 MaskedInterruptible -> blockUninterruptible $ io block
316 MaskedUninterruptible -> io blockUninterruptible
317
318 bracket
319 :: IO a -- ^ computation to run first (\"acquire resource\")
320 -> (a -> IO b) -- ^ computation to run last (\"release resource\")
321 -> (a -> IO c) -- ^ computation to run in-between
322 -> IO c -- returns the value from the in-between computation
323 bracket before after thing =
324 mask $ \restore -> do
325 a <- before
326 r <- restore (thing a) `onException` after a
327 _ <- after a
328 return r
329
330 finally :: IO a -- ^ computation to run first
331 -> IO b -- ^ computation to run afterward (even if an exception
332 -- was raised)
333 -> IO a -- returns the value from the first computation
334 a `finally` sequel =
335 mask $ \restore -> do
336 r <- restore a `onException` sequel
337 _ <- sequel
338 return r
339
340 -- | Evaluate the argument to weak head normal form.
341 --
342 -- 'evaluate' is typically used to uncover any exceptions that a lazy value
343 -- may contain, and possibly handle them.
344 --
345 -- 'evaluate' only evaluates to /weak head normal form/. If deeper
346 -- evaluation is needed, the @force@ function from @Control.DeepSeq@
347 -- may be handy:
348 --
349 -- > evaluate $ force x
350 --
351 -- There is a subtle difference between @'evaluate' x@ and @'return' '$!' x@,
352 -- analogous to the difference between 'throwIO' and 'throw'. If the lazy
353 -- value @x@ throws an exception, @'return' '$!' x@ will fail to return an
354 -- 'IO' action and will throw an exception instead. @'evaluate' x@, on the
355 -- other hand, always produces an 'IO' action; that action will throw an
356 -- exception upon /execution/ iff @x@ throws an exception upon /evaluation/.
357 --
358 -- The practical implication of this difference is that due to the
359 -- /imprecise exceptions/ semantics,
360 --
361 -- > (return $! error "foo") >> error "bar"
362 --
363 -- may throw either @"foo"@ or @"bar"@, depending on the optimizations
364 -- performed by the compiler. On the other hand,
365 --
366 -- > evaluate (error "foo") >> error "bar"
367 --
368 -- is guaranteed to throw @"foo"@.
369 --
370 -- The rule of thumb is to use 'evaluate' to force or handle exceptions in
371 -- lazy values. If, on the other hand, you are forcing a lazy value for
372 -- efficiency reasons only and do not care about exceptions, you may
373 -- use @'return' '$!' x@.
374 evaluate :: a -> IO a
375 evaluate a = IO $ \s -> seq# a s -- NB. see #2273, #5129