Use let !y = x in .. x .. instead of seq in $! and evaluate (#2273)
[ghc-base.git] / GHC / IO.hs
1 {-# OPTIONS_GHC -fno-warn-orphans #-}
2 {-# OPTIONS_GHC -XNoImplicitPrelude -funbox-strict-fields -XBangPatterns #-}
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,
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 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
69 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
70
71 failIO :: String -> IO a
72 failIO s = IO (raiseIO# (toException (userError s)))
73
74 -- ---------------------------------------------------------------------------
75 -- Coercions between IO and ST
76
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
82 stToIO (ST m) = IO m
83
84 ioToST        :: IO a -> ST RealWorld a
85 ioToST (IO m) = (ST m)
86
87 -- This relies on IO and ST having the same representation modulo the
88 -- constraint on the type of the state
89 --
90 unsafeIOToST        :: IO a -> ST s a
91 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
92
93 unsafeSTToIO :: ST s a -> IO a
94 unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
95
96 -- ---------------------------------------------------------------------------
97 -- Unsafe IO operations
98
99 {-|
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.
104
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':
110
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.
114
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).
119
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, 
122         if you say:
123         @
124            f x = unsafePerformIO (newIORef [])
125         @
126         you may get only one reference cell shared between all calls to @f@.
127         Better would be
128         @
129            f x = unsafePerformIO (newIORef [x])
130         @
131         because now it can't float outside the lambda.
132
133 It is less well known that
134 'unsafePerformIO' is not type safe.  For example:
135
136 >     test :: IORef [a]
137 >     test = unsafePerformIO $ newIORef []
138 >     
139 >     main = do
140 >             writeIORef test [42]
141 >             bang <- readIORef test
142 >             print (bang :: [Char])
143
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!
150 -}
151 unsafePerformIO :: IO a -> a
152 unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)
153
154 {-| 
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.
161 -}
162 {-# NOINLINE unsafeDupablePerformIO #-}
163 unsafeDupablePerformIO  :: IO a -> a
164 unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
165
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.
171
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))
175 -- But then consider
176 --      unsafeDupablePerformIO (\s -> let r = f x in 
177 --                             case writeIORef v r s of (# s1, _ #) ->
178 --                             (# s1, r #)
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
182 -- get a deadlock!  
183 --
184 -- Solution: don't expose the strictness of unsafeDupablePerformIO,
185 --           by hiding it with 'lazy'
186
187 {-|
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'.
192 -}
193 {-# INLINE unsafeInterleaveIO #-}
194 unsafeInterleaveIO :: IO a -> IO a
195 unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)
196
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.
200
201 {-# INLINE unsafeDupableInterleaveIO #-}
202 unsafeDupableInterleaveIO :: IO a -> IO a
203 unsafeDupableInterleaveIO (IO m)
204   = IO ( \ s -> let
205                    r = case m s of (# _, res #) -> res
206                 in
207                 (# s, r #))
208
209 {-| 
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
213 'noDuplicate'.
214
215 This operation is used in the definition of 'unsafePerformIO' to
216 prevent the IO action from being executed multiple times, which is usually
217 undesirable.
218 -}
219 noDuplicate :: IO ()
220 noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)
221
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.
226
227 type FilePath = String
228
229 -- -----------------------------------------------------------------------------
230 -- Primitive catch and throwIO
231
232 {-
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...).
237
238 Now catch# has type
239
240     catch# :: IO a -> (b -> IO a) -> IO a
241
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).
244 -}
245
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')
250                        Nothing -> raise# e
251
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)
255
256 -- | A variant of 'throw' that can only be used within the 'IO' monad.
257 --
258 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
259 -- two functions are subtly different:
260 --
261 -- > throw e   `seq` x  ===> throw e
262 -- > throwIO e `seq` x  ===> x
263 --
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'
270 -- does not.
271 throwIO :: Exception e => e -> IO a
272 throwIO e = IO (raiseIO# (toException e))
273
274 -- -----------------------------------------------------------------------------
275 -- Controlling asynchronous exception delivery
276
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
284 -- 'block'.
285 --
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
292
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
299
300 block (IO io) = IO $ blockAsyncExceptions# io
301 unblock (IO io) = IO $ unblockAsyncExceptions# io
302
303 -- | returns True if asynchronous exceptions are blocked in the
304 -- current thread.
305 blocked :: IO Bool
306 blocked = IO $ \s -> case asyncExceptionsBlocked# s of
307                         (# s', i #) -> (# s', i /=# 0# #)
308
309 onException :: IO a -> IO b -> IO a
310 onException io what = io `catchException` \e -> do _ <- what
311                                                    throw (e :: SomeException)
312
313 finally :: IO a         -- ^ computation to run first
314         -> IO b         -- ^ computation to run afterward (even if an exception
315                         -- was raised)
316         -> IO a         -- returns the value from the first computation
317 a `finally` sequel =
318   block (do
319     r <- unblock a `onException` sequel
320     _ <- sequel
321     return r
322   )
323
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
327 -- given by
328 --
329 -- >   evaluate x `seq` y    ==>  y
330 -- >   evaluate x `catch` f  ==>  (return $! x) `catch` f
331 -- >   evaluate x >>= f      ==>  (return $! x) >>= f
332 --
333 -- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
334 -- same as @(return $! x)@.  A correct definition is
335 --
336 -- >   evaluate x = (return $! x) >>= return
337 --
338 evaluate :: a -> IO a
339 evaluate a = IO $ \s -> let !va = a in (# s, va #) -- NB. see #2273