|
| 1 | +{-# LANGUAGE ImplicitParams #-} |
| 2 | +-- | Support for access to read only values supplied by a specified monadic |
| 3 | +-- action. |
| 4 | +module Effectful.Input.Static.Action |
| 5 | + ( -- * Effect |
| 6 | + Input |
| 7 | + |
| 8 | + -- ** Handlers |
| 9 | + , runInput |
| 10 | + |
| 11 | + -- ** Operations |
| 12 | + , input |
| 13 | + , inputs |
| 14 | + ) where |
| 15 | + |
| 16 | +import Data.Kind |
| 17 | +import GHC.Stack |
| 18 | + |
| 19 | +import Effectful |
| 20 | +import Effectful.Dispatch.Static |
| 21 | +import Effectful.Dispatch.Static.Primitive |
| 22 | +import Effectful.Internal.Utils |
| 23 | + |
| 24 | +-- | Provide access to read only values of type @i@. |
| 25 | +data Input (i :: Type) :: Effect |
| 26 | + |
| 27 | +type instance DispatchOf (Input i) = Static NoSideEffects |
| 28 | + |
| 29 | +-- | Wrapper to prevent a space leak on reconstruction of 'Input' in |
| 30 | +-- 'relinkInput' (see https://gitlab.haskell.org/ghc/ghc/-/issues/25520). |
| 31 | +newtype InputImpl i es where |
| 32 | + InputImpl :: (HasCallStack => Eff es i) -> InputImpl i es |
| 33 | + |
| 34 | +data instance StaticRep (Input i) where |
| 35 | + Input |
| 36 | + :: !(Env inputEs) |
| 37 | + -> !(InputImpl i inputEs) |
| 38 | + -> StaticRep (Input i) |
| 39 | + |
| 40 | +-- | Run an 'Input' effect with the given action that supplies values. |
| 41 | +runInput |
| 42 | + :: forall i es a |
| 43 | + . HasCallStack |
| 44 | + => (HasCallStack => Eff es i) |
| 45 | + -- ^ The action for input generation. |
| 46 | + -> Eff (Input i : es) a |
| 47 | + -> Eff es a |
| 48 | +runInput inputAction action = unsafeEff $ \es -> do |
| 49 | + inlineBracket |
| 50 | + (consEnv (Input es inputImpl) relinkInput es) |
| 51 | + unconsEnv |
| 52 | + (unEff action) |
| 53 | + where |
| 54 | + inputImpl = InputImpl $ let ?callStack = thawCallStack ?callStack in inputAction |
| 55 | + |
| 56 | +-- | Fetch the value. |
| 57 | +input :: (HasCallStack, Input i :> es) => Eff es i |
| 58 | +input = unsafeEff $ \es -> do |
| 59 | + Input inputEs (InputImpl inputAction) <- getEnv es |
| 60 | + -- Corresponds to thawCallStack in runInput. |
| 61 | + (`unEff` inputEs) $ withFrozenCallStack inputAction |
| 62 | + |
| 63 | +-- | Fetch the result of applying a function to the value. |
| 64 | +-- |
| 65 | +-- @'inputs' f ≡ f '<$>' 'input'@ |
| 66 | +inputs |
| 67 | + :: (HasCallStack, Input i :> es) |
| 68 | + => (i -> a) -- ^ The function to apply to the value. |
| 69 | + -> Eff es a |
| 70 | +inputs f = f <$> input |
| 71 | + |
| 72 | +---------------------------------------- |
| 73 | +-- Helpers |
| 74 | + |
| 75 | +relinkInput :: Relinker StaticRep (Input i) |
| 76 | +relinkInput = Relinker $ \relink (Input inputEs inputAction) -> do |
| 77 | + newActionEs <- relink inputEs |
| 78 | + pure $ Input newActionEs inputAction |
0 commit comments