578d2d2bacb2555b5645f0a906c747d37d991827
[ghc-base.git] / GHC / IO.hs
1 {-# OPTIONS_GHC -XNoImplicitPrelude -funbox-strict-fields -XBangPatterns #-}
2 {-# OPTIONS_HADDOCK hide #-}
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  GHC.IO
6 -- Copyright   :  (c) The University of Glasgow 1994-2002
7 -- License     :  see libraries/base/LICENSE
8 -- 
9 -- Maintainer  :  cvs-ghc@haskell.org
10 -- Stability   :  internal
11 -- Portability :  non-portable (GHC Extensions)
12 --
13 -- Definitions for the 'IO' monad and its friends.
14 --
15 -----------------------------------------------------------------------------
16
17 -- #hide
18 module GHC.IO (
19     IO(..), unIO, failIO, liftIO,
20     unsafePerformIO, unsafeInterleaveIO,
21     unsafeDupablePerformIO, unsafeDupableInterleaveIO,
22     noDuplicate,
23
24         -- To and from from ST
25     stToIO, ioToST, unsafeIOToST, unsafeSTToIO,
26
27     FilePath,
28
29     catchException, catchAny, throwIO,
30     block, unblock, blocked,
31     onException, finally, evaluate
32   ) where
33
34 import GHC.Base
35 import GHC.ST
36 import GHC.Exception
37 import Data.Maybe
38
39 import {-# SOURCE #-} GHC.IO.Exception ( userError )
40
41 -- ---------------------------------------------------------------------------
42 -- The IO Monad
43
44 {-
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.
48
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:
51
52 Compiler  - types of various primitives in PrimOp.lhs
53
54 RTS       - forceIO (StgMiscClosures.hc)
55           - catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast 
56             (Exceptions.hc)
57           - raiseAsync (Schedule.c)
58
59 Prelude   - GHC.IO.lhs, and several other places including
60             GHC.Exception.lhs.
61
62 Libraries - parts of hslibs/lang.
63
64 --SDM
65 -}
66
67 liftIO :: IO a -> State# RealWorld -> STret RealWorld a
68 liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
69
70 failIO :: String -> IO a
71 failIO s = IO (raiseIO# (toException (userError s)))
72
73 -- ---------------------------------------------------------------------------
74 -- Coercions between IO and ST
75
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
81 stToIO (ST m) = IO m
82
83 ioToST        :: IO a -> ST RealWorld a
84 ioToST (IO m) = (ST m)
85
86 -- This relies on IO and ST having the same representation modulo the
87 -- constraint on the type of the state
88 --
89 unsafeIOToST        :: IO a -> ST s a
90 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
91
92 unsafeSTToIO :: ST s a -> IO a
93 unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
94
95 -- ---------------------------------------------------------------------------
96 -- Unsafe IO operations
97
98 {-|
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.
103
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':
109
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.
113
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).
118
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, 
121         if you say:
122         @
123            f x = unsafePerformIO (newIORef [])
124         @
125         you may get only one reference cell shared between all calls to @f@.
126         Better would be
127         @
128            f x = unsafePerformIO (newIORef [x])
129         @
130         because now it can't float outside the lambda.
131
132 It is less well known that
133 'unsafePerformIO' is not type safe.  For example:
134
135 >     test :: IORef [a]
136 >     test = unsafePerformIO $ newIORef []
137 >     
138 >     main = do
139 >             writeIORef test [42]
140 >             bang <- readIORef test
141 >             print (bang :: [Char])
142
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!
149 -}
150 unsafePerformIO :: IO a -> a
151 unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)
152
153 {-| 
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.
160 -}
161 {-# NOINLINE unsafeDupablePerformIO #-}
162 unsafeDupablePerformIO  :: IO a -> a
163 unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
164
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.
170
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))
174 -- But then consider
175 --      unsafeDupablePerformIO (\s -> let r = f x in 
176 --                             case writeIORef v r s of (# s1, _ #) ->
177 --                             (# s1, r #)
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
181 -- get a deadlock!  
182 --
183 -- Solution: don't expose the strictness of unsafeDupablePerformIO,
184 --           by hiding it with 'lazy'
185
186 {-|
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'.
191 -}
192 {-# INLINE unsafeInterleaveIO #-}
193 unsafeInterleaveIO :: IO a -> IO a
194 unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)
195
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.
199
200 {-# INLINE unsafeDupableInterleaveIO #-}
201 unsafeDupableInterleaveIO :: IO a -> IO a
202 unsafeDupableInterleaveIO (IO m)
203   = IO ( \ s -> let
204                    r = case m s of (# _, res #) -> res
205                 in
206                 (# s, r #))
207
208 {-| 
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
212 'noDuplicate'.
213
214 This operation is used in the definition of 'unsafePerformIO' to
215 prevent the IO action from being executed multiple times, which is usually
216 undesirable.
217 -}
218 noDuplicate :: IO ()
219 noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)
220
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.
225
226 type FilePath = String
227
228 -- -----------------------------------------------------------------------------
229 -- Primitive catch and throwIO
230
231 {-
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...).
236
237 Now catch# has type
238
239     catch# :: IO a -> (b -> IO a) -> IO a
240
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).
243 -}
244
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')
249                        Nothing -> raise# e
250
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)
254
255 -- | A variant of 'throw' that can only be used within the 'IO' monad.
256 --
257 -- Although 'throwIO' has a type that is an instance of the type of 'throw', the
258 -- two functions are subtly different:
259 --
260 -- > throw e   `seq` x  ===> throw e
261 -- > throwIO e `seq` x  ===> x
262 --
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'
269 -- does not.
270 throwIO :: Exception e => e -> IO a
271 throwIO e = IO (raiseIO# (toException e))
272
273 -- -----------------------------------------------------------------------------
274 -- Controlling asynchronous exception delivery
275
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
283 -- 'block'.
284 --
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
291
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
298
299 block (IO io) = IO $ blockAsyncExceptions# io
300 unblock (IO io) = IO $ unblockAsyncExceptions# io
301
302 -- | returns True if asynchronous exceptions are blocked in the
303 -- current thread.
304 blocked :: IO Bool
305 blocked = IO $ \s -> case asyncExceptionsBlocked# s of
306                         (# s', i #) -> (# s', i /=# 0# #)
307
308 onException :: IO a -> IO b -> IO a
309 onException io what = io `catchException` \e -> do _ <- what
310                                                    throw (e :: SomeException)
311
312 finally :: IO a         -- ^ computation to run first
313         -> IO b         -- ^ computation to run afterward (even if an exception
314                         -- was raised)
315         -> IO a         -- returns the value from the first computation
316 a `finally` sequel =
317   block (do
318     r <- unblock a `onException` sequel
319     _ <- sequel
320     return r
321   )
322
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
326 -- given by
327 --
328 -- >   evaluate x `seq` y    ==>  y
329 -- >   evaluate x `catch` f  ==>  (return $! x) `catch` f
330 -- >   evaluate x >>= f      ==>  (return $! x) >>= f
331 --
332 -- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
333 -- same as @(return $! x)@.  A correct definition is
334 --
335 -- >   evaluate x = (return $! x) >>= return
336 --
337 evaluate :: a -> IO a
338 evaluate a = IO $ \s -> let !va = a in (# s, va #) -- NB. see #2273