Rejig some code so Control.Exception and GHC.Conc don't need recursive imports
[ghc-base.git] / Control / Exception.hs
1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
2
3 #include "Typeable.h"
4
5 -----------------------------------------------------------------------------
6 -- |
7 -- Module      :  Control.Exception
8 -- Copyright   :  (c) The University of Glasgow 2001
9 -- License     :  BSD-style (see the file libraries/base/LICENSE)
10 -- 
11 -- Maintainer  :  libraries@haskell.org
12 -- Stability   :  experimental
13 -- Portability :  non-portable (extended exceptions)
14 --
15 -- This module provides support for raising and catching both built-in
16 -- and user-defined exceptions.
17 --
18 -- In addition to exceptions thrown by 'IO' operations, exceptions may
19 -- be thrown by pure code (imprecise exceptions) or by external events
20 -- (asynchronous exceptions), but may only be caught in the 'IO' monad.
21 -- For more details, see:
22 --
23 --  * /A semantics for imprecise exceptions/, by Simon Peyton Jones,
24 --    Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson,
25 --    in /PLDI'99/.
26 --
27 --  * /Asynchronous exceptions in Haskell/, by Simon Marlow, Simon Peyton
28 --    Jones, Andy Moran and John Reppy, in /PLDI'01/.
29 --
30 -----------------------------------------------------------------------------
31
32 module Control.Exception (
33
34         -- * The Exception type
35         SomeException(..),
36         Exception(..),          -- instance Eq, Ord, Show, Typeable
37         IOException,            -- instance Eq, Ord, Show, Typeable
38         ArithException(..),     -- instance Eq, Ord, Show, Typeable
39         ArrayException(..),     -- instance Eq, Ord, Show, Typeable
40         AssertionFailed(..),
41         AsyncException(..),     -- instance Eq, Ord, Show, Typeable
42         NonTermination(..), nonTermination,
43         BlockedOnDeadMVar(..),
44         BlockedIndefinitely(..),
45         NestedAtomically(..), nestedAtomically,
46         Deadlock(..),
47         NoMethodError(..),
48         PatternMatchFail(..),
49         RecConError(..),
50         RecSelError(..),
51         RecUpdError(..),
52         ErrorCall(..),
53
54         -- * Throwing exceptions
55         throwIO,        -- :: Exception -> IO a
56         throw,          -- :: Exception -> a
57         ioError,        -- :: IOError -> IO a
58 #ifdef __GLASGOW_HASKELL__
59         throwTo,        -- :: ThreadId -> Exception -> a
60 #endif
61
62         -- * Catching Exceptions
63
64         -- |There are several functions for catching and examining
65         -- exceptions; all of them may only be used from within the
66         -- 'IO' monad.
67
68         -- ** The @catch@ functions
69         catch,     -- :: IO a -> (Exception -> IO a) -> IO a
70         catches, Handler(..),
71         catchAny,
72         catchJust, -- :: (Exception -> Maybe b) -> IO a -> (b -> IO a) -> IO a
73
74         -- ** The @handle@ functions
75         handle,    -- :: (Exception -> IO a) -> IO a -> IO a
76         handleAny,
77         handleJust,-- :: (Exception -> Maybe b) -> (b -> IO a) -> IO a -> IO a
78
79         -- ** The @try@ functions
80         try,       -- :: IO a -> IO (Either Exception a)
81         tryJust,   -- :: (Exception -> Maybe b) -> a    -> IO (Either b a)
82         ignoreExceptions,
83         onException,
84
85         -- ** The @evaluate@ function
86         evaluate,  -- :: a -> IO a
87
88         -- ** The @mapException@ function
89         mapException,           -- :: (Exception -> Exception) -> a -> a
90
91         -- * Asynchronous Exceptions
92
93         -- $async
94
95         -- ** Asynchronous exception control
96
97         -- |The following two functions allow a thread to control delivery of
98         -- asynchronous exceptions during a critical region.
99
100         block,          -- :: IO a -> IO a
101         unblock,        -- :: IO a -> IO a
102         blocked,        -- :: IO Bool
103
104         -- *** Applying @block@ to an exception handler
105
106         -- $block_handler
107
108         -- *** Interruptible operations
109
110         -- $interruptible
111
112         -- * Assertions
113
114         assert,         -- :: Bool -> a -> a
115
116         -- * Utilities
117
118         bracket,        -- :: IO a -> (a -> IO b) -> (a -> IO c) -> IO ()
119         bracket_,       -- :: IO a -> IO b -> IO c -> IO ()
120         bracketOnError,
121
122         finally,        -- :: IO a -> IO b -> IO a
123
124         recSelError, recConError, irrefutPatError, runtimeError,
125         nonExhaustiveGuardsError, patError, noMethodBindingError,
126         assertError,
127   ) where
128
129 #ifdef __GLASGOW_HASKELL__
130 import GHC.Base
131 import GHC.IOBase
132 import GHC.List
133 import GHC.Num
134 import GHC.Show
135 import GHC.IOBase as ExceptionBase
136 import GHC.Exception hiding ( Exception )
137 import GHC.Conc         ( ThreadId(ThreadId) )
138 import Foreign.C.String ( CString, withCString )
139 #endif
140
141 #ifdef __HUGS__
142 import Hugs.Exception   as ExceptionBase
143 #endif
144
145 import Data.Dynamic
146 import Data.Either
147 import Data.Maybe
148
149 #ifdef __NHC__
150 import qualified System.IO.Error as H'98 (catch)
151 import System.IO.Error (ioError)
152 import IO              (bracket)
153 import DIOError         -- defn of IOError type
154 import System          (ExitCode())
155
156 -- minimum needed for nhc98 to pretend it has Exceptions
157 data Exception   = IOException    IOException
158                  | ArithException ArithException
159                  | ArrayException ArrayException
160                  | AsyncException AsyncException
161                  | ExitException  ExitCode
162                  deriving Show
163 type IOException = IOError
164 data ArithException
165 data ArrayException
166 data AsyncException
167 instance Show ArithException
168 instance Show ArrayException
169 instance Show AsyncException
170
171 catch    :: IO a -> (Exception -> IO a) -> IO a
172 a `catch` b = a `H'98.catch` (b . IOException)
173
174 throwIO  :: Exception -> IO a
175 throwIO (IOException e) = ioError e
176 throwIO _               = ioError (UserError "Control.Exception.throwIO"
177                                              "unknown exception")
178 throw    :: Exception -> a
179 throw     = unsafePerformIO . throwIO
180
181 evaluate :: a -> IO a
182 evaluate x = x `seq` return x
183
184 assert :: Bool -> a -> a
185 assert True  x = x
186 assert False _ = throw (IOException (UserError "" "Assertion failed"))
187 #endif
188
189 #ifndef __GLASGOW_HASKELL__
190 -- Dummy definitions for implementations lacking asynchonous exceptions
191
192 block   :: IO a -> IO a
193 block    = id
194 unblock :: IO a -> IO a
195 unblock  = id
196 blocked :: IO Bool
197 blocked  = return False
198 #endif
199
200 -----------------------------------------------------------------------------
201 -- Catching exceptions
202
203 -- |This is the simplest of the exception-catching functions.  It
204 -- takes a single argument, runs it, and if an exception is raised
205 -- the \"handler\" is executed, with the value of the exception passed as an
206 -- argument.  Otherwise, the result is returned as normal.  For example:
207 --
208 -- >   catch (openFile f ReadMode) 
209 -- >       (\e -> hPutStr stderr ("Couldn't open "++f++": " ++ show e))
210 --
211 -- For catching exceptions in pure (non-'IO') expressions, see the
212 -- function 'evaluate'.
213 --
214 -- Note that due to Haskell\'s unspecified evaluation order, an
215 -- expression may return one of several possible exceptions: consider
216 -- the expression @error \"urk\" + 1 \`div\` 0@.  Does
217 -- 'catch' execute the handler passing
218 -- @ErrorCall \"urk\"@, or @ArithError DivideByZero@?
219 --
220 -- The answer is \"either\": 'catch' makes a
221 -- non-deterministic choice about which exception to catch.  If you
222 -- call it again, you might get a different exception back.  This is
223 -- ok, because 'catch' is an 'IO' computation.
224 --
225 -- Note that 'catch' catches all types of exceptions, and is generally
226 -- used for \"cleaning up\" before passing on the exception using
227 -- 'throwIO'.  It is not good practice to discard the exception and
228 -- continue, without first checking the type of the exception (it
229 -- might be a 'ThreadKilled', for example).  In this case it is usually better
230 -- to use 'catchJust' and select the kinds of exceptions to catch.
231 --
232 -- Also note that the "Prelude" also exports a function called
233 -- 'Prelude.catch' with a similar type to 'Control.Exception.catch',
234 -- except that the "Prelude" version only catches the IO and user
235 -- families of exceptions (as required by Haskell 98).  
236 --
237 -- We recommend either hiding the "Prelude" version of 'Prelude.catch'
238 -- when importing "Control.Exception": 
239 --
240 -- > import Prelude hiding (catch)
241 --
242 -- or importing "Control.Exception" qualified, to avoid name-clashes:
243 --
244 -- > import qualified Control.Exception as C
245 --
246 -- and then using @C.catch@
247 --
248 #ifndef __NHC__
249 catch   :: Exception e
250         => IO a         -- ^ The computation to run
251         -> (e -> IO a)  -- ^ Handler to invoke if an exception is raised
252         -> IO a
253 catch = ExceptionBase.catchException
254
255 catches :: IO a -> [Handler a] -> IO a
256 catches io handlers = io `catch` catchesHandler handlers
257
258 catchesHandler :: [Handler a] -> SomeException -> IO a
259 catchesHandler handlers e = foldr tryHandler (throw e) handlers
260     where tryHandler (Handler handler) res
261               = case fromException e of
262                 Just e' -> handler e'
263                 Nothing -> res
264
265 data Handler a = forall e . Exception e => Handler (e -> IO a)
266 #endif
267 -- | The function 'catchJust' is like 'catch', but it takes an extra
268 -- argument which is an /exception predicate/, a function which
269 -- selects which type of exceptions we\'re interested in.
270 --
271 -- >   result <- catchJust errorCalls thing_to_try handler
272 --
273 -- Any other exceptions which are not matched by the predicate
274 -- are re-raised, and may be caught by an enclosing
275 -- 'catch' or 'catchJust'.
276 catchJust
277         :: Exception e
278         => (e -> Maybe b)         -- ^ Predicate to select exceptions
279         -> IO a                   -- ^ Computation to run
280         -> (b -> IO a)            -- ^ Handler
281         -> IO a
282 catchJust p a handler = catch a handler'
283   where handler' e = case p e of 
284                         Nothing -> throw e
285                         Just b  -> handler b
286
287 -- | A version of 'catch' with the arguments swapped around; useful in
288 -- situations where the code for the handler is shorter.  For example:
289 --
290 -- >   do handle (\e -> exitWith (ExitFailure 1)) $
291 -- >      ...
292 handle     :: Exception e => (e -> IO a) -> IO a -> IO a
293 handle     =  flip catch
294
295 handleAny  :: (forall e . Exception e => e -> IO a) -> IO a -> IO a
296 handleAny  =  flip catchAny
297
298 -- | A version of 'catchJust' with the arguments swapped around (see
299 -- 'handle').
300 handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a
301 handleJust p =  flip (catchJust p)
302
303 -----------------------------------------------------------------------------
304 -- 'mapException'
305
306 -- | This function maps one exception into another as proposed in the
307 -- paper \"A semantics for imprecise exceptions\".
308
309 -- Notice that the usage of 'unsafePerformIO' is safe here.
310
311 mapException :: Exception e => (e -> e) -> a -> a
312 mapException f v = unsafePerformIO (catch (evaluate v)
313                                           (\x -> throw (f x)))
314
315 -----------------------------------------------------------------------------
316 -- 'try' and variations.
317
318 -- | Similar to 'catch', but returns an 'Either' result which is
319 -- @('Right' a)@ if no exception was raised, or @('Left' e)@ if an
320 -- exception was raised and its value is @e@.
321 --
322 -- >  try a = catch (Right `liftM` a) (return . Left)
323 --
324 -- Note: as with 'catch', it is only polite to use this variant if you intend
325 -- to re-throw the exception after performing whatever cleanup is needed.
326 -- Otherwise, 'tryJust' is generally considered to be better.
327 --
328 -- Also note that "System.IO.Error" also exports a function called
329 -- 'System.IO.Error.try' with a similar type to 'Control.Exception.try',
330 -- except that it catches only the IO and user families of exceptions
331 -- (as required by the Haskell 98 @IO@ module).
332
333 try :: Exception e => IO a -> IO (Either e a)
334 try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
335
336 -- | A variant of 'try' that takes an exception predicate to select
337 -- which exceptions are caught (c.f. 'catchJust').  If the exception
338 -- does not match the predicate, it is re-thrown.
339 tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)
340 tryJust p a = do
341   r <- try a
342   case r of
343         Right v -> return (Right v)
344         Left  e -> case p e of
345                         Nothing -> throw e
346                         Just b  -> return (Left b)
347
348 ignoreExceptions :: IO () -> IO ()
349 ignoreExceptions io = io `catchAny` \_ -> return ()
350
351 onException :: IO a -> IO () -> IO a
352 onException io what = io `catch` \e -> do what
353                                           throw (e :: SomeException)
354
355 -----------------------------------------------------------------------------
356 -- Some Useful Functions
357
358 -- | When you want to acquire a resource, do some work with it, and
359 -- then release the resource, it is a good idea to use 'bracket',
360 -- because 'bracket' will install the necessary exception handler to
361 -- release the resource in the event that an exception is raised
362 -- during the computation.  If an exception is raised, then 'bracket' will 
363 -- re-raise the exception (after performing the release).
364 --
365 -- A common example is opening a file:
366 --
367 -- > bracket
368 -- >   (openFile "filename" ReadMode)
369 -- >   (hClose)
370 -- >   (\handle -> do { ... })
371 --
372 -- The arguments to 'bracket' are in this order so that we can partially apply 
373 -- it, e.g.:
374 --
375 -- > withFile name mode = bracket (openFile name mode) hClose
376 --
377 #ifndef __NHC__
378 bracket 
379         :: IO a         -- ^ computation to run first (\"acquire resource\")
380         -> (a -> IO b)  -- ^ computation to run last (\"release resource\")
381         -> (a -> IO c)  -- ^ computation to run in-between
382         -> IO c         -- returns the value from the in-between computation
383 bracket before after thing =
384   block (do
385     a <- before 
386     r <- catchAny
387            (unblock (thing a))
388            (\e -> do { after a; throw e })
389     after a
390     return r
391  )
392 #endif
393
394 -- | A specialised variant of 'bracket' with just a computation to run
395 -- afterward.
396 -- 
397 finally :: IO a         -- ^ computation to run first
398         -> IO b         -- ^ computation to run afterward (even if an exception 
399                         -- was raised)
400         -> IO a         -- returns the value from the first computation
401 a `finally` sequel =
402   block (do
403     r <- catchAny
404              (unblock a)
405              (\e -> do { sequel; throw e })
406     sequel
407     return r
408   )
409
410 -- | A variant of 'bracket' where the return value from the first computation
411 -- is not required.
412 bracket_ :: IO a -> IO b -> IO c -> IO c
413 bracket_ before after thing = bracket before (const after) (const thing)
414
415 -- | Like bracket, but only performs the final action if there was an 
416 -- exception raised by the in-between computation.
417 bracketOnError
418         :: IO a         -- ^ computation to run first (\"acquire resource\")
419         -> (a -> IO b)  -- ^ computation to run last (\"release resource\")
420         -> (a -> IO c)  -- ^ computation to run in-between
421         -> IO c         -- returns the value from the in-between computation
422 bracketOnError before after thing =
423   block (do
424     a <- before 
425     catchAny
426         (unblock (thing a))
427         (\e -> do { after a; throw e })
428  )
429
430 -- -----------------------------------------------------------------------------
431 -- Asynchronous exceptions
432
433 {- $async
434
435  #AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
436 external influences, and can be raised at any point during execution.
437 'StackOverflow' and 'HeapOverflow' are two examples of
438 system-generated asynchronous exceptions.
439
440 The primary source of asynchronous exceptions, however, is
441 'throwTo':
442
443 >  throwTo :: ThreadId -> Exception -> IO ()
444
445 'throwTo' (also 'throwDynTo' and 'Control.Concurrent.killThread') allows one
446 running thread to raise an arbitrary exception in another thread.  The
447 exception is therefore asynchronous with respect to the target thread,
448 which could be doing anything at the time it receives the exception.
449 Great care should be taken with asynchronous exceptions; it is all too
450 easy to introduce race conditions by the over zealous use of
451 'throwTo'.
452 -}
453
454 {- $block_handler
455 There\'s an implied 'block' around every exception handler in a call
456 to one of the 'catch' family of functions.  This is because that is
457 what you want most of the time - it eliminates a common race condition
458 in starting an exception handler, because there may be no exception
459 handler on the stack to handle another exception if one arrives
460 immediately.  If asynchronous exceptions are blocked on entering the
461 handler, though, we have time to install a new exception handler
462 before being interrupted.  If this weren\'t the default, one would have
463 to write something like
464
465 >      block (
466 >           catch (unblock (...))
467 >                      (\e -> handler)
468 >      )
469
470 If you need to unblock asynchronous exceptions again in the exception
471 handler, just use 'unblock' as normal.
472
473 Note that 'try' and friends /do not/ have a similar default, because
474 there is no exception handler in this case.  If you want to use 'try'
475 in an asynchronous-exception-safe way, you will need to use
476 'block'.
477 -}
478
479 {- $interruptible
480
481 Some operations are /interruptible/, which means that they can receive
482 asynchronous exceptions even in the scope of a 'block'.  Any function
483 which may itself block is defined as interruptible; this includes
484 'Control.Concurrent.MVar.takeMVar'
485 (but not 'Control.Concurrent.MVar.tryTakeMVar'),
486 and most operations which perform
487 some I\/O with the outside world.  The reason for having
488 interruptible operations is so that we can write things like
489
490 >      block (
491 >         a <- takeMVar m
492 >         catch (unblock (...))
493 >               (\e -> ...)
494 >      )
495
496 if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
497 then this particular
498 combination could lead to deadlock, because the thread itself would be
499 blocked in a state where it can\'t receive any asynchronous exceptions.
500 With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
501 safe in the knowledge that the thread can receive exceptions right up
502 until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
503 Similar arguments apply for other interruptible operations like
504 'System.IO.openFile'.
505 -}
506
507 #if !(__GLASGOW_HASKELL__ || __NHC__)
508 assert :: Bool -> a -> a
509 assert True x = x
510 assert False _ = throw (AssertionFailed "")
511 #endif
512
513 recSelError, recConError, irrefutPatError, runtimeError,
514              nonExhaustiveGuardsError, patError, noMethodBindingError
515         :: Addr# -> a   -- All take a UTF8-encoded C string
516
517 recSelError              s = throw (RecSelError (unpackCStringUtf8# s)) -- No location info unfortunately
518 runtimeError             s = error (unpackCStringUtf8# s)               -- No location info unfortunately
519
520 nonExhaustiveGuardsError s = throw (PatternMatchFail (untangle s "Non-exhaustive guards in"))
521 irrefutPatError          s = throw (PatternMatchFail (untangle s "Irrefutable pattern failed for pattern"))
522 recConError              s = throw (RecConError      (untangle s "Missing field in record construction"))
523 noMethodBindingError     s = throw (NoMethodError    (untangle s "No instance nor default method for class operation"))
524 patError                 s = throw (PatternMatchFail (untangle s "Non-exhaustive patterns in"))
525
526 -----
527
528 data PatternMatchFail = PatternMatchFail String
529 INSTANCE_TYPEABLE0(PatternMatchFail,patternMatchFailTc,"PatternMatchFail")
530
531 instance Exception PatternMatchFail
532
533 instance Show PatternMatchFail where
534     showsPrec _ (PatternMatchFail err) = showString err
535
536 -----
537
538 data RecSelError = RecSelError String
539 INSTANCE_TYPEABLE0(RecSelError,recSelErrorTc,"RecSelError")
540
541 instance Exception RecSelError
542
543 instance Show RecSelError where
544     showsPrec _ (RecSelError err) = showString err
545
546 -----
547
548 data RecConError = RecConError String
549 INSTANCE_TYPEABLE0(RecConError,recConErrorTc,"RecConError")
550
551 instance Exception RecConError
552
553 instance Show RecConError where
554     showsPrec _ (RecConError err) = showString err
555
556 -----
557
558 data RecUpdError = RecUpdError String
559 INSTANCE_TYPEABLE0(RecUpdError,recUpdErrorTc,"RecUpdError")
560
561 instance Exception RecUpdError
562
563 instance Show RecUpdError where
564     showsPrec _ (RecUpdError err) = showString err
565
566 -----
567
568 data NoMethodError = NoMethodError String
569 INSTANCE_TYPEABLE0(NoMethodError,noMethodErrorTc,"NoMethodError")
570
571 instance Exception NoMethodError
572
573 instance Show NoMethodError where
574     showsPrec _ (NoMethodError err) = showString err
575
576 -----
577
578 data AssertionFailed = AssertionFailed String
579 INSTANCE_TYPEABLE0(AssertionFailed,assertionFailedTc,"AssertionFailed")
580
581 instance Exception AssertionFailed
582
583 instance Show AssertionFailed where
584     showsPrec _ (AssertionFailed err) = showString err
585
586 -----
587
588 data NonTermination = NonTermination
589 INSTANCE_TYPEABLE0(NonTermination,nonTerminationTc,"NonTermination")
590
591 instance Exception NonTermination
592
593 instance Show NonTermination where
594     showsPrec _ NonTermination = showString "<<loop>>"
595
596 -- GHC's RTS calls this
597 nonTermination :: SomeException
598 nonTermination = toException NonTermination
599
600 -----
601
602 data NestedAtomically = NestedAtomically
603 INSTANCE_TYPEABLE0(NestedAtomically,nestedAtomicallyTc,"NestedAtomically")
604
605 instance Exception NestedAtomically
606
607 instance Show NestedAtomically where
608     showsPrec _ NestedAtomically = showString "Control.Concurrent.STM.atomically was nested"
609
610 -- GHC's RTS calls this
611 nestedAtomically :: SomeException
612 nestedAtomically = toException NestedAtomically
613
614 -----
615
616 instance Exception Dynamic
617
618 -----
619
620 assertError :: Addr# -> Bool -> a -> a
621 assertError str pred v
622   | pred      = v
623   | otherwise = throw (AssertionFailed (untangle str "Assertion failed"))
624
625 {-
626 (untangle coded message) expects "coded" to be of the form
627         "location|details"
628 It prints
629         location message details
630 -}
631 untangle :: Addr# -> String -> String
632 untangle coded message
633   =  location
634   ++ ": " 
635   ++ message
636   ++ details
637   ++ "\n"
638   where
639     coded_str = unpackCStringUtf8# coded
640
641     (location, details)
642       = case (span not_bar coded_str) of { (loc, rest) ->
643         case rest of
644           ('|':det) -> (loc, ' ' : det)
645           _         -> (loc, "")
646         }
647     not_bar c = c /= '|'
648
649 -- XXX From GHC.Conc
650 throwTo :: Exception e => ThreadId -> e -> IO ()
651 throwTo (ThreadId id) ex = IO $ \ s ->
652    case (killThread# id (toException ex) s) of s1 -> (# s1, () #)
653