elaborate the docs for unsafePerformIO a bit
[ghc.git] / libraries / base / GHC / IO.hs
1 {-# OPTIONS_GHC -XNoImplicitPrelude -funbox-strict-fields -XBangPatterns #-}
2 {-# OPTIONS_HADDOCK hide #-}
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module : GHC.IO
6 -- Copyright : (c) The University of Glasgow 1994-2002
7 -- License : see libraries/base/LICENSE
8 --
9 -- Maintainer : cvs-ghc@haskell.org
10 -- Stability : internal
11 -- Portability : non-portable (GHC Extensions)
12 --
13 -- Definitions for the 'IO' monad and its friends.
14 --
15 -----------------------------------------------------------------------------
16
17 -- #hide
18 module GHC.IO (
19 IO(..), unIO, failIO, liftIO,
20 unsafePerformIO, unsafeInterleaveIO,
21 unsafeDupablePerformIO, unsafeDupableInterleaveIO,
22 noDuplicate,
23
24 -- To and from from ST
25 stToIO, ioToST, unsafeIOToST, unsafeSTToIO,
26
27 FilePath,
28
29 catchException, catchAny, throwIO,
30 block, unblock, blocked,
31 onException, finally, evaluate
32 ) where
33
34 import GHC.Base
35 import GHC.ST
36 import GHC.Exception
37 import Data.Maybe
38
39 import {-# SOURCE #-} GHC.IO.Exception ( userError )
40
41 -- ---------------------------------------------------------------------------
42 -- The IO Monad
43
44 {-
45 The IO Monad is just an instance of the ST monad, where the state is
46 the real world. We use the exception mechanism (in GHC.Exception) to
47 implement IO exceptions.
48
49 NOTE: The IO representation is deeply wired in to various parts of the
50 system. The following list may or may not be exhaustive:
51
52 Compiler - types of various primitives in PrimOp.lhs
53
54 RTS - forceIO (StgMiscClosures.hc)
55 - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast
56 (Exceptions.hc)
57 - raiseAsync (Schedule.c)
58
59 Prelude - GHC.IO.lhs, and several other places including
60 GHC.Exception.lhs.
61
62 Libraries - parts of hslibs/lang.
63
64 --SDM
65 -}
66
67 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
68 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
69
70 failIO :: String -> IO a
71 failIO s = IO (raiseIO# (toException (userError s)))
72
73 -- ---------------------------------------------------------------------------
74 -- Coercions between IO and ST
75
76 -- | A monad transformer embedding strict state transformers in the 'IO'
77 -- monad. The 'RealWorld' parameter indicates that the internal state
78 -- used by the 'ST' computation is a special one supplied by the 'IO'
79 -- monad, and thus distinct from those used by invocations of 'runST'.
80 stToIO :: ST RealWorld a -> IO a
81 stToIO (ST m) = IO m
82
83 ioToST :: IO a -> ST RealWorld a
84 ioToST (IO m) = (ST m)
85
86 -- This relies on IO and ST having the same representation modulo the
87 -- constraint on the type of the state
88 --
89 unsafeIOToST :: IO a -> ST s a
90 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
91
92 unsafeSTToIO :: ST s a -> IO a
93 unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
94
95 -- ---------------------------------------------------------------------------
96 -- Unsafe IO operations
97
98 {-|
99 This is the \"back door\" into the 'IO' monad, allowing
100 'IO' computation to be performed at any time. For
101 this to be safe, the 'IO' computation should be
102 free of side effects and independent of its environment.
103
104 If the I\/O computation wrapped in 'unsafePerformIO' performs side
105 effects, then the relative order in which those side effects take
106 place (relative to the main I\/O trunk, or other calls to
107 'unsafePerformIO') is indeterminate. Furthermore, when using
108 'unsafePerformIO' to cause side-effects, you should take the following
109 precautions to ensure the side effects are performed as many times as
110 you expect them to be. Note that these precautions are necessary for
111 GHC, but may not be sufficient, and other compilers may require
112 different precautions:
113
114 * Use @{\-\# NOINLINE foo \#-\}@ as a pragma on any function @foo@
115 that calls 'unsafePerformIO'. If the call is inlined,
116 the I\/O may be performed more than once.
117
118 * Use the compiler flag @-fno-cse@ to prevent common sub-expression
119 elimination being performed on the module, which might combine
120 two side effects that were meant to be separate. A good example
121 is using multiple global variables (like @test@ in the example below).
122
123 * Make sure that the either you switch off let-floating (@-fno-full-laziness@), or that the
124 call to 'unsafePerformIO' cannot float outside a lambda. For example,
125 if you say:
126 @
127 f x = unsafePerformIO (newIORef [])
128 @
129 you may get only one reference cell shared between all calls to @f@.
130 Better would be
131 @
132 f x = unsafePerformIO (newIORef [x])
133 @
134 because now it can't float outside the lambda.
135
136 It is less well known that
137 'unsafePerformIO' is not type safe. For example:
138
139 > test :: IORef [a]
140 > test = unsafePerformIO $ newIORef []
141 >
142 > main = do
143 > writeIORef test [42]
144 > bang <- readIORef test
145 > print (bang :: [Char])
146
147 This program will core dump. This problem with polymorphic references
148 is well known in the ML community, and does not arise with normal
149 monadic use of references. There is no easy way to make it impossible
150 once you use 'unsafePerformIO'. Indeed, it is
151 possible to write @coerce :: a -> b@ with the
152 help of 'unsafePerformIO'. So be careful!
153 -}
154 unsafePerformIO :: IO a -> a
155 unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)
156
157 {-|
158 This version of 'unsafePerformIO' is slightly more efficient,
159 because it omits the check that the IO is only being performed by a
160 single thread. Hence, when you write 'unsafeDupablePerformIO',
161 there is a possibility that the IO action may be performed multiple
162 times (on a multiprocessor), and you should therefore ensure that
163 it gives the same results each time.
164 -}
165 {-# NOINLINE unsafeDupablePerformIO #-}
166 unsafeDupablePerformIO :: IO a -> a
167 unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
168
169 -- Why do we NOINLINE unsafeDupablePerformIO? See the comment with
170 -- GHC.ST.runST. Essentially the issue is that the IO computation
171 -- inside unsafePerformIO must be atomic: it must either all run, or
172 -- not at all. If we let the compiler see the application of the IO
173 -- to realWorld#, it might float out part of the IO.
174
175 -- Why is there a call to 'lazy' in unsafeDupablePerformIO?
176 -- If we don't have it, the demand analyser discovers the following strictness
177 -- for unsafeDupablePerformIO: C(U(AV))
178 -- But then consider
179 -- unsafeDupablePerformIO (\s -> let r = f x in
180 -- case writeIORef v r s of (# s1, _ #) ->
181 -- (# s1, r #)
182 -- The strictness analyser will find that the binding for r is strict,
183 -- (becuase of uPIO's strictness sig), and so it'll evaluate it before
184 -- doing the writeIORef. This actually makes tests/lib/should_run/memo002
185 -- get a deadlock!
186 --
187 -- Solution: don't expose the strictness of unsafeDupablePerformIO,
188 -- by hiding it with 'lazy'
189
190 {-|
191 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
192 When passed a value of type @IO a@, the 'IO' will only be performed
193 when the value of the @a@ is demanded. This is used to implement lazy
194 file reading, see 'System.IO.hGetContents'.
195 -}
196 {-# INLINE unsafeInterleaveIO #-}
197 unsafeInterleaveIO :: IO a -> IO a
198 unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)
199
200 -- We believe that INLINE on unsafeInterleaveIO is safe, because the
201 -- state from this IO thread is passed explicitly to the interleaved
202 -- IO, so it cannot be floated out and shared.
203
204 {-# INLINE unsafeDupableInterleaveIO #-}
205 unsafeDupableInterleaveIO :: IO a -> IO a
206 unsafeDupableInterleaveIO (IO m)
207 = IO ( \ s -> let
208 r = case m s of (# _, res #) -> res
209 in
210 (# s, r #))
211
212 {-|
213 Ensures that the suspensions under evaluation by the current thread
214 are unique; that is, the current thread is not evaluating anything
215 that is also under evaluation by another thread that has also executed
216 'noDuplicate'.
217
218 This operation is used in the definition of 'unsafePerformIO' to
219 prevent the IO action from being executed multiple times, which is usually
220 undesirable.
221 -}
222 noDuplicate :: IO ()
223 noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)
224
225 -- -----------------------------------------------------------------------------
226 -- | File and directory names are values of type 'String', whose precise
227 -- meaning is operating system dependent. Files can be opened, yielding a
228 -- handle which can then be used to operate on the contents of that file.
229
230 type FilePath = String
231
232 -- -----------------------------------------------------------------------------
233 -- Primitive catch and throwIO
234
235 {-
236 catchException used to handle the passing around of the state to the
237 action and the handler. This turned out to be a bad idea - it meant
238 that we had to wrap both arguments in thunks so they could be entered
239 as normal (remember IO returns an unboxed pair...).
240
241 Now catch# has type
242
243 catch# :: IO a -> (b -> IO a) -> IO a
244
245 (well almost; the compiler doesn't know about the IO newtype so we
246 have to work around that in the definition of catchException below).
247 -}
248
249 catchException :: Exception e => IO a -> (e -> IO a) -> IO a
250 catchException (IO io) handler = IO $ catch# io handler'
251 where handler' e = case fromException e of
252 Just e' -> unIO (handler e')
253 Nothing -> raise# e
254
255 catchAny :: IO a -> (forall e . Exception e => e -> IO a) -> IO a
256 catchAny (IO io) handler = IO $ catch# io handler'
257 where handler' (SomeException e) = unIO (handler e)
258
259 -- | A variant of 'throw' that can only be used within the 'IO' monad.
260 --
261 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
262 -- two functions are subtly different:
263 --
264 -- > throw e `seq` x ===> throw e
265 -- > throwIO e `seq` x ===> x
266 --
267 -- The first example will cause the exception @e@ to be raised,
268 -- whereas the second one won\'t. In fact, 'throwIO' will only cause
269 -- an exception to be raised when it is used within the 'IO' monad.
270 -- The 'throwIO' variant should be used in preference to 'throw' to
271 -- raise an exception within the 'IO' monad because it guarantees
272 -- ordering with respect to other 'IO' operations, whereas 'throw'
273 -- does not.
274 throwIO :: Exception e => e -> IO a
275 throwIO e = IO (raiseIO# (toException e))
276
277 -- -----------------------------------------------------------------------------
278 -- Controlling asynchronous exception delivery
279
280 -- | Applying 'block' to a computation will
281 -- execute that computation with asynchronous exceptions
282 -- /blocked/. That is, any thread which
283 -- attempts to raise an exception in the current thread with 'Control.Exception.throwTo' will be
284 -- blocked until asynchronous exceptions are enabled again. There\'s
285 -- no need to worry about re-enabling asynchronous exceptions; that is
286 -- done automatically on exiting the scope of
287 -- 'block'.
288 --
289 -- Threads created by 'Control.Concurrent.forkIO' inherit the blocked
290 -- state from the parent; that is, to start a thread in blocked mode,
291 -- use @block $ forkIO ...@. This is particularly useful if you need to
292 -- establish an exception handler in the forked thread before any
293 -- asynchronous exceptions are received.
294 block :: IO a -> IO a
295
296 -- | To re-enable asynchronous exceptions inside the scope of
297 -- 'block', 'unblock' can be
298 -- used. It scopes in exactly the same way, so on exit from
299 -- 'unblock' asynchronous exception delivery will
300 -- be disabled again.
301 unblock :: IO a -> IO a
302
303 block (IO io) = IO $ blockAsyncExceptions# io
304 unblock (IO io) = IO $ unblockAsyncExceptions# io
305
306 -- | returns True if asynchronous exceptions are blocked in the
307 -- current thread.
308 blocked :: IO Bool
309 blocked = IO $ \s -> case asyncExceptionsBlocked# s of
310 (# s', i #) -> (# s', i /=# 0# #)
311
312 onException :: IO a -> IO b -> IO a
313 onException io what = io `catchException` \e -> do _ <- what
314 throw (e :: SomeException)
315
316 finally :: IO a -- ^ computation to run first
317 -> IO b -- ^ computation to run afterward (even if an exception
318 -- was raised)
319 -> IO a -- returns the value from the first computation
320 a `finally` sequel =
321 block (do
322 r <- unblock a `onException` sequel
323 _ <- sequel
324 return r
325 )
326
327 -- | Forces its argument to be evaluated to weak head normal form when
328 -- the resultant 'IO' action is executed. It can be used to order
329 -- evaluation with respect to other 'IO' operations; its semantics are
330 -- given by
331 --
332 -- > evaluate x `seq` y ==> y
333 -- > evaluate x `catch` f ==> (return $! x) `catch` f
334 -- > evaluate x >>= f ==> (return $! x) >>= f
335 --
336 -- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
337 -- same as @(return $! x)@. A correct definition is
338 --
339 -- > evaluate x = (return $! x) >>= return
340 --
341 evaluate :: a -> IO a
342 evaluate a = IO $ \s -> let !va = a in (# s, va #) -- NB. see #2273