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'
105 performs side effects, then the relative order in which those side
106 effects take place (relative to the main I\/O trunk, or other calls to
107 'unsafePerformIO') is indeterminate. You have to be careful when
108 writing and compiling modules that use 'unsafePerformIO':
110 * Use @{\-\# NOINLINE foo \#-\}@ as a pragma on any function @foo@
111 that calls 'unsafePerformIO'. If the call is inlined,
112 the I\/O may be performed more than once.
114 * Use the compiler flag @-fno-cse@ to prevent common sub-expression
115 elimination being performed on the module, which might combine
116 two side effects that were meant to be separate. A good example
117 is using multiple global variables (like @test@ in the example below).
119 * Make sure that the either you switch off let-floating, or that the
120 call to 'unsafePerformIO' cannot float outside a lambda. For example,
123 f x = unsafePerformIO (newIORef [])
125 you may get only one reference cell shared between all calls to @f@.
128 f x = unsafePerformIO (newIORef [x])
130 because now it can't float outside the lambda.
132 It is less well known that
133 'unsafePerformIO' is not type safe. For example:
136 > test = unsafePerformIO $ newIORef []
139 > writeIORef test [42]
140 > bang <- readIORef test
141 > print (bang :: [Char])
143 This program will core dump. This problem with polymorphic references
144 is well known in the ML community, and does not arise with normal
145 monadic use of references. There is no easy way to make it impossible
146 once you use 'unsafePerformIO'. Indeed, it is
147 possible to write @coerce :: a -> b@ with the
148 help of 'unsafePerformIO'. So be careful!
150 unsafePerformIO :: IO a -> a
151 unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)
154 This version of 'unsafePerformIO' is slightly more efficient,
155 because it omits the check that the IO is only being performed by a
156 single thread. Hence, when you write 'unsafeDupablePerformIO',
157 there is a possibility that the IO action may be performed multiple
158 times (on a multiprocessor), and you should therefore ensure that
159 it gives the same results each time.
161 {-# NOINLINE unsafeDupablePerformIO #-}
162 unsafeDupablePerformIO :: IO a -> a
163 unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
165 -- Why do we NOINLINE unsafeDupablePerformIO? See the comment with
166 -- GHC.ST.runST. Essentially the issue is that the IO computation
167 -- inside unsafePerformIO must be atomic: it must either all run, or
168 -- not at all. If we let the compiler see the application of the IO
169 -- to realWorld#, it might float out part of the IO.
171 -- Why is there a call to 'lazy' in unsafeDupablePerformIO?
172 -- If we don't have it, the demand analyser discovers the following strictness
173 -- for unsafeDupablePerformIO: C(U(AV))
175 -- unsafeDupablePerformIO (\s -> let r = f x in
176 -- case writeIORef v r s of (# s1, _ #) ->
178 -- The strictness analyser will find that the binding for r is strict,
179 -- (becuase of uPIO's strictness sig), and so it'll evaluate it before
180 -- doing the writeIORef. This actually makes tests/lib/should_run/memo002
183 -- Solution: don't expose the strictness of unsafeDupablePerformIO,
184 -- by hiding it with 'lazy'
187 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
188 When passed a value of type @IO a@, the 'IO' will only be performed
189 when the value of the @a@ is demanded. This is used to implement lazy
190 file reading, see 'System.IO.hGetContents'.
192 {-# INLINE unsafeInterleaveIO #-}
193 unsafeInterleaveIO :: IO a -> IO a
194 unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)
196 -- We believe that INLINE on unsafeInterleaveIO is safe, because the
197 -- state from this IO thread is passed explicitly to the interleaved
198 -- IO, so it cannot be floated out and shared.
200 {-# INLINE unsafeDupableInterleaveIO #-}
201 unsafeDupableInterleaveIO :: IO a -> IO a
202 unsafeDupableInterleaveIO (IO m)
204 r = case m s of (# _, res #) -> res
209 Ensures that the suspensions under evaluation by the current thread
210 are unique; that is, the current thread is not evaluating anything
211 that is also under evaluation by another thread that has also executed
214 This operation is used in the definition of 'unsafePerformIO' to
215 prevent the IO action from being executed multiple times, which is usually
219 noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)
221 -- -----------------------------------------------------------------------------
222 -- | File and directory names are values of type 'String', whose precise
223 -- meaning is operating system dependent. Files can be opened, yielding a
224 -- handle which can then be used to operate on the contents of that file.
226 type FilePath = String
228 -- -----------------------------------------------------------------------------
229 -- Primitive catch and throwIO
232 catchException used to handle the passing around of the state to the
233 action and the handler. This turned out to be a bad idea - it meant
234 that we had to wrap both arguments in thunks so they could be entered
235 as normal (remember IO returns an unboxed pair...).
239 catch# :: IO a -> (b -> IO a) -> IO a
241 (well almost; the compiler doesn't know about the IO newtype so we
242 have to work around that in the definition of catchException below).
245 catchException :: Exception e => IO a -> (e -> IO a) -> IO a
246 catchException (IO io) handler = IO $ catch# io handler'
247 where handler' e = case fromException e of
248 Just e' -> unIO (handler e')
251 catchAny :: IO a -> (forall e . Exception e => e -> IO a) -> IO a
252 catchAny (IO io) handler = IO $ catch# io handler'
253 where handler' (SomeException e) = unIO (handler e)
255 -- | A variant of 'throw' that can only be used within the 'IO' monad.
257 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
258 -- two functions are subtly different:
260 -- > throw e `seq` x ===> throw e
261 -- > throwIO e `seq` x ===> x
263 -- The first example will cause the exception @e@ to be raised,
264 -- whereas the second one won\'t. In fact, 'throwIO' will only cause
265 -- an exception to be raised when it is used within the 'IO' monad.
266 -- The 'throwIO' variant should be used in preference to 'throw' to
267 -- raise an exception within the 'IO' monad because it guarantees
268 -- ordering with respect to other 'IO' operations, whereas 'throw'
270 throwIO :: Exception e => e -> IO a
271 throwIO e = IO (raiseIO# (toException e))
273 -- -----------------------------------------------------------------------------
274 -- Controlling asynchronous exception delivery
276 -- | Applying 'block' to a computation will
277 -- execute that computation with asynchronous exceptions
278 -- /blocked/. That is, any thread which
279 -- attempts to raise an exception in the current thread with 'Control.Exception.throwTo' will be
280 -- blocked until asynchronous exceptions are enabled again. There\'s
281 -- no need to worry about re-enabling asynchronous exceptions; that is
282 -- done automatically on exiting the scope of
285 -- Threads created by 'Control.Concurrent.forkIO' inherit the blocked
286 -- state from the parent; that is, to start a thread in blocked mode,
287 -- use @block $ forkIO ...@. This is particularly useful if you need to
288 -- establish an exception handler in the forked thread before any
289 -- asynchronous exceptions are received.
290 block :: IO a -> IO a
292 -- | To re-enable asynchronous exceptions inside the scope of
293 -- 'block', 'unblock' can be
294 -- used. It scopes in exactly the same way, so on exit from
295 -- 'unblock' asynchronous exception delivery will
296 -- be disabled again.
297 unblock :: IO a -> IO a
299 block (IO io) = IO $ blockAsyncExceptions# io
300 unblock (IO io) = IO $ unblockAsyncExceptions# io
302 -- | returns True if asynchronous exceptions are blocked in the
305 blocked = IO $ \s -> case asyncExceptionsBlocked# s of
306 (# s', i #) -> (# s', i /=# 0# #)
308 onException :: IO a -> IO b -> IO a
309 onException io what = io `catchException` \e -> do _ <- what
310 throw (e :: SomeException)
312 finally :: IO a -- ^ computation to run first
313 -> IO b -- ^ computation to run afterward (even if an exception
315 -> IO a -- returns the value from the first computation
318 r <- unblock a `onException` sequel
323 -- | Forces its argument to be evaluated to weak head normal form when
324 -- the resultant 'IO' action is executed. It can be used to order
325 -- evaluation with respect to other 'IO' operations; its semantics are
328 -- > evaluate x `seq` y ==> y
329 -- > evaluate x `catch` f ==> (return $! x) `catch` f
330 -- > evaluate x >>= f ==> (return $! x) >>= f
332 -- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
333 -- same as @(return $! x)@. A correct definition is
335 -- > evaluate x = (return $! x) >>= return
337 evaluate :: a -> IO a
338 evaluate a = IO $ \s -> let !va = a in (# s, va #) -- NB. see #2273