-- |
-- License: GPL-3.0-or-later
-- Copyright: Oleg Grenrus
module CabalFmt.Parser where

import qualified Data.ByteString                              as BS
import qualified Distribution.Fields                          as C
import qualified Distribution.PackageDescription.Parsec       as C
import qualified Distribution.Parsec                          as C
import qualified Distribution.Types.GenericPackageDescription as C

import CabalFmt.Error
import CabalFmt.Monad
import CabalFmt.Prelude

runParseResult :: MonadCabalFmt r m => FilePath -> BS.ByteString -> C.ParseResult a -> m a
runParseResult :: FilePath -> ByteString -> ParseResult a -> m a
runParseResult FilePath
filepath ByteString
contents ParseResult a
pr = case Either (Maybe Version, NonEmpty PError) a
result of
    Right a
gpd -> a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return a
gpd
    Left (Maybe Version
mspecVersion, NonEmpty PError
errors) -> Error -> m a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (Error -> m a) -> Error -> m a
forall a b. (a -> b) -> a -> b
$ FilePath
-> ByteString
-> NonEmpty PError
-> Maybe Version
-> [PWarning]
-> Error
CabalParseError FilePath
filepath ByteString
contents NonEmpty PError
errors Maybe Version
mspecVersion [PWarning]
warnings
  where
    ([PWarning]
warnings, Either (Maybe Version, NonEmpty PError) a
result) = ParseResult a
-> ([PWarning], Either (Maybe Version, NonEmpty PError) a)
forall a.
ParseResult a
-> ([PWarning], Either (Maybe Version, NonEmpty PError) a)
C.runParseResult ParseResult a
pr

parseGpd :: MonadCabalFmt r m => FilePath -> BS.ByteString -> m C.GenericPackageDescription
parseGpd :: FilePath -> ByteString -> m GenericPackageDescription
parseGpd FilePath
filepath ByteString
contents = FilePath
-> ByteString
-> ParseResult GenericPackageDescription
-> m GenericPackageDescription
forall r (m :: * -> *) a.
MonadCabalFmt r m =>
FilePath -> ByteString -> ParseResult a -> m a
runParseResult FilePath
filepath ByteString
contents (ParseResult GenericPackageDescription
 -> m GenericPackageDescription)
-> ParseResult GenericPackageDescription
-> m GenericPackageDescription
forall a b. (a -> b) -> a -> b
$ ByteString -> ParseResult GenericPackageDescription
C.parseGenericPackageDescription ByteString
contents

parseFields :: MonadCabalFmt r m => BS.ByteString -> m [C.Field C.Position]
parseFields :: ByteString -> m [Field Position]
parseFields ByteString
contents = case ByteString -> Either ParseError [Field Position]
C.readFields ByteString
contents of
    Left ParseError
err -> Error -> m [Field Position]
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (Error -> m [Field Position]) -> Error -> m [Field Position]
forall a b. (a -> b) -> a -> b
$ ParseError -> Error
PanicCannotParseInput ParseError
err
    Right [Field Position]
x  -> [Field Position] -> m [Field Position]
forall (m :: * -> *) a. Monad m => a -> m a
return [Field Position]
x