1 {-# OPTIONS_GHC -fno-warn-orphans #-}
2 {-# OPTIONS_GHC -fno-implicit-prelude -funbox-strict-fields #-}
3 {-# OPTIONS_HADDOCK hide #-}
4 -----------------------------------------------------------------------------
7 -- Copyright : (c) The University of Glasgow 1994-2002
8 -- License : see libraries/base/LICENSE
10 -- Maintainer : cvs-ghc@haskell.org
11 -- Stability : internal
12 -- Portability : non-portable (GHC Extensions)
14 -- Definitions for the 'IO' monad and its friends.
16 -----------------------------------------------------------------------------
20 IO(..), unIO, failIO, liftIO, bindIO, thenIO, returnIO,
21 unsafePerformIO, unsafeInterleaveIO,
22 unsafeDupablePerformIO, unsafeDupableInterleaveIO,
25 -- To and from from ST
26 stToIO, ioToST, unsafeIOToST, unsafeSTToIO,
30 catchException, catchAny, throwIO,
31 block, unblock, blocked,
32 onException, finally, evaluate
40 import {-# SOURCE #-} GHC.IO.Exception ( userError )
42 -- ---------------------------------------------------------------------------
46 The IO Monad is just an instance of the ST monad, where the state is
47 the real world. We use the exception mechanism (in GHC.Exception) to
48 implement IO exceptions.
50 NOTE: The IO representation is deeply wired in to various parts of the
51 system. The following list may or may not be exhaustive:
53 Compiler - types of various primitives in PrimOp.lhs
55 RTS - forceIO (StgMiscClosures.hc)
56 - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast
58 - raiseAsync (Schedule.c)
60 Prelude - GHC.IO.lhs, and several other places including
63 Libraries - parts of hslibs/lang.
68 unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
71 instance Functor IO where
72 fmap f x = x >>= (return . f)
74 instance Monad IO where
78 m >> k = m >>= \ _ -> k
84 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
85 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
87 bindIO :: IO a -> (a -> IO b) -> IO b
88 bindIO (IO m) k = IO ( \ s ->
90 (# new_s, a #) -> unIO (k a) new_s
93 thenIO :: IO a -> IO b -> IO b
94 thenIO (IO m) k = IO ( \ s ->
96 (# new_s, _ #) -> unIO k new_s
100 returnIO x = IO (\ s -> (# s, x #))
102 failIO :: String -> IO a
103 failIO s = IO (raiseIO# (toException (userError s)))
105 -- ---------------------------------------------------------------------------
106 -- Coercions between IO and ST
108 -- | A monad transformer embedding strict state transformers in the 'IO'
109 -- monad. The 'RealWorld' parameter indicates that the internal state
110 -- used by the 'ST' computation is a special one supplied by the 'IO'
111 -- monad, and thus distinct from those used by invocations of 'runST'.
112 stToIO :: ST RealWorld a -> IO a
115 ioToST :: IO a -> ST RealWorld a
116 ioToST (IO m) = (ST m)
118 -- This relies on IO and ST having the same representation modulo the
119 -- constraint on the type of the state
121 unsafeIOToST :: IO a -> ST s a
122 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
124 unsafeSTToIO :: ST s a -> IO a
125 unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
127 -- ---------------------------------------------------------------------------
128 -- Unsafe IO operations
131 This is the \"back door\" into the 'IO' monad, allowing
132 'IO' computation to be performed at any time. For
133 this to be safe, the 'IO' computation should be
134 free of side effects and independent of its environment.
136 If the I\/O computation wrapped in 'unsafePerformIO'
137 performs side effects, then the relative order in which those side
138 effects take place (relative to the main I\/O trunk, or other calls to
139 'unsafePerformIO') is indeterminate. You have to be careful when
140 writing and compiling modules that use 'unsafePerformIO':
142 * Use @{\-\# NOINLINE foo \#-\}@ as a pragma on any function @foo@
143 that calls 'unsafePerformIO'. If the call is inlined,
144 the I\/O may be performed more than once.
146 * Use the compiler flag @-fno-cse@ to prevent common sub-expression
147 elimination being performed on the module, which might combine
148 two side effects that were meant to be separate. A good example
149 is using multiple global variables (like @test@ in the example below).
151 * Make sure that the either you switch off let-floating, or that the
152 call to 'unsafePerformIO' cannot float outside a lambda. For example,
155 f x = unsafePerformIO (newIORef [])
157 you may get only one reference cell shared between all calls to @f@.
160 f x = unsafePerformIO (newIORef [x])
162 because now it can't float outside the lambda.
164 It is less well known that
165 'unsafePerformIO' is not type safe. For example:
168 > test = unsafePerformIO $ newIORef []
171 > writeIORef test [42]
172 > bang <- readIORef test
173 > print (bang :: [Char])
175 This program will core dump. This problem with polymorphic references
176 is well known in the ML community, and does not arise with normal
177 monadic use of references. There is no easy way to make it impossible
178 once you use 'unsafePerformIO'. Indeed, it is
179 possible to write @coerce :: a -> b@ with the
180 help of 'unsafePerformIO'. So be careful!
182 unsafePerformIO :: IO a -> a
183 unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)
186 This version of 'unsafePerformIO' is slightly more efficient,
187 because it omits the check that the IO is only being performed by a
188 single thread. Hence, when you write 'unsafeDupablePerformIO',
189 there is a possibility that the IO action may be performed multiple
190 times (on a multiprocessor), and you should therefore ensure that
191 it gives the same results each time.
193 {-# NOINLINE unsafeDupablePerformIO #-}
194 unsafeDupablePerformIO :: IO a -> a
195 unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
197 -- Why do we NOINLINE unsafeDupablePerformIO? See the comment with
198 -- GHC.ST.runST. Essentially the issue is that the IO computation
199 -- inside unsafePerformIO must be atomic: it must either all run, or
200 -- not at all. If we let the compiler see the application of the IO
201 -- to realWorld#, it might float out part of the IO.
203 -- Why is there a call to 'lazy' in unsafeDupablePerformIO?
204 -- If we don't have it, the demand analyser discovers the following strictness
205 -- for unsafeDupablePerformIO: C(U(AV))
207 -- unsafeDupablePerformIO (\s -> let r = f x in
208 -- case writeIORef v r s of (# s1, _ #) ->
210 -- The strictness analyser will find that the binding for r is strict,
211 -- (becuase of uPIO's strictness sig), and so it'll evaluate it before
212 -- doing the writeIORef. This actually makes tests/lib/should_run/memo002
215 -- Solution: don't expose the strictness of unsafeDupablePerformIO,
216 -- by hiding it with 'lazy'
219 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
220 When passed a value of type @IO a@, the 'IO' will only be performed
221 when the value of the @a@ is demanded. This is used to implement lazy
222 file reading, see 'System.IO.hGetContents'.
224 {-# INLINE unsafeInterleaveIO #-}
225 unsafeInterleaveIO :: IO a -> IO a
226 unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)
228 -- We believe that INLINE on unsafeInterleaveIO is safe, because the
229 -- state from this IO thread is passed explicitly to the interleaved
230 -- IO, so it cannot be floated out and shared.
232 {-# INLINE unsafeDupableInterleaveIO #-}
233 unsafeDupableInterleaveIO :: IO a -> IO a
234 unsafeDupableInterleaveIO (IO m)
236 r = case m s of (# _, res #) -> res
241 Ensures that the suspensions under evaluation by the current thread
242 are unique; that is, the current thread is not evaluating anything
243 that is also under evaluation by another thread that has also executed
246 This operation is used in the definition of 'unsafePerformIO' to
247 prevent the IO action from being executed multiple times, which is usually
251 noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)
253 -- -----------------------------------------------------------------------------
254 -- | File and directory names are values of type 'String', whose precise
255 -- meaning is operating system dependent. Files can be opened, yielding a
256 -- handle which can then be used to operate on the contents of that file.
258 type FilePath = String
260 -- -----------------------------------------------------------------------------
261 -- Primitive catch and throwIO
264 catchException used to handle the passing around of the state to the
265 action and the handler. This turned out to be a bad idea - it meant
266 that we had to wrap both arguments in thunks so they could be entered
267 as normal (remember IO returns an unboxed pair...).
271 catch# :: IO a -> (b -> IO a) -> IO a
273 (well almost; the compiler doesn't know about the IO newtype so we
274 have to work around that in the definition of catchException below).
277 catchException :: Exception e => IO a -> (e -> IO a) -> IO a
278 catchException (IO io) handler = IO $ catch# io handler'
279 where handler' e = case fromException e of
280 Just e' -> unIO (handler e')
283 catchAny :: IO a -> (forall e . Exception e => e -> IO a) -> IO a
284 catchAny (IO io) handler = IO $ catch# io handler'
285 where handler' (SomeException e) = unIO (handler e)
287 -- | A variant of 'throw' that can only be used within the 'IO' monad.
289 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
290 -- two functions are subtly different:
292 -- > throw e `seq` x ===> throw e
293 -- > throwIO e `seq` x ===> x
295 -- The first example will cause the exception @e@ to be raised,
296 -- whereas the second one won\'t. In fact, 'throwIO' will only cause
297 -- an exception to be raised when it is used within the 'IO' monad.
298 -- The 'throwIO' variant should be used in preference to 'throw' to
299 -- raise an exception within the 'IO' monad because it guarantees
300 -- ordering with respect to other 'IO' operations, whereas 'throw'
302 throwIO :: Exception e => e -> IO a
303 throwIO e = IO (raiseIO# (toException e))
305 -- -----------------------------------------------------------------------------
306 -- Controlling asynchronous exception delivery
308 -- | Applying 'block' to a computation will
309 -- execute that computation with asynchronous exceptions
310 -- /blocked/. That is, any thread which
311 -- attempts to raise an exception in the current thread with 'Control.Exception.throwTo' will be
312 -- blocked until asynchronous exceptions are enabled again. There\'s
313 -- no need to worry about re-enabling asynchronous exceptions; that is
314 -- done automatically on exiting the scope of
317 -- Threads created by 'Control.Concurrent.forkIO' inherit the blocked
318 -- state from the parent; that is, to start a thread in blocked mode,
319 -- use @block $ forkIO ...@. This is particularly useful if you need to
320 -- establish an exception handler in the forked thread before any
321 -- asynchronous exceptions are received.
322 block :: IO a -> IO a
324 -- | To re-enable asynchronous exceptions inside the scope of
325 -- 'block', 'unblock' can be
326 -- used. It scopes in exactly the same way, so on exit from
327 -- 'unblock' asynchronous exception delivery will
328 -- be disabled again.
329 unblock :: IO a -> IO a
331 block (IO io) = IO $ blockAsyncExceptions# io
332 unblock (IO io) = IO $ unblockAsyncExceptions# io
334 -- | returns True if asynchronous exceptions are blocked in the
337 blocked = IO $ \s -> case asyncExceptionsBlocked# s of
338 (# s', i #) -> (# s', i /=# 0# #)
340 onException :: IO a -> IO b -> IO a
341 onException io what = io `catchException` \e -> do what
342 throw (e :: SomeException)
344 finally :: IO a -- ^ computation to run first
345 -> IO b -- ^ computation to run afterward (even if an exception
347 -> IO a -- returns the value from the first computation
350 r <- unblock a `onException` sequel
355 -- | Forces its argument to be evaluated to weak head normal form when
356 -- the resultant 'IO' action is executed. It can be used to order
357 -- evaluation with respect to other 'IO' operations; its semantics are
360 -- > evaluate x `seq` y ==> y
361 -- > evaluate x `catch` f ==> (return $! x) `catch` f
362 -- > evaluate x >>= f ==> (return $! x) >>= f
364 -- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
365 -- same as @(return $! x)@. A correct definition is
367 -- > evaluate x = (return $! x) >>= return
369 evaluate :: a -> IO a
370 evaluate a = IO $ \s -> case a `seq` () of () -> (# s, a #)
372 -- a `seq` (# s, a #)
373 -- because we can't have an unboxed tuple as a function argument