papa-0.7.0: src/Papa/Base/Control/Exception.hs
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -Wall #-}
-- | Exceptions in 'Prelude.IO', caught without catching asynchronous
-- exceptions, and released without being interrupted.
--
-- 'catch', 'handle' and 'try' differ from "Control.Exception"'s: they never
-- catch an asynchronous exception (one thrown to the thread by
-- 'Control.Concurrent.killThread', 'Control.Concurrent.throwTo' or
-- 'System.Timeout.timeout'), even at 'SomeException'. They rethrow it, so
-- that a thread told to stop, stops.
--
-- 'bracket', 'bracket_', 'bracketOnError', 'finally' and 'onException' differ
-- too: they run the release action under 'uninterruptibleMask_', so that a
-- second asynchronous exception cannot interrupt a release that blocks (an
-- 'Control.Concurrent.MVar', closing a socket) and leak the resource. The
-- cost: a release action that blocks forever cannot be interrupted, so it
-- hangs the thread. When the body throws, an exception thrown by the release
-- action is discarded and the body's is rethrown. These are the semantics of
-- the @safe-exceptions@ package, which Papa does not depend on.
--
-- @throw@, which throws from pure code, is not exported: like @error@, it
-- makes a function partial. It is in "Papa.Unsafe.Exception".
module Papa.Base.Control.Exception (
module P,
catch,
handle,
try,
bracket,
bracket_,
bracketOnError,
finally,
onException,
) where
import Control.Applicative (pure, (<$>))
import Control.Category ((.))
import Control.Exception as P (
ArithException (..),
ArrayException (..),
AsyncException (HeapOverflow, StackOverflow, ThreadKilled, UserInterrupt),
ErrorCall,
Exception (displayException, fromException, toException),
IOException,
MaskingState (MaskedInterruptible, MaskedUninterruptible, Unmasked),
SomeAsyncException (SomeAsyncException),
SomeException,
asyncExceptionFromException,
asyncExceptionToException,
evaluate,
getMaskingState,
mask,
mask_,
throwIO,
throwTo,
uninterruptibleMask,
uninterruptibleMask_,
)
import qualified Control.Exception as E
import Control.Monad ((>>=))
import Data.Bool (Bool, bool)
import Data.Either (Either (Left, Right), either)
import Data.Function (const, flip)
import Data.Maybe (Maybe, isJust)
import Prelude (IO)
-- $setup
-- >>> :set -XNoImplicitPrelude
-- >>> :set -XScopedTypeVariables
-- >>> :set -XTypeApplications
-- >>> import Papa
-- >>> import Hedgehog
-- >>> import qualified Hedgehog.Gen as Gen
-- >>> import qualified Hedgehog.Range as Range
-- | Whether an exception was thrown asynchronously.
isAsync :: SomeException -> Bool
isAsync e =
isJust (fromException e :: Maybe SomeAsyncException)
{-# INLINE isAsync #-}
-- | Run the action; if it throws a synchronous exception of type @e@, run the
-- handler on it. An asynchronous exception is rethrown, even where @e@ is
-- 'SomeException'.
--
-- ==== __Examples__
--
-- >>> catch (throwIO (userError "u")) (\(e :: IOException) -> pure (displayException e))
-- "user error (u)"
--
-- >>> catch (throwIO DivideByZero) (\(_ :: SomeException) -> pure "caught")
-- "caught"
--
-- An asynchronous exception is not caught, even at 'SomeException':
--
-- >>> do { s <- newEmptyMVar; v <- newEmptyMVar; t <- forkFinally (catch (putMVar s () *> threadDelay 10000000 *> pure "finished") (\(_ :: SomeException) -> pure "caught")) (putMVar v . either show id); takeMVar s; killThread t; takeMVar v }
-- "thread killed"
--
-- >>> check $ withTests 100 $ property $ do n <- forAll (Gen.int Range.linearBounded); r <- evalIO (catch (throwIO (userError (show n))) (\(e :: IOException) -> pure (displayException e))); r === "user error (" <> show n <> ")"
-- ...passed 100 tests.
-- True
--
-- @since 0.7.0
catch :: (Exception e) => IO a -> (e -> IO a) -> IO a
catch a h =
E.catch a (\e -> bool (h e) (E.throwIO e) (isAsync (toException e)))
{-# INLINE catch #-}
-- | 'catch' with its arguments flipped.
--
-- ==== __Examples__
--
-- >>> handle (\(e :: ArithException) -> pure (show e)) (throwIO Overflow)
-- "arithmetic overflow"
--
-- >>> check $ withTests 100 $ property $ do n <- forAll (Gen.int Range.linearBounded); r <- evalIO (handle (\(_ :: SomeException) -> pure 0) (pure n)); r === n
-- ...passed 100 tests.
-- True
--
-- @since 0.7.0
handle :: (Exception e) => (e -> IO a) -> IO a -> IO a
handle =
flip catch
{-# INLINE handle #-}
-- | Run the action, returning a synchronous exception of type @e@ as a
-- 'Left'. An asynchronous exception is rethrown, even where @e@ is
-- 'SomeException'.
--
-- ==== __Examples__
--
-- >>> try @ArithException (throwIO DivideByZero)
-- Left divide by zero
--
-- >>> try @ArithException (pure 'a')
-- Right 'a'
--
-- An asynchronous exception is not caught, even at 'SomeException':
--
-- >>> do { s <- newEmptyMVar; v <- newEmptyMVar; t <- forkFinally (try @SomeException (putMVar s () *> threadDelay 10000000)) (putMVar v . either show (either (\(_ :: SomeException) -> "caught") (\() -> "finished"))); takeMVar s; killThread t; takeMVar v }
-- "thread killed"
--
-- >>> check $ withTests 100 $ property $ do n <- forAll (Gen.int Range.linearBounded); r <- evalIO (try @SomeException (pure n)); either (\(_ :: SomeException) -> Nothing) Just r === Just n
-- ...passed 100 tests.
-- True
--
-- @since 0.7.0
try :: (Exception e) => IO a -> IO (Either e a)
try a =
catch (Right <$> a) (pure . Left)
{-# INLINE try #-}
-- | Acquire a resource, use it, and release it, whether or not the use
-- throws. The release runs under 'uninterruptibleMask_'; if the use throws,
-- the release's own exception is discarded and the use's rethrown.
--
-- ==== __Examples__
--
-- >>> do { r <- newIORef []; _ <- try @ArithException (bracket (modifyIORef' r ("acquire" :)) (\_ -> modifyIORef' r ("release" :)) (\_ -> throwIO Overflow)); readIORef r }
-- ["release","acquire"]
--
-- >>> bracket (pure 1) (\_ -> pure ()) (\n -> pure (n + 1))
-- 2
--
-- >>> check $ withTests 100 $ property $ do n <- forAll (Gen.int (Range.linear 0 100)); r <- evalIO (do v <- newIORef 0; _ <- bracket (pure n) (writeIORef v) pure; readIORef v); r === n
-- ...passed 100 tests.
-- True
--
-- @since 0.7.0
bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracket acquire release use =
mask
( \restore ->
acquire
>>= \a ->
E.try (restore (use a))
>>= either
(\(e :: SomeException) -> E.try (uninterruptibleMask_ (release a)) >>= \(_ :: Either SomeException b) -> E.throwIO e)
(\c -> uninterruptibleMask_ (release a) >>= const (pure c))
)
{-# INLINEABLE bracket #-}
-- | 'bracket' whose release and use do not take the resource.
--
-- ==== __Examples__
--
-- >>> do { r <- newIORef []; bracket_ (modifyIORef' r ("acquire" :)) (modifyIORef' r ("release" :)) (modifyIORef' r ("use" :)); readIORef r }
-- ["release","use","acquire"]
--
-- >>> check $ withTests 100 $ property $ do n <- forAll (Gen.int (Range.linear 0 100)); r <- evalIO (bracket_ (pure ()) (pure ()) (pure n)); r === n
-- ...passed 100 tests.
-- True
--
-- @since 0.7.0
bracket_ :: IO a -> IO b -> IO c -> IO c
bracket_ acquire release use =
bracket acquire (const release) (const use)
{-# INLINE bracket_ #-}
-- | 'bracket' that releases the resource only if the use throws.
--
-- ==== __Examples__
--
-- >>> do { r <- newIORef []; _ <- bracketOnError (pure ()) (\_ -> modifyIORef' r ("release" :)) (\_ -> pure ()); readIORef r }
-- []
--
-- >>> do { r <- newIORef []; _ <- try @ArithException (bracketOnError (pure ()) (\_ -> modifyIORef' r ("release" :)) (\_ -> throwIO Overflow)); readIORef r }
-- ["release"]
--
-- >>> check $ withTests 100 $ property $ do n <- forAll (Gen.int (Range.linear 0 100)); r <- evalIO (bracketOnError (pure n) (\_ -> pure ()) pure); r === n
-- ...passed 100 tests.
-- True
--
-- @since 0.7.0
bracketOnError :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracketOnError acquire release use =
mask
( \restore ->
acquire
>>= \a ->
E.try (restore (use a))
>>= either
(\(e :: SomeException) -> E.try (uninterruptibleMask_ (release a)) >>= \(_ :: Either SomeException b) -> E.throwIO e)
pure
)
{-# INLINEABLE bracketOnError #-}
-- | Run the first action, then the second, whether or not the first throws.
-- The second runs under 'uninterruptibleMask_'.
--
-- ==== __Examples__
--
-- >>> do { r <- newIORef []; _ <- try @ArithException (throwIO Overflow `finally` modifyIORef' r ("finally" :)); readIORef r }
-- ["finally"]
--
-- >>> check $ withTests 100 $ property $ do n <- forAll (Gen.int (Range.linear 0 100)); r <- evalIO (pure n `finally` pure ()); r === n
-- ...passed 100 tests.
-- True
--
-- @since 0.7.0
finally :: IO a -> IO b -> IO a
finally use release =
bracket_ (pure ()) release use
{-# INLINE finally #-}
-- | Run the first action, then, only if it throws, the second, and rethrow.
-- The second runs under 'uninterruptibleMask_'.
--
-- ==== __Examples__
--
-- >>> do { r <- newIORef []; _ <- try @ArithException (throwIO Overflow `onException` modifyIORef' r ("onException" :)); readIORef r }
-- ["onException"]
--
-- >>> do { r <- newIORef []; _ <- pure () `onException` modifyIORef' r ("onException" :); readIORef r }
-- []
--
-- >>> check $ withTests 100 $ property $ do n <- forAll (Gen.int (Range.linear 0 100)); r <- evalIO (pure n `onException` pure ()); r === n
-- ...passed 100 tests.
-- True
--
-- @since 0.7.0
onException :: IO a -> IO b -> IO a
onException use release =
bracketOnError (pure ()) (const release) (const use)
{-# INLINE onException #-}