module CssParser.Parser.Monad ( module CssParser.Parser.Monad , module X ) whereimport CssParser.Preludeimport Data.List qualified as Limport Expression.Reorder as X ( reorder, Validation(..), SyntaxTree )import GHC.Stack (HasCallStack)data P a = Ok a | Failed String deriving (Functor)reorderErr :: (HasCallStack, Show a, SyntaxTree a String) => a -> areorderErr x = case reorderInP x of Failed x' -> error x' Ok x' -> x'reorderInP :: (Show a, SyntaxTree a String) => a -> P areorderInP a = validationToP a (reorder a)validationToP :: Show a => a -> Validation (NonEmpty String) a -> P avalidationToP x = \case Failure er -> Failed $ "Failed to reorder " <> show x <> " due: " <> L.intercalate "\n" (toList er) Success a -> Ok ainstance Applicative P where pure = Ok Ok f <*> Ok a = Ok (f a) Failed f <*> _ = Failed f _ <*> Failed b = Failed binstance Monad P where Failed v >>= _ = Failed v Ok v >>= f = f vinstance MonadFail P where fail = FailedthenP :: P a -> (a -> P b) -> P bm `thenP` k = case m of Ok a -> k a Failed e -> Failed ereturnP :: a -> P areturnP = OkfailP :: String -> P afailP = FailedcatchP :: P a -> (String -> P a) -> P acatchP m k = case m of Ok a -> Ok a Failed e -> k efromEitherM :: Applicative m => (e -> m a) -> Either e a -> m afromEitherM ef = \case Right v -> pure v Left e -> ef e