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