warning fix: -fno-implicit-prelude -> -XNoImplicitPrelude
[ghc.git] / libraries / base / GHC / IO.hs
1 {-# OPTIONS_GHC -fno-warn-orphans #-}
2 {-# OPTIONS_GHC -XNoImplicitPrelude -funbox-strict-fields #-}
3 {-# OPTIONS_HADDOCK hide #-}
4 -----------------------------------------------------------------------------
5 -- |
6 -- Module : GHC.IO
7 -- Copyright : (c) The University of Glasgow 1994-2002
8 -- License : see libraries/base/LICENSE
9 --
10 -- Maintainer : cvs-ghc@haskell.org
11 -- Stability : internal
12 -- Portability : non-portable (GHC Extensions)
13 --
14 -- Definitions for the 'IO' monad and its friends.
15 --
16 -----------------------------------------------------------------------------
17
18 -- #hide
19 module GHC.IO (
20 IO(..), unIO, failIO, liftIO, bindIO, thenIO, returnIO,
21 unsafePerformIO, unsafeInterleaveIO,
22 unsafeDupablePerformIO, unsafeDupableInterleaveIO,
23 noDuplicate,
24
25 -- To and from from ST
26 stToIO, ioToST, unsafeIOToST, unsafeSTToIO,
27
28 FilePath,
29
30 catchException, catchAny, throwIO,
31 block, unblock, blocked,
32 onException, finally, evaluate
33 ) where
34
35 import GHC.Base
36 import GHC.ST
37 import GHC.Exception
38 import Data.Maybe
39
40 import {-# SOURCE #-} GHC.IO.Exception ( userError )
41
42 -- ---------------------------------------------------------------------------
43 -- The IO Monad
44
45 {-
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.
49
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:
52
53 Compiler - types of various primitives in PrimOp.lhs
54
55 RTS - forceIO (StgMiscClosures.hc)
56 - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast
57 (Exceptions.hc)
58 - raiseAsync (Schedule.c)
59
60 Prelude - GHC.IO.lhs, and several other places including
61 GHC.Exception.lhs.
62
63 Libraries - parts of hslibs/lang.
64
65 --SDM
66 -}
67
68 unIO :: IO a -> (State# RealWorld -> (# State# RealWorld, a #))
69 unIO (IO a) = a
70
71 instance Functor IO where
72 fmap f x = x >>= (return . f)
73
74 instance Monad IO where
75 {-# INLINE return #-}
76 {-# INLINE (>>) #-}
77 {-# INLINE (>>=) #-}
78 m >> k = m >>= \ _ -> k
79 return x = returnIO x
80
81 m >>= k = bindIO m k
82 fail s = failIO s
83
84 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
85 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
86
87 bindIO :: IO a -> (a -> IO b) -> IO b
88 bindIO (IO m) k = IO ( \ s ->
89 case m s of
90 (# new_s, a #) -> unIO (k a) new_s
91 )
92
93 thenIO :: IO a -> IO b -> IO b
94 thenIO (IO m) k = IO ( \ s ->
95 case m s of
96 (# new_s, _ #) -> unIO k new_s
97 )
98
99 returnIO :: a -> IO a
100 returnIO x = IO (\ s -> (# s, x #))
101
102 failIO :: String -> IO a
103 failIO s = IO (raiseIO# (toException (userError s)))
104
105 -- ---------------------------------------------------------------------------
106 -- Coercions between IO and ST
107
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
113 stToIO (ST m) = IO m
114
115 ioToST :: IO a -> ST RealWorld a
116 ioToST (IO m) = (ST m)
117
118 -- This relies on IO and ST having the same representation modulo the
119 -- constraint on the type of the state
120 --
121 unsafeIOToST :: IO a -> ST s a
122 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
123
124 unsafeSTToIO :: ST s a -> IO a
125 unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
126
127 -- ---------------------------------------------------------------------------
128 -- Unsafe IO operations
129
130 {-|
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.
135
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':
141
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.
145
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).
150
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,
153 if you say:
154 @
155 f x = unsafePerformIO (newIORef [])
156 @
157 you may get only one reference cell shared between all calls to @f@.
158 Better would be
159 @
160 f x = unsafePerformIO (newIORef [x])
161 @
162 because now it can't float outside the lambda.
163
164 It is less well known that
165 'unsafePerformIO' is not type safe. For example:
166
167 > test :: IORef [a]
168 > test = unsafePerformIO $ newIORef []
169 >
170 > main = do
171 > writeIORef test [42]
172 > bang <- readIORef test
173 > print (bang :: [Char])
174
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!
181 -}
182 unsafePerformIO :: IO a -> a
183 unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)
184
185 {-|
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.
192 -}
193 {-# NOINLINE unsafeDupablePerformIO #-}
194 unsafeDupablePerformIO :: IO a -> a
195 unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
196
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.
202
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))
206 -- But then consider
207 -- unsafeDupablePerformIO (\s -> let r = f x in
208 -- case writeIORef v r s of (# s1, _ #) ->
209 -- (# s1, r #)
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
213 -- get a deadlock!
214 --
215 -- Solution: don't expose the strictness of unsafeDupablePerformIO,
216 -- by hiding it with 'lazy'
217
218 {-|
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'.
223 -}
224 {-# INLINE unsafeInterleaveIO #-}
225 unsafeInterleaveIO :: IO a -> IO a
226 unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)
227
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.
231
232 {-# INLINE unsafeDupableInterleaveIO #-}
233 unsafeDupableInterleaveIO :: IO a -> IO a
234 unsafeDupableInterleaveIO (IO m)
235 = IO ( \ s -> let
236 r = case m s of (# _, res #) -> res
237 in
238 (# s, r #))
239
240 {-|
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
244 'noDuplicate'.
245
246 This operation is used in the definition of 'unsafePerformIO' to
247 prevent the IO action from being executed multiple times, which is usually
248 undesirable.
249 -}
250 noDuplicate :: IO ()
251 noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)
252
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.
257
258 type FilePath = String
259
260 -- -----------------------------------------------------------------------------
261 -- Primitive catch and throwIO
262
263 {-
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...).
268
269 Now catch# has type
270
271 catch# :: IO a -> (b -> IO a) -> IO a
272
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).
275 -}
276
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')
281 Nothing -> raise# e
282
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)
286
287 -- | A variant of 'throw' that can only be used within the 'IO' monad.
288 --
289 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
290 -- two functions are subtly different:
291 --
292 -- > throw e `seq` x ===> throw e
293 -- > throwIO e `seq` x ===> x
294 --
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'
301 -- does not.
302 throwIO :: Exception e => e -> IO a
303 throwIO e = IO (raiseIO# (toException e))
304
305 -- -----------------------------------------------------------------------------
306 -- Controlling asynchronous exception delivery
307
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
315 -- 'block'.
316 --
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
323
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
330
331 block (IO io) = IO $ blockAsyncExceptions# io
332 unblock (IO io) = IO $ unblockAsyncExceptions# io
333
334 -- | returns True if asynchronous exceptions are blocked in the
335 -- current thread.
336 blocked :: IO Bool
337 blocked = IO $ \s -> case asyncExceptionsBlocked# s of
338 (# s', i #) -> (# s', i /=# 0# #)
339
340 onException :: IO a -> IO b -> IO a
341 onException io what = io `catchException` \e -> do _ <- what
342 throw (e :: SomeException)
343
344 finally :: IO a -- ^ computation to run first
345 -> IO b -- ^ computation to run afterward (even if an exception
346 -- was raised)
347 -> IO a -- returns the value from the first computation
348 a `finally` sequel =
349 block (do
350 r <- unblock a `onException` sequel
351 _ <- sequel
352 return r
353 )
354
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
358 -- given by
359 --
360 -- > evaluate x `seq` y ==> y
361 -- > evaluate x `catch` f ==> (return $! x) `catch` f
362 -- > evaluate x >>= f ==> (return $! x) >>= f
363 --
364 -- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
365 -- same as @(return $! x)@. A correct definition is
366 --
367 -- > evaluate x = (return $! x) >>= return
368 --
369 evaluate :: a -> IO a
370 evaluate a = IO $ \s -> case a `seq` () of () -> (# s, a #)
371 -- NB. can't write
372 -- a `seq` (# s, a #)
373 -- because we can't have an unboxed tuple as a function argument