1 {-# OPTIONS_GHC -fno-warn-orphans #-}
2 {-# OPTIONS_GHC -XNoImplicitPrelude -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,
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 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
69 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
71 failIO :: String -> IO a
72 failIO s = IO (raiseIO# (toException (userError s)))
74 -- ---------------------------------------------------------------------------
75 -- Coercions between IO and ST
77 -- | A monad transformer embedding strict state transformers in the 'IO'
78 -- monad. The 'RealWorld' parameter indicates that the internal state
79 -- used by the 'ST' computation is a special one supplied by the 'IO'
80 -- monad, and thus distinct from those used by invocations of 'runST'.
81 stToIO :: ST RealWorld a -> IO a
84 ioToST :: IO a -> ST RealWorld a
85 ioToST (IO m) = (ST m)
87 -- This relies on IO and ST having the same representation modulo the
88 -- constraint on the type of the state
90 unsafeIOToST :: IO a -> ST s a
91 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
93 unsafeSTToIO :: ST s a -> IO a
94 unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
96 -- ---------------------------------------------------------------------------
97 -- Unsafe IO operations
100 This is the \"back door\" into the 'IO' monad, allowing
101 'IO' computation to be performed at any time. For
102 this to be safe, the 'IO' computation should be
103 free of side effects and independent of its environment.
105 If the I\/O computation wrapped in 'unsafePerformIO'
106 performs side effects, then the relative order in which those side
107 effects take place (relative to the main I\/O trunk, or other calls to
108 'unsafePerformIO') is indeterminate. You have to be careful when
109 writing and compiling modules that use 'unsafePerformIO':
111 * Use @{\-\# NOINLINE foo \#-\}@ as a pragma on any function @foo@
112 that calls 'unsafePerformIO'. If the call is inlined,
113 the I\/O may be performed more than once.
115 * Use the compiler flag @-fno-cse@ to prevent common sub-expression
116 elimination being performed on the module, which might combine
117 two side effects that were meant to be separate. A good example
118 is using multiple global variables (like @test@ in the example below).
120 * Make sure that the either you switch off let-floating, or that the
121 call to 'unsafePerformIO' cannot float outside a lambda. For example,
124 f x = unsafePerformIO (newIORef [])
126 you may get only one reference cell shared between all calls to @f@.
129 f x = unsafePerformIO (newIORef [x])
131 because now it can't float outside the lambda.
133 It is less well known that
134 'unsafePerformIO' is not type safe. For example:
137 > test = unsafePerformIO $ newIORef []
140 > writeIORef test [42]
141 > bang <- readIORef test
142 > print (bang :: [Char])
144 This program will core dump. This problem with polymorphic references
145 is well known in the ML community, and does not arise with normal
146 monadic use of references. There is no easy way to make it impossible
147 once you use 'unsafePerformIO'. Indeed, it is
148 possible to write @coerce :: a -> b@ with the
149 help of 'unsafePerformIO'. So be careful!
151 unsafePerformIO :: IO a -> a
152 unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)
155 This version of 'unsafePerformIO' is slightly more efficient,
156 because it omits the check that the IO is only being performed by a
157 single thread. Hence, when you write 'unsafeDupablePerformIO',
158 there is a possibility that the IO action may be performed multiple
159 times (on a multiprocessor), and you should therefore ensure that
160 it gives the same results each time.
162 {-# NOINLINE unsafeDupablePerformIO #-}
163 unsafeDupablePerformIO :: IO a -> a
164 unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
166 -- Why do we NOINLINE unsafeDupablePerformIO? See the comment with
167 -- GHC.ST.runST. Essentially the issue is that the IO computation
168 -- inside unsafePerformIO must be atomic: it must either all run, or
169 -- not at all. If we let the compiler see the application of the IO
170 -- to realWorld#, it might float out part of the IO.
172 -- Why is there a call to 'lazy' in unsafeDupablePerformIO?
173 -- If we don't have it, the demand analyser discovers the following strictness
174 -- for unsafeDupablePerformIO: C(U(AV))
176 -- unsafeDupablePerformIO (\s -> let r = f x in
177 -- case writeIORef v r s of (# s1, _ #) ->
179 -- The strictness analyser will find that the binding for r is strict,
180 -- (becuase of uPIO's strictness sig), and so it'll evaluate it before
181 -- doing the writeIORef. This actually makes tests/lib/should_run/memo002
184 -- Solution: don't expose the strictness of unsafeDupablePerformIO,
185 -- by hiding it with 'lazy'
188 'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
189 When passed a value of type @IO a@, the 'IO' will only be performed
190 when the value of the @a@ is demanded. This is used to implement lazy
191 file reading, see 'System.IO.hGetContents'.
193 {-# INLINE unsafeInterleaveIO #-}
194 unsafeInterleaveIO :: IO a -> IO a
195 unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)
197 -- We believe that INLINE on unsafeInterleaveIO is safe, because the
198 -- state from this IO thread is passed explicitly to the interleaved
199 -- IO, so it cannot be floated out and shared.
201 {-# INLINE unsafeDupableInterleaveIO #-}
202 unsafeDupableInterleaveIO :: IO a -> IO a
203 unsafeDupableInterleaveIO (IO m)
205 r = case m s of (# _, res #) -> res
210 Ensures that the suspensions under evaluation by the current thread
211 are unique; that is, the current thread is not evaluating anything
212 that is also under evaluation by another thread that has also executed
215 This operation is used in the definition of 'unsafePerformIO' to
216 prevent the IO action from being executed multiple times, which is usually
220 noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)
222 -- -----------------------------------------------------------------------------
223 -- | File and directory names are values of type 'String', whose precise
224 -- meaning is operating system dependent. Files can be opened, yielding a
225 -- handle which can then be used to operate on the contents of that file.
227 type FilePath = String
229 -- -----------------------------------------------------------------------------
230 -- Primitive catch and throwIO
233 catchException used to handle the passing around of the state to the
234 action and the handler. This turned out to be a bad idea - it meant
235 that we had to wrap both arguments in thunks so they could be entered
236 as normal (remember IO returns an unboxed pair...).
240 catch# :: IO a -> (b -> IO a) -> IO a
242 (well almost; the compiler doesn't know about the IO newtype so we
243 have to work around that in the definition of catchException below).
246 catchException :: Exception e => IO a -> (e -> IO a) -> IO a
247 catchException (IO io) handler = IO $ catch# io handler'
248 where handler' e = case fromException e of
249 Just e' -> unIO (handler e')
252 catchAny :: IO a -> (forall e . Exception e => e -> IO a) -> IO a
253 catchAny (IO io) handler = IO $ catch# io handler'
254 where handler' (SomeException e) = unIO (handler e)
256 -- | A variant of 'throw' that can only be used within the 'IO' monad.
258 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
259 -- two functions are subtly different:
261 -- > throw e `seq` x ===> throw e
262 -- > throwIO e `seq` x ===> x
264 -- The first example will cause the exception @e@ to be raised,
265 -- whereas the second one won\'t. In fact, 'throwIO' will only cause
266 -- an exception to be raised when it is used within the 'IO' monad.
267 -- The 'throwIO' variant should be used in preference to 'throw' to
268 -- raise an exception within the 'IO' monad because it guarantees
269 -- ordering with respect to other 'IO' operations, whereas 'throw'
271 throwIO :: Exception e => e -> IO a
272 throwIO e = IO (raiseIO# (toException e))
274 -- -----------------------------------------------------------------------------
275 -- Controlling asynchronous exception delivery
277 -- | Applying 'block' to a computation will
278 -- execute that computation with asynchronous exceptions
279 -- /blocked/. That is, any thread which
280 -- attempts to raise an exception in the current thread with 'Control.Exception.throwTo' will be
281 -- blocked until asynchronous exceptions are enabled again. There\'s
282 -- no need to worry about re-enabling asynchronous exceptions; that is
283 -- done automatically on exiting the scope of
286 -- Threads created by 'Control.Concurrent.forkIO' inherit the blocked
287 -- state from the parent; that is, to start a thread in blocked mode,
288 -- use @block $ forkIO ...@. This is particularly useful if you need to
289 -- establish an exception handler in the forked thread before any
290 -- asynchronous exceptions are received.
291 block :: IO a -> IO a
293 -- | To re-enable asynchronous exceptions inside the scope of
294 -- 'block', 'unblock' can be
295 -- used. It scopes in exactly the same way, so on exit from
296 -- 'unblock' asynchronous exception delivery will
297 -- be disabled again.
298 unblock :: IO a -> IO a
300 block (IO io) = IO $ blockAsyncExceptions# io
301 unblock (IO io) = IO $ unblockAsyncExceptions# io
303 -- | returns True if asynchronous exceptions are blocked in the
306 blocked = IO $ \s -> case asyncExceptionsBlocked# s of
307 (# s', i #) -> (# s', i /=# 0# #)
309 onException :: IO a -> IO b -> IO a
310 onException io what = io `catchException` \e -> do _ <- what
311 throw (e :: SomeException)
313 finally :: IO a -- ^ computation to run first
314 -> IO b -- ^ computation to run afterward (even if an exception
316 -> IO a -- returns the value from the first computation
319 r <- unblock a `onException` sequel
324 -- | Forces its argument to be evaluated to weak head normal form when
325 -- the resultant 'IO' action is executed. It can be used to order
326 -- evaluation with respect to other 'IO' operations; its semantics are
329 -- > evaluate x `seq` y ==> y
330 -- > evaluate x `catch` f ==> (return $! x) `catch` f
331 -- > evaluate x >>= f ==> (return $! x) >>= f
333 -- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
334 -- same as @(return $! x)@. A correct definition is
336 -- > evaluate x = (return $! x) >>= return
338 evaluate :: a -> IO a
339 evaluate a = IO $ \s -> case a `seq` () of () -> (# s, a #)
341 -- a `seq` (# s, a #)
342 -- because we can't have an unboxed tuple as a function argument