{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-} -- new
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-} -- new

module Text.Megaparsec.Custom (
  -- * Custom parse error types
  HledgerParseErrorData,
  HledgerParseErrors,

  -- * Failing with an arbitrary source position
  parseErrorAt,
  parseErrorAtRegion,

  -- * Re-parsing
  SourceExcerpt,
  getExcerptText,

  excerpt_,
  reparseExcerpt,

  -- * Pretty-printing custom parse errors
  customErrorBundlePretty,


  -- * "Final" parse errors
  FinalParseError,
  FinalParseError',
  FinalParseErrorBundle,
  FinalParseErrorBundle',

  -- * Constructing "final" parse errors
  finalError,
  finalFancyFailure,
  finalFail,
  finalCustomFailure,

  -- * Pretty-printing "final" parse errors
  finalErrorBundlePretty,
  attachSource,

  -- * Handling parse errors from include files with "final" parse errors
  parseIncludeFile,
)
where

import Control.Monad.Except
import Control.Monad.State.Strict (StateT, evalStateT)
import qualified Data.List.NonEmpty as NE
import Data.Monoid (Alt(..))
import qualified Data.Set as S
import Data.Text (Text)
import Text.Megaparsec


--- * Custom parse error types

-- | Custom error data for hledger parsers. Specialised for a 'Text' parse stream.
data HledgerParseErrorData
  -- | Fail with a message at a specific source position interval. The
  -- interval must be contained within a single line.
  = ErrorFailAt Int -- Starting offset
                Int -- Ending offset
                String -- Error message
  -- | Re-throw parse errors obtained from the "re-parsing" of an excerpt
  -- of the source text.
  | ErrorReparsing
      (NE.NonEmpty (ParseError Text HledgerParseErrorData)) -- Source fragment parse errors
  deriving (Int -> HledgerParseErrorData -> ShowS
[HledgerParseErrorData] -> ShowS
HledgerParseErrorData -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [HledgerParseErrorData] -> ShowS
$cshowList :: [HledgerParseErrorData] -> ShowS
show :: HledgerParseErrorData -> String
$cshow :: HledgerParseErrorData -> String
showsPrec :: Int -> HledgerParseErrorData -> ShowS
$cshowsPrec :: Int -> HledgerParseErrorData -> ShowS
Show, HledgerParseErrorData -> HledgerParseErrorData -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: HledgerParseErrorData -> HledgerParseErrorData -> Bool
$c/= :: HledgerParseErrorData -> HledgerParseErrorData -> Bool
== :: HledgerParseErrorData -> HledgerParseErrorData -> Bool
$c== :: HledgerParseErrorData -> HledgerParseErrorData -> Bool
Eq, Eq HledgerParseErrorData
HledgerParseErrorData -> HledgerParseErrorData -> Bool
HledgerParseErrorData -> HledgerParseErrorData -> Ordering
HledgerParseErrorData
-> HledgerParseErrorData -> HledgerParseErrorData
forall a.
Eq a
-> (a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
min :: HledgerParseErrorData
-> HledgerParseErrorData -> HledgerParseErrorData
$cmin :: HledgerParseErrorData
-> HledgerParseErrorData -> HledgerParseErrorData
max :: HledgerParseErrorData
-> HledgerParseErrorData -> HledgerParseErrorData
$cmax :: HledgerParseErrorData
-> HledgerParseErrorData -> HledgerParseErrorData
>= :: HledgerParseErrorData -> HledgerParseErrorData -> Bool
$c>= :: HledgerParseErrorData -> HledgerParseErrorData -> Bool
> :: HledgerParseErrorData -> HledgerParseErrorData -> Bool
$c> :: HledgerParseErrorData -> HledgerParseErrorData -> Bool
<= :: HledgerParseErrorData -> HledgerParseErrorData -> Bool
$c<= :: HledgerParseErrorData -> HledgerParseErrorData -> Bool
< :: HledgerParseErrorData -> HledgerParseErrorData -> Bool
$c< :: HledgerParseErrorData -> HledgerParseErrorData -> Bool
compare :: HledgerParseErrorData -> HledgerParseErrorData -> Ordering
$ccompare :: HledgerParseErrorData -> HledgerParseErrorData -> Ordering
Ord)

-- | A specialised version of ParseErrorBundle: 
-- a non-empty collection of hledger parse errors, 
-- equipped with PosState to help pretty-print them.
-- Specialised for a 'Text' parse stream.
type HledgerParseErrors = ParseErrorBundle Text HledgerParseErrorData

-- We require an 'Ord' instance for 'CustomError' so that they may be
-- stored in a 'Set'. The actual instance is inconsequential, so we just
-- derive it, but the derived instance requires an (orphan) instance for
-- 'ParseError'. Hopefully this does not cause any trouble.

deriving instance Ord (ParseError Text HledgerParseErrorData)

-- Note: the pretty-printing of our 'HledgerParseErrorData' type is only partally
-- defined in its 'ShowErrorComponent' instance; we perform additional
-- adjustments in 'customErrorBundlePretty'.

instance ShowErrorComponent HledgerParseErrorData where
  showErrorComponent :: HledgerParseErrorData -> String
showErrorComponent (ErrorFailAt Int
_ Int
_ String
errMsg) = String
errMsg
  showErrorComponent (ErrorReparsing NonEmpty (ParseError Text HledgerParseErrorData)
_) = String
"" -- dummy value

  errorComponentLen :: HledgerParseErrorData -> Int
errorComponentLen (ErrorFailAt Int
startOffset Int
endOffset String
_) =
    Int
endOffset forall a. Num a => a -> a -> a
- Int
startOffset
  errorComponentLen (ErrorReparsing NonEmpty (ParseError Text HledgerParseErrorData)
_) = Int
1 -- dummy value


--- * Failing with an arbitrary source position

-- | Fail at a specific source position, given by the raw offset from the
-- start of the input stream (the number of tokens processed at that
-- point).

parseErrorAt :: Int -> String -> HledgerParseErrorData
parseErrorAt :: Int -> String -> HledgerParseErrorData
parseErrorAt Int
offset = Int -> Int -> String -> HledgerParseErrorData
ErrorFailAt Int
offset (Int
offsetforall a. Num a => a -> a -> a
+Int
1)

-- | Fail at a specific source interval, given by the raw offsets of its
-- endpoints from the start of the input stream (the numbers of tokens
-- processed at those points).
--
-- Note that care must be taken to ensure that the specified interval does
-- not span multiple lines of the input source. This will not be checked.

parseErrorAtRegion
  :: Int    -- ^ Start offset
  -> Int    -- ^ End end offset
  -> String -- ^ Error message
  -> HledgerParseErrorData
parseErrorAtRegion :: Int -> Int -> String -> HledgerParseErrorData
parseErrorAtRegion Int
startOffset Int
endOffset String
msg =
  if Int
startOffset forall a. Ord a => a -> a -> Bool
< Int
endOffset
    then Int -> Int -> String -> HledgerParseErrorData
ErrorFailAt Int
startOffset Int
endOffset String
msg'
    else Int -> Int -> String -> HledgerParseErrorData
ErrorFailAt Int
startOffset (Int
startOffsetforall a. Num a => a -> a -> a
+Int
1) String
msg'
  where
    msg' :: String
msg' = String
"\n" forall a. [a] -> [a] -> [a]
++ String
msg


--- * Re-parsing

-- | A fragment of source suitable for "re-parsing". The purpose of this
-- data type is to preserve the content and source position of the excerpt
-- so that parse errors raised during "re-parsing" may properly reference
-- the original source.

data SourceExcerpt = SourceExcerpt Int  -- Offset of beginning of excerpt
                                   Text -- Fragment of source file

-- | Get the raw text of a source excerpt.

getExcerptText :: SourceExcerpt -> Text
getExcerptText :: SourceExcerpt -> Text
getExcerptText (SourceExcerpt Int
_ Text
txt) = Text
txt

-- | 'excerpt_ p' applies the given parser 'p' and extracts the portion of
-- the source consumed by 'p', along with the source position of this
-- portion. This is the only way to create a source excerpt suitable for
-- "re-parsing" by 'reparseExcerpt'.

-- This function could be extended to return the result of 'p', but we don't
-- currently need this.

excerpt_ :: MonadParsec HledgerParseErrorData Text m => m a -> m SourceExcerpt
excerpt_ :: forall (m :: * -> *) a.
MonadParsec HledgerParseErrorData Text m =>
m a -> m SourceExcerpt
excerpt_ m a
p = do
  Int
offset <- forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
  (!Text
txt, a
_) <- forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> m (Tokens s, a)
match m a
p
  forall (f :: * -> *) a. Applicative f => a -> f a
pure forall a b. (a -> b) -> a -> b
$ Int -> Text -> SourceExcerpt
SourceExcerpt Int
offset Text
txt

-- | 'reparseExcerpt s p' "re-parses" the source excerpt 's' using the
-- parser 'p'. Parse errors raised by 'p' will be re-thrown at the source
-- position of the source excerpt.
--
-- In order for the correct source file to be displayed when re-throwing
-- parse errors, we must ensure that the source file during the use of
-- 'reparseExcerpt s p' is the same as that during the use of 'excerpt_'
-- that generated the source excerpt 's'. However, we can usually expect
-- this condition to be satisfied because, at the time of writing, the
-- only changes of source file in the codebase take place through include
-- files, and the parser for include files neither accepts nor returns
-- 'SourceExcerpt's.

reparseExcerpt
  :: Monad m
  => SourceExcerpt
  -> ParsecT HledgerParseErrorData Text m a
  -> ParsecT HledgerParseErrorData Text m a
reparseExcerpt :: forall (m :: * -> *) a.
Monad m =>
SourceExcerpt
-> ParsecT HledgerParseErrorData Text m a
-> ParsecT HledgerParseErrorData Text m a
reparseExcerpt (SourceExcerpt Int
offset Text
txt) ParsecT HledgerParseErrorData Text m a
p = do
  (State Text HledgerParseErrorData
_, Either (ParseErrorBundle Text HledgerParseErrorData) a
res) <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) e s a.
Monad m =>
ParsecT e s m a
-> State s e -> m (State s e, Either (ParseErrorBundle s e) a)
runParserT' ParsecT HledgerParseErrorData Text m a
p (forall s e. Int -> s -> State s e
offsetInitialState Int
offset Text
txt)
  case Either (ParseErrorBundle Text HledgerParseErrorData) a
res of
    Right a
result -> forall (f :: * -> *) a. Applicative f => a -> f a
pure a
result
    Left ParseErrorBundle Text HledgerParseErrorData
errBundle -> forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure forall a b. (a -> b) -> a -> b
$ NonEmpty (ParseError Text HledgerParseErrorData)
-> HledgerParseErrorData
ErrorReparsing forall a b. (a -> b) -> a -> b
$ forall s e. ParseErrorBundle s e -> NonEmpty (ParseError s e)
bundleErrors ParseErrorBundle Text HledgerParseErrorData
errBundle

  where
    offsetInitialState :: Int -> s ->
#if MIN_VERSION_megaparsec(8,0,0)
      State s e
#else
      State s
#endif
    offsetInitialState :: forall s e. Int -> s -> State s e
offsetInitialState Int
initialOffset s
s = State
      { stateInput :: s
stateInput  = s
s
      , stateOffset :: Int
stateOffset = Int
initialOffset
      , statePosState :: PosState s
statePosState = PosState
        { pstateInput :: s
pstateInput = s
s
        , pstateOffset :: Int
pstateOffset = Int
initialOffset
        , pstateSourcePos :: SourcePos
pstateSourcePos = String -> SourcePos
initialPos String
""
        , pstateTabWidth :: Pos
pstateTabWidth = Pos
defaultTabWidth
        , pstateLinePrefix :: String
pstateLinePrefix = String
""
        }
#if MIN_VERSION_megaparsec(8,0,0)
      , stateParseErrors :: [ParseError s e]
stateParseErrors = []
#endif
      }

--- * Pretty-printing custom parse errors

-- | Pretty-print our custom parse errors. It is necessary to use this
-- instead of 'errorBundlePretty' when custom parse errors are thrown.
--
-- This function intercepts our custom parse errors and applies final
-- adjustments ('finalizeCustomError') before passing them to
-- 'errorBundlePretty'. These adjustments are part of the implementation
-- of the behaviour of our custom parse errors.
--
-- Note: We must ensure that the offset of the 'PosState' of the provided
-- 'ParseErrorBundle' is no larger than the offset specified by a
-- 'ErrorFailAt' constructor. This is guaranteed if this offset is set to
-- 0 (that is, the beginning of the source file), which is the
-- case for 'ParseErrorBundle's returned from 'runParserT'.

customErrorBundlePretty :: HledgerParseErrors -> String
customErrorBundlePretty :: ParseErrorBundle Text HledgerParseErrorData -> String
customErrorBundlePretty ParseErrorBundle Text HledgerParseErrorData
errBundle =
  let errBundle' :: ParseErrorBundle Text HledgerParseErrorData
errBundle' = ParseErrorBundle Text HledgerParseErrorData
errBundle { bundleErrors :: NonEmpty (ParseError Text HledgerParseErrorData)
bundleErrors =
        forall o a. Ord o => (a -> o) -> NonEmpty a -> NonEmpty a
NE.sortWith forall s e. ParseError s e -> Int
errorOffset forall a b. (a -> b) -> a -> b
$ -- megaparsec requires that the list of errors be sorted by their offsets
        forall s e. ParseErrorBundle s e -> NonEmpty (ParseError s e)
bundleErrors ParseErrorBundle Text HledgerParseErrorData
errBundle forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ParseError Text HledgerParseErrorData
-> NonEmpty (ParseError Text HledgerParseErrorData)
finalizeCustomError }
  in  forall s e.
(VisualStream s, TraversableStream s, ShowErrorComponent e) =>
ParseErrorBundle s e -> String
errorBundlePretty ParseErrorBundle Text HledgerParseErrorData
errBundle'

  where
    finalizeCustomError
      :: ParseError Text HledgerParseErrorData -> NE.NonEmpty (ParseError Text HledgerParseErrorData)
    finalizeCustomError :: ParseError Text HledgerParseErrorData
-> NonEmpty (ParseError Text HledgerParseErrorData)
finalizeCustomError ParseError Text HledgerParseErrorData
err = case ParseError Text HledgerParseErrorData
-> Maybe HledgerParseErrorData
findCustomError ParseError Text HledgerParseErrorData
err of
      Maybe HledgerParseErrorData
Nothing -> forall (f :: * -> *) a. Applicative f => a -> f a
pure ParseError Text HledgerParseErrorData
err

      Just errFailAt :: HledgerParseErrorData
errFailAt@(ErrorFailAt Int
startOffset Int
_ String
_) ->
        -- Adjust the offset
        forall (f :: * -> *) a. Applicative f => a -> f a
pure forall a b. (a -> b) -> a -> b
$ forall s e. Int -> Set (ErrorFancy e) -> ParseError s e
FancyError Int
startOffset forall a b. (a -> b) -> a -> b
$ forall a. a -> Set a
S.singleton forall a b. (a -> b) -> a -> b
$ forall e. e -> ErrorFancy e
ErrorCustom HledgerParseErrorData
errFailAt

      Just (ErrorReparsing NonEmpty (ParseError Text HledgerParseErrorData)
errs) ->
        -- Extract and finalize the inner errors
        NonEmpty (ParseError Text HledgerParseErrorData)
errs forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ParseError Text HledgerParseErrorData
-> NonEmpty (ParseError Text HledgerParseErrorData)
finalizeCustomError

    -- If any custom errors are present, arbitrarily take the first one
    -- (since only one custom error should be used at a time).
    findCustomError :: ParseError Text HledgerParseErrorData -> Maybe HledgerParseErrorData
    findCustomError :: ParseError Text HledgerParseErrorData
-> Maybe HledgerParseErrorData
findCustomError ParseError Text HledgerParseErrorData
err = case ParseError Text HledgerParseErrorData
err of
      FancyError Int
_ Set (ErrorFancy HledgerParseErrorData)
errSet ->
        forall (t :: * -> *) a b.
Foldable t =>
(a -> Maybe b) -> t a -> Maybe b
finds (\case {ErrorCustom HledgerParseErrorData
e -> forall a. a -> Maybe a
Just HledgerParseErrorData
e; ErrorFancy HledgerParseErrorData
_ -> forall a. Maybe a
Nothing}) Set (ErrorFancy HledgerParseErrorData)
errSet
      ParseError Text HledgerParseErrorData
_ -> forall a. Maybe a
Nothing

    finds :: (Foldable t) => (a -> Maybe b) -> t a -> Maybe b
    finds :: forall (t :: * -> *) a b.
Foldable t =>
(a -> Maybe b) -> t a -> Maybe b
finds a -> Maybe b
f = forall {k} (f :: k -> *) (a :: k). Alt f a -> f a
getAlt forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (forall {k} (f :: k -> *) (a :: k). f a -> Alt f a
Alt forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> Maybe b
f)


--- * "Final" parse errors
--
-- | A type representing "final" parse errors that cannot be backtracked
-- from and are guaranteed to halt parsing. The anti-backtracking
-- behaviour is implemented by an 'ExceptT' layer in the parser's monad
-- stack, using this type as the 'ExceptT' error type.
--
-- We have three goals for this type:
-- (1) it should be possible to convert any parse error into a "final"
-- parse error,
-- (2) it should be possible to take a parse error thrown from an include
-- file and re-throw it in the parent file, and
-- (3) the pretty-printing of "final" parse errors should be consistent
-- with that of ordinary parse errors, but should also report a stack of
-- files for errors thrown from include files.
--
-- In order to pretty-print a "final" parse error (goal 3), it must be
-- bundled with include filepaths and its full source text. When a "final"
-- parse error is thrown from within a parser, we do not have access to
-- the full source, so we must hold the parse error until it can be joined
-- with its source (and include filepaths, if it was thrown from an
-- include file) by the parser's caller.
--
-- A parse error with include filepaths and its full source text is
-- represented by the 'FinalParseErrorBundle' type, while a parse error in
-- need of either include filepaths, full source text, or both is
-- represented by the 'FinalParseError' type.

data FinalParseError' e
  -- a parse error thrown as a "final" parse error
  = FinalError           (ParseError Text e)
  -- a parse error obtained from running a parser, e.g. using 'runParserT'
  | FinalBundle          (ParseErrorBundle Text e)
  -- a parse error thrown from an include file
  | FinalBundleWithStack (FinalParseErrorBundle' e)
  deriving (Int -> FinalParseError' e -> ShowS
forall e. Show e => Int -> FinalParseError' e -> ShowS
forall e. Show e => [FinalParseError' e] -> ShowS
forall e. Show e => FinalParseError' e -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [FinalParseError' e] -> ShowS
$cshowList :: forall e. Show e => [FinalParseError' e] -> ShowS
show :: FinalParseError' e -> String
$cshow :: forall e. Show e => FinalParseError' e -> String
showsPrec :: Int -> FinalParseError' e -> ShowS
$cshowsPrec :: forall e. Show e => Int -> FinalParseError' e -> ShowS
Show)

type FinalParseError = FinalParseError' HledgerParseErrorData

-- We need a 'Monoid' instance for 'FinalParseError' so that 'ExceptT
-- FinalParseError m' is an instance of Alternative and MonadPlus, which
-- is needed to use some parser combinators, e.g. 'many'.
--
-- This monoid instance simply takes the first (left-most) error.

instance Semigroup (FinalParseError' e) where
  FinalParseError' e
e <> :: FinalParseError' e -> FinalParseError' e -> FinalParseError' e
<> FinalParseError' e
_ = FinalParseError' e
e

instance Monoid (FinalParseError' e) where
  mempty :: FinalParseError' e
mempty = forall e. ParseError Text e -> FinalParseError' e
FinalError forall a b. (a -> b) -> a -> b
$ forall s e. Int -> Set (ErrorFancy e) -> ParseError s e
FancyError Int
0 forall a b. (a -> b) -> a -> b
$
            forall a. a -> Set a
S.singleton (forall e. String -> ErrorFancy e
ErrorFail String
"default parse error")
  mappend :: FinalParseError' e -> FinalParseError' e -> FinalParseError' e
mappend = forall a. Semigroup a => a -> a -> a
(<>)

-- | A type bundling a 'ParseError' with its full source text, filepath,
-- and stack of include files. Suitable for pretty-printing.
--
-- Megaparsec's 'ParseErrorBundle' type already bundles a parse error with
-- its full source text and filepath, so we just add a stack of include
-- files.

data FinalParseErrorBundle' e = FinalParseErrorBundle'
  { forall e. FinalParseErrorBundle' e -> ParseErrorBundle Text e
finalErrorBundle :: ParseErrorBundle Text e
  , forall e. FinalParseErrorBundle' e -> [String]
includeFileStack :: [FilePath]
  } deriving (Int -> FinalParseErrorBundle' e -> ShowS
forall e. Show e => Int -> FinalParseErrorBundle' e -> ShowS
forall e. Show e => [FinalParseErrorBundle' e] -> ShowS
forall e. Show e => FinalParseErrorBundle' e -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [FinalParseErrorBundle' e] -> ShowS
$cshowList :: forall e. Show e => [FinalParseErrorBundle' e] -> ShowS
show :: FinalParseErrorBundle' e -> String
$cshow :: forall e. Show e => FinalParseErrorBundle' e -> String
showsPrec :: Int -> FinalParseErrorBundle' e -> ShowS
$cshowsPrec :: forall e. Show e => Int -> FinalParseErrorBundle' e -> ShowS
Show)

type FinalParseErrorBundle = FinalParseErrorBundle' HledgerParseErrorData


--- * Constructing and throwing final parse errors

-- | Convert a "regular" parse error into a "final" parse error.

finalError :: ParseError Text e -> FinalParseError' e
finalError :: forall e. ParseError Text e -> FinalParseError' e
finalError = forall e. ParseError Text e -> FinalParseError' e
FinalError

-- | Like megaparsec's 'fancyFailure', but as a "final" parse error.

finalFancyFailure
  :: (MonadParsec e s m, MonadError (FinalParseError' e) m)
  => S.Set (ErrorFancy e) -> m a
finalFancyFailure :: forall e s (m :: * -> *) a.
(MonadParsec e s m, MonadError (FinalParseError' e) m) =>
Set (ErrorFancy e) -> m a
finalFancyFailure Set (ErrorFancy e)
errSet = do
  Int
offset <- forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
  forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError forall a b. (a -> b) -> a -> b
$ forall e. ParseError Text e -> FinalParseError' e
FinalError forall a b. (a -> b) -> a -> b
$ forall s e. Int -> Set (ErrorFancy e) -> ParseError s e
FancyError Int
offset Set (ErrorFancy e)
errSet

-- | Like 'fail', but as a "final" parse error.

finalFail
  :: (MonadParsec e s m, MonadError (FinalParseError' e) m) => String -> m a
finalFail :: forall e s (m :: * -> *) a.
(MonadParsec e s m, MonadError (FinalParseError' e) m) =>
String -> m a
finalFail = forall e s (m :: * -> *) a.
(MonadParsec e s m, MonadError (FinalParseError' e) m) =>
Set (ErrorFancy e) -> m a
finalFancyFailure forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. a -> Set a
S.singleton forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall e. String -> ErrorFancy e
ErrorFail

-- | Like megaparsec's 'customFailure', but as a "final" parse error.

finalCustomFailure
  :: (MonadParsec e s m, MonadError (FinalParseError' e) m) => e -> m a
finalCustomFailure :: forall e s (m :: * -> *) a.
(MonadParsec e s m, MonadError (FinalParseError' e) m) =>
e -> m a
finalCustomFailure = forall e s (m :: * -> *) a.
(MonadParsec e s m, MonadError (FinalParseError' e) m) =>
Set (ErrorFancy e) -> m a
finalFancyFailure forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. a -> Set a
S.singleton forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall e. e -> ErrorFancy e
ErrorCustom


--- * Pretty-printing "final" parse errors

-- | Pretty-print a "final" parse error: print the stack of include files,
-- then apply the pretty-printer for parse error bundles. Note that
-- 'attachSource' must be used on a "final" parse error before it can be
-- pretty-printed.

finalErrorBundlePretty :: FinalParseErrorBundle' HledgerParseErrorData -> String
finalErrorBundlePretty :: FinalParseErrorBundle' HledgerParseErrorData -> String
finalErrorBundlePretty FinalParseErrorBundle' HledgerParseErrorData
bundle =
     forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap ShowS
showIncludeFilepath (forall e. FinalParseErrorBundle' e -> [String]
includeFileStack FinalParseErrorBundle' HledgerParseErrorData
bundle)
  forall a. Semigroup a => a -> a -> a
<> ParseErrorBundle Text HledgerParseErrorData -> String
customErrorBundlePretty (forall e. FinalParseErrorBundle' e -> ParseErrorBundle Text e
finalErrorBundle FinalParseErrorBundle' HledgerParseErrorData
bundle)
  where
    showIncludeFilepath :: ShowS
showIncludeFilepath String
path = String
"in file included from " forall a. Semigroup a => a -> a -> a
<> String
path forall a. Semigroup a => a -> a -> a
<> String
",\n"

-- | Supply a filepath and source text to a "final" parse error so that it
-- can be pretty-printed. You must ensure that you provide the appropriate
-- source text and filepath.

attachSource
  :: FilePath -> Text -> FinalParseError' e -> FinalParseErrorBundle' e
attachSource :: forall e.
String -> Text -> FinalParseError' e -> FinalParseErrorBundle' e
attachSource String
filePath Text
sourceText FinalParseError' e
finalParseError = case FinalParseError' e
finalParseError of

  -- A parse error thrown directly with the 'FinalError' constructor
  -- requires both source and filepath.
  FinalError ParseError Text e
err ->
    let bundle :: ParseErrorBundle Text e
bundle = ParseErrorBundle
          { bundleErrors :: NonEmpty (ParseError Text e)
bundleErrors = ParseError Text e
err forall a. a -> [a] -> NonEmpty a
NE.:| []
          , bundlePosState :: PosState Text
bundlePosState = String -> Text -> PosState Text
initialPosState String
filePath Text
sourceText }
    in  FinalParseErrorBundle'
          { finalErrorBundle :: ParseErrorBundle Text e
finalErrorBundle = ParseErrorBundle Text e
bundle
          , includeFileStack :: [String]
includeFileStack  = [] }

  -- A 'ParseErrorBundle' already has the appropriate source and filepath
  -- and so needs neither.
  FinalBundle ParseErrorBundle Text e
peBundle -> FinalParseErrorBundle'
    { finalErrorBundle :: ParseErrorBundle Text e
finalErrorBundle = ParseErrorBundle Text e
peBundle
    , includeFileStack :: [String]
includeFileStack = [] }

  -- A parse error from a 'FinalParseErrorBundle' was thrown from an
  -- include file, so we add the filepath to the stack.
  FinalBundleWithStack FinalParseErrorBundle' e
fpeBundle -> FinalParseErrorBundle' e
fpeBundle
    { includeFileStack :: [String]
includeFileStack = String
filePath forall a. a -> [a] -> [a]
: forall e. FinalParseErrorBundle' e -> [String]
includeFileStack FinalParseErrorBundle' e
fpeBundle }


--- * Handling parse errors from include files with "final" parse errors

-- | Parse a file with the given parser and initial state, discarding the
-- final state and re-throwing any parse errors as "final" parse errors.

parseIncludeFile
  :: Monad m
  => StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m)) a
  -> st
  -> FilePath
  -> Text
  -> StateT st (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m)) a
parseIncludeFile :: forall (m :: * -> *) st a.
Monad m =>
StateT
  st
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  a
-> st
-> String
-> Text
-> StateT
     st
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     a
parseIncludeFile StateT
  st
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  a
parser st
initialState String
filepath Text
text =
  forall e (m :: * -> *) a.
MonadError e m =>
m a -> (e -> m a) -> m a
catchError StateT
  st
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  a
parser' forall {e} {m :: * -> *} {a}.
MonadError (FinalParseError' e) m =>
FinalParseError' e -> m a
handler
  where
    parser' :: StateT
  st
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  a
parser' = do
      Either (ParseErrorBundle Text HledgerParseErrorData) a
eResult <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall a b. (a -> b) -> a -> b
$ forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall a b. (a -> b) -> a -> b
$
                  forall (m :: * -> *) e s a.
Monad m =>
ParsecT e s m a
-> String -> s -> m (Either (ParseErrorBundle s e) a)
runParserT (forall (m :: * -> *) s a. Monad m => StateT s m a -> s -> m a
evalStateT StateT
  st
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  a
parser st
initialState) String
filepath Text
text
      case Either (ParseErrorBundle Text HledgerParseErrorData) a
eResult of
        Left ParseErrorBundle Text HledgerParseErrorData
parseErrorBundle -> forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError forall a b. (a -> b) -> a -> b
$ forall e. ParseErrorBundle Text e -> FinalParseError' e
FinalBundle ParseErrorBundle Text HledgerParseErrorData
parseErrorBundle
        Right a
result -> forall (f :: * -> *) a. Applicative f => a -> f a
pure a
result

    -- Attach source and filepath of the include file to its parse errors
    handler :: FinalParseError' e -> m a
handler FinalParseError' e
e = forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError forall a b. (a -> b) -> a -> b
$ forall e. FinalParseErrorBundle' e -> FinalParseError' e
FinalBundleWithStack forall a b. (a -> b) -> a -> b
$ forall e.
String -> Text -> FinalParseError' e -> FinalParseErrorBundle' e
attachSource String
filepath Text
text FinalParseError' e
e


--- * Helpers

-- Like megaparsec's 'initialState', but instead for 'PosState'. Used when
-- constructing 'ParseErrorBundle's. The values for "tab width" and "line
-- prefix" are taken from 'initialState'.

initialPosState :: FilePath -> Text -> PosState Text
initialPosState :: String -> Text -> PosState Text
initialPosState String
filePath Text
sourceText = PosState
  { pstateInput :: Text
pstateInput      = Text
sourceText
  , pstateOffset :: Int
pstateOffset     = Int
0
  , pstateSourcePos :: SourcePos
pstateSourcePos  = String -> SourcePos
initialPos String
filePath
  , pstateTabWidth :: Pos
pstateTabWidth   = Pos
defaultTabWidth
  , pstateLinePrefix :: String
pstateLinePrefix = String
"" }