-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | Haskell / Erlang interoperability library -- -- A library for building nodes of a distributed Erlang system in -- Haskell. Nodes can be created and registered to an epmd, Erlang terms -- can be marshalled to/from Erlangs binary term representation and -- message can be sent to or received from processes running on a -- different node. In it's preliminary state hinterface supports of -- Erlangs binary terms and a subset of the distribution protocol. @package hinterface @version 0.8.3 module Foreign.Erlang.Digest genChallenge :: IO Word32 genDigest :: Word32 -> ByteString -> ByteString -- | This module was written based on -- http://hackage.haskell.org/package/reinterpret-cast-0.1.0/docs/src/Data-ReinterpretCast-Internal-ImplArray.html. -- -- Implements casting via a 1-elemnt STUArray, as described in -- http://stackoverflow.com/a/7002812/263061. module Util.FloatCast -- | Reinterpret-casts a Float to a Word32. floatToWord :: Float -> Word32 -- | Reinterpret-casts a Word32 to a Float. wordToFloat :: Word32 -> Float -- | Reinterpret-casts a Double to a Word64. doubleToWord :: Double -> Word64 -- | Reinterpret-casts a Word64 to a Double. wordToDouble :: Word64 -> Double module Util.IOExtra requireM :: (HasCallStack, MonadCatch m, MonadLogger m) => String -> Bool -> m () tryAndLogIO :: (HasCallStack, MonadCatch m, MonadLogger m) => m a -> m (Maybe a) tryAndLogAll :: forall a m. (HasCallStack, MonadCatch m, MonadLogger m) => m a -> m (Maybe a) catchAndLogIO :: (HasCallStack, MonadCatch m, MonadLogger m) => m a -> (IOError -> m a) -> m a catchAndLogAll :: (HasCallStack, MonadCatch m, MonadLogger m) => m a -> (SomeException -> m a) -> m a onExceptionLog :: (HasCallStack, MonadCatch m, MonadLogger m) => m a -> m b -> m a bracketOnErrorLog :: (HasCallStack, MonadMask m, MonadLogger m) => m a -> (a -> m b) -> (a -> m c) -> m c handleAndLogAll :: (HasCallStack, MonadCatch m, MonadLogger m) => (SomeException -> m a) -> m a -> m a catchAndLog :: (HasCallStack, MonadCatch m, MonadLogger m, Exception e) => m a -> (e -> m a) -> m a handleAndLog :: (HasCallStack, MonadCatch m, MonadLogger m, Exception e) => (e -> m a) -> m a -> m a logWarnStr :: (HasCallStack, MonadLogger m) => String -> m () logInfoStr :: (HasCallStack, MonadLogger m) => String -> m () logErrorStr :: (HasCallStack, MonadLogger m) => String -> m () logAndThrow :: (HasCallStack, MonadMask m, MonadLogger m, Exception e) => e -> m a logInfoShow :: (HasCallStack, Show s, MonadLogger m) => s -> m () logErrorShow :: (HasCallStack, Show s, MonadLogger m) => s -> m () throwLeftM :: (HasCallStack, MonadMask m, MonadLogger m, Exception e) => m (Either e r) -> m r throwNothingM :: (HasCallStack, MonadLogger m, MonadCatch m) => m (Maybe r) -> m r data ErrMsg a ErrMsg :: String -> a -> ErrMsg a data OneBillionDollarBug OneBillionDollarBug :: OneBillionDollarBug -- | A ThreadId is an abstract type representing a handle to a -- thread. ThreadId is an instance of Eq, Ord and -- Show, where the Ord instance implements an arbitrary -- total ordering over ThreadIds. The Show instance lets -- you convert an arbitrary-valued ThreadId to string form; -- showing a ThreadId value is occasionally useful when debugging -- or diagnosing the behaviour of a concurrent program. -- -- Note: in GHC, if you have a ThreadId, you essentially -- have a pointer to the thread itself. This means the thread itself -- can't be garbage collected until you drop the ThreadId. This -- misfeature will hopefully be corrected at a later date. data ThreadId -- | A version of waitBoth that can be used inside an STM -- transaction. waitBothSTM :: () => Async a -> Async b -> STM (a, b) -- | A version of waitEither_ that can be used inside an STM -- transaction. waitEitherSTM_ :: () => Async a -> Async b -> STM () -- | A version of waitEither that can be used inside an STM -- transaction. waitEitherSTM :: () => Async a -> Async b -> STM (Either a b) -- | A version of waitEitherCatch that can be used inside an STM -- transaction. waitEitherCatchSTM :: () => Async a -> Async b -> STM (Either (Either SomeException a) (Either SomeException b)) -- | A version of waitAny that can be used inside an STM -- transaction. waitAnySTM :: () => [Async a] -> STM (Async a, a) -- | A version of waitAnyCatch that can be used inside an STM -- transaction. waitAnyCatchSTM :: () => [Async a] -> STM (Async a, Either SomeException a) -- | A version of poll that can be used inside an STM transaction. pollSTM :: () => Async a -> STM (Maybe (Either SomeException a)) -- | A version of waitCatch that can be used inside an STM -- transaction. waitCatchSTM :: () => Async a -> STM (Either SomeException a) -- | A version of wait that can be used inside an STM transaction. waitSTM :: () => Async a -> STM a -- | Compare two Asyncs that may have different types compareAsyncs :: () => Async a -> Async b -> Ordering -- | An asynchronous action spawned by async or withAsync. -- Asynchronous actions are executed in a separate thread, and operations -- are provided for waiting for asynchronous actions to complete and -- obtaining their results (see e.g. wait). data Async a -- | The exception thrown by cancel to terminate a thread. data AsyncCancelled AsyncCancelled :: AsyncCancelled data ExceptionInLinkedThread [ExceptionInLinkedThread] :: forall a. () => Async a -> SomeException -> ExceptionInLinkedThread -- | True if bound threads are supported. If -- rtsSupportsBoundThreads is False, -- isCurrentThreadBound will always return False and both -- forkOS and runInBoundThread will fail. rtsSupportsBoundThreads :: Bool -- | Chan is an abstract type representing an unbounded FIFO -- channel. data Chan a -- | QSem is a quantity semaphore in which the resource is acquired -- and released in units of one. It provides guaranteed FIFO ordering for -- satisfying blocked waitQSem calls. -- -- The pattern -- --
-- bracket_ waitQSem signalQSem (...) ---- -- is safe; it never loses a unit of the resource. data QSem -- | QSemN is a quantity semaphore in which the resource is acquired -- and released in units of one. It provides guaranteed FIFO ordering for -- satisfying blocked waitQSemN calls. -- -- The pattern -- --
-- bracket_ (waitQSemN n) (signalQSemN n) (...) ---- -- is safe; it never loses any of the resource. data QSemN -- | Monads in which IO computations may be embedded. Any monad -- built by applying a sequence of monad transformers to the IO -- monad will be an instance of this class. -- -- Instances should satisfy the following laws, which state that -- liftIO is a transformer of monads: -- -- class Monad m => MonadIO (m :: Type -> Type) -- | Lift a computation from the IO monad. liftIO :: MonadIO m => IO a -> m a -- | Calls perror to indicate that there is a type error or similar -- in the given argument. errorBadArgument :: () => a -- | Calls perror to indicate that there is a missing argument in -- the argument list. errorMissingArgument :: () => a -- | Calls perror to indicate that the format string ended early. errorShortFormat :: () => a -- | Calls perror to indicate an unknown format letter for a given -- type. errorBadFormat :: () => Char -> a -- | Raises an error with a printf-specific prefix on the message -- string. perror :: () => String -> a -- | Formatter for RealFloat values. formatRealFloat :: RealFloat a => a -> FieldFormatter -- | Formatter for Integer values. formatInteger :: Integer -> FieldFormatter -- | Formatter for Int values. formatInt :: (Integral a, Bounded a) => a -> FieldFormatter -- | Formatter for String values. formatString :: IsChar a => [a] -> FieldFormatter -- | Formatter for Char values. formatChar :: Char -> FieldFormatter -- | Substitute a 'v' format character with the given default format -- character in the FieldFormat. A convenience for -- user-implemented types, which should support "%v". vFmt :: Char -> FieldFormat -> FieldFormat -- | Similar to printf, except that output is via the specified -- Handle. The return type is restricted to (IO -- a). hPrintf :: HPrintfType r => Handle -> String -> r -- | Format a variable number of arguments with the C-style formatting -- string. -- --
-- >>> printf "%s, %d, %.4f" "hello" 123 pi -- hello, 123, 3.1416 ---- -- The return value is either String or (IO a) -- (which should be (IO '()'), but Haskell's type system -- makes this hard). -- -- The format string consists of ordinary characters and conversion -- specifications, which specify how to format one of the arguments -- to printf in the output string. A format specification is -- introduced by the % character; this character can be -- self-escaped into the format string using %%. A format -- specification ends with a /format character/ that provides the primary -- information about how to format the value. The rest of the conversion -- specification is optional. In order, one may have flag characters, a -- width specifier, a precision specifier, and type-specific modifier -- characters. -- -- Unlike C printf(3), the formatting of this printf is -- driven by the argument type; formatting is type specific. The types -- formatted by printf "out of the box" are: -- -- -- -- printf is also extensible to support other types: see below. -- -- A conversion specification begins with the character %, -- followed by zero or more of the following flags: -- --
-- - left adjust (default is right adjust) -- + always use a sign (+ or -) for signed conversions -- space leading space for positive numbers in signed conversions -- 0 pad with zeros rather than spaces -- # use an \"alternate form\": see below ---- -- When both flags are given, - overrides 0 and -- + overrides space. A negative width specifier in a * -- conversion is treated as positive but implies the left adjust flag. -- -- The "alternate form" for unsigned radix conversions is as in C -- printf(3): -- --
-- %o prefix with a leading 0 if needed -- %x prefix with a leading 0x if nonzero -- %X prefix with a leading 0X if nonzero -- %b prefix with a leading 0b if nonzero -- %[eEfFgG] ensure that the number contains a decimal point ---- -- Any flags are followed optionally by a field width: -- --
-- num field width -- * as num, but taken from argument list ---- -- The field width is a minimum, not a maximum: it will be expanded as -- needed to avoid mutilating a value. -- -- Any field width is followed optionally by a precision: -- --
-- .num precision -- . same as .0 -- .* as num, but taken from argument list ---- -- Negative precision is taken as 0. The meaning of the precision depends -- on the conversion type. -- --
-- Integral minimum number of digits to show -- RealFloat number of digits after the decimal point -- String maximum number of characters ---- -- The precision for Integral types is accomplished by zero-padding. If -- both precision and zero-pad are given for an Integral field, the -- zero-pad is ignored. -- -- Any precision is followed optionally for Integral types by a width -- modifier; the only use of this modifier being to set the implicit size -- of the operand for conversion of a negative operand to unsigned: -- --
-- hh Int8 -- h Int16 -- l Int32 -- ll Int64 -- L Int64 ---- -- The specification ends with a format character: -- --
-- c character Integral -- d decimal Integral -- o octal Integral -- x hexadecimal Integral -- X hexadecimal Integral -- b binary Integral -- u unsigned decimal Integral -- f floating point RealFloat -- F floating point RealFloat -- g general format float RealFloat -- G general format float RealFloat -- e exponent format float RealFloat -- E exponent format float RealFloat -- s string String -- v default format any type ---- -- The "%v" specifier is provided for all built-in types, and should be -- provided for user-defined type formatters as well. It picks a "best" -- representation for the given type. For the built-in types the "%v" -- specifier is converted as follows: -- --
-- c Char -- u other unsigned Integral -- d other signed Integral -- g RealFloat -- s String ---- -- Mismatch between the argument types and the format string, as well as -- any other syntactic or semantic errors in the format string, will -- cause an exception to be thrown at runtime. -- -- Note that the formatting for RealFloat types is currently a bit -- different from that of C printf(3), conforming instead to -- showEFloat, showFFloat and showGFloat (and their -- alternate versions showFFloatAlt and showGFloatAlt). -- This is hard to fix: the fixed versions would format in a -- backward-incompatible way. In any case the Haskell behavior is -- generally more sensible than the C behavior. A brief summary of some -- key differences: -- --
-- data MyException = ThisException | ThatException -- deriving Show -- -- instance Exception MyException ---- -- The default method definitions in the Exception class do what -- we need in this case. You can now throw and catch -- ThisException and ThatException as exceptions: -- --
-- *Main> throw ThisException `catch` \e -> putStrLn ("Caught " ++ show (e :: MyException))
-- Caught ThisException
--
--
-- In more complicated examples, you may wish to define a whole hierarchy
-- of exceptions:
--
-- -- --------------------------------------------------------------------- -- -- Make the root exception type for all the exceptions in a compiler -- -- data SomeCompilerException = forall e . Exception e => SomeCompilerException e -- -- instance Show SomeCompilerException where -- show (SomeCompilerException e) = show e -- -- instance Exception SomeCompilerException -- -- compilerExceptionToException :: Exception e => e -> SomeException -- compilerExceptionToException = toException . SomeCompilerException -- -- compilerExceptionFromException :: Exception e => SomeException -> Maybe e -- compilerExceptionFromException x = do -- SomeCompilerException a <- fromException x -- cast a -- -- --------------------------------------------------------------------- -- -- Make a subhierarchy for exceptions in the frontend of the compiler -- -- data SomeFrontendException = forall e . Exception e => SomeFrontendException e -- -- instance Show SomeFrontendException where -- show (SomeFrontendException e) = show e -- -- instance Exception SomeFrontendException where -- toException = compilerExceptionToException -- fromException = compilerExceptionFromException -- -- frontendExceptionToException :: Exception e => e -> SomeException -- frontendExceptionToException = toException . SomeFrontendException -- -- frontendExceptionFromException :: Exception e => SomeException -> Maybe e -- frontendExceptionFromException x = do -- SomeFrontendException a <- fromException x -- cast a -- -- --------------------------------------------------------------------- -- -- Make an exception type for a particular frontend compiler exception -- -- data MismatchedParentheses = MismatchedParentheses -- deriving Show -- -- instance Exception MismatchedParentheses where -- toException = frontendExceptionToException -- fromException = frontendExceptionFromException ---- -- We can now catch a MismatchedParentheses exception as -- MismatchedParentheses, SomeFrontendException or -- SomeCompilerException, but not other types, e.g. -- IOException: -- --
-- *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: MismatchedParentheses))
-- Caught MismatchedParentheses
-- *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeFrontendException))
-- Caught MismatchedParentheses
-- *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: SomeCompilerException))
-- Caught MismatchedParentheses
-- *Main> throw MismatchedParentheses `catch` \e -> putStrLn ("Caught " ++ show (e :: IOException))
-- *** Exception: MismatchedParentheses
--
class (Typeable e, Show e) => Exception e
toException :: Exception e => e -> SomeException
fromException :: Exception e => SomeException -> Maybe e
-- | Render this exception value in a human-friendly manner.
--
-- Default implementation: show.
displayException :: Exception e => e -> String
-- | void value discards or ignores the result of
-- evaluation, such as the return value of an IO action.
--
-- -- >>> void Nothing -- Nothing -- -- >>> void (Just 3) -- Just () ---- -- Replace the contents of an Either Int -- Int with unit, resulting in an Either -- Int '()': -- --
-- >>> void (Left 8675309) -- Left 8675309 -- -- >>> void (Right 8675309) -- Right () ---- -- Replace every element of a list with unit: -- --
-- >>> void [1,2,3] -- [(),(),()] ---- -- Replace the second element of a pair with unit: -- --
-- >>> void (1,2) -- (1,()) ---- -- Discard the result of an IO action: -- --
-- >>> mapM print [1,2] -- 1 -- 2 -- [(),()] -- -- >>> void $ mapM print [1,2] -- 1 -- 2 --void :: Functor f => f a -> f () -- | The fromJust function extracts the element out of a Just -- and throws an error if its argument is Nothing. -- --
-- >>> fromJust (Just 1) -- 1 ---- --
-- >>> 2 * (fromJust (Just 10)) -- 20 ---- --
-- >>> 2 * (fromJust Nothing) -- *** Exception: Maybe.fromJust: Nothing --fromJust :: () => Maybe a -> a -- | The isJust function returns True iff its argument is of -- the form Just _. -- --
-- >>> isJust (Just 3) -- True ---- --
-- >>> isJust (Just ()) -- True ---- --
-- >>> isJust Nothing -- False ---- -- Only the outer constructor is taken into consideration: -- --
-- >>> isJust (Just Nothing) -- True --isJust :: () => Maybe a -> Bool -- | An MVar (pronounced "em-var") is a synchronising variable, used -- for communication between concurrent threads. It can be thought of as -- a box, which may be empty or full. data MVar a -- | Conditional execution of Applicative expressions. For example, -- --
-- when debug (putStrLn "Debugging") ---- -- will output the string Debugging if the Boolean value -- debug is True, and otherwise do nothing. when :: Applicative f => Bool -> f () -> f () -- | The SomeException type is the root of the exception type -- hierarchy. When an exception of type e is thrown, behind the -- scenes it is encapsulated in a SomeException. data SomeException [SomeException] :: forall e. Exception e => e -> SomeException -- | Monads which allow their actions to be run in IO. -- -- While MonadIO allows an IO action to be lifted into -- another monad, this class captures the opposite concept: allowing you -- to capture the monadic context. Note that, in order to meet the laws -- given below, the intuition is that a monad must have no monadic state, -- but may have monadic context. This essentially limits -- MonadUnliftIO to ReaderT and IdentityT -- transformers on top of IO. -- -- Laws. For any value u returned by askUnliftIO, it must -- meet the monad transformer laws as reformulated for -- MonadUnliftIO: -- --
unliftIO u . return = return
unliftIO u (m >>= f) = unliftIO u m >>= unliftIO -- u . f
askUnliftIO >>= (u -> liftIO (unliftIO u m)) = -- m
-- throwM e >> x = throwM e ---- -- In other words, throwing an exception short-circuits the rest of the -- monadic computation. class Monad m => MonadThrow (m :: Type -> Type) -- | Throw an exception. Note that this throws when this action is run in -- the monad m, not when it is applied. It is a generalization -- of Control.Exception's throwIO. -- -- Should satisfy the law: -- --
-- throwM e >> f = throwM e --throwM :: (MonadThrow m, Exception e) => e -> m a -- | Like bracket, but only performs the final action if an error is -- thrown by the in-between computation. bracketOnError :: MonadMask m => m a -> (a -> m c) -> (a -> m b) -> m b -- | Perform an action with a finalizer action that is run, even if an -- error occurs. finally :: MonadMask m => m a -> m b -> m a -- | Version of bracket without any value being passed to the second -- and third actions. bracket_ :: MonadMask m => m a -> m c -> m b -> m b -- | Generalized abstracted pattern of safe resource acquisition and -- release in the face of errors. The first action "acquires" some value, -- which is "released" by the second action at the end. The third action -- "uses" the value and its result is the result of the bracket. -- -- If an error is thrown during the use, the release still happens before -- the error is rethrown. -- -- Note that this is essentially a type-specialized version of -- generalBracket. This function has a more common signature -- (matching the signature from Control.Exception), and is often -- more convenient to use. By contrast, generalBracket is more -- expressive, allowing us to implement other functions like -- bracketOnError. bracket :: MonadMask m => m a -> (a -> m c) -> (a -> m b) -> m b -- | Run an action only if an error is thrown in the main action. Unlike -- onException, this works with every kind of error, not just -- exceptions. For example, if f is an ExceptT -- computation which aborts with a Left, the computation -- onError f g will execute g, while onException f -- g will not. -- -- This distinction is only meaningful for monads which have multiple -- exit points, such as Except and MaybeT. For monads -- that only have a single exit point, there is no difference between -- onException and onError, except that onError has -- a more constrained type. onError :: MonadMask m => m a -> m b -> m a -- | Run an action only if an exception is thrown in the main action. The -- exception is not caught, simply rethrown. -- -- NOTE The action is only run if an exception is thrown. -- If the monad supports other ways of aborting the computation, the -- action won't run if those other kinds of errors are thrown. See -- onError. onException :: MonadCatch m => m a -> m b -> m a -- | Catches different sorts of exceptions. See Control.Exception's -- catches catches :: (Foldable f, MonadCatch m) => m a -> f (Handler m a) -> m a -- | A variant of try that takes an exception predicate to select -- which exceptions are caught. See Control.Exception's -- tryJust tryJust :: (MonadCatch m, Exception e) => (e -> Maybe b) -> m a -> m (Either b a) -- | Similar to catch, but returns an Either result. See -- Control.Exception's try. try :: (MonadCatch m, Exception e) => m a -> m (Either e a) -- | Flipped catchJust. See Control.Exception's -- handleJust. handleJust :: (MonadCatch m, Exception e) => (e -> Maybe b) -> (b -> m a) -> m a -> m a -- | Flipped catchIf handleIf :: (MonadCatch m, Exception e) => (e -> Bool) -> (e -> m a) -> m a -> m a -- | Flipped catchAll handleAll :: MonadCatch m => (SomeException -> m a) -> m a -> m a -- | Flipped catchIOError handleIOError :: MonadCatch m => (IOError -> m a) -> m a -> m a -- | Flipped catch. See Control.Exception's handle. handle :: (MonadCatch m, Exception e) => (e -> m a) -> m a -> m a -- | A more generalized way of determining which exceptions to catch at run -- time. catchJust :: (MonadCatch m, Exception e) => (e -> Maybe b) -> m a -> (b -> m a) -> m a -- | Catch exceptions only if they pass some predicate. Often useful with -- the predicates for testing IOError values in -- System.IO.Error. catchIf :: (MonadCatch m, Exception e) => (e -> Bool) -> m a -> (e -> m a) -> m a -- | Catch all IOError (eqv. IOException) exceptions. Still -- somewhat too general, but better than using catchAll. See -- catchIf for an easy way of catching specific IOErrors -- based on the predicates in System.IO.Error. catchIOError :: MonadCatch m => m a -> (IOError -> m a) -> m a -- | Catches all exceptions, and somewhat defeats the purpose of the -- extensible exception system. Use sparingly. -- -- NOTE This catches all exceptions, but if the monad -- supports other ways of aborting the computation, those other kinds of -- errors will not be caught. catchAll :: MonadCatch m => m a -> (SomeException -> m a) -> m a -- | Like uninterruptibleMask, but does not pass a restore -- action to the argument. uninterruptibleMask_ :: MonadMask m => m a -> m a -- | Like mask, but does not pass a restore action to the -- argument. mask_ :: MonadMask m => m a -> m a -- | A class for monads which allow exceptions to be caught, in particular -- exceptions which were thrown by throwM. -- -- Instances should obey the following law: -- --
-- catch (throwM e) f = f e ---- -- Note that the ability to catch an exception does not guarantee -- that we can deal with all possible exit points from a computation. -- Some monads, such as continuation-based stacks, allow for more than -- just a success/failure strategy, and therefore catch -- cannot be used by those monads to properly implement a function -- such as finally. For more information, see MonadMask. class MonadThrow m => MonadCatch (m :: Type -> Type) -- | Provide a handler for exceptions thrown during execution of the first -- action. Note that type of the type of the argument to the handler will -- constrain which exceptions are caught. See Control.Exception's -- catch. catch :: (MonadCatch m, Exception e) => m a -> (e -> m a) -> m a -- | A class for monads which provide for the ability to account for all -- possible exit points from a computation, and to mask asynchronous -- exceptions. Continuation-based monads are invalid instances of this -- class. -- -- Instances should ensure that, in the following code: -- --
-- fg = f `finally` g ---- -- The action g is called regardless of what occurs within -- f, including async exceptions. Some monads allow f -- to abort the computation via other effects than throwing an exception. -- For simplicity, we will consider aborting and throwing an exception to -- be two forms of "throwing an error". -- -- If f and g both throw an error, the error thrown by -- fg depends on which errors we're talking about. In a monad -- transformer stack, the deeper layers override the effects of the inner -- layers; for example, ExceptT e1 (Except e2) a represents a -- value of type Either e2 (Either e1 a), so throwing both an -- e1 and an e2 will result in Left e2. If -- f and g both throw an error from the same layer, -- instances should ensure that the error from g wins. -- -- Effects other than throwing an error are also overriden by the deeper -- layers. For example, StateT s Maybe a represents a value of -- type s -> Maybe (a, s), so if an error thrown from -- f causes this function to return Nothing, any -- changes to the state which f also performed will be erased. -- As a result, g will see the state as it was before -- f. Once g completes, f's error will be -- rethrown, so g' state changes will be erased as well. This is -- the normal interaction between effects in a monad transformer stack. -- -- By contrast, lifted-base's version of finally always -- discards all of g's non-IO effects, and g never sees -- any of f's non-IO effects, regardless of the layer ordering -- and regardless of whether f throws an error. This is not the -- result of interacting effects, but a consequence of -- MonadBaseControl's approach. class MonadCatch m => MonadMask (m :: Type -> Type) -- | Runs an action with asynchronous exceptions disabled. The action is -- provided a method for restoring the async. environment to what it was -- at the mask call. See Control.Exception's mask. mask :: MonadMask m => ((forall a. () => m a -> m a) -> m b) -> m b -- | Like mask, but the masked computation is not interruptible (see -- Control.Exception's uninterruptibleMask. WARNING: Only -- use if you need to mask exceptions around an interruptible operation -- AND you can guarantee the interruptible operation will only block for -- a short period of time. Otherwise you render the program/thread -- unresponsive and/or unkillable. uninterruptibleMask :: MonadMask m => ((forall a. () => m a -> m a) -> m b) -> m b -- | A generalized version of bracket which uses ExitCase to -- distinguish the different exit cases, and returns the values of both -- the use and release actions. In practice, this extra -- information is rarely needed, so it is often more convenient to use -- one of the simpler functions which are defined in terms of this one, -- such as bracket, finally, onError, and -- bracketOnError. -- -- This function exists because in order to thread their effects through -- the execution of bracket, monad transformers need values to be -- threaded from use to release and from -- release to the output value. -- -- NOTE This method was added in version 0.9.0 of this library. -- Previously, implementation of functions like bracket and -- finally in this module were based on the mask and -- uninterruptibleMask functions only, disallowing some classes of -- tranformers from having MonadMask instances (notably -- multi-exit-point transformers like ExceptT). If you are a -- library author, you'll now need to provide an implementation for this -- method. The StateT implementation demonstrates most of the -- subtleties: -- --
-- generalBracket acquire release use = StateT $ s0 -> do -- ((b, _s2), (c, s3)) <- generalBracket -- (runStateT acquire s0) -- ((resource, s1) exitCase -> case exitCase of -- ExitCaseSuccess (b, s2) -> runStateT (release resource (ExitCaseSuccess b)) s2 -- -- -- In the two other cases, the base monad overrides use's state -- -- changes and the state reverts to s1. -- ExitCaseException e -> runStateT (release resource (ExitCaseException e)) s1 -- ExitCaseAbort -> runStateT (release resource ExitCaseAbort) s1 -- ) -- ((resource, s1) -> runStateT (use resource) s1) -- return ((b, c), s3) ---- -- The StateT s m implementation of generalBracket -- delegates to the m implementation of generalBracket. -- The acquire, use, and release arguments -- given to StateT's implementation produce actions of type -- StateT s m a, StateT s m b, and StateT s m -- c. In order to run those actions in the base monad, we need to -- call runStateT, from which we obtain actions of type m -- (a, s), m (b, s), and m (c, s). Since each -- action produces the next state, it is important to feed the state -- produced by the previous action to the next action. -- -- In the ExitCaseSuccess case, the state starts at s0, -- flows through acquire to become s1, flows through -- use to become s2, and finally flows through -- release to become s3. In the other two cases, -- release does not receive the value s2, so its action -- cannot see the state changes performed by use. This is fine, -- because in those two cases, an error was thrown in the base monad, so -- as per the usual interaction between effects in a monad transformer -- stack, those state changes get reverted. So we start from s1 -- instead. -- -- Finally, the m implementation of generalBracket -- returns the pairs (b, s) and (c, s). For monad -- transformers other than StateT, this will be some other type -- representing the effects and values performed and returned by the -- use and release actions. The effect part of the -- use result, in this case _s2, usually needs to be -- discarded, since those effects have already been incorporated in the -- release action. -- -- The only effect which is intentionally not incorporated in the -- release action is the effect of throwing an error. In that -- case, the error must be re-thrown. One subtlety which is easy to miss -- is that in the case in which use and release both -- throw an error, the error from release should take priority. -- Here is an implementation for ExceptT which demonstrates how -- to do this. -- --
-- generalBracket acquire release use = ExceptT $ do -- (eb, ec) <- generalBracket -- (runExceptT acquire) -- (eresource exitCase -> case eresource of -- Left e -> return (Left e) -- nothing to release, acquire didn't succeed -- Right resource -> case exitCase of -- ExitCaseSuccess (Right b) -> runExceptT (release resource (ExitCaseSuccess b)) -- ExitCaseException e -> runExceptT (release resource (ExitCaseException e)) -- _ -> runExceptT (release resource ExitCaseAbort)) -- (either (return . Left) (runExceptT . use)) -- return $ do -- -- The order in which we perform those two Either effects determines -- -- which error will win if they are both Lefts. We want the error from -- -- release to win. -- c <- ec -- b <- eb -- return (b, c) --generalBracket :: MonadMask m => m a -> (a -> ExitCase b -> m c) -> (a -> m b) -> m (b, c) -- | A MonadMask computation may either succeed with a value, abort -- with an exception, or abort for some other reason. For example, in -- ExceptT e IO you can use throwM to abort with an -- exception (ExitCaseException) or throwE to abort with a -- value of type e (ExitCaseAbort). data ExitCase a ExitCaseSuccess :: a -> ExitCase a ExitCaseException :: SomeException -> ExitCase a ExitCaseAbort :: ExitCase a -- | Generalized version of Handler data Handler (m :: Type -> Type) a [Handler] :: forall (m :: Type -> Type) a e. Exception e => (e -> m a) -> Handler m a -- | Generalized version of replicateConcurrently_. replicateConcurrently_ :: MonadBaseControl IO m => Int -> m a -> m () -- | Generalized version of replicateConcurrently. replicateConcurrently :: MonadBaseControl IO m => Int -> m a -> m [a] -- | Generalized version of forConcurrently_. forConcurrently_ :: (Foldable t, MonadBaseControl IO m) => t a -> (a -> m b) -> m () -- | Generalized version of forConcurrently. forConcurrently :: (Traversable t, MonadBaseControl IO m) => t a -> (a -> m b) -> m (t b) -- | Generalized version of mapConcurrently_. mapConcurrently_ :: (Foldable t, MonadBaseControl IO m) => (a -> m b) -> t a -> m () -- | Generalized version of mapConcurrently. mapConcurrently :: (Traversable t, MonadBaseControl IO m) => (a -> m b) -> t a -> m (t b) -- | Generalized version of concurrently_. concurrently_ :: MonadBaseControl IO m => m a -> m b -> m () -- | Generalized version of concurrently. concurrently :: MonadBaseControl IO m => m a -> m b -> m (a, b) -- | Generalized version of race_. -- -- NOTE: This function discards the monadic effects besides IO in the -- forked computation. race_ :: MonadBaseControl IO m => m a -> m b -> m () -- | Generalized version of race. race :: MonadBaseControl IO m => m a -> m b -> m (Either a b) -- | Generalized version of link2. link2 :: MonadBase IO m => Async a -> Async b -> m () -- | Generalized version of link. link :: MonadBase IO m => Async a -> m () -- | Generalized version of waitBoth. waitBoth :: MonadBaseControl IO m => Async (StM m a) -> Async (StM m b) -> m (a, b) -- | Generalized version of waitEither_. -- -- NOTE: This function discards the monadic effects besides IO in the -- forked computation. waitEither_ :: MonadBase IO m => Async a -> Async b -> m () -- | Generalized version of waitEitherCatchCancel. waitEitherCatchCancel :: MonadBaseControl IO m => Async (StM m a) -> Async (StM m b) -> m (Either (Either SomeException a) (Either SomeException b)) -- | Generalized version of waitEitherCancel. waitEitherCancel :: MonadBaseControl IO m => Async (StM m a) -> Async (StM m b) -> m (Either a b) -- | Generalized version of waitEitherCatch. waitEitherCatch :: MonadBaseControl IO m => Async (StM m a) -> Async (StM m b) -> m (Either (Either SomeException a) (Either SomeException b)) -- | Generalized version of waitEither. waitEither :: MonadBaseControl IO m => Async (StM m a) -> Async (StM m b) -> m (Either a b) -- | Generalized version of waitAnyCatchCancel. waitAnyCatchCancel :: MonadBaseControl IO m => [Async (StM m a)] -> m (Async (StM m a), Either SomeException a) -- | Generalized version of waitAnyCancel. waitAnyCancel :: MonadBaseControl IO m => [Async (StM m a)] -> m (Async (StM m a), a) -- | Generalized version of waitAnyCatch. waitAnyCatch :: MonadBaseControl IO m => [Async (StM m a)] -> m (Async (StM m a), Either SomeException a) -- | Generalized version of waitAny. waitAny :: MonadBaseControl IO m => [Async (StM m a)] -> m (Async (StM m a), a) -- | Generalized version of waitCatch. waitCatch :: MonadBaseControl IO m => Async (StM m a) -> m (Either SomeException a) -- | Generalized version of uninterruptibleCancel. uninterruptibleCancel :: MonadBase IO m => Async a -> m () -- | Generalized version of cancelWith. cancelWith :: (MonadBase IO m, Exception e) => Async a -> e -> m () -- | Generalized version of cancel. cancel :: MonadBase IO m => Async a -> m () -- | Generalized version of poll. poll :: MonadBaseControl IO m => Async (StM m a) -> m (Maybe (Either SomeException a)) -- | Generalized version of wait. wait :: MonadBaseControl IO m => Async (StM m a) -> m a -- | Generalized version of withAsyncOnWithUnmask. withAsyncOnWithUnmask :: MonadBaseControl IO m => Int -> ((forall c. () => m c -> m c) -> m a) -> (Async (StM m a) -> m b) -> m b -- | Generalized version of withAsyncWithUnmask. withAsyncWithUnmask :: MonadBaseControl IO m => ((forall c. () => m c -> m c) -> m a) -> (Async (StM m a) -> m b) -> m b -- | Generalized version of withAsyncOn. withAsyncOn :: MonadBaseControl IO m => Int -> m a -> (Async (StM m a) -> m b) -> m b -- | Generalized version of withAsyncBound. withAsyncBound :: MonadBaseControl IO m => m a -> (Async (StM m a) -> m b) -> m b -- | Generalized version of withAsync. withAsync :: MonadBaseControl IO m => m a -> (Async (StM m a) -> m b) -> m b -- | Generalized version of asyncOnWithUnmask. asyncOnWithUnmask :: MonadBaseControl IO m => Int -> ((forall b. () => m b -> m b) -> m a) -> m (Async (StM m a)) -- | Generalized version of asyncWithUnmask. asyncWithUnmask :: MonadBaseControl IO m => ((forall b. () => m b -> m b) -> m a) -> m (Async (StM m a)) -- | Generalized version of asyncOn. asyncOn :: MonadBaseControl IO m => Int -> m a -> m (Async (StM m a)) -- | Generalized version of asyncBound. asyncBound :: MonadBaseControl IO m => m a -> m (Async (StM m a)) -- | Generalized version of async. async :: MonadBaseControl IO m => m a -> m (Async (StM m a)) -- | Generalized version of Concurrently. -- -- A value of type Concurrently m a is an IO-based -- operation that can be composed with other Concurrently values, -- using the Applicative and Alternative instances. -- -- Calling runConcurrently on a value of type -- Concurrently m a will execute the IO-based lifted -- operations it contains concurrently, before delivering the result of -- type a. -- -- For example -- --
-- (page1, page2, page3) <- runConcurrently $ (,,) -- <$> Concurrently (getURL "url1") -- <*> Concurrently (getURL "url2") -- <*> Concurrently (getURL "url3") --newtype Concurrently (m :: Type -> Type) a Concurrently :: m a -> Concurrently a [runConcurrently] :: Concurrently a -> m a -- | liftBaseOp_ is a particular application of -- liftBaseWith that allows lifting control operations of type: -- --
-- (b a -> b a) ---- -- to: -- --
-- (MonadBaseControl b m => m a -> m a) ---- -- For example: -- --
-- liftBaseOp_ mask_ :: MonadBaseControl IO m => m a -> m a --liftBaseOp_ :: MonadBaseControl b m => (b (StM m a) -> b (StM m c)) -> m a -> m c -- | Generalized versio of mkWeakThreadId. mkWeakThreadId :: MonadBase IO m => ThreadId -> m (Weak ThreadId) -- | Generalized version of runInUnboundThread. runInUnboundThread :: MonadBaseControl IO m => m a -> m a -- | Generalized version of runInBoundThread. runInBoundThread :: MonadBaseControl IO m => m a -> m a -- | Generalized version of isCurrentThreadBound. isCurrentThreadBound :: MonadBase IO m => m Bool -- | Generalized version of forkOS. -- -- Note that, while the forked computation m () has access to -- the captured state, all its side-effects in m are discarded. -- It is run only for its side-effects in IO. forkOS :: MonadBaseControl IO m => m () -> m ThreadId -- | Generalized version of threadWaitWrite. threadWaitWrite :: MonadBase IO m => Fd -> m () -- | Generalized version of threadWaitRead. threadWaitRead :: MonadBase IO m => Fd -> m () -- | Generalized version of threadDelay. threadDelay :: MonadBase IO m => Int -> m () -- | Generalized version of yield. yield :: MonadBase IO m => m () -- | Generalized version of threadCapability. threadCapability :: MonadBase IO m => ThreadId -> m (Int, Bool) -- | Generalized version of setNumCapabilities. setNumCapabilities :: MonadBase IO m => Int -> m () -- | Generalized version of getNumCapabilities. getNumCapabilities :: MonadBase IO m => m Int -- | Generalized version of forkOnWithUnmask. -- -- Note that, while the forked computation m () has access to -- the captured state, all its side-effects in m are discarded. -- It is run only for its side-effects in IO. forkOnWithUnmask :: MonadBaseControl IO m => Int -> ((forall a. () => m a -> m a) -> m ()) -> m ThreadId -- | Generalized version of forkOn. -- -- Note that, while the forked computation m () has access to -- the captured state, all its side-effects in m are discarded. -- It is run only for its side-effects in IO. forkOn :: MonadBaseControl IO m => Int -> m () -> m ThreadId -- | Generalized version of killThread. killThread :: MonadBase IO m => ThreadId -> m () -- | Generalized version of forkFinally. -- -- Note that in forkFinally action and_then, while the forked -- action and the and_then function have access to the -- captured state, all their side-effects in m are discarded. -- They're run only for their side-effects in IO. forkFinally :: MonadBaseControl IO m => m a -> (Either SomeException a -> m ()) -> m ThreadId -- | Generalized version of forkIOWithUnmask. -- -- Note that, while the forked computation m () has access to -- the captured state, all its side-effects in m are discarded. -- It is run only for its side-effects in IO. forkWithUnmask :: MonadBaseControl IO m => ((forall a. () => m a -> m a) -> m ()) -> m ThreadId -- | Generalized version of forkIO. -- -- Note that, while the forked computation m () has access to -- the captured state, all its side-effects in m are discarded. -- It is run only for its side-effects in IO. fork :: MonadBaseControl IO m => m () -> m ThreadId -- | Generalized version of myThreadId. myThreadId :: MonadBase IO m => m ThreadId -- | Generalized version of throwTo. throwTo :: (MonadBase IO m, Exception e) => ThreadId -> e -> m () -- | Generalized version of signalQSemN. signalQSemN :: MonadBase IO m => QSemN -> Int -> m () -- | Generalized version of waitQSemN. waitQSemN :: MonadBase IO m => QSemN -> Int -> m () -- | Generalized version of newQSemN. newQSemN :: MonadBase IO m => Int -> m QSemN -- | Generalized version of signalQSem. signalQSem :: MonadBase IO m => QSem -> m () -- | Generalized version of waitQSem. waitQSem :: MonadBase IO m => QSem -> m () -- | Generalized version of newQSem. newQSem :: MonadBase IO m => Int -> m QSem -- | Generalized version of tryReadMVar. tryReadMVar :: MonadBase IO m => MVar a -> m (Maybe a) -- | Generalized version of withMVarMasked. withMVarMasked :: MonadBaseControl IO m => MVar a -> (a -> m b) -> m b -- | Generalized version of mkWeakMVar. -- -- Note any monadic side effects in m of the "finalizer" -- computation are discarded. mkWeakMVar :: MonadBaseControl IO m => MVar a -> m () -> m (Weak (MVar a)) -- | Generalized version of modifyMVarMasked. modifyMVarMasked :: MonadBaseControl IO m => MVar a -> (a -> m (a, b)) -> m b -- | Generalized version of modifyMVarMasked_. modifyMVarMasked_ :: MonadBaseControl IO m => MVar a -> (a -> m a) -> m () -- | Generalized version of modifyMVar. modifyMVar :: MonadBaseControl IO m => MVar a -> (a -> m (a, b)) -> m b -- | Generalized version of modifyMVar_. modifyMVar_ :: MonadBaseControl IO m => MVar a -> (a -> m a) -> m () -- | Generalized version of withMVar. withMVar :: MonadBaseControl IO m => MVar a -> (a -> m b) -> m b -- | Generalized version of isEmptyMVar. isEmptyMVar :: MonadBase IO m => MVar a -> m Bool -- | Generalized version of tryPutMVar. tryPutMVar :: MonadBase IO m => MVar a -> a -> m Bool -- | Generalized version of tryTakeMVar. tryTakeMVar :: MonadBase IO m => MVar a -> m (Maybe a) -- | Generalized version of swapMVar. swapMVar :: MonadBase IO m => MVar a -> a -> m a -- | Generalized version of readMVar. readMVar :: MonadBase IO m => MVar a -> m a -- | Generalized version of putMVar. putMVar :: MonadBase IO m => MVar a -> a -> m () -- | Generalized version of takeMVar. takeMVar :: MonadBase IO m => MVar a -> m a -- | Generalized version of newMVar. newMVar :: MonadBase IO m => a -> m (MVar a) -- | Generalized version of newEmptyMVar. newEmptyMVar :: MonadBase IO m => m (MVar a) -- | Generalized version of writeList2Chan. writeList2Chan :: MonadBase IO m => Chan a -> [a] -> m () -- | Generalized version of getChanContents. getChanContents :: MonadBase IO m => Chan a -> m [a] -- | Generalized version of dupChan. dupChan :: MonadBase IO m => Chan a -> m (Chan a) -- | Generalized version of readChan. readChan :: MonadBase IO m => Chan a -> m a -- | Generalized version of writeChan. writeChan :: MonadBase IO m => Chan a -> a -> m () -- | Generalized version of newChan. newChan :: MonadBase IO m => m (Chan a) -- | Transform an action in t m using a transformer that operates -- on the underlying monad m liftThrough :: (MonadTransControl t, Monad (t m), Monad m) => (m (StT t a) -> m (StT t b)) -> t m a -> t m b -- | liftBaseOpDiscard is a particular application of -- liftBaseWith that allows lifting control operations of type: -- --
-- ((a -> b ()) -> b c) ---- -- to: -- --
-- (MonadBaseControl b m => (a -> m ()) -> m c) ---- -- Note that, while the argument computation m () has access to -- the captured state, all its side-effects in m are discarded. -- It is run only for its side-effects in the base monad b. -- -- For example: -- --
-- liftBaseDiscard (runServer addr port) :: MonadBaseControl IO m => m () -> m () --liftBaseOpDiscard :: MonadBaseControl b m => ((a -> b ()) -> b c) -> (a -> m ()) -> m c -- | liftBaseDiscard is a particular application of -- liftBaseWith that allows lifting control operations of type: -- --
-- (b () -> b a) ---- -- to: -- --
-- (MonadBaseControl b m => m () -> m a) ---- -- Note that, while the argument computation m () has access to -- the captured state, all its side-effects in m are discarded. -- It is run only for its side-effects in the base monad b. -- -- For example: -- --
-- liftBaseDiscard forkIO :: MonadBaseControl IO m => m () -> m ThreadId --liftBaseDiscard :: MonadBaseControl b m => (b () -> b a) -> m () -> m a -- | liftBaseOp is a particular application of liftBaseWith -- that allows lifting control operations of type: -- --
-- ((a -> b c) -> b c) ---- -- to: -- --
-- (MonadBaseControl b m => (a -> m c) -> m c) ---- -- For example: -- --
-- liftBaseOp alloca :: (Storable a, MonadBaseControl IO m) => (Ptr a -> m c) -> m c --liftBaseOp :: MonadBaseControl b m => ((a -> b (StM m c)) -> b (StM m d)) -> (a -> m c) -> m d -- | Capture the current state above the base monad captureM :: MonadBaseControl b m => m (StM m ()) -- | Capture the current state of a transformer captureT :: (MonadTransControl t, Monad (t m), Monad m) => t m (StT t ()) -- | Performs the same function as embed, but discards transformer -- state from the embedded function. embed_ :: MonadBaseControl b m => (a -> m ()) -> m (a -> b ()) -- | Embed a transformer function as an function in the base monad -- returning a mutated transformer state. embed :: MonadBaseControl b m => (a -> m c) -> m (a -> b (StM m c)) -- | An often used composition: control f = liftBaseWith f -- >>= restoreM -- -- Example: -- --
-- liftedBracket :: MonadBaseControl IO m => m a -> (a -> m b) -> (a -> m c) -> m c -- liftedBracket acquire release action = control $ \runInBase -> -- bracket (runInBase acquire) -- (\saved -> runInBase (restoreM saved >>= release)) -- (\saved -> runInBase (restoreM saved >>= action)) --control :: MonadBaseControl b m => (RunInBase m b -> b (StM m a)) -> m a -- | Default definition for the restoreM method. -- -- Note that: defaultRestoreM = restoreT . -- restoreM defaultRestoreM :: (MonadTransControl t, MonadBaseControl b m) => ComposeSt t m a -> t m a -- | Default definition for the liftBaseWith method. -- -- Note that it composes a liftWith of t with a -- liftBaseWith of m to give a liftBaseWith of -- t m: -- --
-- defaultLiftBaseWith = \f -> liftWith $ \run -> -- liftBaseWith $ \runInBase -> -- f $ runInBase . run --defaultLiftBaseWith :: (MonadTransControl t, MonadBaseControl b m) => (RunInBaseDefault t m b -> b a) -> t m a -- | Default definition for the restoreT method for double -- MonadTransControl. defaultRestoreT2 :: (Monad m, Monad (n' m), MonadTransControl n, MonadTransControl n') => (n (n' m) a -> t m a) -> m (StT n' (StT n a)) -> t m a -- | Default definition for the liftWith method. defaultLiftWith2 :: (Monad m, Monad (n' m), MonadTransControl n, MonadTransControl n') => (forall b. () => n (n' m) b -> t m b) -> (forall (o :: Type -> Type) b. () => t o b -> n (n' o) b) -> (RunDefault2 t n n' -> m a) -> t m a -- | Default definition for the restoreT method. defaultRestoreT :: (Monad m, MonadTransControl n) => (n m a -> t m a) -> m (StT n a) -> t m a -- | Default definition for the liftWith method. defaultLiftWith :: (Monad m, MonadTransControl n) => (forall b. () => n m b -> t m b) -> (forall (o :: Type -> Type) b. () => t o b -> n o b) -> (RunDefault t n -> m a) -> t m a -- | The MonadTransControl type class is a stronger version of -- MonadTrans: -- -- Instances of MonadTrans know how to -- lift actions in the base monad to the transformed -- monad. These lifted actions, however, are completely unaware of the -- monadic state added by the transformer. -- -- MonadTransControl instances are aware of the monadic -- state of the transformer and allow to save and restore this state. -- -- This allows to lift functions that have a monad transformer in both -- positive and negative position. Take, for example, the function -- --
-- withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r ---- -- MonadTrans instances can only lift the return type of -- the withFile function: -- --
-- withFileLifted :: MonadTrans t => FilePath -> IOMode -> (Handle -> IO r) -> t IO r -- withFileLifted file mode action = lift (withFile file mode action) ---- -- However, MonadTrans is not powerful enough to make -- withFileLifted accept a function that returns t IO. -- The reason is that we need to take away the transformer layer in order -- to pass the function to withFile. -- MonadTransControl allows us to do this: -- --
-- withFileLifted' :: (Monad (t IO), MonadTransControl t) => FilePath -> IOMode -> (Handle -> t IO r) -> t IO r -- withFileLifted' file mode action = liftWith (\run -> withFile file mode (run . action)) >>= restoreT . return --class MonadTrans t => MonadTransControl (t :: Type -> Type -> Type -> Type) where { -- | Monadic state of t. -- -- The monadic state of a monad transformer is the result type of its -- run function, e.g.: -- --
-- runReaderT :: ReaderT r m a -> r -> m a
-- StT (ReaderT r) a ~ a
--
-- runStateT :: StateT s m a -> s -> m (a, s)
-- StT (StateT s) a ~ (a, s)
--
-- runMaybeT :: MaybeT m a -> m (Maybe a)
-- StT MaybeT a ~ Maybe a
--
--
-- Provided type instances:
--
--
-- StT IdentityT a ~ a
-- StT MaybeT a ~ Maybe a
-- StT (ErrorT e) a ~ Error e => Either e a
-- StT (ExceptT e) a ~ Either e a
-- StT ListT a ~ [a]
-- StT (ReaderT r) a ~ a
-- StT (StateT s) a ~ (a, s)
-- StT (WriterT w) a ~ Monoid w => (a, w)
-- StT (RWST r w s) a ~ Monoid w => (a, s, w)
--
type family StT (t :: Type -> Type -> Type -> Type) a :: Type;
}
-- | liftWith is similar to lift in that it lifts a
-- computation from the argument monad to the constructed monad.
--
-- Instances should satisfy similar laws as the MonadTrans laws:
--
-- -- liftWith . const . return = return ---- --
-- liftWith (const (m >>= f)) = liftWith (const m) >>= liftWith . const . f ---- -- The difference with lift is that before lifting the -- m computation liftWith captures the state of -- t. It then provides the m computation with a -- Run function that allows running t n computations in -- n (for all n) on the captured state, e.g. -- --
-- withFileLifted :: (Monad (t IO), MonadTransControl t) => FilePath -> IOMode -> (Handle -> t IO r) -> t IO r -- withFileLifted file mode action = liftWith (\run -> withFile file mode (run . action)) >>= restoreT . return ---- -- If the Run function is ignored, liftWith coincides -- with lift: -- --
-- lift f = liftWith (const f) ---- -- Implementations use the Run function associated with a -- transformer: -- --
-- liftWith :: Monad m => ((Monad n => ReaderT r n b -> n b) -> m a) -> ReaderT r m a -- liftWith f = ReaderT (r -> f (action -> runReaderT action r)) -- -- liftWith :: Monad m => ((Monad n => StateT s n b -> n (b, s)) -> m a) -> StateT s m a -- liftWith f = StateT (s -> liftM (x -> (x, s)) (f (action -> runStateT action s))) -- -- liftWith :: Monad m => ((Monad n => MaybeT n b -> n (Maybe b)) -> m a) -> MaybeT m a -- liftWith f = MaybeT (liftM Just (f runMaybeT)) --liftWith :: (MonadTransControl t, Monad m) => (Run t -> m a) -> t m a -- | Construct a t computation from the monadic state of -- t that is returned from a Run function. -- -- Instances should satisfy: -- --
-- liftWith (\run -> run t) >>= restoreT . return = t ---- -- restoreT is usually implemented through the constructor of -- the monad transformer: -- --
-- ReaderT :: (r -> m a) -> ReaderT r m a
-- restoreT :: m a -> ReaderT r m a
-- restoreT action = ReaderT { runReaderT = const action }
--
-- StateT :: (s -> m (a, s)) -> StateT s m a
-- restoreT :: m (a, s) -> StateT s m a
-- restoreT action = StateT { runStateT = const action }
--
-- MaybeT :: m (Maybe a) -> MaybeT m a
-- restoreT :: m (Maybe a) -> MaybeT m a
-- restoreT action = MaybeT action
--
--
-- Example type signatures:
--
-- -- restoreT :: Monad m => m a -> IdentityT m a -- restoreT :: Monad m => m (Maybe a) -> MaybeT m a -- restoreT :: (Monad m, Error e) => m (Either e a) -> ErrorT e m a -- restoreT :: Monad m => m (Either e a) -> ExceptT e m a -- restoreT :: Monad m => m [a] -> ListT m a -- restoreT :: Monad m => m a -> ReaderT r m a -- restoreT :: Monad m => m (a, s) -> StateT s m a -- restoreT :: (Monad m, Monoid w) => m (a, w) -> WriterT w m a -- restoreT :: (Monad m, Monoid w) => m (a, s, w) -> RWST r w s m a --restoreT :: (MonadTransControl t, Monad m) => m (StT t a) -> t m a -- | A function that runs a transformed monad t n on the monadic -- state that was captured by liftWith -- -- A Run t function yields a computation in n that -- returns the monadic state of t. This state can later be used -- to restore a t computation using restoreT. -- -- Example type equalities: -- --
-- Run IdentityT ~ forall n b. Monad n => IdentityT n b -> n b -- Run MaybeT ~ forall n b. Monad n => MaybeT n b -> n (Maybe b) -- Run (ErrorT e) ~ forall n b. (Monad n, Error e) => ErrorT e n b -> n (Either e b) -- Run (ExceptT e) ~ forall n b. Monad n => ExceptT e n b -> n (Either e b) -- Run ListT ~ forall n b. Monad n => ListT n b -> n [b] -- Run (ReaderT r) ~ forall n b. Monad n => ReaderT r n b -> n b -- Run (StateT s) ~ forall n b. Monad n => StateT s n b -> n (a, s) -- Run (WriterT w) ~ forall n b. (Monad n, Monoid w) => WriterT w n b -> n (a, w) -- Run (RWST r w s) ~ forall n b. (Monad n, Monoid w) => RWST r w s n b -> n (a, s, w) ---- -- This type is usually satisfied by the run function of a -- transformer: -- --
-- flip runReaderT :: r -> Run (ReaderT r) -- flip runStateT :: s -> Run (StateT s) -- runMaybeT :: Run MaybeT --type Run (t :: Type -> Type -> Type -> Type) = forall (n :: Type -> Type) b. Monad n => t n b -> n StT t b -- | A function like Run that runs a monad transformer t -- which wraps the monad transformer t'. This is used in -- defaultLiftWith. type RunDefault (t :: Type -> Type -> Type -> Type) (t' :: Type -> Type -> Type -> Type) = forall (n :: Type -> Type) b. Monad n => t n b -> n StT t' b -- | A function like Run that runs a monad transformer t -- which wraps the monad transformers n and n'. This is -- used in defaultLiftWith2. type RunDefault2 (t :: Type -> Type -> Type -> Type) (n :: Type -> Type -> Type -> Type) (n' :: Type -> Type -> Type -> Type) = forall (m :: Type -> Type) b. (Monad m, Monad n' m) => t m b -> m StT n' StT n b -- |
-- StM IO a ~ a
-- StM Maybe a ~ a
-- StM (Either e) a ~ a
-- StM [] a ~ a
-- StM ((->) r) a ~ a
-- StM Identity a ~ a
-- StM STM a ~ a
-- StM (ST s) a ~ a
--
--
-- If m is a transformed monad, m ~ t b,
-- StM is the monadic state of the transformer t
-- (given by its StT from MonadTransControl). For a
-- transformer stack, StM is defined recursively:
--
--
-- StM (IdentityT m) a ~ ComposeSt IdentityT m a ~ StM m a
-- StM (MaybeT m) a ~ ComposeSt MaybeT m a ~ StM m (Maybe a)
-- StM (ErrorT e m) a ~ ComposeSt ErrorT m a ~ Error e => StM m (Either e a)
-- StM (ExceptT e m) a ~ ComposeSt ExceptT m a ~ StM m (Either e a)
-- StM (ListT m) a ~ ComposeSt ListT m a ~ StM m [a]
-- StM (ReaderT r m) a ~ ComposeSt ReaderT m a ~ StM m a
-- StM (StateT s m) a ~ ComposeSt StateT m a ~ StM m (a, s)
-- StM (WriterT w m) a ~ ComposeSt WriterT m a ~ Monoid w => StM m (a, w)
-- StM (RWST r w s m) a ~ ComposeSt RWST m a ~ Monoid w => StM m (a, s, w)
--
type family StM (m :: Type -> Type) a :: Type;
}
-- | liftBaseWith is similar to liftIO and
-- liftBase in that it lifts a base computation to the
-- constructed monad.
--
-- Instances should satisfy similar laws as the MonadIO and
-- MonadBase laws:
--
-- -- liftBaseWith . const . return = return ---- --
-- liftBaseWith (const (m >>= f)) = liftBaseWith (const m) >>= liftBaseWith . const . f ---- -- The difference with liftBase is that before lifting the base -- computation liftBaseWith captures the state of m. It -- then provides the base computation with a RunInBase function -- that allows running m computations in the base monad on the -- captured state: -- --
-- withFileLifted :: MonadBaseControl IO m => FilePath -> IOMode -> (Handle -> m a) -> m a -- withFileLifted file mode action = liftBaseWith (\runInBase -> withFile file mode (runInBase . action)) >>= restoreM -- -- = control $ \runInBase -> withFile file mode (runInBase . action) -- -- = liftBaseOp (withFile file mode) action ---- -- liftBaseWith is usually not implemented directly, but -- using defaultLiftBaseWith. liftBaseWith :: MonadBaseControl b m => (RunInBase m b -> b a) -> m a -- | Construct a m computation from the monadic state of -- m that is returned from a RunInBase function. -- -- Instances should satisfy: -- --
-- liftBaseWith (\runInBase -> runInBase m) >>= restoreM = m ---- -- restoreM is usually not implemented directly, but -- using defaultRestoreM. restoreM :: MonadBaseControl b m => StM m a -> m a -- | A function that runs a m computation on the monadic state -- that was captured by liftBaseWith -- -- A RunInBase m function yields a computation in the base monad -- of m that returns the monadic state of m. This state -- can later be used to restore the m computation using -- restoreM. -- -- Example type equalities: -- --
-- RunInBase (IdentityT m) b ~ forall a. IdentityT m a -> b (StM m a) -- RunInBase (MaybeT m) b ~ forall a. MaybeT m a -> b (StM m (Maybe a)) -- RunInBase (ErrorT e m) b ~ forall a. Error e => ErrorT e m a -> b (StM m (Either e a)) -- RunInBase (ExceptT e m) b ~ forall a. ExceptT e m a -> b (StM m (Either e a)) -- RunInBase (ListT m) b ~ forall a. ListT m a -> b (StM m [a]) -- RunInBase (ReaderT r m) b ~ forall a. ReaderT m a -> b (StM m a) -- RunInBase (StateT s m) b ~ forall a. StateT s m a -> b (StM m (a, s)) -- RunInBase (WriterT w m) b ~ forall a. Monoid w => WriterT w m a -> b (StM m (a, w)) -- RunInBase (RWST r w s m) b ~ forall a. Monoid w => RWST r w s m a -> b (StM m (a, s, w)) ---- -- For a transformed base monad m ~ t b, 'RunInBase m b' ~ -- Run t. type RunInBase (m :: Type -> Type) (b :: Type -> Type) = forall a. () => m a -> b StM m a -- | Handy type synonym that composes the monadic states of t and -- m. -- -- It can be used to define the StM for new -- MonadBaseControl instances. type ComposeSt (t :: Type -> Type -> Type -> Type) (m :: Type -> Type) a = StM m StT t a -- | A function like RunInBase that runs a monad transformer -- t in its base monad b. It is used in -- defaultLiftBaseWith. type RunInBaseDefault (t :: Type -> Type -> Type -> Type) (m :: Type -> Type) (b :: Type -> Type) = forall a. () => t m a -> b ComposeSt t m a -- | See logDebug logError :: (HasCallStack, MonadLogger m) => Text -> m () -- | See logDebug logInfo :: (HasCallStack, MonadLogger m) => Text -> m () -- | See logDebugCS logErrorCS :: MonadLogger m => CallStack -> Text -> m () -- | See logDebugCS logWarnCS :: MonadLogger m => CallStack -> Text -> m () -- | See logDebugCS logInfoCS :: MonadLogger m => CallStack -> Text -> m () -- | A Monad which has the ability to log messages in some manner. class Monad m => MonadLogger (m :: Type -> Type) -- | An extension of MonadLogger for the common case where the -- logging action is a simple IO action. The advantage of using -- this typeclass is that the logging function itself can be extracted as -- a first-class value, which can make it easier to manipulate monad -- transformer stacks, as an example. class (MonadLogger m, MonadIO m) => MonadLoggerIO (m :: Type -> Type) -- | Monad transformer that adds a new logging function. data LoggingT (m :: Type -> Type) a -- | Run an action in the underlying monad, providing it the -- InternalState. -- -- Since 0.4.6 withInternalState :: () => (InternalState -> m a) -> ResourceT m a -- | Unwrap a ResourceT using the given InternalState. -- -- Since 0.4.6 runInternalState :: () => ResourceT m a -> InternalState -> m a -- | Get the internal state of the current ResourceT. -- -- Since 0.4.6 getInternalState :: Monad m => ResourceT m InternalState -- | Close an internal state created by createInternalState. -- -- Since 0.4.9 closeInternalState :: MonadIO m => InternalState -> m () -- | Create a new internal state. This state must be closed with -- closeInternalState. It is your responsibility to ensure -- exception safety. Caveat emptor! -- -- Since 0.4.9 createInternalState :: MonadIO m => m InternalState -- | Launch a new reference counted resource context using forkIO. -- -- This is defined as resourceForkWith forkIO. resourceForkIO :: MonadUnliftIO m => ResourceT m () -> ResourceT m ThreadId -- | Introduce a reference-counting scheme to allow a resource context to -- be shared by multiple threads. Once the last thread exits, all -- remaining resources will be released. -- -- The first parameter is a function which will be used to create the -- thread, such as forkIO or async. -- -- Note that abuse of this function will greatly delay the deallocation -- of registered resources. This function should be used with care. A -- general guideline: -- -- If you are allocating a resource that should be shared by multiple -- threads, and will be held for a long time, you should allocate it at -- the beginning of a new ResourceT block and then call -- resourceForkWith from there. resourceForkWith :: MonadUnliftIO m => (IO () -> IO a) -> ResourceT m () -> ResourceT m a -- | This function mirrors join at the transformer level: it will -- collapse two levels of ResourceT into a single -- ResourceT. -- -- Since 0.4.6 joinResourceT :: () => ResourceT (ResourceT m) a -> ResourceT m a -- | Backwards compatible alias for runResourceT. runResourceTChecked :: MonadUnliftIO m => ResourceT m a -> m a -- | Perform asynchronous exception masking. -- -- This is more general then Control.Exception.mask, yet more -- efficient than Control.Exception.Lifted.mask. -- -- Since 0.3.0 resourceMask :: MonadResource m => ((forall a. () => ResourceT IO a -> ResourceT IO a) -> ResourceT IO b) -> m b -- | Perform some allocation, and automatically register a cleanup action. -- -- This is almost identical to calling the allocation and then -- registering the release action, but this properly handles -- masking of asynchronous exceptions. -- -- Since 0.3.0 allocate :: MonadResource m => IO a -> (a -> IO ()) -> m (ReleaseKey, a) -- | Unprotect resource from cleanup actions; this allows you to send -- resource into another resourcet process and reregister it there. It -- returns a release action that should be run in order to clean resource -- or Nothing in case if resource is already freed. -- -- Since 0.4.5 unprotect :: MonadIO m => ReleaseKey -> m (Maybe (IO ())) -- | Call a release action early, and deregister it from the list of -- cleanup actions to be performed. -- -- Since 0.3.0 release :: MonadIO m => ReleaseKey -> m () -- | Register some action that will be called precisely once, either when -- runResourceT is called, or when the ReleaseKey is passed -- to release. -- -- Since 0.3.0 register :: MonadResource m => IO () -> m ReleaseKey -- | Just use MonadUnliftIO directly now, legacy explanation -- continues: -- -- A Monad which can be used as a base for a ResourceT. -- -- A ResourceT has some restrictions on its base monad: -- --