1 {-# OPTIONS_GHC -XNoImplicitPrelude -funbox-strict-fields -XBangPatterns #-}
2 {-# OPTIONS_HADDOCK hide #-}
3 -----------------------------------------------------------------------------
6 -- Copyright : (c) The University of Glasgow 1994-2002
7 -- License : see libraries/base/LICENSE
9 -- Maintainer : cvs-ghc@haskell.org
10 -- Stability : internal
11 -- Portability : non-portable (GHC Extensions)
13 -- Definitions for the 'IO' monad and its friends.
15 -----------------------------------------------------------------------------
19 IO(..), unIO, failIO, liftIO,
20 unsafePerformIO, unsafeInterleaveIO,
21 unsafeDupablePerformIO, unsafeDupableInterleaveIO,
24 -- To and from from ST
25 stToIO, ioToST, unsafeIOToST, unsafeSTToIO,
29 catchException, catchAny, throwIO,
30 block, unblock, blocked,
31 onException, finally, evaluate
39 import {-# SOURCE #-} GHC.IO.Exception ( userError )
41 -- ---------------------------------------------------------------------------
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.
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:
52 Compiler - types of various primitives in PrimOp.lhs
54 RTS - forceIO (StgMiscClosures.hc)
55 - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast
57 - raiseAsync (Schedule.c)
59 Prelude - GHC.IO.lhs, and several other places including
62 Libraries - parts of hslibs/lang.
67 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
68 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
70 failIO :: String -> IO a
71 failIO s = IO (raiseIO# (toException (userError s)))
73 -- ---------------------------------------------------------------------------
74 -- Coercions between IO and ST
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
83 ioToST :: IO a -> ST RealWorld a
84 ioToST (IO m) = (ST m)
86 -- This relies on IO and ST having the same representation modulo the
87 -- constraint on the type of the state
89 unsafeIOToST :: IO a -> ST s a
90 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
92 unsafeSTToIO :: ST s a -> IO a
93 unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
95 -- ---------------------------------------------------------------------------
96 -- Unsafe IO operations
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.
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:
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.
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).
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,
127 f x = unsafePerformIO (newIORef [])
129 you may get only one reference cell shared between all calls to @f@.
132 f x = unsafePerformIO (newIORef [x])
134 because now it can't float outside the lambda.
136 It is less well known that
137 'unsafePerformIO' is not type safe. For example:
140 > test = unsafePerformIO $ newIORef []
143 > writeIORef test [42]
144 > bang <- readIORef test
145 > print (bang :: [Char])
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!
154 unsafePerformIO :: IO a -> a
155 unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)
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.
165 {-# NOINLINE unsafeDupablePerformIO #-}
166 unsafeDupablePerformIO :: IO a -> a
167 unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
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.
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))
179 -- unsafeDupablePerformIO (\s -> let r = f x in
180 -- case writeIORef v r s of (# s1, _ #) ->
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
187 -- Solution: don't expose the strictness of unsafeDupablePerformIO,
188 -- by hiding it with 'lazy'
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'.
196 {-# INLINE unsafeInterleaveIO #-}
197 unsafeInterleaveIO :: IO a -> IO a
198 unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)
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.
204 {-# INLINE unsafeDupableInterleaveIO #-}
205 unsafeDupableInterleaveIO :: IO a -> IO a
206 unsafeDupableInterleaveIO (IO m)
208 r = case m s of (# _, res #) -> res
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
218 This operation is used in the definition of 'unsafePerformIO' to
219 prevent the IO action from being executed multiple times, which is usually
223 noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)
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.
230 type FilePath = String
232 -- -----------------------------------------------------------------------------
233 -- Primitive catch and throwIO
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...).
243 catch# :: IO a -> (b -> IO a) -> IO a
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).
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')
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)
259 -- | A variant of 'throw' that can only be used within the 'IO' monad.
261 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
262 -- two functions are subtly different:
264 -- > throw e `seq` x ===> throw e
265 -- > throwIO e `seq` x ===> x
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'
274 throwIO :: Exception e => e -> IO a
275 throwIO e = IO (raiseIO# (toException e))
277 -- -----------------------------------------------------------------------------
278 -- Controlling asynchronous exception delivery
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
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
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
303 block (IO io) = IO $ blockAsyncExceptions# io
304 unblock (IO io) = IO $ unblockAsyncExceptions# io
306 -- | returns True if asynchronous exceptions are blocked in the
309 blocked = IO $ \s -> case asyncExceptionsBlocked# s of
310 (# s', i #) -> (# s', i /=# 0# #)
312 onException :: IO a -> IO b -> IO a
313 onException io what = io `catchException` \e -> do _ <- what
314 throw (e :: SomeException)
316 finally :: IO a -- ^ computation to run first
317 -> IO b -- ^ computation to run afterward (even if an exception
319 -> IO a -- returns the value from the first computation
322 r <- unblock a `onException` sequel
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
332 -- > evaluate x `seq` y ==> y
333 -- > evaluate x `catch` f ==> (return $! x) `catch` f
334 -- > evaluate x >>= f ==> (return $! x) >>= f
336 -- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
337 -- same as @(return $! x)@. A correct definition is
339 -- > evaluate x = (return $! x) >>= return
341 evaluate :: a -> IO a
342 evaluate a = IO $ \s -> let !va = a in (# s, va #) -- NB. see #2273