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