1 {-# OPTIONS_GHC -fno-implicit-prelude -funbox-strict-fields #-}
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, bindIO, thenIO, returnIO,
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.
68 A value of type @'IO' a@ is a computation which, when performed,
69 does some I\/O before returning a value of type @a@.
71 There is really only one way to \"perform\" an I\/O action: bind it to
72 @Main.main@ in your program. When your program is run, the I\/O will
73 be performed. It isn't possible to perform I\/O from an arbitrary
74 function, unless that function is itself in the 'IO' monad and called
75 at some point, directly or indirectly, from @Main.main@.
77 'IO' is a monad, so 'IO' actions can be combined using either the do-notation
78 or the '>>' and '>>=' operations from the 'Monad' class.
80 newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #))
82 unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
85 instance Functor IO where
86 fmap f x = x >>= (return . f)
88 instance Monad IO where
92 m >> k = m >>= \ _ -> k
98 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
99 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
101 bindIO :: IO a -> (a -> IO b) -> IO b
102 bindIO (IO m) k = IO ( \ s ->
104 (# new_s, a #) -> unIO (k a) new_s
107 thenIO :: IO a -> IO b -> IO b
108 thenIO (IO m) k = IO ( \ s ->
110 (# new_s, _ #) -> unIO k new_s
113 returnIO :: a -> IO a
114 returnIO x = IO (\ s -> (# s, x #))
116 failIO :: String -> IO a
117 failIO s = IO (raiseIO# (toException (userError s)))
119 -- ---------------------------------------------------------------------------
120 -- Coercions between IO and ST
122 -- | A monad transformer embedding strict state transformers in the 'IO'
123 -- monad. The 'RealWorld' parameter indicates that the internal state
124 -- used by the 'ST' computation is a special one supplied by the 'IO'
125 -- monad, and thus distinct from those used by invocations of 'runST'.
126 stToIO :: ST RealWorld a -> IO a
129 ioToST :: IO a -> ST RealWorld a
130 ioToST (IO m) = (ST m)
132 -- This relies on IO and ST having the same representation modulo the
133 -- constraint on the type of the state
135 unsafeIOToST :: IO a -> ST s a
136 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
138 unsafeSTToIO :: ST s a -> IO a
139 unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
141 -- ---------------------------------------------------------------------------
142 -- Unsafe IO operations
145 This is the \"back door\" into the 'IO' monad, allowing
146 'IO' computation to be performed at any time. For
147 this to be safe, the 'IO' computation should be
148 free of side effects and independent of its environment.
150 If the I\/O computation wrapped in 'unsafePerformIO'
151 performs side effects, then the relative order in which those side
152 effects take place (relative to the main I\/O trunk, or other calls to
153 'unsafePerformIO') is indeterminate. You have to be careful when
154 writing and compiling modules that use 'unsafePerformIO':
156 * Use @{\-\# NOINLINE foo \#-\}@ as a pragma on any function @foo@
157 that calls 'unsafePerformIO'. If the call is inlined,
158 the I\/O may be performed more than once.
160 * Use the compiler flag @-fno-cse@ to prevent common sub-expression
161 elimination being performed on the module, which might combine
162 two side effects that were meant to be separate. A good example
163 is using multiple global variables (like @test@ in the example below).
165 * Make sure that the either you switch off let-floating, or that the
166 call to 'unsafePerformIO' cannot float outside a lambda. For example,
169 f x = unsafePerformIO (newIORef [])
171 you may get only one reference cell shared between all calls to @f@.
174 f x = unsafePerformIO (newIORef [x])
176 because now it can't float outside the lambda.
178 It is less well known that
179 'unsafePerformIO' is not type safe. For example:
182 > test = unsafePerformIO $ newIORef []
185 > writeIORef test [42]
186 > bang <- readIORef test
187 > print (bang :: [Char])
189 This program will core dump. This problem with polymorphic references
190 is well known in the ML community, and does not arise with normal
191 monadic use of references. There is no easy way to make it impossible
192 once you use 'unsafePerformIO'. Indeed, it is
193 possible to write @coerce :: a -> b@ with the
194 help of 'unsafePerformIO'. So be careful!
196 unsafePerformIO :: IO a -> a
197 unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)
200 This version of 'unsafePerformIO' is slightly more efficient,
201 because it omits the check that the IO is only being performed by a
202 single thread. Hence, when you write 'unsafeDupablePerformIO',
203 there is a possibility that the IO action may be performed multiple
204 times (on a multiprocessor), and you should therefore ensure that
205 it gives the same results each time.
207 {-# NOINLINE unsafeDupablePerformIO #-}
208 unsafeDupablePerformIO :: IO a -> a
209 unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
211 -- Why do we NOINLINE unsafeDupablePerformIO? See the comment with
212 -- GHC.ST.runST. Essentially the issue is that the IO computation
213 -- inside unsafePerformIO must be atomic: it must either all run, or
214 -- not at all. If we let the compiler see the application of the IO
215 -- to realWorld#, it might float out part of the IO.
217 -- Why is there a call to 'lazy' in unsafeDupablePerformIO?
218 -- If we don't have it, the demand analyser discovers the following strictness
219 -- for unsafeDupablePerformIO: C(U(AV))
221 -- unsafeDupablePerformIO (\s -> let r = f x in
222 -- case writeIORef v r s of (# s1, _ #) ->
224 -- The strictness analyser will find that the binding for r is strict,
225 -- (becuase of uPIO's strictness sig), and so it'll evaluate it before
226 -- doing the writeIORef. This actually makes tests/lib/should_run/memo002
229 -- Solution: don't expose the strictness of unsafeDupablePerformIO,
230 -- by hiding it with 'lazy'
233 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
234 When passed a value of type @IO a@, the 'IO' will only be performed
235 when the value of the @a@ is demanded. This is used to implement lazy
236 file reading, see 'System.IO.hGetContents'.
238 {-# INLINE unsafeInterleaveIO #-}
239 unsafeInterleaveIO :: IO a -> IO a
240 unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)
242 -- We believe that INLINE on unsafeInterleaveIO is safe, because the
243 -- state from this IO thread is passed explicitly to the interleaved
244 -- IO, so it cannot be floated out and shared.
246 {-# INLINE unsafeDupableInterleaveIO #-}
247 unsafeDupableInterleaveIO :: IO a -> IO a
248 unsafeDupableInterleaveIO (IO m)
250 r = case m s of (# _, res #) -> res
255 Ensures that the suspensions under evaluation by the current thread
256 are unique; that is, the current thread is not evaluating anything
257 that is also under evaluation by another thread that has also executed
260 This operation is used in the definition of 'unsafePerformIO' to
261 prevent the IO action from being executed multiple times, which is usually
265 noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)
267 -- -----------------------------------------------------------------------------
268 -- | File and directory names are values of type 'String', whose precise
269 -- meaning is operating system dependent. Files can be opened, yielding a
270 -- handle which can then be used to operate on the contents of that file.
272 type FilePath = String
274 -- -----------------------------------------------------------------------------
275 -- Primitive catch and throwIO
278 catchException used to handle the passing around of the state to the
279 action and the handler. This turned out to be a bad idea - it meant
280 that we had to wrap both arguments in thunks so they could be entered
281 as normal (remember IO returns an unboxed pair...).
285 catch# :: IO a -> (b -> IO a) -> IO a
287 (well almost; the compiler doesn't know about the IO newtype so we
288 have to work around that in the definition of catchException below).
291 catchException :: Exception e => IO a -> (e -> IO a) -> IO a
292 catchException (IO io) handler = IO $ catch# io handler'
293 where handler' e = case fromException e of
294 Just e' -> unIO (handler e')
297 catchAny :: IO a -> (forall e . Exception e => e -> IO a) -> IO a
298 catchAny (IO io) handler = IO $ catch# io handler'
299 where handler' (SomeException e) = unIO (handler e)
301 -- | A variant of 'throw' that can only be used within the 'IO' monad.
303 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
304 -- two functions are subtly different:
306 -- > throw e `seq` x ===> throw e
307 -- > throwIO e `seq` x ===> x
309 -- The first example will cause the exception @e@ to be raised,
310 -- whereas the second one won\'t. In fact, 'throwIO' will only cause
311 -- an exception to be raised when it is used within the 'IO' monad.
312 -- The 'throwIO' variant should be used in preference to 'throw' to
313 -- raise an exception within the 'IO' monad because it guarantees
314 -- ordering with respect to other 'IO' operations, whereas 'throw'
316 throwIO :: Exception e => e -> IO a
317 throwIO e = IO (raiseIO# (toException e))
319 -- -----------------------------------------------------------------------------
320 -- Controlling asynchronous exception delivery
322 -- | Applying 'block' to a computation will
323 -- execute that computation with asynchronous exceptions
324 -- /blocked/. That is, any thread which
325 -- attempts to raise an exception in the current thread with 'Control.Exception.throwTo' will be
326 -- blocked until asynchronous exceptions are enabled again. There\'s
327 -- no need to worry about re-enabling asynchronous exceptions; that is
328 -- done automatically on exiting the scope of
331 -- Threads created by 'Control.Concurrent.forkIO' inherit the blocked
332 -- state from the parent; that is, to start a thread in blocked mode,
333 -- use @block $ forkIO ...@. This is particularly useful if you need to
334 -- establish an exception handler in the forked thread before any
335 -- asynchronous exceptions are received.
336 block :: IO a -> IO a
338 -- | To re-enable asynchronous exceptions inside the scope of
339 -- 'block', 'unblock' can be
340 -- used. It scopes in exactly the same way, so on exit from
341 -- 'unblock' asynchronous exception delivery will
342 -- be disabled again.
343 unblock :: IO a -> IO a
345 block (IO io) = IO $ blockAsyncExceptions# io
346 unblock (IO io) = IO $ unblockAsyncExceptions# io
348 -- | returns True if asynchronous exceptions are blocked in the
351 blocked = IO $ \s -> case asyncExceptionsBlocked# s of
352 (# s', i #) -> (# s', i /=# 0# #)
354 onException :: IO a -> IO b -> IO a
355 onException io what = io `catchException` \e -> do what
356 throw (e :: SomeException)
358 finally :: IO a -- ^ computation to run first
359 -> IO b -- ^ computation to run afterward (even if an exception
361 -> IO a -- returns the value from the first computation
364 r <- unblock a `onException` sequel
369 -- | Forces its argument to be evaluated to weak head normal form when
370 -- the resultant 'IO' action is executed. It can be used to order
371 -- evaluation with respect to other 'IO' operations; its semantics are
374 -- > evaluate x `seq` y ==> y
375 -- > evaluate x `catch` f ==> (return $! x) `catch` f
376 -- > evaluate x >>= f ==> (return $! x) >>= f
378 -- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
379 -- same as @(return $! x)@. A correct definition is
381 -- > evaluate x = (return $! x) >>= return
383 evaluate :: a -> IO a
384 evaluate a = IO $ \s -> case a `seq` () of () -> (# s, a #)
386 -- a `seq` (# s, a #)
387 -- because we can't have an unboxed tuple as a function argument