--- * -*- outline-regexp:"--- *"; -*-
--- ** doc
-- In Emacs, use TAB on lines beginning with "-- *" to collapse/expand sections.
{-|

A reader for hledger's journal file format
(<http://hledger.org/hledger.html#the-journal-file>).  hledger's journal
format is a compatible subset of c++ ledger's
(<http://ledger-cli.org/3.0/doc/ledger3.html#Journal-Format>), so this
reader should handle many ledger files as well. Example:

@
2012\/3\/24 gift
    expenses:gifts  $10
    assets:cash
@

Journal format supports the include directive which can read files in
other formats, so the other file format readers need to be importable
and invocable here.

Some important parts of journal parsing are therefore kept in
Hledger.Read.Common, to avoid import cycles.

-}

--- ** language

{-# LANGUAGE FlexibleContexts    #-}
{-# LANGUAGE NamedFieldPuns      #-}
{-# LANGUAGE NoMonoLocalBinds    #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE PackageImports      #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiWayIf #-}

--- ** exports
module Hledger.Read.JournalReader (

  -- * Reader-finding utils
  findReader,
  splitReaderPrefix,

  -- * Reader
  reader,

  -- * Parsing utils
  parseAndFinaliseJournal,
  runJournalParser,
  rjp,
  runErroringJournalParser,
  rejp,

  -- * Parsers used elsewhere
  getParentAccount,
  journalp,
  directivep,
  defaultyeardirectivep,
  marketpricedirectivep,
  datetimep,
  datep,
  modifiedaccountnamep,
  tmpostingrulep,
  statusp,
  emptyorcommentlinep,
  followingcommentp,
  accountaliasp,
  parseAssertDirective

  -- * Tests
  ,tests_JournalReader
)
where

--- ** imports
import Control.Exception qualified as C
import Control.Monad (forM_, when, void, unless, filterM, forM, guard)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Except (ExceptT(..), runExceptT)
import Control.Monad.State.Strict (evalStateT,get,modify',put)
import Control.Monad.Trans.Class (lift)
import Data.Bifunctor (first)
import Data.Char (isDigit, isSpace, toLower)
import Data.Either (isRight, lefts)
import Data.Functor ((<&>))
import Data.Map.Strict qualified as M
import Data.Text (Text)
import Data.String
import Data.List
import Data.Maybe
import Data.Text qualified as T
import Data.Time.Calendar
import Data.Time.LocalTime
import Safe
import Text.Megaparsec hiding (parse)
import Text.Megaparsec.Char
import Text.Printf
import System.Directory (canonicalizePath, doesFileExist, makeAbsolute)
import System.Environment (lookupEnv)
import System.FilePath
import System.IO.Unsafe (unsafePerformIO)
import "Glob" System.FilePath.Glob hiding (match)
-- import "filepattern" System.FilePattern.Directory

import Hledger.Data
import Hledger.Query (parseQuery, querySplitRowTerms)
import Hledger.Read.Common
import Hledger.Utils

import Hledger.Read.CsvReader qualified as CsvReader (reader)
import Hledger.Read.RulesReader qualified as RulesReader (reader)
import Hledger.Read.TimeclockReader qualified as TimeclockReader (reader)
import Hledger.Read.TimedotReader qualified as TimedotReader (reader)
import Data.Function ((&))

--- ** doctest setup
-- $setup
-- >>> :set -XOverloadedStrings
--
--- ** parsing utilities

-- | Run a journal parser in some monad. See also: parseWithState.
runJournalParser, rjp
  :: Monad m
  => JournalParser m a -> Text -> m (Either HledgerParseErrors a)
runJournalParser :: forall (m :: * -> *) a.
Monad m =>
JournalParser m a -> Text -> m (Either HledgerParseErrors a)
runJournalParser JournalParser m a
p = ParsecT HledgerParseErrorData Text m a
-> String -> Text -> m (Either HledgerParseErrors a)
forall (m :: * -> *) e s a.
Monad m =>
ParsecT e s m a
-> String -> s -> m (Either (ParseErrorBundle s e) a)
runParserT (JournalParser m a
-> Journal -> ParsecT HledgerParseErrorData Text m a
forall (m :: * -> *) s a. Monad m => StateT s m a -> s -> m a
evalStateT JournalParser m a
p Journal
nulljournal) String
""
rjp :: forall (m :: * -> *) a.
Monad m =>
JournalParser m a -> Text -> m (Either HledgerParseErrors a)
rjp = JournalParser m a -> Text -> m (Either HledgerParseErrors a)
forall (m :: * -> *) a.
Monad m =>
JournalParser m a -> Text -> m (Either HledgerParseErrors a)
runJournalParser

-- | Run an erroring journal parser in some monad. See also: parseWithState.
runErroringJournalParser, rejp
  :: Monad m
  => ErroringJournalParser m a
  -> Text
  -> m (Either FinalParseError (Either HledgerParseErrors a))
runErroringJournalParser :: forall (m :: * -> *) a.
Monad m =>
ErroringJournalParser m a
-> Text -> m (Either FinalParseError (Either HledgerParseErrors a))
runErroringJournalParser ErroringJournalParser m a
p Text
t =
  ExceptT FinalParseError m (Either HledgerParseErrors a)
-> m (Either FinalParseError (Either HledgerParseErrors a))
forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT (ExceptT FinalParseError m (Either HledgerParseErrors a)
 -> m (Either FinalParseError (Either HledgerParseErrors a)))
-> ExceptT FinalParseError m (Either HledgerParseErrors a)
-> m (Either FinalParseError (Either HledgerParseErrors a))
forall a b. (a -> b) -> a -> b
$ ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m) a
-> String
-> Text
-> ExceptT FinalParseError m (Either HledgerParseErrors a)
forall (m :: * -> *) e s a.
Monad m =>
ParsecT e s m a
-> String -> s -> m (Either (ParseErrorBundle s e) a)
runParserT (ErroringJournalParser m a
-> Journal
-> ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m) a
forall (m :: * -> *) s a. Monad m => StateT s m a -> s -> m a
evalStateT ErroringJournalParser m a
p Journal
nulljournal) String
"" Text
t
rejp :: forall (m :: * -> *) a.
Monad m =>
ErroringJournalParser m a
-> Text -> m (Either FinalParseError (Either HledgerParseErrors a))
rejp = ErroringJournalParser m a
-> Text -> m (Either FinalParseError (Either HledgerParseErrors a))
forall (m :: * -> *) a.
Monad m =>
ErroringJournalParser m a
-> Text -> m (Either FinalParseError (Either HledgerParseErrors a))
runErroringJournalParser


--- ** reader finding utilities
-- Defined here rather than Hledger.Read so that we can use them in includedirectivep below.

-- The available journal readers, each one handling a particular data format.
readers' :: MonadIO m => [Reader m]
readers' :: forall (m :: * -> *). MonadIO m => [Reader m]
readers' = [
  Reader m
forall (m :: * -> *). MonadIO m => Reader m
reader
 ,Reader m
forall (m :: * -> *). MonadIO m => Reader m
TimeclockReader.reader
 ,Reader m
forall (m :: * -> *). MonadIO m => Reader m
TimedotReader.reader
 ,Reader m
forall (m :: * -> *). MonadIO m => Reader m
RulesReader.reader
 ,SepFormat -> Reader m
forall (m :: * -> *). MonadIO m => SepFormat -> Reader m
CsvReader.reader SepFormat
Csv
 ,SepFormat -> Reader m
forall (m :: * -> *). MonadIO m => SepFormat -> Reader m
CsvReader.reader SepFormat
Tsv
 ,SepFormat -> Reader m
forall (m :: * -> *). MonadIO m => SepFormat -> Reader m
CsvReader.reader SepFormat
Ssv
--  ,LedgerReader.reader
 ]

readerNames :: [String]
readerNames :: [String]
readerNames = (Reader IO -> String) -> [Reader IO] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (StorageFormat -> String
forall a. Show a => a -> String
show (StorageFormat -> String)
-> (Reader IO -> StorageFormat) -> Reader IO -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Reader IO -> StorageFormat
forall (m :: * -> *). Reader m -> StorageFormat
rFormat) ([Reader IO]
forall (m :: * -> *). MonadIO m => [Reader m]
readers'::[Reader IO])

-- | @findReader mformat mpath@
--
-- Find the reader named by @mformat@, if provided.
-- ("ssv" and "tsv" are recognised as alternate names for the csv reader,
-- which also handles those formats.)
-- Or, if a file path is provided, find the first reader that handles
-- its file extension, if any.
findReader :: MonadIO m => Maybe StorageFormat -> Maybe FilePath -> Maybe (Reader m)
findReader :: forall (m :: * -> *).
MonadIO m =>
Maybe StorageFormat -> Maybe String -> Maybe (Reader m)
findReader Maybe StorageFormat
Nothing Maybe String
Nothing     = Maybe (Reader m)
forall a. Maybe a
Nothing
findReader (Just StorageFormat
fmt) Maybe String
_        = [Reader m] -> Maybe (Reader m)
forall a. [a] -> Maybe a
headMay [Reader m
r | Reader m
r <- [Reader m]
forall (m :: * -> *). MonadIO m => [Reader m]
readers', let rname :: StorageFormat
rname = Reader m -> StorageFormat
forall (m :: * -> *). Reader m -> StorageFormat
rFormat Reader m
r, StorageFormat
rname StorageFormat -> StorageFormat -> Bool
forall a. Eq a => a -> a -> Bool
== StorageFormat
fmt]
findReader Maybe StorageFormat
Nothing (Just String
path) =
  case Maybe StorageFormat
prefix of
    Just StorageFormat
fmt -> [Reader m] -> Maybe (Reader m)
forall a. [a] -> Maybe a
headMay [Reader m
r | Reader m
r <- [Reader m]
forall (m :: * -> *). MonadIO m => [Reader m]
readers', Reader m -> StorageFormat
forall (m :: * -> *). Reader m -> StorageFormat
rFormat Reader m
r StorageFormat -> StorageFormat -> Bool
forall a. Eq a => a -> a -> Bool
== StorageFormat
fmt]
    Maybe StorageFormat
Nothing  -> [Reader m] -> Maybe (Reader m)
forall a. [a] -> Maybe a
headMay [Reader m
r | Reader m
r <- [Reader m]
forall (m :: * -> *). MonadIO m => [Reader m]
readers', String
ext String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` Reader m -> [String]
forall (m :: * -> *). Reader m -> [String]
rExtensions Reader m
r]
  where
    (Maybe StorageFormat
prefix,String
path') = String -> (Maybe StorageFormat, String)
splitReaderPrefix String
path
    ext :: String
ext            = (Char -> Char) -> String -> String
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ Int -> String -> String
forall a. Int -> [a] -> [a]
drop Int
1 (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ String -> String
takeExtension String
path'

-- | Separate a file path and its reader prefix, if any.
--
-- >>> splitReaderPrefix "csv:-"
-- (Just csv,"-")
splitReaderPrefix :: PrefixedFilePath -> (Maybe StorageFormat, FilePath)
splitReaderPrefix :: String -> (Maybe StorageFormat, String)
splitReaderPrefix String
f =
  let 
    candidates :: [(Maybe String, String)]
candidates = [(String -> Maybe String
forall a. a -> Maybe a
Just String
r, Int -> String -> String
forall a. Int -> [a] -> [a]
drop (String -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length String
r Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1) String
f) | String
r <- [String]
readerNames [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [String
"ssv",String
"tsv"], (String
rString -> String -> String
forall a. [a] -> [a] -> [a]
++String
":") String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf` String
f]
    (Maybe String
strPrefix, String
newF) = (Maybe String, String)
-> [(Maybe String, String)] -> (Maybe String, String)
forall a. a -> [a] -> a
headDef (Maybe String
forall a. Maybe a
Nothing, String
f) [(Maybe String, String)]
candidates
  in case Maybe String
strPrefix of
    Just String
"csv" -> (StorageFormat -> Maybe StorageFormat
forall a. a -> Maybe a
Just (SepFormat -> StorageFormat
Sep SepFormat
Csv), String
newF)
    Just String
"tsv" -> (StorageFormat -> Maybe StorageFormat
forall a. a -> Maybe a
Just (SepFormat -> StorageFormat
Sep SepFormat
Tsv), String
newF)
    Just String
"ssv" -> (StorageFormat -> Maybe StorageFormat
forall a. a -> Maybe a
Just (SepFormat -> StorageFormat
Sep SepFormat
Ssv), String
newF)
    Just String
"journal" -> (StorageFormat -> Maybe StorageFormat
forall a. a -> Maybe a
Just StorageFormat
Journal', String
newF)
    Just String
"timeclock" -> (StorageFormat -> Maybe StorageFormat
forall a. a -> Maybe a
Just StorageFormat
Timeclock, String
newF)
    Just String
"timedot" -> (StorageFormat -> Maybe StorageFormat
forall a. a -> Maybe a
Just StorageFormat
Timedot, String
newF)
    Maybe String
_ -> (Maybe StorageFormat
forall a. Maybe a
Nothing, String
f)

-- -- | Does this file path have a reader prefix ?
-- hasReaderPrefix :: PrefixedFilePath -> Bool
-- hasReaderPrefix = isJust . fst. splitReaderPrefix

-- -- | Add a reader prefix to a file path, unless it already has one.
-- -- The argument should be a valid reader name.
-- --
-- -- >>> addReaderPrefix "csv" "a.txt"
-- -- >>> "csv:a.txt"
-- -- >>> addReaderPrefix "csv" "timedot:a.txt"
-- -- >>> "timedot:a.txt"
-- addReaderPrefix :: ReaderPrefix -> FilePath -> PrefixedFilePath
-- addReaderPrefix readername f
--   | hasReaderPrefix f = f
--   | otherwise = readername <> ":" <> f

--- ** reader

reader :: MonadIO m => Reader m
reader :: forall (m :: * -> *). MonadIO m => Reader m
reader = Reader
  {rFormat :: StorageFormat
rFormat     = StorageFormat
Journal'
  ,rExtensions :: [String]
rExtensions = [String
"journal", String
"j", String
"hledger", String
"ledger"]
  ,rReadFn :: InputOpts -> String -> Handle -> ExceptT String IO Journal
rReadFn     = (InputOpts -> String -> Text -> ExceptT String IO Journal)
-> InputOpts -> String -> Handle -> ExceptT String IO Journal
handleReadFnToTextReadFn InputOpts -> String -> Text -> ExceptT String IO Journal
parse
  ,rParser :: MonadIO m => InputOpts -> ErroringJournalParser m Journal
rParser    = MonadIO m => InputOpts -> ErroringJournalParser m Journal
InputOpts -> ErroringJournalParser m Journal
forall (m :: * -> *).
MonadIO m =>
InputOpts -> ErroringJournalParser m Journal
journalp  -- no need to add command line aliases like journalp'
                           -- when called as a subparser I think
  }

-- | Parse and post-process a "Journal" from hledger's journal file
-- format, or give an error.
parse :: InputOpts -> FilePath -> Text -> ExceptT String IO Journal
parse :: InputOpts -> String -> Text -> ExceptT String IO Journal
parse InputOpts
iopts String
f = ErroringJournalParser IO Journal
-> InputOpts -> String -> Text -> ExceptT String IO Journal
parseAndFinaliseJournal ErroringJournalParser IO Journal
journalp' InputOpts
iopts String
f
  where
    journalp' :: ErroringJournalParser IO Journal
journalp' = do
      (Journal -> Journal)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO))
     ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' (\Journal
j -> Journal
j{jparseoptaliases = aliasesFromOpts iopts})
      InputOpts -> ErroringJournalParser IO Journal
forall (m :: * -> *).
MonadIO m =>
InputOpts -> ErroringJournalParser m Journal
journalp InputOpts
iopts

--- ** parsers
--- *** journal

-- | A journal parser. Accumulates and returns a "ParsedJournal",
-- which should be finalised/validated before use.
--
-- >>> rejp (journalp definputopts <* eof) "2015/1/1\n a  0\n"
-- Right (Right Journal (unknown) with 1 transactions, 1 accounts)
--
journalp :: MonadIO m => InputOpts -> ErroringJournalParser m ParsedJournal
journalp :: forall (m :: * -> *).
MonadIO m =>
InputOpts -> ErroringJournalParser m Journal
journalp InputOpts
iopts = do
  StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     [()]
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
many (StateT
   Journal
   (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
   ()
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
      [()])
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     [()]
forall a b. (a -> b) -> a -> b
$ InputOpts
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall (m :: * -> *).
MonadIO m =>
InputOpts -> ErroringJournalParser m ()
addJournalItemP InputOpts
iopts
  StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall e s (m :: * -> *). MonadParsec e s m => m ()
eof
  (Journal -> Journal)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' ((Journal -> Journal)
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
      ())
-> (Journal -> Journal)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall a b. (a -> b) -> a -> b
$ \Journal
j -> Journal
j{jparsepos = Nothing, jparseamountstyles = mempty, jparsetexts = mempty}  -- drop parse-time state that is only meaningful during parsing
  StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  Journal
forall s (m :: * -> *). MonadState s m => m s
get

-- | A side-effecting parser; parses any kind of journal item
-- and updates the parse state accordingly.
-- Every item is also recorded in jitems, so the file can be reproduced.
addJournalItemP :: MonadIO m => InputOpts -> ErroringJournalParser m ()
addJournalItemP :: forall (m :: * -> *).
MonadIO m =>
InputOpts -> ErroringJournalParser m ()
addJournalItemP InputOpts
iopts = (StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
-> String
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"transaction or directive") (StateT
   Journal
   (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
   ()
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
      ())
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall a b. (a -> b) -> a -> b
$ do
  -- Journal item types can be told apart by their first character. Where that
  -- is unambiguous, go straight to the right parser: trying every alternative
  -- for every item (mostly transactions and blank lines) was a large parsing cost.
  -- The fallbacks keep the error messages the same as before.
  c <- StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  Char
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     Char
forall a.
StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  a
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
lookAhead StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  Char
StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  (Token Text)
forall e s (m :: * -> *). MonadParsec e s m => m (Token s)
anySingle
  if | isDigit c                         -> transactionitem
     | c == 'P'                          -> priceitem <|> anyitem
     | isSpace c || isLineCommentStart c -> blankorcommentitem <|> anyitem
     | otherwise                         -> anyitem
  where
    transactionitem :: StateT Journal (ParsecT HledgerParseErrorData Text m) ()
transactionitem    = JournalParser m Transaction
forall (m :: * -> *). JournalParser m Transaction
transactionOrFastp JournalParser m Transaction
-> (Transaction
    -> StateT Journal (ParsecT HledgerParseErrorData Text m) ())
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> (a -> StateT Journal (ParsecT HledgerParseErrorData Text m) b)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (Journal -> Journal)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' ((Journal -> Journal)
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) ())
-> (Transaction -> Journal -> Journal)
-> Transaction
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> Journal -> Journal
addTransactionItem   -- (fastPathEnabled disables the fast path)
    priceitem :: StateT Journal (ParsecT HledgerParseErrorData Text m) ()
priceitem          = (Text -> JournalItem)
-> JournalParser m PriceDirective -> JournalParser m PriceDirective
forall (m :: * -> *) a.
(Text -> JournalItem) -> JournalParser m a -> JournalParser m a
recordItem Text -> JournalItem
JIDirective JournalParser m PriceDirective
forall (m :: * -> *). JournalParser m PriceDirective
marketpriceOrFastp JournalParser m PriceDirective
-> (PriceDirective
    -> StateT Journal (ParsecT HledgerParseErrorData Text m) ())
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> (a -> StateT Journal (ParsecT HledgerParseErrorData Text m) b)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (Journal -> Journal)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' ((Journal -> Journal)
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) ())
-> (PriceDirective -> Journal -> Journal)
-> PriceDirective
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PriceDirective -> Journal -> Journal
addPriceDirective
    blankorcommentitem :: JournalParser m ()
blankorcommentitem = (Text -> JournalItem) -> JournalParser m () -> JournalParser m ()
forall (m :: * -> *) a.
(Text -> JournalItem) -> JournalParser m a -> JournalParser m a
recordItem Text -> JournalItem
commentOrBlankItem (JournalParser m () -> JournalParser m ())
-> JournalParser m () -> JournalParser m ()
forall a b. (a -> b) -> a -> b
$ ParsecT HledgerParseErrorData Text m () -> JournalParser m ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall (m :: * -> *). TextParser m ()
emptyorcommentlinep
    anyitem :: StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
anyitem = [StateT
   Journal
   (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
   ()]
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall (f :: * -> *) (m :: * -> *) a.
(Foldable f, Alternative m) =>
f (m a) -> m a
choice [
        InputOpts
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall (m :: * -> *).
MonadIO m =>
InputOpts -> ErroringJournalParser m ()
directivep InputOpts
iopts
      , StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
transactionitem
      , (Text -> JournalItem)
-> JournalParser (ExceptT FinalParseError m) TransactionModifier
-> JournalParser (ExceptT FinalParseError m) TransactionModifier
forall (m :: * -> *) a.
(Text -> JournalItem) -> JournalParser m a -> JournalParser m a
recordItem Text -> JournalItem
JIDirective JournalParser (ExceptT FinalParseError m) TransactionModifier
forall (m :: * -> *). JournalParser m TransactionModifier
transactionmodifierp  JournalParser (ExceptT FinalParseError m) TransactionModifier
-> (TransactionModifier
    -> StateT
         Journal
         (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
         ())
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall a b.
StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  a
-> (a
    -> StateT
         Journal
         (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
         b)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (Journal -> Journal)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' ((Journal -> Journal)
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
      ())
-> (TransactionModifier -> Journal -> Journal)
-> TransactionModifier
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TransactionModifier -> Journal -> Journal
addTransactionModifier
      , (Text -> JournalItem)
-> JournalParser (ExceptT FinalParseError m) PeriodicTransaction
-> JournalParser (ExceptT FinalParseError m) PeriodicTransaction
forall (m :: * -> *) a.
(Text -> JournalItem) -> JournalParser m a -> JournalParser m a
recordItem Text -> JournalItem
JIDirective JournalParser (ExceptT FinalParseError m) PeriodicTransaction
forall (m :: * -> *).
MonadIO m =>
JournalParser m PeriodicTransaction
periodictransactionp  JournalParser (ExceptT FinalParseError m) PeriodicTransaction
-> (PeriodicTransaction
    -> StateT
         Journal
         (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
         ())
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall a b.
StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  a
-> (a
    -> StateT
         Journal
         (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
         b)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (Journal -> Journal)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' ((Journal -> Journal)
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
      ())
-> (PeriodicTransaction -> Journal -> Journal)
-> PeriodicTransaction
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PeriodicTransaction -> Journal -> Journal
addPeriodicTransaction
      , StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
priceitem
      , StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
blankorcommentitem
      , (Text -> JournalItem)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall (m :: * -> *) a.
(Text -> JournalItem) -> JournalParser m a -> JournalParser m a
recordItem Text -> JournalItem
JICommentBlock (StateT
   Journal
   (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
   ()
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
      ())
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall a b. (a -> b) -> a -> b
$ ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m) ()
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m) ()
forall (m :: * -> *). TextParser m ()
multilinecommentp
      ]
    commentOrBlankItem :: Text -> JournalItem
commentOrBlankItem Text
txt = if (Char -> Bool) -> Text -> Bool
T.all Char -> Bool
isSpace Text
txt then JournalItem
JIBlank else Text -> JournalItem
JIComment Text
txt

-- | Run a parser, also recording the text it consumed as a journal item of the given kind.
recordItem :: (Text -> JournalItem) -> JournalParser m a -> JournalParser m a
recordItem :: forall (m :: * -> *) a.
(Text -> JournalItem) -> JournalParser m a -> JournalParser m a
recordItem Text -> JournalItem
mkitem JournalParser m a
p = do
  -- This is like megaparsec's `match`, but written out; `match` was found to allocate
  -- ~20KB per item here, costing ~9% of total run time on a 100k-transaction journal.
  -- Note T.take does not copy bytes: it returns a small Text value (array pointer, offset, length)
  -- viewing the same byte array as the remaining input, which is the whole file's text, already
  -- kept in jfiles. So each jitems entry costs a few words, however long its text is,
  -- and jitems adds little memory even though it holds every directive and comment line verbatim.
  o <- StateT Journal (ParsecT HledgerParseErrorData Text m) Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
  s <- getInput
  a <- p
  o' <- getOffset
  modify' $ addJournalItem $ mkitem $ T.take (o' - o) s
  return a

--- *** directives

-- | Parse any journal directive and update the parse state accordingly,
-- and record it as a journal item (exported or not by print --export).
-- Cf http://hledger.org/hledger.html#directives,
-- http://ledger-cli.org/3.0/doc/ledger3.html#Command-Directives
directivep :: MonadIO m => InputOpts -> ErroringJournalParser m ()
directivep :: forall (m :: * -> *).
MonadIO m =>
InputOpts -> ErroringJournalParser m ()
directivep InputOpts
iopts = (do
  StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  Char
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     (Maybe Char)
forall (f :: * -> *) a. Alternative f => f a -> f (Maybe a)
optional (StateT
   Journal
   (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
   Char
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
      (Maybe Char))
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     Char
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     (Maybe Char)
forall a b. (a -> b) -> a -> b
$ [Token Text]
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     (Token Text)
forall (f :: * -> *) e s (m :: * -> *).
(Foldable f, MonadParsec e s m) =>
f (Token s) -> m (Token s)
oneOf [Char
'!',Char
'@']
  [StateT
   Journal
   (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
   ()]
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall (f :: * -> *) (m :: * -> *) a.
(Foldable f, Alternative m) =>
f (m a) -> m a
choice [
    InputOpts
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall (m :: * -> *).
MonadIO m =>
InputOpts -> ErroringJournalParser m ()
includedirectivep InputOpts
iopts
   -- directives which print --export reproduces
   ,(Text -> JournalItem)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall (m :: * -> *) a.
(Text -> JournalItem) -> JournalParser m a -> JournalParser m a
recordItem Text -> JournalItem
JIDirective (StateT
   Journal
   (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
   ()
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
      ())
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall a b. (a -> b) -> a -> b
$ [StateT
   Journal
   (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
   ()]
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall (f :: * -> *) (m :: * -> *) a.
(Foldable f, Alternative m) =>
f (m a) -> m a
choice [
     StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
accountdirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
commoditydirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
decimalmarkdirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
defaultyeardirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
defaultcommoditydirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
payeedirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
tagdirectivep
    ,Day -> JournalParser (ExceptT FinalParseError m) AssertDirective
forall (m :: * -> *).
Monad m =>
Day -> JournalParser m AssertDirective
assertdirectivep (InputOpts -> Day
_ioDay InputOpts
iopts) JournalParser (ExceptT FinalParseError m) AssertDirective
-> (AssertDirective
    -> StateT
         Journal
         (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
         ())
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall a b.
StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  a
-> (a
    -> StateT
         Journal
         (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
         b)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (Journal -> Journal)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' ((Journal -> Journal)
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
      ())
-> (AssertDirective -> Journal -> Journal)
-> AssertDirective
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AssertDirective -> Journal -> Journal
addAssertDirective
    ]
   -- directives which print --export does not reproduce:
   -- those whose effect is already applied to the parsed data,
   -- and the Ledger directives which hledger ignores.
   -- (endtagdirectivep consumes "end" before failing, so it must come after the other end directives.)
   ,(Text -> JournalItem)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall (m :: * -> *) a.
(Text -> JournalItem) -> JournalParser m a -> JournalParser m a
recordItem Text -> JournalItem
JINonExportedDirective (StateT
   Journal
   (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
   ()
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
      ())
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall a b. (a -> b) -> a -> b
$ [StateT
   Journal
   (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
   ()]
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall (f :: * -> *) (m :: * -> *) a.
(Foldable f, Alternative m) =>
f (m a) -> m a
choice [
     StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
aliasdirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
endaliasesdirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
applyaccountdirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
applyyeardirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
bareenddirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
endapplyaccountdirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
endapplyyeardirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
applyfixeddirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
applytagdirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
bucketdirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
capturedirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
checkdirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
commandlineflagdirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
commodityconversiondirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
definedirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
endapplyfixeddirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
endapplytagdirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
endtagdirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
evaldirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
exprdirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
ignoredpricecommoditydirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
pythondirectivep
    ,StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
valuedirectivep
    ]
   ]
  ) StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  ()
-> String
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"directive"

-- | Parse an include directive, and the file(s) it refers to, possibly recursively.
-- Input options are required since they may affect parsing (of timeclock files, specifically).
-- include's argument is a file path or glob pattern (see findMatchedFiles for details),
-- optionally with a file type prefix. Relative paths are relative to the current file.
includedirectivep :: MonadIO m => InputOpts -> ErroringJournalParser m ()
includedirectivep :: forall (m :: * -> *).
MonadIO m =>
InputOpts -> ErroringJournalParser m ()
includedirectivep InputOpts
iopts = do
  -- save the position at start of include directive, for error messages
  eoff <- StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
  pos <- getSourcePos'
  let errorNoArg = HledgerParseErrorData
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     a
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
      a)
-> HledgerParseErrorData
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     a
forall a b. (a -> b) -> a -> b
$ Int -> String -> HledgerParseErrorData
parseErrorAt Int
eoff String
"include needs a file path or glob pattern argument"

  -- parse the directive, and record it as a journal item (before the included files' items)
  prefixedglob <- recordItem JIInclude $ do
    string "include"
    -- notFollowedBy newline <?> "a file path or glob pattern argument"
    (do
      lift skipNonNewlineSpaces1
      prefixedglob <- rstrip . T.unpack <$> takeWhileP Nothing (`notElem` [';','\n'])
      lift followingcommentp
      return prefixedglob
      ) <|> errorNoArg

  let (mprefix,path) = splitReaderPrefix prefixedglob
  parentf <- sourcePosFilePath pos
  when (null $ dbg6 (parentf <> " include: path ") path) errorNoArg

  -- Find the file or glob-matched files (just the ones from this include directive), with some IO error checking.
  paths <- findMatchedFiles eoff parentf path
  -- Also report whether a glob pattern was used, and not just a literal file path.
  -- (paths, isglob) <- findMatchedFiles off pos glb

  -- XXX worth the trouble ? no
  -- Comprehensively exclude files already processed. Some complexities here:
  -- If this include directive uses a glob pattern, remove duplicates. 
  -- Ie if this glob pattern matches any files we have already processed (or the current file),
  -- due to multiple includes in sequence or in a cycle, exclude those files so they're not processed again.
  -- If this include directive uses a literal file path, don't remove duplicates.
  -- Multiple includes in sequence will cause the included file to be processed multiple times.
  -- Multiple includes forming a cycle will be detected and reported as an error in parseIncludedFile.
  -- let paths' = if isglob then filter (...) paths else paths

  -- if there was a reader prefix, apply it to all the file paths
  let prefixedpaths = case Maybe StorageFormat
mprefix of
        Maybe StorageFormat
Nothing  -> [String]
paths
        Just StorageFormat
fmt -> (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map ((StorageFormat -> String
forall a. Show a => a -> String
show StorageFormat
fmtString -> String -> String
forall a. [a] -> [a] -> [a]
++String
":")String -> String -> String
forall a. [a] -> [a] -> [a]
++) [String]
paths

  -- Parse each one, as if inlined here.
  -- Or when just finding the files read, record a missing one and carry on.
  forM_ prefixedpaths $ \String
p -> do
    let f :: String
f = (Maybe StorageFormat, String) -> String
forall a b. (a, b) -> b
snd ((Maybe StorageFormat, String) -> String)
-> (Maybe StorageFormat, String) -> String
forall a b. (a -> b) -> a -> b
$ String -> (Maybe StorageFormat, String)
splitReaderPrefix String
p
    missing <- IO Bool
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     Bool
forall a.
IO a
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO Bool
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
      Bool)
-> IO Bool
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     Bool
forall a b. (a -> b) -> a -> b
$ Bool -> Bool
not (Bool -> Bool) -> IO Bool -> IO Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> IO Bool
doesFileExist String
f
    if _scanfiles iopts && missing
    then modify' $ \Journal
pj -> Journal
pj{jfiles = JournalFile f T.empty (length $ jparseincludefilestack pj) : jfiles pj}
    else parseIncludedFile iopts eoff p

  where

    -- | Find the files matched by a literal path or a glob pattern.
    -- Examples: foo.j, ../foo/bar.j, timedot:/foo/2020*, *.journal, **.journal.
    --
    -- Uses the current parse context for detecting the current directory and for error messages.
    -- Expands a leading tilde to the user's home directory.
    -- Converts ** without a slash to **/*, like zsh's GLOB_STAR_SHORT, so ** also matches file name parts.
    -- Checks if any matched paths are directories and excludes those.
    -- Converts all matched paths to their canonical form.
    -- Note * and ** mostly won't implicitly match dot files or dot directories,
    -- but ** will implicitly search non-top-level dot directories (see #2498, Glob#49).

    findMatchedFiles :: (MonadIO m) => Int -> FilePath -> FilePath -> JournalParser m [FilePath]
    findMatchedFiles :: forall (m :: * -> *).
MonadIO m =>
Int -> String -> String -> JournalParser m [String]
findMatchedFiles Int
off String
parentf String
path = do

      -- Some notes about the Glob library that we use (related: https://github.com/Deewiant/glob/issues/49):
      -- It does not expand tilde.
      -- It does not canonicalise paths.
      -- The results are not in any particular order.
      -- The results can include directories.
      -- DIRPAT/ is equivalent to DIRPAT, except results will end with // (double slash).
      -- A . or .. path component can match the current or parent directories (including them in the results).
      -- * matches zero or more characters in a file or directory name.
      -- * at the start of a file name ignores dot-named files and directories, by default.
      -- ** (or zero or more consecutive *'s) not followed by slash is equivalent to *.
      -- A **/ component matches any number of directory parts.
      -- A **/ does not implicitly search top-level dot directories or implicitly match do files,
      -- but it does search non-top-level dot directories. Eg ** will find the c file in a/.b/c.
      -- It tends to get attributes of all files in a directory.

      -- expand a tilde at the start of the glob pattern, or throw an error
      expandedpath <- ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (ParsecT HledgerParseErrorData Text m String
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) String)
-> ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a b. (a -> b) -> a -> b
$ String -> IO String
expandHomePath String
path IO String
-> (IO String -> ParsecT HledgerParseErrorData Text m String)
-> ParsecT HledgerParseErrorData Text m String
forall a b. a -> (a -> b) -> b
& Int
-> String
-> IO String
-> ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *) a.
MonadIO m =>
Int -> String -> IO a -> TextParser m a
handleIOError Int
off String
"failed to expand ~"

      -- get the directory of the including file
      -- need to canonicalise a symlink parentf so takeDirectory works correctly [#2503]
      cwd <- fmap takeDirectory <$> liftIO $ canonicalizePath parentf

      -- Don't allow 3 or more stars.
      when ("***" `isInfixOf` expandedpath) $
        customFailure $ parseErrorAt off $ "Invalid glob pattern: too many stars, use * or **"

      -- Make ** also match file name parts like zsh's GLOB_STAR_SHORT.
      let
        finalpath =
          -- ** without a slash is equivalent to **/*
          case Regexp -> String -> String -> Either String String
regexReplace (Text -> Regexp
toRegex' (Text -> Regexp) -> Text -> Regexp
forall a b. (a -> b) -> a -> b
$ String -> Text
T.pack String
"\\*\\*([^/\\])") String
"**/*\\1" String
expandedpath of
            Right String
s -> String
s
            Left  String
_ -> String
expandedpath   -- ignore any error, there should be none

      -- Compile as a Pattern. Can throw an error.
      pat <- case tryCompileWith compDefault{errorRecovery=False} finalpath of
        Left String
e  -> HledgerParseErrorData
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Pattern
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) Pattern)
-> HledgerParseErrorData
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Pattern
forall a b. (a -> b) -> a -> b
$ Int -> String -> HledgerParseErrorData
parseErrorAt Int
off (String -> HledgerParseErrorData)
-> String -> HledgerParseErrorData
forall a b. (a -> b) -> a -> b
$ String
"Invalid glob pattern: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
e
        Right Pattern
x -> Pattern
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Pattern
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Pattern
x

      -- Find all paths matched by the glob pattern.
      -- If it is a literal (non-glob) path, don't use the Glob lib, because it gets attributes
      -- of all files in the directory, which confuses build systems like tup.
      paths <-
        if isLiteral pat
        then return $ if isAbsolute finalpath then [finalpath] else [cwd </> finalpath]
        else liftIO $ globDir1 pat cwd

      -- Exclude any directories or symlinks to directories, and canonicalise, and sort.
      files <- liftIO $
        filterM doesFileExist paths
        >>= mapM makeAbsolute
        <&> sort

      -- Throw an error if one of these files is among the grandparent files, forming a cycle.
      -- Though, ignore the immediate parent file for convenience. XXX inconsistent - should it ignore all cyclic includes ?
      -- Use canonical paths for cycle detection, show nominal absolute paths in error messages.
      parentj <- get
      let parentfiles = Journal -> [(String, String)]
jparseincludefilestack Journal
parentj
          cparentfiles = ((String, String) -> String) -> [(String, String)] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (String, String) -> String
forall a b. (a, b) -> b
snd [(String, String)]
parentfiles
          cparentf = Int -> [String] -> [String]
forall a. Int -> [a] -> [a]
take Int
1 [String]
cparentfiles
      files2 <- forM files $ \String
f -> do
        cf <- IO String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a.
IO a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) String)
-> IO String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a b. (a -> b) -> a -> b
$ String -> IO String
canonicalizePath String
f
        if
          | [cf] == cparentf -> return cf  -- current file - return canonicalised, will be excluded later
          | cf `elem` drop 1 cparentfiles -> customFailure $ parseErrorAt off $ "This included file forms a cycle: " ++ f
          | otherwise -> return f

      -- Throw an error if no files were matched.
      -- Or when just finding the files read, return the path or pattern itself, to be recorded as missing.
      let unmatched = [if String -> Bool
isAbsolute String
finalpath then String
finalpath else String
cwd String -> String -> String
</> String
finalpath]
      when (null files2 && not (_scanfiles iopts)) $ customFailure $ parseErrorAt off $ "No files were matched by: " ++ path

      -- If the current file got included, ignore it (last, to avoid triggering the error above).
      let
        files3 =
          String -> [String] -> [String]
forall a. Show a => String -> a -> a
dbg6 (String
parentf String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" include: matched files (excluding current file)") ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$
          if [String] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [String]
files2 then [String]
unmatched else (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not(Bool -> Bool) -> (String -> Bool) -> String -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
.(String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [String]
cparentf)) [String]
files2

      return files3

    -- Parse the given included file (and any deeper includes, recursively) as if it was inlined in the current (parent) file.
    -- The offset of the start of the include directive in the parent file is provided for error messages.
    parseIncludedFile :: MonadIO m => InputOpts -> Int -> PrefixedFilePath -> ErroringJournalParser m ()
    parseIncludedFile :: forall (m :: * -> *).
MonadIO m =>
InputOpts -> Int -> String -> ErroringJournalParser m ()
parseIncludedFile InputOpts
iopts1 Int
off String
prefixedpath = do
      let (Maybe StorageFormat
_mprefix,String
filepath) = String -> (Maybe StorageFormat, String)
splitReaderPrefix String
prefixedpath

      -- Choose a reader based on the file path prefix or file extension,
      -- defaulting to JournalReader. Duplicating readJournal a bit here.
      let r :: Reader m
r = Reader m -> Maybe (Reader m) -> Reader m
forall a. a -> Maybe a -> a
fromMaybe Reader m
forall (m :: * -> *). MonadIO m => Reader m
reader (Maybe (Reader m) -> Reader m) -> Maybe (Reader m) -> Reader m
forall a b. (a -> b) -> a -> b
$ Maybe StorageFormat -> Maybe String -> Maybe (Reader m)
forall (m :: * -> *).
MonadIO m =>
Maybe StorageFormat -> Maybe String -> Maybe (Reader m)
findReader Maybe StorageFormat
forall a. Maybe a
Nothing (String -> Maybe String
forall a. a -> Maybe a
Just String
prefixedpath)
          parser :: ErroringJournalParser m Journal
parser = (Reader m
-> MonadIO m => InputOpts -> ErroringJournalParser m Journal
forall (m :: * -> *).
Reader m
-> MonadIO m => InputOpts -> ErroringJournalParser m Journal
rParser Reader m
r) InputOpts
iopts1
      String
-> StorageFormat
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     ()
forall (m :: * -> *) a. (MonadIO m, Show a) => String -> a -> m ()
dbg7IO String
"parseIncludedFile: trying reader" (Reader m -> StorageFormat
forall (m :: * -> *). Reader m -> StorageFormat
rFormat Reader m
r)

      -- Read the file's content (or its replacement text from the input options), or throw an error.
      -- Readers which read their own input (CSV, rules) are given empty text instead.
      cfilepath <- IO String
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     String
forall a.
IO a
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
      String)
-> IO String
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     String
forall a b. (a -> b) -> a -> b
$ String -> IO String
canonicalizePath String
filepath
      childInput <-
        if readerReadsOwnInput r then pure ""
        else case M.lookup cfilepath (_fileoverrides iopts1) of
          Just Text
t  -> Text
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     Text
forall a.
a
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Text
t
          Maybe Text
Nothing -> ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m) Text
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     Text
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (ParsecT
   HledgerParseErrorData Text (ExceptT FinalParseError m) Text
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
      Text)
-> ParsecT
     HledgerParseErrorData Text (ExceptT FinalParseError m) Text
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     Text
forall a b. (a -> b) -> a -> b
$ String -> IO Text
readFilePortably String
filepath IO Text
-> (IO Text
    -> ParsecT
         HledgerParseErrorData Text (ExceptT FinalParseError m) Text)
-> ParsecT
     HledgerParseErrorData Text (ExceptT FinalParseError m) Text
forall a b. a -> (a -> b) -> b
& Int
-> String
-> IO Text
-> ParsecT
     HledgerParseErrorData Text (ExceptT FinalParseError m) Text
forall (m :: * -> *) a.
MonadIO m =>
Int -> String -> IO a -> TextParser m a
handleIOError Int
off String
"failed to read a file"
      parentj <- get
      let initChildj = String -> String -> Journal -> Journal
newJournalWithParseStateFrom String
filepath String
cfilepath Journal
parentj

      -- Parse the file (and its own includes, if any) to a Journal
      -- with file path and source text attached. Or throw an error.
      -- Its include depth is the length of the parent's include file stack (which includes the parent).
      updatedChildj <- journalAddFile (JournalFile filepath childInput (length $ jparseincludefilestack parentj)) <$>
                        parseIncludeFile parser initChildj filepath childInput

      -- Child journal was parsed successfully; now merge it into the parent journal.
      -- Debug logging is provided for troubleshooting account display order (eg).
      -- The parent journal is the second argument to journalConcat; this means
      -- its parse state is kept, and its lists are appended to child's (which
      -- ultimately produces the right list order, because parent's and child's
      -- lists are in reverse order at this stage. Cf #1909)
      let
        parentj' =
          String -> Journal -> Journal
dbgJournalAcctDeclOrder (String
"parseChild: child " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
childfilename String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" acct decls: ") Journal
updatedChildj
          Journal -> Journal -> Journal
`journalConcat`
          String -> Journal -> Journal
dbgJournalAcctDeclOrder (String
"parseChild: parent " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
parentfilename String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" acct decls: ") Journal
parentj

          where
            childfilename :: String
childfilename = String -> String
takeFileName String
filepath
            parentfilename :: String
parentfilename = String -> (String -> String) -> Maybe String -> String
forall b a. b -> (a -> b) -> Maybe a -> b
maybe String
"(unknown)" String -> String
takeFileName (Maybe String -> String) -> Maybe String -> String
forall a b. (a -> b) -> a -> b
$ ((String, String) -> String)
-> Maybe (String, String) -> Maybe String
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (String, String) -> String
forall a b. (a, b) -> a
fst (Maybe (String, String) -> Maybe String)
-> Maybe (String, String) -> Maybe String
forall a b. (a -> b) -> a -> b
$ [(String, String)] -> Maybe (String, String)
forall a. [a] -> Maybe a
headMay ([(String, String)] -> Maybe (String, String))
-> [(String, String)] -> Maybe (String, String)
forall a b. (a -> b) -> a -> b
$ Journal -> [(String, String)]
jparseincludefilestack Journal
parentj  -- XXX more accurate than journalFilePath for some reason

      -- And update the current parse state.
      put parentj'

      where
        newJournalWithParseStateFrom :: FilePath -> FilePath -> Journal -> Journal
        newJournalWithParseStateFrom :: String -> String -> Journal -> Journal
newJournalWithParseStateFrom String
filepath String
cfilepath Journal
j = Journal
nulljournal{
          jparsedefaultyear      = jparsedefaultyear j
          ,jparseapplyyears       = jparseapplyyears j
          ,jparsedefaultcommodity = jparsedefaultcommodity j
          ,jparseparentaccounts   = jparseparentaccounts j
          ,jparsedecimalmark      = jparsedecimalmark j
          ,jparsealiases          = jparsealiases j
          ,jparseoptaliases       = jparseoptaliases j
          ,jdeclaredcommodities           = jdeclaredcommodities j
          -- ,jparsetransactioncount = jparsetransactioncount j
          ,jparsetimeclockentries = jparsetimeclockentries j
          ,jparseincludefilestack = (filepath, cfilepath) : jparseincludefilestack j
          }

-- Get the absolute path of the file referenced by this parse position.
-- (Symbolic links will not be dereferenced.)
-- This probably will always succeed, since the parse file's path is probably always absolute.
sourcePosFilePath :: (MonadIO m) => SourcePos -> m FilePath
sourcePosFilePath :: forall (m :: * -> *). MonadIO m => SourcePos -> m String
sourcePosFilePath = IO String -> m String
forall a. IO a -> m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String -> m String)
-> (SourcePos -> IO String) -> SourcePos -> m String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> IO String
makeAbsolute (String -> IO String)
-> (SourcePos -> String) -> SourcePos -> IO String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SourcePos -> String
sourceName

-- | Lift an IO action into the exception monad, converting any IO error
-- to a parse error message at the given offset.
handleIOError :: MonadIO m => Int -> String -> IO a -> TextParser m a
handleIOError :: forall (m :: * -> *) a.
MonadIO m =>
Int -> String -> IO a -> TextParser m a
handleIOError Int
off String
msg IO a
io = do
  eResult <- IO (Either String a)
-> ParsecT HledgerParseErrorData Text m (Either String a)
forall a. IO a -> ParsecT HledgerParseErrorData Text m a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (Either String a)
 -> ParsecT HledgerParseErrorData Text m (Either String a))
-> IO (Either String a)
-> ParsecT HledgerParseErrorData Text m (Either String a)
forall a b. (a -> b) -> a -> b
$ (a -> Either String a
forall a b. b -> Either a b
Right (a -> Either String a) -> IO a -> IO (Either String a)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO a
io) IO (Either String a)
-> (IOException -> IO (Either String a)) -> IO (Either String a)
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`C.catch` \(IOException
e::C.IOException) -> Either String a -> IO (Either String a)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either String a -> IO (Either String a))
-> Either String a -> IO (Either String a)
forall a b. (a -> b) -> a -> b
$ String -> Either String a
forall a b. a -> Either a b
Left (String -> Either String a) -> String -> Either String a
forall a b. (a -> b) -> a -> b
$ String -> String -> String -> String
forall r. PrintfType r => String -> r
printf String
"%s:\n%s" String
msg (IOException -> String
forall a. Show a => a -> String
show IOException
e)
  case eResult of
    Right a
res -> a -> ParsecT HledgerParseErrorData Text m a
forall a. a -> ParsecT HledgerParseErrorData Text m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure a
res
    Left String
errMsg -> Int -> ParsecT HledgerParseErrorData Text m ()
forall e s (m :: * -> *). MonadParsec e s m => Int -> m ()
setOffset Int
off ParsecT HledgerParseErrorData Text m ()
-> ParsecT HledgerParseErrorData Text m a
-> ParsecT HledgerParseErrorData Text m a
forall a b.
ParsecT HledgerParseErrorData Text m a
-> ParsecT HledgerParseErrorData Text m b
-> ParsecT HledgerParseErrorData Text m b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> String -> ParsecT HledgerParseErrorData Text m a
forall a.
HasCallStack =>
String -> ParsecT HledgerParseErrorData Text m a
forall (m :: * -> *) a.
(MonadFail m, HasCallStack) =>
String -> m a
fail String
errMsg

-- Parse an account directive, adding its info to the journal's
-- list of account declarations.
accountdirectivep :: JournalParser m ()
accountdirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
accountdirectivep = do
  off <- StateT Journal (ParsecT HledgerParseErrorData Text m) Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset -- XXX figure out a more precise position later
  pos <- getSourcePos'

  string "account"
  lift skipNonNewlineSpaces1

  -- the account name, possibly modified by preceding alias or apply account directives;
  -- also kept without the parent account, as the target of any alias: tags below
  -- (which, like alias directives, are applied before the parent account is added; see accountNameApplyModifiers)
  aliasedacct <- (notFollowedBy (char '(' <|> char '[') <?> "account name without brackets") >>
                 aliasedaccountnamep True
  acct <- applyParentAndOptionAliases aliasedacct

  -- maybe a comment, on this and/or following lines
  commentoff <- getOffset
  (cmt, commenttags) <- lift transactioncommentp

  -- maybe Ledger-style subdirectives: alias NAME declares an account alias, and is kept as an alias: tag;
  -- the others are ignored
  subdirectivealiases <- catMaybes <$> many (try aliassubdirectivep <|> (Nothing <$ indentedlinep))
  let tags = [Tag]
commenttags [Tag] -> [Tag] -> [Tag]
forall a. [a] -> [a] -> [a]
++ [(Text
"alias", Text
a) | Text
a <- [Text]
subdirectivealiases]

  -- an account type may have been set by account type code or a tag;
  -- the latter takes precedence
  let
    metype = Text -> Either String AccountType
parseAccountTypeCode (Text -> Either String AccountType)
-> Maybe Text -> Maybe (Either String AccountType)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Text -> [Tag] -> Maybe Text
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Text
accountTypeTagName [Tag]
tags

  -- alias: tags declare account aliases, like alias directives at this point
  let acctaliases = [Text
v | (Text
n, Text
v) <- [Tag]
tags, Text -> Text
T.toLower Text
n Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"alias"]
  when (any T.null acctaliases) $ customFailure $ parseErrorAt commentoff
    "an alias: tag on an account directive should have an account name as its value, eg alias: checking"
  mapM_ (addAccountAlias . (`BasicAlias` aliasedacct)) acctaliases

  -- update the journal
  addAccountDeclaration (acct, cmt, tags, pos)
  unless (null tags) $ addDeclaredAccountTags acct tags
  case metype of
    Maybe (Either String AccountType)
Nothing         -> () -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
    Just (Right AccountType
t)  -> Text
-> AccountType
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *). Text -> AccountType -> JournalParser m ()
addDeclaredAccountType Text
acct AccountType
t
    Just (Left String
err) -> HledgerParseErrorData
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) ())
-> HledgerParseErrorData
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b. (a -> b) -> a -> b
$ Int -> String -> HledgerParseErrorData
parseErrorAt Int
off String
err

-- The special tag used for declaring account type. XXX change to "class" ?
accountTypeTagName :: Text
accountTypeTagName = Text
"type"

-- | Parse the value of an account declaration's type: tag (a one-letter code or long-form name).
parseAccountTypeCode :: Text -> Either String AccountType
parseAccountTypeCode :: Text -> Either String AccountType
parseAccountTypeCode Text
s = (String -> String)
-> Either String AccountType -> Either String AccountType
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first String -> String
forall {p}. p -> String
err (Either String AccountType -> Either String AccountType)
-> Either String AccountType -> Either String AccountType
forall a b. (a -> b) -> a -> b
$ Bool -> Text -> Either String AccountType
parseAccountType Bool
True Text
s
  where
    err :: p -> String
err p
_ = Text -> String
T.unpack (Text -> String) -> Text -> String
forall a b. (a -> b) -> a -> b
$ Text
"invalid account type code "Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>Text
sText -> Text -> Text
forall a. Semigroup a => a -> a -> a
<>Text
", should be one of " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> String -> Text
T.pack (Bool -> String
accountTypeChoices Bool
True)

-- Add an account declaration to the journal, auto-numbering it.
addAccountDeclaration :: (AccountName,Text,[Tag],SourcePos) -> JournalParser m ()
addAccountDeclaration :: forall (m :: * -> *).
(Text, Text, [Tag], SourcePos) -> JournalParser m ()
addAccountDeclaration (Text
a,Text
cmt,[Tag]
tags,SourcePos
pos) = do
  (Journal -> Journal)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' (\Journal
j ->
             let
               decls :: [(Text, AccountDeclarationInfo)]
decls = Journal -> [(Text, AccountDeclarationInfo)]
jdeclaredaccounts Journal
j
               d :: (Text, AccountDeclarationInfo)
d     = (Text
a, AccountDeclarationInfo
nullaccountdeclarationinfo{
                              adicomment          = cmt
                             ,aditags             = tags
                             ,adideclarationorder = length decls + 1  -- gets renumbered when Journals are finalised or merged
                             ,adisourcepos        = pos
                             })
             in
               Journal
j{jdeclaredaccounts = d:decls})

-- Add a payee declaration to the journal.
addPayeeDeclaration :: (Payee,Text,[Tag]) -> JournalParser m ()
addPayeeDeclaration :: forall (m :: * -> *). (Text, Text, [Tag]) -> JournalParser m ()
addPayeeDeclaration (Text
p, Text
cmt, [Tag]
tags) =
  (Journal -> Journal)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' (\j :: Journal
j@Journal{[(Text, PayeeDeclarationInfo)]
jdeclaredpayees :: [(Text, PayeeDeclarationInfo)]
jdeclaredpayees :: Journal -> [(Text, PayeeDeclarationInfo)]
jdeclaredpayees} -> Journal
j{jdeclaredpayees=d:jdeclaredpayees})
             where
               d :: (Text, PayeeDeclarationInfo)
d = (Text
p
                   ,PayeeDeclarationInfo
nullpayeedeclarationinfo{
                     pdicomment = cmt
                    ,pditags    = tags
                    })

-- Add a tag declaration to the journal.
addTagDeclaration :: (TagName,Text) -> JournalParser m ()
addTagDeclaration :: forall (m :: * -> *). Tag -> JournalParser m ()
addTagDeclaration (Text
t, Text
cmt) =
  (Journal -> Journal)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' (\j :: Journal
j@Journal{[(Text, TagDeclarationInfo)]
jdeclaredtags :: [(Text, TagDeclarationInfo)]
jdeclaredtags :: Journal -> [(Text, TagDeclarationInfo)]
jdeclaredtags} -> Journal
j{jdeclaredtags=tagandinfo:jdeclaredtags})
  where
    tagandinfo :: (Text, TagDeclarationInfo)
tagandinfo = (Text
t, TagDeclarationInfo
nulltagdeclarationinfo{tdicomment=cmt})

indentedlinep :: JournalParser m String
indentedlinep :: forall (m :: * -> *). JournalParser m String
indentedlinep = ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1 StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> (String -> String
rstrip (String -> String)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline)

-- | Parse a Ledger-style @alias NAME@ subdirective (an indented line) of an account directive,
-- returning the alias name.
aliassubdirectivep :: JournalParser m (Maybe AccountName)
aliassubdirectivep :: forall (m :: * -> *). JournalParser m (Maybe Text)
aliassubdirectivep = do
  ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"alias"
  ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  Text -> Maybe Text
forall a. a -> Maybe a
Just (Text -> Maybe Text) -> (String -> Text) -> String -> Maybe Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Text
T.pack (String -> Text) -> (String -> String) -> String -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> String
rstrip (String -> Maybe Text)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Maybe Text)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline

-- | Parse a one-line or multi-line commodity directive.
--
-- >>> Right _ <- rjp commoditydirectivep "commodity $1.00"
-- >>> Right _ <- rjp commoditydirectivep "commodity $\n  format $1.00"
-- >>> Right _ <- rjp commoditydirectivep "commodity $\n\n" -- a commodity with no format
-- >>> Right _ <- rjp commoditydirectivep "commodity $1.00\n  format $1.00" -- both, what happens ?
commoditydirectivep :: JournalParser m ()
commoditydirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
commoditydirectivep = JournalParser m ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
commoditydirectiveonelinep JournalParser m () -> JournalParser m () -> JournalParser m ()
forall a.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> JournalParser m ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
commoditydirectivemultilinep

-- | Parse a one-line commodity directive.
--
-- >>> Right _ <- rjp commoditydirectiveonelinep "commodity $1.00"
-- >>> Right _ <- rjp commoditydirectiveonelinep "commodity $1.00 ; blah\n"
commoditydirectiveonelinep :: JournalParser m ()
commoditydirectiveonelinep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
commoditydirectiveonelinep = do
  (off, pos, Amount{acommodity,astyle}) <- StateT
  Journal
  (ParsecT HledgerParseErrorData Text m)
  (Int, SourcePos, Amount)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text m)
     (Int, SourcePos, Amount)
forall a.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (StateT
   Journal
   (ParsecT HledgerParseErrorData Text m)
   (Int, SourcePos, Amount)
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData Text m)
      (Int, SourcePos, Amount))
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text m)
     (Int, SourcePos, Amount)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text m)
     (Int, SourcePos, Amount)
forall a b. (a -> b) -> a -> b
$ do
    Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"commodity"
    pos <- JournalParser m SourcePos
forall (m :: * -> *). JournalParser m SourcePos
getSourcePos'
    lift skipNonNewlineSpaces1
    off <- getOffset
    amt <- amountp' StyleAmount
    pure $ (off, pos, amt)
  lift skipNonNewlineSpaces
  commentoff <- getOffset
  (comment, tags) <- lift transactioncommentp
  commaliases <- commodityaliasesp commentoff acommodity tags
  let comm = Commodity{csymbol :: Text
csymbol=Text
acommodity, cformat :: Maybe AmountStyle
cformat=AmountStyle -> Maybe AmountStyle
forall a. a -> Maybe a
Just (AmountStyle -> Maybe AmountStyle)
-> AmountStyle -> Maybe AmountStyle
forall a b. (a -> b) -> a -> b
$ String -> AmountStyle -> AmountStyle
forall a. Show a => String -> a -> a
dbg7 String
"style from commodity directive" AmountStyle
astyle, ccomment :: Text
ccomment=Text
comment, ctags :: [Tag]
ctags=[Tag]
tags, caliases :: [(Amount, SourcePos)]
caliases=[(Amount
a, SourcePos
pos) | Amount
a <- [Amount]
commaliases], csourcepos :: SourcePos
csourcepos=SourcePos
pos}
  if isNothing $ asdecimalmark astyle
  then customFailure $ parseErrorAt off pleaseincludedecimalpoint
  else modify' (addCommodityDeclaration comm)

pleaseincludedecimalpoint :: String
pleaseincludedecimalpoint :: String
pleaseincludedecimalpoint = String -> String
chomp (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ [String] -> String
unlines [
   String
"Please include a decimal point or decimal comma in commodity directives,"
  ,String
"to help us parse correctly. It may be followed by zero or more decimal digits."
  ,String
"Examples:"
  ,String
"commodity $1000.            ; no thousands mark, decimal period, no decimals"
  ,String
"commodity 1.234,00 ARS      ; period at thousands, decimal comma, 2 decimals"
  ,String
"commodity EUR 1 000,000     ; space at thousands, decimal comma, 3 decimals"
  ,String
"commodity INR1,23,45,678.0  ; comma at thousands/lakhs/crores, decimal period, 1 decimal"
  ]

-- | Parse a multi-line commodity directive, containing 0 or more format subdirectives.
--
-- >>> Right _ <- rjp commoditydirectivemultilinep "commodity $ ; blah \n  format $1.00 ; blah"
commoditydirectivemultilinep :: JournalParser m ()
commoditydirectivemultilinep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
commoditydirectivemultilinep = do
  Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"commodity"
  pos <- JournalParser m SourcePos
forall (m :: * -> *). JournalParser m SourcePos
getSourcePos'
  lift skipNonNewlineSpaces1
  sym <- lift commoditysymbolp
  commentoff <- getOffset
  (comment, tags) <- lift transactioncommentp
  commaliases <- commodityaliasesp commentoff sym tags
  -- read all subdirectives, saving format subdirectives as Lefts
  subdirectives <- many $ indented (eitherP (formatdirectivep sym) (lift restofline))
  let mfmt = [AmountStyle] -> Maybe AmountStyle
forall a. [a] -> Maybe a
lastMay ([AmountStyle] -> Maybe AmountStyle)
-> [AmountStyle] -> Maybe AmountStyle
forall a b. (a -> b) -> a -> b
$ [Either AmountStyle String] -> [AmountStyle]
forall a b. [Either a b] -> [a]
lefts [Either AmountStyle String]
subdirectives
  let comm = Commodity{csymbol :: Text
csymbol=Text
sym, cformat :: Maybe AmountStyle
cformat=Maybe AmountStyle
mfmt, ccomment :: Text
ccomment=Text
comment, ctags :: [Tag]
ctags=[Tag]
tags, caliases :: [(Amount, SourcePos)]
caliases=[(Amount
a, SourcePos
pos) | Amount
a <- [Amount]
commaliases], csourcepos :: SourcePos
csourcepos=SourcePos
pos}
  modify' (addCommodityDeclaration comm)
  where
    indented :: StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
indented = (ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1 StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>)

-- | Add a commodity directive's declaration to the journal.
-- A commodity declared again adds to its earlier declaration (see 'commodityRedeclare').
addCommodityDeclaration :: Commodity -> Journal -> Journal
addCommodityDeclaration :: Commodity -> Journal -> Journal
addCommodityDeclaration comm :: Commodity
comm@Commodity{Text
csymbol :: Commodity -> Text
csymbol :: Text
csymbol, [Tag]
ctags :: Commodity -> [Tag]
ctags :: [Tag]
ctags} Journal
j = Journal
j{
   jdeclaredcommodities   = M.insertWith commodityRedeclare csymbol comm $ jdeclaredcommodities j
  ,jdeclaredcommoditytags = if null ctags then jdeclaredcommoditytags j
                            else M.insertWith union csymbol ctags $ jdeclaredcommoditytags j
  }

-- | Parse a format (sub)directive, throwing a parse error if its
-- symbol does not match the one given.
formatdirectivep :: CommoditySymbol -> JournalParser m AmountStyle
formatdirectivep :: forall (m :: * -> *). Text -> JournalParser m AmountStyle
formatdirectivep Text
expectedsym = do
  Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"format"
  ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  off <- StateT Journal (ParsecT HledgerParseErrorData Text m) Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
  Amount{acommodity,astyle} <- amountp' StyleAmount
  _ <- lift followingcommentp
  if acommodity==expectedsym
    then
      if isNothing $ asdecimalmark astyle
      then customFailure $ parseErrorAt off pleaseincludedecimalpoint
      else return $ dbg7 "style from format subdirective" astyle
    else customFailure $ parseErrorAt off $
         printf "commodity directive symbol \"%s\" and format directive symbol \"%s\" should be the same" expectedsym acommodity

-- | Parse the values of a commodity directive's alias: tags, if any.
-- Each value is one commodity symbol, optionally with a positive quantity:
-- the number of alias units equal to one unit of the commodity (1 if omitted).
-- These are returned as amounts, keeping the style they were written with.
-- A 1:1 alias to the commodity itself, or a repeat of an earlier alias, is ignored.
-- An alias already declared for this commodity (by an earlier commodity directive) with a different quantity is an error.
-- Errors are reported at the given offset (the start of the directive's comment).
commodityaliasesp :: Int -> CommoditySymbol -> [Tag] -> JournalParser m [Amount]
commodityaliasesp :: forall (m :: * -> *).
Int -> Text -> [Tag] -> JournalParser m [Amount]
commodityaliasesp Int
off Text
sym [Tag]
tags = do
  j <- StateT Journal (ParsecT HledgerParseErrorData Text m) Journal
forall s (m :: * -> *). MonadState s m => m s
get
  commaliases <- nubOn symqty . filter ((/= (sym, 1)) . symqty) <$> mapM (aliasvalue j) [v | (n, v) <- tags, T.toLower n == "alias"]
  let aliassyms = (Amount -> Text) -> [Amount] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Amount -> Text
acommodity [Amount]
commaliases
  if sym `elem` aliassyms then customFailure $ errAt $ printf "%s can't be an alias of itself with a quantity other than 1" (quote sym)
  else case aliassyms \\ nub aliassyms of
    Text
a:[Text]
_ -> HledgerParseErrorData
-> StateT Journal (ParsecT HledgerParseErrorData Text m) [Amount]
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) [Amount])
-> HledgerParseErrorData
-> StateT Journal (ParsecT HledgerParseErrorData Text m) [Amount]
forall a b. (a -> b) -> a -> b
$ String -> HledgerParseErrorData
errAt (String -> HledgerParseErrorData)
-> String -> HledgerParseErrorData
forall a b. (a -> b) -> a -> b
$ String -> String -> String
forall r. PrintfType r => String -> r
printf String
"alias %s is declared more than once, with different quantities" (Text -> String
quote Text
a)
    []  -> case [(Amount
a, Amount
e, SourcePos
epos) | Amount
a <- [Amount]
commaliases, (Amount
e, SourcePos
epos) <- Journal -> [(Amount, SourcePos)]
earlieraliases Journal
j, Amount -> Text
acommodity Amount
e Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Amount -> Text
acommodity Amount
a, Amount -> Quantity
aquantity Amount
e Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
/= Amount -> Quantity
aquantity Amount
a] of
      (Amount
a, Amount
e, SourcePos
epos):[(Amount, Amount, SourcePos)]
_ -> HledgerParseErrorData
-> StateT Journal (ParsecT HledgerParseErrorData Text m) [Amount]
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) [Amount])
-> HledgerParseErrorData
-> StateT Journal (ParsecT HledgerParseErrorData Text m) [Amount]
forall a b. (a -> b) -> a -> b
$ String -> HledgerParseErrorData
errAt (String -> HledgerParseErrorData)
-> String -> HledgerParseErrorData
forall a b. (a -> b) -> a -> b
$ String -> String -> String -> String -> String -> String
forall r. PrintfType r => String -> r
printf String
"alias %s was declared earlier for %s with a different quantity (%s), at %s"
                    (Text -> String
quote (Text -> String) -> Text -> String
forall a b. (a -> b) -> a -> b
$ Amount -> Text
acommodity Amount
a) (Text -> String
quote Text
sym) (Quantity -> String
forall a. Show a => a -> String
show (Quantity -> String) -> Quantity -> String
forall a b. (a -> b) -> a -> b
$ Amount -> Quantity
aquantity Amount
e) (SourcePos -> String
sourcePosFileLine SourcePos
epos)
      []       -> [Amount]
-> StateT Journal (ParsecT HledgerParseErrorData Text m) [Amount]
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure [Amount]
commaliases
  where
    earlieraliases :: Journal -> [(Amount, SourcePos)]
earlieraliases Journal
j = [(Amount, SourcePos)]
-> (Commodity -> [(Amount, SourcePos)])
-> Maybe Commodity
-> [(Amount, SourcePos)]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] Commodity -> [(Amount, SourcePos)]
caliases (Maybe Commodity -> [(Amount, SourcePos)])
-> Maybe Commodity -> [(Amount, SourcePos)]
forall a b. (a -> b) -> a -> b
$ Text -> Map Text Commodity -> Maybe Commodity
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup Text
sym (Map Text Commodity -> Maybe Commodity)
-> Map Text Commodity -> Maybe Commodity
forall a b. (a -> b) -> a -> b
$ Journal -> Map Text Commodity
jdeclaredcommodities Journal
j
    errAt :: String -> HledgerParseErrorData
errAt = Int -> String -> HledgerParseErrorData
parseErrorAt Int
off
    symqty :: Amount -> (Text, Quantity)
symqty Amount
a = (Amount -> Text
acommodity Amount
a, Amount -> Quantity
aquantity Amount
a)
    nubOn :: (t -> a) -> [t] -> [t]
nubOn t -> a
f = (t -> t -> Bool) -> [t] -> [t]
forall a. (a -> a -> Bool) -> [a] -> [a]
nubBy (\t
a t
b -> t -> a
f t
a a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== t -> a
f t
b)
    quote :: Text -> String
quote Text
t = String
"\"" String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Text -> String
T.unpack Text
t String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
"\""
    aliasvalue :: Journal -> Text -> f Amount
aliasvalue Journal
j Text
v = case Parsec HledgerParseErrorData Text Amount
-> String -> Text -> Either HledgerParseErrors Amount
forall e s a.
Parsec e s a -> String -> s -> Either (ParseErrorBundle s e) a
runParser (StateT Journal (ParsecT HledgerParseErrorData Text Identity) Amount
-> Journal -> Parsec HledgerParseErrorData Text Amount
forall (m :: * -> *) s a. Monad m => StateT s m a -> s -> m a
evalStateT StateT Journal (ParsecT HledgerParseErrorData Text Identity) Amount
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
aliasp Journal
j) String
"" Text
v of
      Right Amount
a | Bool -> Bool
not (Text -> Bool
T.null (Text -> Bool) -> Text -> Bool
forall a b. (a -> b) -> a -> b
$ Amount -> Text
acommodity Amount
a) Bool -> Bool -> Bool
&& Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
0 -> Amount -> f Amount
forall a. a -> f a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Amount
a
      Either HledgerParseErrors Amount
_ -> HledgerParseErrorData -> f Amount
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData -> f Amount)
-> HledgerParseErrorData -> f Amount
forall a b. (a -> b) -> a -> b
$ String -> HledgerParseErrorData
errAt (String -> HledgerParseErrorData)
-> String -> HledgerParseErrorData
forall a b. (a -> b) -> a -> b
$ String -> String -> String -> String
forall r. PrintfType r => String -> r
printf ([String] -> String
unlines
             [String
"could not parse commodity alias %s."
             ,String
"Each alias: tag should contain one commodity symbol, optionally with a positive quantity,"
             ,String
"the number of alias units equal to one %s. Eg: alias: $, alias: 100 cents"
             ]) (Text -> String
quote Text
v) (Text -> String
T.unpack Text
sym)
    aliasp :: StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
aliasp = do
      let spaces :: StateT Journal (ParsecT HledgerParseErrorData Text m) ()
spaces = ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
      StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
spaces
      StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
forall a.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try ((\Text
a -> Amount
nullamt{acommodity=a, aquantity=1}) (Text -> Amount)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Text
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ParsecT HledgerParseErrorData Text m Text
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Text
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m Text
forall (m :: * -> *). TextParser m Text
commoditysymbolp StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
spaces StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall e s (m :: * -> *). MonadParsec e s m => m ()
eof)
        StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
forall a.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> (AmountParseKind
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
forall (m :: * -> *). AmountParseKind -> JournalParser m Amount
simpleamountp AmountParseKind
MultiplierAmount StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
spaces StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall e s (m :: * -> *). MonadParsec e s m => m ()
eof)

-- More Ledger directives, ignore for now:
-- apply fixed, apply tag, bucket, A, capture, check, define, expr
-- (Ledger's assert directive is not supported; hledger's assert directive is different, see assertdirectivep.)
applyfixeddirectivep, endapplyfixeddirectivep, applytagdirectivep, endapplytagdirectivep,
  bucketdirectivep, capturedirectivep, checkdirectivep,
  definedirectivep, exprdirectivep, valuedirectivep,
  evaldirectivep, pythondirectivep, commandlineflagdirectivep
  :: JournalParser m ()
applyfixeddirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
applyfixeddirectivep    = do Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"apply fixed" StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
endapplyfixeddirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
endapplyfixeddirectivep = do Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"end apply fixed" StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
applytagdirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
applytagdirectivep      = do Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"apply tag" StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
endapplytagdirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
endapplytagdirectivep   = do Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"end apply tag" StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()

bucketdirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
bucketdirectivep        = do Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"A " StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall a.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Text
Tokens Text
"bucket " StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
capturedirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
capturedirectivep       = do Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"capture" StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
checkdirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
checkdirectivep         = do Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"check"   StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
definedirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
definedirectivep        = do Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"define"  StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
exprdirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
exprdirectivep          = do Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"expr"    StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
valuedirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
valuedirectivep         = do Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"value"   StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
evaldirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
evaldirectivep          = do Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"eval"   StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
commandlineflagdirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
commandlineflagdirectivep = do Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"--" StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
pythondirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
pythondirectivep = do
  Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"python" StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline
  StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) [String]
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
many (StateT Journal (ParsecT HledgerParseErrorData Text m) String
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) [String])
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) [String]
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text m) String
indentedline StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> StateT Journal (ParsecT HledgerParseErrorData Text m) String
blankline
  () -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
  where
    indentedline :: StateT Journal (ParsecT HledgerParseErrorData Text m) String
indentedline = ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1 StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline
    blankline :: StateT Journal (ParsecT HledgerParseErrorData Text m) String
blankline = ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Char
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Char
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> StateT Journal (ParsecT HledgerParseErrorData Text m) Char
StateT Journal (ParsecT HledgerParseErrorData Text m) (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m (Token s)
newline StateT Journal (ParsecT HledgerParseErrorData Text m) Char
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return String
"" StateT Journal (ParsecT HledgerParseErrorData Text m) String
-> String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"blank line"

keywordp :: String -> JournalParser m ()
keywordp :: forall (m :: * -> *). String -> JournalParser m ()
keywordp = StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (StateT
   Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) ())
-> (String
    -> StateT
         Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text))
-> String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string (Tokens Text
 -> StateT
      Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text))
-> (String -> Tokens Text)
-> String
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Tokens Text
forall a. IsString a => String -> a
fromString

spacesp :: JournalParser m ()
spacesp :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
spacesp = StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (StateT Journal (ParsecT HledgerParseErrorData Text m) ()
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) ())
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b. (a -> b) -> a -> b
$ ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1

-- | Backtracking parser similar to string, but allows varying amount of space between words
keywordsp :: String -> JournalParser m ()
keywordsp :: forall (m :: * -> *). String -> JournalParser m ()
keywordsp = StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (StateT Journal (ParsecT HledgerParseErrorData Text m) ()
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) ())
-> (String
    -> StateT Journal (ParsecT HledgerParseErrorData Text m) ())
-> String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [StateT Journal (ParsecT HledgerParseErrorData Text m) ()]
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (t :: * -> *) (m :: * -> *) a.
(Foldable t, Monad m) =>
t (m a) -> m ()
sequence_ ([StateT Journal (ParsecT HledgerParseErrorData Text m) ()]
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) ())
-> (String
    -> [StateT Journal (ParsecT HledgerParseErrorData Text m) ()])
-> String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> [StateT Journal (ParsecT HledgerParseErrorData Text m) ()]
-> [StateT Journal (ParsecT HledgerParseErrorData Text m) ()]
forall a. a -> [a] -> [a]
intersperse StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
spacesp ([StateT Journal (ParsecT HledgerParseErrorData Text m) ()]
 -> [StateT Journal (ParsecT HledgerParseErrorData Text m) ()])
-> (String
    -> [StateT Journal (ParsecT HledgerParseErrorData Text m) ()])
-> String
-> [StateT Journal (ParsecT HledgerParseErrorData Text m) ()]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) ())
-> [String]
-> [StateT Journal (ParsecT HledgerParseErrorData Text m) ()]
forall a b. (a -> b) -> [a] -> [b]
map String -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *). String -> JournalParser m ()
keywordp ([String]
 -> [StateT Journal (ParsecT HledgerParseErrorData Text m) ()])
-> (String -> [String])
-> String
-> [StateT Journal (ParsecT HledgerParseErrorData Text m) ()]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> [String]
words

applyaccountdirectivep :: JournalParser m ()
applyaccountdirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
applyaccountdirectivep = do
  String -> JournalParser m ()
forall (m :: * -> *). String -> JournalParser m ()
keywordsp String
"apply account" JournalParser m () -> String -> JournalParser m ()
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"apply account directive"
  ParsecT HledgerParseErrorData Text m () -> JournalParser m ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  parent <- ParsecT HledgerParseErrorData Text m Text
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Text
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m Text
forall (m :: * -> *). TextParser m Text
parentaccountnamep
  newline
  pushParentAccount parent

endapplyaccountdirectivep :: JournalParser m ()
endapplyaccountdirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
endapplyaccountdirectivep = do
  off <- StateT Journal (ParsecT HledgerParseErrorData Text m) Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
  keywordsp "end apply account" <?> "end apply account directive"
  lift restofline
  j <- get
  case jparseparentaccounts j of
    []       -> HledgerParseErrorData -> JournalParser m ()
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData -> JournalParser m ())
-> HledgerParseErrorData -> JournalParser m ()
forall a b. (a -> b) -> a -> b
$ Int -> String -> HledgerParseErrorData
parseErrorAt Int
off String
"end apply account has no matching apply account"
    (Text
_:[Text]
rest) -> Journal -> JournalParser m ()
forall s (m :: * -> *). MonadState s m => s -> m ()
put Journal
j{jparseparentaccounts = rest}

-- | Set the default year until the matching end apply year, saving the current one.
applyyeardirectivep :: JournalParser m ()
applyyeardirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
applyyeardirectivep = do
  String -> JournalParser m ()
forall (m :: * -> *). String -> JournalParser m ()
keywordsp String
"apply year" JournalParser m () -> String -> JournalParser m ()
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"apply year directive"
  ParsecT HledgerParseErrorData Text m () -> JournalParser m ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  y <- ParsecT HledgerParseErrorData Text m Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Integer
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m Integer
forall (m :: * -> *). TextParser m Integer
yearp
  lift restofline
  modify' (\Journal
j -> Journal
j{jparseapplyyears = jparsedefaultyear j : jparseapplyyears j, jparsedefaultyear = Just y})

-- | Restore the default year that was in effect before the matching apply year.
endapplyyeardirectivep :: JournalParser m ()
endapplyyeardirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
endapplyyeardirectivep = do
  off <- StateT Journal (ParsecT HledgerParseErrorData Text m) Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
  keywordsp "end apply year" <?> "end apply year directive"
  lift restofline
  j <- get
  case jparseapplyyears j of
    []     -> HledgerParseErrorData -> JournalParser m ()
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData -> JournalParser m ())
-> HledgerParseErrorData -> JournalParser m ()
forall a b. (a -> b) -> a -> b
$ Int -> String -> HledgerParseErrorData
parseErrorAt Int
off String
"end apply year has no matching apply year"
    (Maybe Integer
y:[Maybe Integer]
ys) -> Journal -> JournalParser m ()
forall s (m :: * -> *). MonadState s m => s -> m ()
put Journal
j{jparsedefaultyear = y, jparseapplyyears = ys}

-- | Reject Ledger's bare "end" or "end apply" (which closes the innermost apply block)
-- with a clear error, since hledger requires the kind of block to be named.
bareenddirectivep :: JournalParser m ()
bareenddirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
bareenddirectivep = do
  off <- StateT Journal (ParsecT HledgerParseErrorData Text m) Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
  try $ keywordp "end" >> optional (try $ spacesp >> keywordp "apply") >> lift skipNonNewlineSpaces >> lookAhead (void eol <|> eof)
  customFailure $ parseErrorAt off $
    "hledger needs the kind of apply block here:\n"
    ++ "end apply account, end apply fixed, end apply tag, or end apply year"

aliasdirectivep :: JournalParser m ()
aliasdirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
aliasdirectivep = do
  Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"alias"
  ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  alias <- ParsecT HledgerParseErrorData Text m AccountAlias
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) AccountAlias
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m AccountAlias
forall (m :: * -> *). TextParser m AccountAlias
accountaliasp
  addAccountAlias alias

endaliasesdirectivep :: JournalParser m ()
endaliasesdirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
endaliasesdirectivep = do
  String -> JournalParser m ()
forall (m :: * -> *). String -> JournalParser m ()
keywordsp String
"end aliases" JournalParser m () -> String -> JournalParser m ()
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"end aliases directive"
  ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline
  -- forget the aliases from alias directives/tags (--alias options are kept separately; see accountNameApplyModifiers)
  (Journal -> Journal) -> JournalParser m ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' (\Journal
j -> Journal
j{jparsealiases = []})

tagdirectivep :: JournalParser m ()
tagdirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
tagdirectivep = do
  Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"tag" StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> String
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"tag directive"
  ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  tagname <- ParsecT HledgerParseErrorData Text m Text
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Text
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (ParsecT HledgerParseErrorData Text m Text
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) Text)
-> ParsecT HledgerParseErrorData Text m Text
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Text
forall a b. (a -> b) -> a -> b
$ String -> Text
T.pack (String -> Text)
-> ParsecT HledgerParseErrorData Text m String
-> ParsecT HledgerParseErrorData Text m Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ParsecT HledgerParseErrorData Text m Char
-> ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
some ParsecT HledgerParseErrorData Text m Char
forall (m :: * -> *). TextParser m Char
nonspace
  (comment, _) <- lift transactioncommentp
  skipMany indentedlinep
  addTagDeclaration (tagname,comment)
  return ()

-- end tag or end apply tag
endtagdirectivep :: JournalParser m ()
endtagdirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
endtagdirectivep = (do
  Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"end"
  ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) (Maybe ())
forall (f :: * -> *) a. Alternative f => f a -> f (Maybe a)
optional (StateT Journal (ParsecT HledgerParseErrorData Text m) ()
 -> StateT
      Journal (ParsecT HledgerParseErrorData Text m) (Maybe ()))
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) (Maybe ())
forall a b. (a -> b) -> a -> b
$ Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"apply" StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"tag"
  ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m (Tokens s)
eol
  () -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
  ) StateT Journal (ParsecT HledgerParseErrorData Text m) ()
-> String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"end tag or end apply tag directive"

payeedirectivep :: JournalParser m ()
payeedirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
payeedirectivep = do
  Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"payee" StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> String
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"payee directive"
  ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  payee <- ParsecT HledgerParseErrorData Text m Text
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Text
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (ParsecT HledgerParseErrorData Text m Text
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) Text)
-> ParsecT HledgerParseErrorData Text m Text
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Text
forall a b. (a -> b) -> a -> b
$ Text -> Text
T.strip (Text -> Text)
-> ParsecT HledgerParseErrorData Text m Text
-> ParsecT HledgerParseErrorData Text m Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (ParsecT HledgerParseErrorData Text m Text
-> ParsecT HledgerParseErrorData Text m Text
forall a.
ParsecT HledgerParseErrorData Text m a
-> ParsecT HledgerParseErrorData Text m a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try ParsecT HledgerParseErrorData Text m Text
forall (m :: * -> *). TextParser m Text
doublequotedtextp ParsecT HledgerParseErrorData Text m Text
-> ParsecT HledgerParseErrorData Text m Text
-> ParsecT HledgerParseErrorData Text m Text
forall a.
ParsecT HledgerParseErrorData Text m a
-> ParsecT HledgerParseErrorData Text m a
-> ParsecT HledgerParseErrorData Text m a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> ParsecT HledgerParseErrorData Text m Text
forall (m :: * -> *). TextParser m Text
noncommenttext1p)
  (comment, tags) <- lift transactioncommentp
  skipMany indentedlinep
  addPayeeDeclaration (payee, comment, tags)
  return ()

defaultyeardirectivep :: JournalParser m ()
defaultyeardirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
defaultyeardirectivep = do
  (Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"Y" StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall a.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Text
Tokens Text
"year") StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> String
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"default year"
  ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  y <- ParsecT HledgerParseErrorData Text m Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Integer
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m Integer
forall (m :: * -> *). TextParser m Integer
yearp
  lift restofline
  setYear y

defaultcommoditydirectivep :: JournalParser m ()
defaultcommoditydirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
defaultcommoditydirectivep = do
  Token Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'D' StateT Journal (ParsecT HledgerParseErrorData Text m) Char
-> String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Char
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"default commodity"
  ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  off <- StateT Journal (ParsecT HledgerParseErrorData Text m) Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
  Amount{acommodity,astyle} <- amountp' StyleAmount
  lift restofline
  if isNothing $ asdecimalmark astyle
  then customFailure $ parseErrorAt off pleaseincludedecimalpoint
  else setDefaultCommodityAndStyle (acommodity, astyle)

marketpricedirectivep :: JournalParser m PriceDirective
marketpricedirectivep :: forall (m :: * -> *). JournalParser m PriceDirective
marketpricedirectivep = do
  pos <- JournalParser m SourcePos
forall (m :: * -> *). JournalParser m SourcePos
getSourcePos'
  char 'P' <?> "market price"
  lift skipNonNewlineSpaces
  date <- datep
  lift skipNonNewlineSpaces1
  -- a time of day may follow the date; it is ignored (checked cheaply first, since usually there is none)
  mc <- lift peekChar
  mtime <- if maybe False isDigit mc then lift $ optional $ try timeofdayp else pure Nothing
  when (isJust mtime) $ lift skipNonNewlineSpaces1
  symbol <- shareText =<< lift commoditysymbolp
  lift skipNonNewlineSpaces1
  price <- amountp
  lift restofline
  return $ PriceDirective pos date symbol price

ignoredpricecommoditydirectivep :: JournalParser m ()
ignoredpricecommoditydirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
ignoredpricecommoditydirectivep = do
  Token Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'N' StateT Journal (ParsecT HledgerParseErrorData Text m) Char
-> String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Char
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"ignored-price commodity"
  ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  ParsecT HledgerParseErrorData Text m Text
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Text
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m Text
forall (m :: * -> *). TextParser m Text
commoditysymbolp
  ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline
  () -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()

commodityconversiondirectivep :: JournalParser m ()
commodityconversiondirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
commodityconversiondirectivep = do
  Token Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'C' StateT Journal (ParsecT HledgerParseErrorData Text m) Char
-> String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Char
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"commodity conversion"
  ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  JournalParser m Amount
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
amountp
  ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  Token Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'='
  ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  JournalParser m Amount
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
amountp
  ParsecT HledgerParseErrorData Text m String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) String
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m String
forall (m :: * -> *). TextParser m String
restofline
  () -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return ()

-- | Read a valid decimal mark from the decimal-mark directive e.g
--
-- decimal-mark ,
decimalmarkdirectivep :: JournalParser m ()
decimalmarkdirectivep :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
decimalmarkdirectivep = do
  Tokens Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"decimal-mark" StateT Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
-> String
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Tokens Text)
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"decimal mark"
  ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  mark <- (Token Text -> Bool)
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Token Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
(Token s -> Bool) -> m (Token s)
satisfy Char -> Bool
Token Text -> Bool
isDecimalMark
  modify' $ \Journal
j -> Journal
j{jparsedecimalmark=Just mark}
  lift restofline
  return ()

--- *** transactions

-- | Parse a transaction modifier (auto postings) rule.
transactionmodifierp :: JournalParser m TransactionModifier
transactionmodifierp :: forall (m :: * -> *). JournalParser m TransactionModifier
transactionmodifierp = do
  Token Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'=' StateT Journal (ParsecT HledgerParseErrorData Text m) Char
-> String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Char
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"modifier transaction"
  ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  querytxt <- ParsecT HledgerParseErrorData Text m Text
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Text
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (ParsecT HledgerParseErrorData Text m Text
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) Text)
-> ParsecT HledgerParseErrorData Text m Text
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Text
forall a b. (a -> b) -> a -> b
$ Text -> Text
T.strip (Text -> Text)
-> ParsecT HledgerParseErrorData Text m Text
-> ParsecT HledgerParseErrorData Text m Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ParsecT HledgerParseErrorData Text m Text
forall (m :: * -> *). TextParser m Text
descriptionp
  (_comment, _tags) <- lift transactioncommentp   -- TODO apply these to modified txns ?
  postingrules <- tmpostingrulesp Nothing
  return $ TransactionModifier querytxt postingrules

-- | Parse a periodic transaction rule.
--
-- This reuses periodexprp which parses period expressions on the command line.
-- This is awkward because periodexprp supports relative and partial dates,
-- which we don't really need here, and it doesn't support the notion of a
-- default year set by a Y directive, which we do need to consider here.
-- We resolve it as follows: in periodic transactions' period expressions,
-- if there is a default year Y in effect, partial/relative dates are calculated
-- relative to Y/1/1. If not, they are calculated related to today as usual.
periodictransactionp :: MonadIO m => JournalParser m PeriodicTransaction
periodictransactionp :: forall (m :: * -> *).
MonadIO m =>
JournalParser m PeriodicTransaction
periodictransactionp = do
  startpos <- JournalParser m SourcePos
forall (m :: * -> *). JournalParser m SourcePos
getSourcePos'

  -- first line
  char '~' <?> "periodic transaction"
  lift $ skipNonNewlineSpaces

  -- if there's a default year in effect, use Y/1/1 as base for partial/relative dates
  today <- liftIO getCurrentDay
  mdefaultyear <- getYear
  let refdate = case Maybe Integer
mdefaultyear of
                  Maybe Integer
Nothing -> Day
today
                  Just Integer
y  -> Integer -> Int -> Int -> Day
fromGregorian Integer
y Int
1 Int
1
  periodExcerpt <- lift $ excerpt_ $
                    singlespacedtextsatisfying1p (\Char
c -> Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
';' Bool -> Bool -> Bool
&& Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\n')
  let periodtxt = Text -> Text
T.strip (Text -> Text) -> Text -> Text
forall a b. (a -> b) -> a -> b
$ SourceExcerpt -> Text
getExcerptText SourceExcerpt
periodExcerpt

  -- first parsing with 'singlespacedtextp', then "re-parsing" with
  -- 'periodexprp' saves 'periodexprp' from having to respect the single-
  -- and double-space parsing rules
  (interval, spn) <- lift $ reparseExcerpt periodExcerpt $ do
    pexp <- periodexprp refdate
    (<|>) eof $ do
      offset1 <- getOffset
      void takeRest
      offset2 <- getOffset
      customFailure $ parseErrorAtRegion offset1 offset2 $
           "remainder of period expression cannot be parsed"
        <> "\nperhaps you need to terminate the period expression with a double space?"
        <> "\na double space is required between period expression and description/comment"
    pure pexp

  status <- lift statusp <?> "cleared status"
  code <- lift codep <?> "transaction code"
  description <- lift $ T.strip <$> descriptionp
  (comment, tags) <- lift transactioncommentp
  -- next lines; use same year determined above.
  -- Amounts calculated with * or / are rounded to their own precision (#2648).
  postings <- map (fst . postingRoundCalculatedAmounts mempty) <$> postingsp (Just $ first3 $ toGregorian refdate)

  endpos <- getSourcePos'
  let sourcepos = (SourcePos
startpos, SourcePos
endpos)

  return $ nullperiodictransaction{
     ptperiodexpr=periodtxt
    ,ptinterval=interval
    ,ptspan=spn
    ,ptsourcepos=sourcepos
    ,ptstatus=status
    ,ptcode=code
    ,ptdescription=description
    ,ptcomment=comment
    ,pttags=tags
    ,ptpostings=postings
    }

-- | Parse an assert directive:
--
-- > assert (none|some)[ PERIODEXPR][  QUERY]  [; COMMENT]
--
-- A period expression follows the quantifier after one space,
-- and a query follows the quantifier or period expression after two or more spaces.
-- Relative dates in the period expression and the query are relative to the given day (today).
-- The query is parsed to check it, and kept as text.
assertdirectivep :: Monad m => Day -> JournalParser m AssertDirective
assertdirectivep :: forall (m :: * -> *).
Monad m =>
Day -> JournalParser m AssertDirective
assertdirectivep Day
today = do
  pos <- JournalParser m SourcePos
forall (m :: * -> *). JournalParser m SourcePos
getSourcePos'
  line <- T.takeWhile (/= '\n') <$> getInput
  try (string "assert" <* lift skipNonNewlineSpaces1) <?> "assert directive"
  quantoff <- getOffset
  quantword <- lift $ takeWhileP Nothing (not . isSpace)
  quant <- case quantword of
    Text
"none" -> AssertQuantifier
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) AssertQuantifier
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure AssertQuantifier
AssertNone
    Text
"some" -> AssertQuantifier
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) AssertQuantifier
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure AssertQuantifier
AssertSome
    Text
_ -> HledgerParseErrorData
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) AssertQuantifier
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData
 -> StateT
      Journal (ParsecT HledgerParseErrorData Text m) AssertQuantifier)
-> HledgerParseErrorData
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) AssertQuantifier
forall a b. (a -> b) -> a -> b
$ Int -> Int -> String -> HledgerParseErrorData
parseErrorAtRegion Int
quantoff (Int
quantoff Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Text -> Int
T.length Text
quantword) (String -> HledgerParseErrorData)
-> String -> HledgerParseErrorData
forall a b. (a -> b) -> a -> b
$
           String
"assert should be followed by none or some (and the query must match no rows, or some rows)"
  mperiod <- optional $ do
    lift $ try $ singlespacep *> lookAhead (satisfy (\Token Text
c -> Char
Token Text
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
';' Bool -> Bool -> Bool
&& Bool -> Bool
not (Char -> Bool
isSpace Char
Token Text
c)))
    periodExcerpt <- lift $ excerpt_ $ singlespacedtextsatisfying1p (\Char
c -> Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
';' Bool -> Bool -> Bool
&& Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\n')
    lift $ reparseExcerpt periodExcerpt $ do
      pexp <- try (periodexprp today) <|> do
        offset1 <- getOffset
        void takeRest
        offset2 <- getOffset
        customFailure $ parseErrorAtRegion offset1 offset2 $
             "could not parse this as a period expression"
          <> "\none space after none/some begins a period expression;"
          <> "\nthe query must follow two or more spaces"
      (<|>) eof $ do
        offset1 <- getOffset
        void takeRest
        offset2 <- getOffset
        customFailure $ parseErrorAtRegion offset1 offset2 $
             "remainder of period expression cannot be parsed"
          <> "\nperhaps you need to terminate the period expression with a double space?"
          <> "\na double space separates the period expression from the query"
      pure (pexp, T.strip $ getExcerptText periodExcerpt)
  -- What remains is the query, after two or more spaces (or nothing).
  lift skipNonNewlineSpaces
  queryoff <- getOffset
  querytxt <- lift $ T.strip <$> noncommenttextp
  queryend <- getOffset
  let queryerr = HledgerParseErrorData
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) a)
-> (String -> HledgerParseErrorData)
-> String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Int -> String -> HledgerParseErrorData
parseErrorAtRegion Int
queryoff Int
queryend
  either queryerr (const $ pure ()) $ querySplitRowTerms . fst =<< parseQuery today querytxt
  void $ lift followingcommentp
  -- Then any skip subdirectives, on indented lines.
  skips <- many skipsubdirectivep
  case (skips, mperiod) of
    ((Int
off1, Int
off2, DateSpan
_, Text
_):[(Int, Int, DateSpan, Text)]
_, Maybe ((Interval, DateSpan), Text)
m) | Bool
-> (((Interval, DateSpan), Text) -> Bool)
-> Maybe ((Interval, DateSpan), Text)
-> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
True ((Interval -> Interval -> Bool
forall a. Eq a => a -> a -> Bool
== Interval
NoInterval) (Interval -> Bool)
-> (((Interval, DateSpan), Text) -> Interval)
-> ((Interval, DateSpan), Text)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Interval, DateSpan) -> Interval
forall a b. (a, b) -> a
fst ((Interval, DateSpan) -> Interval)
-> (((Interval, DateSpan), Text) -> (Interval, DateSpan))
-> ((Interval, DateSpan), Text)
-> Interval
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((Interval, DateSpan), Text) -> (Interval, DateSpan)
forall a b. (a, b) -> a
fst) Maybe ((Interval, DateSpan), Text)
m ->
      HledgerParseErrorData
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) ())
-> HledgerParseErrorData
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b. (a -> b) -> a -> b
$ Int -> Int -> String -> HledgerParseErrorData
parseErrorAtRegion Int
off1 Int
off2 (String -> HledgerParseErrorData)
-> String -> HledgerParseErrorData
forall a b. (a -> b) -> a -> b
$
        String
"skip is only allowed when the assert directive has a period expression with a report interval (like daily or monthly)"
    ([(Int, Int, DateSpan, Text)], Maybe ((Interval, DateSpan), Text))
_ -> () -> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  return AssertDirective{adQuantifier=quant, adPeriod=fst <$> mperiod, adPeriodText=maybe "" snd mperiod,
                         adQueryText=querytxt, adSkips=[sp | (_, _, sp, _) <- skips],
                         adSourceText=T.intercalate "\n" $ line : [l | (_, _, _, l) <- skips], adSourcePos=pos}
  where
    -- A skip subdirective: an indented line @skip PERIOD@, with an optional comment,
    -- where PERIOD is a period expression without a report interval.
    -- Returns the PERIOD's start and end offsets, its date span, and the line as written.
    -- Any other indented line (other than a comment line, which followingcommentp consumes) is an error.
    skipsubdirectivep :: StateT
  Journal
  (ParsecT HledgerParseErrorData Text m)
  (Int, Int, DateSpan, Text)
skipsubdirectivep = do
      ParsecT HledgerParseErrorData Text m (Token Text)
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Token Text)
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (ParsecT HledgerParseErrorData Text m (Token Text)
 -> StateT
      Journal (ParsecT HledgerParseErrorData Text m) (Token Text))
-> ParsecT HledgerParseErrorData Text m (Token Text)
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Token Text)
forall a b. (a -> b) -> a -> b
$ ParsecT HledgerParseErrorData Text m (Token Text)
-> ParsecT HledgerParseErrorData Text m (Token Text)
forall a.
ParsecT HledgerParseErrorData Text m a
-> ParsecT HledgerParseErrorData Text m a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (ParsecT HledgerParseErrorData Text m (Token Text)
 -> ParsecT HledgerParseErrorData Text m (Token Text))
-> ParsecT HledgerParseErrorData Text m (Token Text)
-> ParsecT HledgerParseErrorData Text m (Token Text)
forall a b. (a -> b) -> a -> b
$ ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1 ParsecT HledgerParseErrorData Text m ()
-> ParsecT HledgerParseErrorData Text m (Token Text)
-> ParsecT HledgerParseErrorData Text m (Token Text)
forall a b.
ParsecT HledgerParseErrorData Text m a
-> ParsecT HledgerParseErrorData Text m b
-> ParsecT HledgerParseErrorData Text m b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> ParsecT HledgerParseErrorData Text m (Token Text)
-> ParsecT HledgerParseErrorData Text m (Token Text)
forall a.
ParsecT HledgerParseErrorData Text m a
-> ParsecT HledgerParseErrorData Text m a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
lookAhead ((Token Text -> Bool)
-> ParsecT HledgerParseErrorData Text m (Token Text)
forall e s (m :: * -> *).
MonadParsec e s m =>
(Token s -> Bool) -> m (Token s)
satisfy (Bool -> Bool
not (Bool -> Bool) -> (Char -> Bool) -> Char -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> Bool
isSpace))
      line' <- (Text -> Text
T.stripStart (Text -> Text) -> (Text -> Text) -> Text -> Text
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Char -> Bool) -> Text -> Text
T.takeWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\n')) (Text -> Text)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Text
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Text
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> StateT Journal (ParsecT HledgerParseErrorData Text m) Text
forall e s (m :: * -> *). MonadParsec e s m => m s
getInput
      off0 <- getOffset
      word <- lift $ takeWhileP Nothing (not . isSpace)
      off0' <- getOffset
      when (word /= "skip") $ customFailure $ parseErrorAtRegion off0 off0' $
        "an indented line after an assert directive should be a skip subdirective, like:  skip 2026-05"
      lift skipNonNewlineSpaces1
      off1 <- getOffset
      periodtxt <- lift $ singlespacedtextsatisfying1p (\Char
c -> Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
';' Bool -> Bool -> Bool
&& Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\n')
      off2 <- getOffset
      sp <- case parsePeriodExpr today periodtxt of
        Right (Interval
NoInterval, DateSpan
sp) -> DateSpan
-> StateT Journal (ParsecT HledgerParseErrorData Text m) DateSpan
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure DateSpan
sp
        Right (Interval, DateSpan)
_ -> HledgerParseErrorData
-> StateT Journal (ParsecT HledgerParseErrorData Text m) DateSpan
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) DateSpan)
-> HledgerParseErrorData
-> StateT Journal (ParsecT HledgerParseErrorData Text m) DateSpan
forall a b. (a -> b) -> a -> b
$ Int -> Int -> String -> HledgerParseErrorData
parseErrorAtRegion Int
off1 Int
off2 String
"a skip period can't have a report interval"
        Left HledgerParseErrors
_  -> HledgerParseErrorData
-> StateT Journal (ParsecT HledgerParseErrorData Text m) DateSpan
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) DateSpan)
-> HledgerParseErrorData
-> StateT Journal (ParsecT HledgerParseErrorData Text m) DateSpan
forall a b. (a -> b) -> a -> b
$ Int -> Int -> String -> HledgerParseErrorData
parseErrorAtRegion Int
off1 Int
off2 String
"could not parse this as a period (a date, or a period expression without a report interval)"
      lift skipNonNewlineSpaces
      void $ lift followingcommentp
      pure (off1, off2, sp, line')

-- | Parse one assert directive given as text, such as a check command argument,
-- naming its source in error messages with the given name.
-- Relative dates are relative to the given day (today).
parseAssertDirective :: Day -> String -> Text -> Either String AssertDirective
parseAssertDirective :: Day -> String -> Text -> Either String AssertDirective
parseAssertDirective Day
today String
srcname Text
t =
  (HledgerParseErrors -> String)
-> Either HledgerParseErrors AssertDirective
-> Either String AssertDirective
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first HledgerParseErrors -> String
customErrorBundlePretty (Either HledgerParseErrors AssertDirective
 -> Either String AssertDirective)
-> Either HledgerParseErrors AssertDirective
-> Either String AssertDirective
forall a b. (a -> b) -> a -> b
$
  Parsec HledgerParseErrorData Text AssertDirective
-> String -> Text -> Either HledgerParseErrors AssertDirective
forall e s a.
Parsec e s a -> String -> s -> Either (ParseErrorBundle s e) a
runParser (StateT
  Journal
  (ParsecT HledgerParseErrorData Text Identity)
  AssertDirective
-> Journal -> Parsec HledgerParseErrorData Text AssertDirective
forall (m :: * -> *) s a. Monad m => StateT s m a -> s -> m a
evalStateT (Day
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text Identity)
     AssertDirective
forall (m :: * -> *).
Monad m =>
Day -> JournalParser m AssertDirective
assertdirectivep Day
today StateT
  Journal
  (ParsecT HledgerParseErrorData Text Identity)
  AssertDirective
-> StateT Journal (ParsecT HledgerParseErrorData Text Identity) ()
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text Identity)
     AssertDirective
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text Identity) a
-> StateT Journal (ParsecT HledgerParseErrorData Text Identity) b
-> StateT Journal (ParsecT HledgerParseErrorData Text Identity) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* StateT Journal (ParsecT HledgerParseErrorData Text Identity) ()
forall e s (m :: * -> *). MonadParsec e s m => m ()
eof) Journal
nulljournal) String
srcname (Text -> Text
T.stripEnd Text
t Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"\n")

-- | Parse a (possibly unbalanced) transaction.
transactionp :: JournalParser m Transaction
transactionp :: forall (m :: * -> *). JournalParser m Transaction
transactionp = do
  -- dbgparse 0 "transactionp"
  startpos <- JournalParser m SourcePos
forall (m :: * -> *). JournalParser m SourcePos
getSourcePos'
  date <- datep <?> "transaction"
  mc <- lift peekChar
  edate <- if mc == Just '=' then optional (lift $ secondarydatep date) <?> "secondary date" else pure Nothing
  lookAhead (lift spacenonewline <|> newline) <?> "whitespace or newline"
  status <- lift statusp <?> "cleared status"
  code <- lift codep <?> "transaction code"
  description <- lift $ T.strip <$> descriptionp
  (comment, tags) <- lift transactioncommentp
  let year = (Integer, Int, Int) -> Integer
forall {a} {b} {c}. (a, b, c) -> a
first3 ((Integer, Int, Int) -> Integer) -> (Integer, Int, Int) -> Integer
forall a b. (a -> b) -> a -> b
$ Day -> (Integer, Int, Int)
toGregorian Day
date
  postings <- postingsp (Just year)
  endpos <- getSourcePos'
  let sourcepos = (SourcePos
startpos, SourcePos
endpos)
  return $ txnTieKnot $ transactionRoundCalculatedAmounts $
    Transaction 0 "" sourcepos date edate status code description comment tags postings

--- *** fast path

-- The parser's fast path: cheaper parsing of the commonest kinds of transaction and market
-- price directive. Most of the time spent parsing a large journal goes to megaparsec parsers,
-- which allocate heavily for every token and for every failed attempt at optional syntax.
-- So before running the general transactionp or marketpricedirectivep, the parser first tries
-- a scanner (scanSimpleTransaction, scanSimplePrice) which reads the input Text directly.
-- If the entry has the common simple form, the scanner extracts its parts and the fast path
-- builds the same value the general parser would have built; otherwise the scanner "declines",
-- returning a short reason (as a Left) without consuming anything, and the general parser runs
-- as before. With --debug, the outcomes are counted and reported after parsing (see
-- countFastPath), showing how much of a journal takes the fast path and what keeps the rest
-- off it. On a journal of simple transactions this makes parsing about a third faster, with a
-- third of the allocation (see doc/PERFORMANCE.md).
--
-- The one rule for all of this code: the fast path must produce exactly what the general parser
-- would, or decline. So each scanner below mirrors one general parser (named in its doc comment),
-- copying that parser's rules, and declines on anything it does not fully handle, including
-- anything that would be a parse error (the general parser knows how to report those).
-- Declining is always safe, it just means the general parser does the work; so when in doubt,
-- decline. To extend the fast path to more syntax: find the general parser whose behaviour is
-- to be copied, copy it exactly (including the parse-time sharing of names and styles, see
-- shareText and shareAmountStyle), add a case to hledger/test/journal/fastpath.test, and run
-- the whole functional test suite in check mode (below) to confirm the two parsers still agree.

-- | To disable the fast path entirely, eg while investigating a parsing problem, set this to
-- False: transactions and price directives are then parsed by the general parsers only,
-- exactly as before the fast path existed. (At run time, setting HLEDGER_FASTPATH=off in the
-- environment does the same, without rebuilding; see fastPathMode.)
fastPathEnabled :: Bool
fastPathEnabled :: Bool
fastPathEnabled = Bool
True

-- | How the fast path is used, as set by the HLEDGER_FASTPATH environment variable (for
-- testing): unset or empty means use it; "off" means don't; "check" means use it, and also
-- parse each fast-path entry with the general parser and fail if the results differ.
-- The variable is read once, when first needed (hence unsafePerformIO and NOINLINE),
-- so that consulting this for every entry costs almost nothing.
fastPathMode :: String
fastPathMode :: String
fastPathMode = IO String -> String
forall a. IO a -> a
unsafePerformIO (IO String -> String) -> IO String -> String
forall a b. (a -> b) -> a -> b
$ String -> Maybe String -> String
forall a. a -> Maybe a -> a
fromMaybe String
"" (Maybe String -> String) -> IO (Maybe String) -> IO String
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> String -> IO (Maybe String)
lookupEnv String
"HLEDGER_FASTPATH"
{-# NOINLINE fastPathMode #-}

-- | Run a fast-path parser (which returns a decline reason, as a Left, when it declines),
-- falling back to the general parser when it declines, or when HLEDGER_FASTPATH says to (see
-- fastPathMode); and count the outcome (see countFastPath).
-- In check mode, after the fast path accepts an entry, the parser state and journal state are
-- rewound and the general parser is run on the same input; the two results are compared after
-- applying the given normalising function (txnUntieKnot for transactions, whose postings refer
-- back to their transaction: comparing or showing such cyclic values would not terminate).
-- If they agree, the fast path's end state is restored (so that the journal keeps its result,
-- and its parse-time sharing sets); otherwise the parse fails with a message showing both.
withFastPath :: (Eq a, Show a) => FastPathKind -> (a -> a) -> JournalParser m (Either Text a) -> JournalParser m a -> JournalParser m a
withFastPath :: forall a (m :: * -> *).
(Eq a, Show a) =>
FastPathKind
-> (a -> a)
-> JournalParser m (Either Text a)
-> JournalParser m a
-> JournalParser m a
withFastPath FastPathKind
kind a -> a
norm JournalParser m (Either Text a)
fastp JournalParser m a
generalp
  | Bool -> Bool
not Bool
fastPathEnabled = JournalParser m a
generalp
  | Bool
otherwise = case String
fastPathMode of
  String
"off"   -> JournalParser m a
generalp
  String
"check" -> do
    st0 <- StateT
  Journal
  (ParsecT HledgerParseErrorData Text m)
  (State Text HledgerParseErrorData)
forall e s (m :: * -> *). MonadParsec e s m => m (State s e)
getParserState
    j0  <- get
    ex  <- fastp
    countFastPath kind ex
    case ex of
      Left Text
_ -> JournalParser m a
generalp
      Right a
x -> do
        st1 <- StateT
  Journal
  (ParsecT HledgerParseErrorData Text m)
  (State Text HledgerParseErrorData)
forall e s (m :: * -> *). MonadParsec e s m => m (State s e)
getParserState
        j1  <- get
        setParserState st0
        put j0
        x' <- generalp
        when (norm x /= norm x') $
          fail $ "fast path mismatch:\n" ++ show (norm x) ++ "\ngeneral parser:\n" ++ show (norm x')
        setParserState st1
        put j1
        return x
  -- (Without --debug, the outcome is not counted; keep that path free of the extra bind,
  -- whose continuation closures would cost about 2% of parsing.)
  String
_ | Int
debugLevel Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0 -> do
        ex <- JournalParser m (Either Text a)
fastp
        countFastPath kind ex
        either (const generalp) pure ex
    | Bool
otherwise -> JournalParser m (Either Text a)
fastp JournalParser m (Either Text a)
-> (Either Text a -> JournalParser m a) -> JournalParser m a
forall a b.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> (a -> StateT Journal (ParsecT HledgerParseErrorData Text m) b)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (Text -> JournalParser m a)
-> (a -> JournalParser m a) -> Either Text a -> JournalParser m a
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (JournalParser m a -> Text -> JournalParser m a
forall a b. a -> b -> a
const JournalParser m a
generalp) a -> JournalParser m a
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure

-- | The kinds of entry the fast path handles, for counting its outcomes.
data FastPathKind = FastPathTransaction | FastPathPrice

-- | Count a fast path outcome (Right: the entry was accepted; Left: it was declined, with
-- the reason) in the journal's fast path statistics, which are reported after parsing
-- (see Hledger.Read.Common.dbgFastPathStats). Called only with --debug.
countFastPath :: FastPathKind -> Either Text a -> JournalParser m ()
countFastPath :: forall a (m :: * -> *).
FastPathKind -> Either Text a -> JournalParser m ()
countFastPath FastPathKind
kind Either Text a
outcome = (Journal -> Journal)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' ((Journal -> Journal)
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) ())
-> (Journal -> Journal)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall a b. (a -> b) -> a -> b
$ \Journal
j -> Journal
j{jparsefastpathstats = tally $ jparsefastpathstats j}
  where
    tally :: FastPathStats -> FastPathStats
tally FastPathStats
s = case (FastPathKind
kind, Either Text a
outcome) of
      (FastPathKind
FastPathTransaction, Right a
_) -> FastPathStats
s{fpsTxnsFast      = fpsTxnsFast s + 1}
      (FastPathKind
FastPathPrice,       Right a
_) -> FastPathStats
s{fpsPricesFast    = fpsPricesFast s + 1}
      (FastPathKind
FastPathTransaction, Left Text
r)  -> FastPathStats
s{fpsTxnsGeneral   = fpsTxnsGeneral s + 1,   fpsDeclines = M.insertWith (+) r 1 $ fpsDeclines s}
      (FastPathKind
FastPathPrice,       Left Text
r)  -> FastPathStats
s{fpsPricesGeneral = fpsPricesGeneral s + 1, fpsDeclines = M.insertWith (+) r 1 $ fpsDeclines s}

-- | Parse a transaction, using the fast path when it is a simple one (see fasttransactionp).
transactionOrFastp :: JournalParser m Transaction
transactionOrFastp :: forall (m :: * -> *). JournalParser m Transaction
transactionOrFastp = FastPathKind
-> (Transaction -> Transaction)
-> JournalParser m (Either Text Transaction)
-> JournalParser m Transaction
-> JournalParser m Transaction
forall a (m :: * -> *).
(Eq a, Show a) =>
FastPathKind
-> (a -> a)
-> JournalParser m (Either Text a)
-> JournalParser m a
-> JournalParser m a
withFastPath FastPathKind
FastPathTransaction Transaction -> Transaction
txnUntieKnot JournalParser m (Either Text Transaction)
forall (m :: * -> *). JournalParser m (Either Text Transaction)
fasttransactionp JournalParser m Transaction
forall (m :: * -> *). JournalParser m Transaction
transactionp

-- | Parse a market price directive, using the fast path when it is a simple one (see fastmarketpricedirectivep).
marketpriceOrFastp :: JournalParser m PriceDirective
marketpriceOrFastp :: forall (m :: * -> *). JournalParser m PriceDirective
marketpriceOrFastp = FastPathKind
-> (PriceDirective -> PriceDirective)
-> JournalParser m (Either Text PriceDirective)
-> JournalParser m PriceDirective
-> JournalParser m PriceDirective
forall a (m :: * -> *).
(Eq a, Show a) =>
FastPathKind
-> (a -> a)
-> JournalParser m (Either Text a)
-> JournalParser m a
-> JournalParser m a
withFastPath FastPathKind
FastPathPrice PriceDirective -> PriceDirective
forall a. a -> a
id JournalParser m (Either Text PriceDirective)
forall (m :: * -> *). JournalParser m (Either Text PriceDirective)
fastmarketpricedirectivep JournalParser m PriceDirective
forall (m :: * -> *). JournalParser m PriceDirective
marketpricedirectivep

-- | The scanners below run in Either Text: a Left is a decline, carrying a short reason
-- (the same wording each time, since --debug counts the declines by reason).
-- This declines with the given reason if the condition holds.
declineIf :: Bool -> Text -> Either Text ()
declineIf :: Bool -> Text -> Either Text ()
declineIf Bool
cond Text
reason = Bool -> Either Text () -> Either Text ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
cond (Either Text () -> Either Text ())
-> Either Text () -> Either Text ()
forall a b. (a -> b) -> a -> b
$ Text -> Either Text ()
forall a b. a -> Either a b
Left Text
reason
{-# INLINE declineIf #-}

-- | Convert a Maybe-returning scanner's result to a decline with the given reason, or a success.
orDecline :: Text -> Maybe a -> Either Text a
orDecline :: forall a. Text -> Maybe a -> Either Text a
orDecline Text
reason = Either Text a -> (a -> Either Text a) -> Maybe a -> Either Text a
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Text -> Either Text a
forall a b. a -> Either a b
Left Text
reason) a -> Either Text a
forall a b. b -> Either a b
Right
{-# INLINE orDecline #-}

-- | A following comment's text as followingcommentpWith builds it, from the same-line comment's
-- text (after the semicolon) if there was one, and any following comment lines' texts: each
-- stripped and newline-terminated, with an empty first line when there was no same-line comment
-- but there are following lines (so that the comment is not rendered as a same-line one).
commentText :: Maybe Text -> [Text] -> Text
commentText :: Maybe Text -> [Text] -> Text
commentText Maybe Text
msameline [Text]
nextlines = case (Maybe Text
msameline, [Text]
nextlines) of
  (Maybe Text
Nothing, []) -> Text
""
  (Maybe Text, [Text])
_ -> [Text] -> Text
T.unlines ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ (Text -> Text) -> [Text] -> [Text]
forall a b. (a -> b) -> [a] -> [b]
map Text -> Text
T.strip ([Text] -> [Text]) -> [Text] -> [Text]
forall a b. (a -> b) -> a -> b
$ Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe Text
"" Maybe Text
msameline Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: [Text]
nextlines

-- | The tags in a transaction comment line's text (after the semicolon), as commentlinetagsp
-- parses them: a colon ends a tag name, which is the last whitespace-separated word before it
-- (if there is none, the colon is just skipped); the tag's value is the whitespace-stripped text
-- up to the next comma or the end of the line; and so on along the line.
scanTransactionTags :: Text -> [Tag]
scanTransactionTags :: Text -> [Tag]
scanTransactionTags Text
t =
  let (Text
before, Text
rest) = (Char -> Bool) -> Text -> Tag
T.break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
':') Text
t
      name :: Text
name = (Char -> Bool) -> Text -> Text
T.takeWhileEnd (Bool -> Bool
not (Bool -> Bool) -> (Char -> Bool) -> Char -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> Bool
isSpace) Text
before
  in case Text -> Text -> Maybe Text
T.stripPrefix Text
":" Text
rest of
    Maybe Text
Nothing -> []
    Just Text
aftercolon
      | Text -> Bool
T.null Text
name -> Text -> [Tag]
scanTransactionTags Text
aftercolon
      | Bool
otherwise ->
          let (Text
valtext, Text
rest2) = (Char -> Bool) -> Text -> Tag
T.break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
',') (Text -> Tag) -> Text -> Tag
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
aftercolon
          in (Text
name, Text -> Text
T.strip Text
valtext) Tag -> [Tag] -> [Tag]
forall a. a -> [a] -> [a]
: Text -> [Tag]
scanTransactionTags (Text -> Text
dropComma Text
rest2)

-- | The tags, and the posting dates from date: and date2: tags, in a posting comment line's
-- text, as commenttagsanddatesp parses them, given the transaction's year for partial dates.
-- Like scanTransactionTags, except that after a colon with no tag name, spaces and a comma are
-- skipped, and a non-empty date tag value must begin with a date, which is returned as well.
-- Returns Nothing if a date tag's value does not begin with a date scanSimpleDate handles (the
-- general parser accepts a few more forms, and reports invalid ones). The text must not contain
-- a bracketed date (callers decline those).
scanPostingTags :: Year -> Text -> Maybe ([Tag], [(TagName, Day)])
scanPostingTags :: Integer -> Text -> Maybe ([Tag], [(Text, Day)])
scanPostingTags Integer
year Text
t =
  let (Text
before, Text
rest) = (Char -> Bool) -> Text -> Tag
T.break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
':') Text
t
      name :: Text
name = (Char -> Bool) -> Text -> Text
T.takeWhileEnd (Bool -> Bool
not (Bool -> Bool) -> (Char -> Bool) -> Char -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> Bool
isSpace) Text
before
  in case Text -> Text -> Maybe Text
T.stripPrefix Text
":" Text
rest of
    Maybe Text
Nothing -> ([Tag], [(Text, Day)]) -> Maybe ([Tag], [(Text, Day)])
forall a. a -> Maybe a
Just ([], [])
    Just Text
aftercolon -> do
      let r :: Text
r = (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
aftercolon
          (Text
valtext, Text
rest2) = (Char -> Bool) -> Text -> Tag
T.break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
',') Text
r
          val :: Text
val = Text -> Text
T.strip Text
valtext
      (tags, dates, rest3) <-
        if Text -> Bool
T.null Text
name then ([Tag], [(Text, Day)], Text) -> Maybe ([Tag], [(Text, Day)], Text)
forall a. a -> Maybe a
Just ([], [], Text
r)
        else if (Text
name Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"date" Bool -> Bool -> Bool
|| Text
name Text -> Text -> Bool
forall a. Eq a => a -> a -> Bool
== Text
"date2") Bool -> Bool -> Bool
&& Bool -> Bool
not (Text -> Bool
T.null Text
val) then do
          (date, _) <- Maybe Integer -> Text -> Maybe (Day, Text)
scanSimpleDate (Integer -> Maybe Integer
forall a. a -> Maybe a
Just Integer
year) Text
r
          Just ([(name, val)], [(name, date)], rest2)
        else ([Tag], [(Text, Day)], Text) -> Maybe ([Tag], [(Text, Day)], Text)
forall a. a -> Maybe a
Just ([(Text
name, Text
val)], [], Text
rest2)
      (moretags, moredates) <- scanPostingTags year (dropComma rest3)
      Just (tags ++ moretags, dates ++ moredates)

-- | Drop a leading comma, if any (like optional (char ',')).
dropComma :: Text -> Text
dropComma :: Text -> Text
dropComma Text
t = Text -> Maybe Text -> Text
forall a. a -> Maybe a -> a
fromMaybe Text
t (Maybe Text -> Text) -> Maybe Text -> Text
forall a b. (a -> b) -> a -> b
$ Text -> Text -> Maybe Text
T.stripPrefix Text
"," Text
t

-- | The parts of a simple transaction recognised by scanSimpleTransaction.
data SimpleTransaction = SimpleTransaction {
   SimpleTransaction -> Day
stDate        :: !Day
  ,SimpleTransaction -> Maybe Day
stDate2       :: !(Maybe Day)
  ,SimpleTransaction -> Status
stStatus      :: !Status
  ,SimpleTransaction -> Text
stCode        :: !Text
  ,SimpleTransaction -> Text
stDescription :: !Text
  ,SimpleTransaction -> Text
stComment     :: !Text
  ,SimpleTransaction -> [Tag]
stTags        :: ![Tag]
  ,SimpleTransaction -> [SimplePosting]
stPostings    :: ![SimplePosting]
  }

-- | The parts of a simple posting recognised by scanSimplePosting.
data SimplePosting = SimplePosting {
   SimplePosting -> Status
spStatus   :: !Status
  ,SimplePosting -> Text
spAccount  :: !AccountName       -- ^ with aliases and the parent account applied, and brackets removed
  ,SimplePosting -> PostingRealness
spRealness :: !PostingRealness
  ,SimplePosting -> Maybe Amount
spAmount   :: !(Maybe Amount)
  ,SimplePosting -> Maybe SimpleAssertion
spAssertion :: !(Maybe SimpleAssertion)
  ,SimplePosting -> Text
spComment  :: !Text
  ,SimplePosting -> [Tag]
spTags     :: ![Tag]
  ,SimplePosting -> Maybe Day
spDate     :: !(Maybe Day)       -- ^ from a date: tag, if any
  ,SimplePosting -> Maybe Day
spDate2    :: !(Maybe Day)       -- ^ from a date2: tag, if any
  }

-- | The parts of a balance assertion or assignment recognised by scanSimpleAssertion.
-- Its position is relative to the transaction, since the scanners don't know where that is
-- in the file; fasttransactionp makes it absolute.
data SimpleAssertion = SimpleAssertion {
   SimpleAssertion -> Amount
saAmount     :: !Amount
  ,SimpleAssertion -> Bool
saTotal      :: !Bool
  ,SimpleAssertion -> Bool
saInclusive  :: !Bool
  ,SimpleAssertion -> Int
saLineOffset :: !Int  -- ^ how many lines after the transaction's first line
  ,SimpleAssertion -> Int
saColumn     :: !Int  -- ^ the column of the first = (1-based)
  }

-- | A fast path for the commonest kind of transaction: if the input begins with one, parse
-- it, consuming its lines; otherwise consume nothing and return the reason for declining, so
-- that the general transactionp can be used. This produces exactly what transactionp would,
-- but much more cheaply, by scanning the text directly instead of running megaparsec parsers
-- (which allocate heavily per token). A simple transaction has:
--
-- - a date (YYYY-MM-DD, or with / or . separators; or MM-DD, using the default year), an
--   optional secondary date, an optional * or ! status mark, an optional (code), a description,
--   and optionally a comment (same-line and/or on following indented lines), possibly with tags;
-- - zero or more postings, each an indented line with an optional status mark, an account name
--   (possibly in parens or brackets), optionally an amount, and optionally a comment (as above),
--   possibly with tags including date tags, but with no bracketed dates; optionally a balance
--   assertion or assignment (with no tab before it on the line); no lot annotation;
-- - amounts whose number is digits, with or without digit group marks, a decimal mark and decimal
--   digits (as rawnumberp accepts; but no exponent), with an optional sign, an optional
--   commodity symbol on either side, and an optional @ or @@ cost of the same form;
--   and when there is no symbol, no default commodity directive in effect;
-- - no CR characters.
--
-- Anything else declines, including anything that would be a parse error, so that the general
-- parser reports it. Numbers are interpreted by the same code as the general parser
-- (interpretRawNumber), so declared commodity styles and decimal marks work.
fasttransactionp :: JournalParser m (Either Text Transaction)
fasttransactionp :: forall (m :: * -> *). JournalParser m (Either Text Transaction)
fasttransactionp = do
  j <- StateT Journal (ParsecT HledgerParseErrorData Text m) Journal
forall s (m :: * -> *). MonadState s m => m s
get
  s <- getInput
  case scanSimpleTransaction j s of
    Left Text
reason -> Either Text Transaction
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text m)
     (Either Text Transaction)
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either Text Transaction
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData Text m)
      (Either Text Transaction))
-> Either Text Transaction
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text m)
     (Either Text Transaction)
forall a b. (a -> b) -> a -> b
$ Text -> Either Text Transaction
forall a b. a -> Either a b
Left Text
reason
    Right (SimpleTransaction
stxn, Int
consumed) -> do
      startpos <- JournalParser m SourcePos
forall (m :: * -> *). JournalParser m SourcePos
getSourcePos'
      -- share the account names, symbols and styles with identical earlier ones, as postingp does
      ps <- mapM (internPosting startpos) $ stPostings stxn
      -- consume the scanned text; megaparsec computes source positions from the offset on demand,
      -- so updating the input and the offset is all that is needed
      updateParserState $ \State Text HledgerParseErrorData
st -> State Text HledgerParseErrorData
st{stateInput = T.drop consumed s, stateOffset = stateOffset st + consumed}
      endpos <- getSourcePos'
      -- the same value transactionp builds; the index and preceding comment are filled in
      -- later, as for any transaction
      return $ Right $ txnTieKnot $ Transaction 0 "" (startpos, endpos) (stDate stxn) (stDate2 stxn) (stStatus stxn) (stCode stxn)
        (stDescription stxn) (stComment stxn) (stTags stxn) ps
  where
    internPosting :: SourcePos
-> SimplePosting
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Posting
internPosting SourcePos
startpos SimplePosting
sp = do
      acct' <- Text -> JournalParser m Text
forall (m :: * -> *). Text -> JournalParser m Text
shareText (Text -> JournalParser m Text) -> Text -> JournalParser m Text
forall a b. (a -> b) -> a -> b
$ SimplePosting -> Text
spAccount SimplePosting
sp
      mamt' <- traverse internSimpleAmount $ spAmount sp
      massertion <- traverse (internAssertion startpos) $ spAssertion sp
      return posting{pdate=spDate sp, pdate2=spDate2 sp, pstatus=spStatus sp, paccount=acct'
                    ,pamount=maybe missingmixedamt mixedAmount mamt', pcomment=spComment sp, preal=spRealness sp, ptags=spTags sp
                    ,pbalanceassertion=massertion}
    internAssertion :: SourcePos
-> SimpleAssertion
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) BalanceAssertion
internAssertion (SourcePos String
f Pos
l Pos
_) SimpleAssertion{Amount
saAmount :: SimpleAssertion -> Amount
saAmount :: Amount
saAmount, Bool
saTotal :: SimpleAssertion -> Bool
saTotal :: Bool
saTotal, Bool
saInclusive :: SimpleAssertion -> Bool
saInclusive :: Bool
saInclusive, Int
saLineOffset :: SimpleAssertion -> Int
saLineOffset :: Int
saLineOffset, Int
saColumn :: SimpleAssertion -> Int
saColumn :: Int
saColumn} = do
      a <- Amount -> JournalParser m Amount
forall (m :: * -> *). Amount -> JournalParser m Amount
internSimpleAmount Amount
saAmount
      let !pos = String -> Pos -> Pos -> SourcePos
SourcePos String
f (Int -> Pos
mkPos (Int -> Pos) -> Int -> Pos
forall a b. (a -> b) -> a -> b
$ Pos -> Int
unPos Pos
l Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
saLineOffset) (Int -> Pos
mkPos Int
saColumn)
      return BalanceAssertion{baamount=a, batotal=saTotal, bainclusive=saInclusive, baposition=pos}

-- | Share a scanned amount's commodity symbol and style (and its cost amount's) with identical
-- ones parsed earlier, as simpleamountp does, so that equal values point to one heap object.
-- (The scanners are pure functions; this sharing, which updates the journal's parse state,
-- is done afterwards, here.)
internSimpleAmount :: Amount -> JournalParser m Amount
internSimpleAmount :: forall (m :: * -> *). Amount -> JournalParser m Amount
internSimpleAmount Amount
a = do
  c <- if Text -> Bool
T.null (Amount -> Text
acommodity Amount
a) then Text -> StateT Journal (ParsecT HledgerParseErrorData Text m) Text
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return Text
"" else Text -> StateT Journal (ParsecT HledgerParseErrorData Text m) Text
forall (m :: * -> *). Text -> JournalParser m Text
shareText (Amount -> Text
acommodity Amount
a)
  s <- shareAmountStyle (astyle a)
  mcost <- traverse internCost (acost a)
  return a{acommodity=c, astyle=s, acost=mcost}
  where
    internCost :: AmountCost
-> StateT Journal (ParsecT HledgerParseErrorData Text m) AmountCost
internCost (UnitCost Amount
ca)  = Amount -> AmountCost
UnitCost  (Amount -> AmountCost)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
-> StateT Journal (ParsecT HledgerParseErrorData Text m) AmountCost
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Amount
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
forall (m :: * -> *). Amount -> JournalParser m Amount
internSimpleAmount Amount
ca
    internCost (TotalCost Amount
ca) = Amount -> AmountCost
TotalCost (Amount -> AmountCost)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
-> StateT Journal (ParsecT HledgerParseErrorData Text m) AmountCost
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Amount
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Amount
forall (m :: * -> *). Amount -> JournalParser m Amount
internSimpleAmount Amount
ca

-- | A fast path for the commonest kind of market price directive, like fasttransactionp:
-- P, a date, an optional time of day (ignored), a commodity symbol, and a simple
-- amount (as described there), separated by spaces, then optionally other text, which is
-- ignored (as marketpricedirectivep does). Declines otherwise.
fastmarketpricedirectivep :: JournalParser m (Either Text PriceDirective)
fastmarketpricedirectivep :: forall (m :: * -> *). JournalParser m (Either Text PriceDirective)
fastmarketpricedirectivep = do
  j <- StateT Journal (ParsecT HledgerParseErrorData Text m) Journal
forall s (m :: * -> *). MonadState s m => m s
get
  s <- getInput
  case scanSimplePrice j s of
    Left Text
reason -> Either Text PriceDirective
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text m)
     (Either Text PriceDirective)
forall a.
a -> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either Text PriceDirective
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData Text m)
      (Either Text PriceDirective))
-> Either Text PriceDirective
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text m)
     (Either Text PriceDirective)
forall a b. (a -> b) -> a -> b
$ Text -> Either Text PriceDirective
forall a b. a -> Either a b
Left Text
reason
    Right (Day
date, Text
sym, Amount
amt, Int
consumed) -> do
      pos <- JournalParser m SourcePos
forall (m :: * -> *). JournalParser m SourcePos
getSourcePos'
      sym' <- shareText sym
      amt' <- internSimpleAmount amt
      -- consume the scanned text, as in fasttransactionp
      updateParserState $ \State Text HledgerParseErrorData
st -> State Text HledgerParseErrorData
st{stateInput = T.drop consumed s, stateOffset = stateOffset st + consumed}
      return $ Right $ PriceDirective pos date sym' amt'

-- | Recognise a simple market price directive (see fastmarketpricedirectivep) at the start of
-- the text, returning its date, commodity symbol and price amount, and the number of characters
-- consumed (through the line's newline). Mirrors marketpricedirectivep: P, optional spaces, a
-- date, at least one space, optionally a time of day and at least one space, the commodity
-- symbol, at least one space, the amount; and then the rest of the line is ignored, whatever it
-- is (as restofline does there). Declines if a cost or lot annotation follows the amount.
scanSimplePrice :: Journal -> Text -> Either Text (Day, CommoditySymbol, Amount, Int)
scanSimplePrice :: Journal -> Text -> Either Text (Day, Text, Amount, Int)
scanSimplePrice Journal
j Text
s = do
  (line, _, n) <- Text -> Maybe (Text, Text, Int) -> Either Text (Text, Text, Int)
forall a. Text -> Maybe a -> Either Text a
orDecline Text
"CR line ending" (Maybe (Text, Text, Int) -> Either Text (Text, Text, Int))
-> Maybe (Text, Text, Int) -> Either Text (Text, Text, Int)
forall a b. (a -> b) -> a -> b
$ Text -> Maybe (Text, Text, Int)
scanSimpleLine Text
s  -- (the text is not empty: it begins with P)
  r0 <- orDecline "malformed price directive" $ T.stripPrefix "P" line
  (date, r1) <- orDecline "unusual date form" $ scanSimpleDate (jparsedefaultyear j) $ T.dropWhile isNonNewlineSpace r0
  declineIf (not $ startsWithSpace r1) "malformed price directive"
  -- a digit here begins a time of day, which is ignored; then at least one space
  r2 <- case T.uncons (T.dropWhile isNonNewlineSpace r1) of
    Just (Char
c, Text
_) | Char -> Bool
isDigit Char
c -> do
      r <- Text -> Maybe Text -> Either Text Text
forall a. Text -> Maybe a -> Either Text a
orDecline Text
"unusual time of day in price directive" (Maybe Text -> Either Text Text) -> Maybe Text -> Either Text Text
forall a b. (a -> b) -> a -> b
$ Text -> Maybe Text
scanTimeOfDay (Text -> Maybe Text) -> Text -> Maybe Text
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
r1
      declineIf (not $ startsWithSpace r) "malformed price directive"
      Right $ T.dropWhile isNonNewlineSpace r
    Maybe (Char, Text)
_ -> Text -> Either Text Text
forall a b. b -> Either a b
Right (Text -> Either Text Text) -> Text -> Either Text Text
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
r1
  (sym, r3) <- orDecline "malformed price directive" $ scanCommoditySymbol r2
  declineIf (not $ startsWithSpace r3) "malformed price directive"
  (amt, r4) <- scanSimpleAmount j $ T.dropWhile isNonNewlineSpace r3
  -- a cost or lot annotation on the price: decline; anything else is ignored
  declineIf (maybe False (\(Char
c', Text
_) -> Char
c' Char -> String -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` (String
"@({[" :: String)) $ T.uncons $ T.dropWhile isNonNewlineSpace r4) "annotation on the price amount"
  Right (date, sym, amt, n)

-- | Recognise a simple transaction (see fasttransactionp) at the start of the text, returning
-- its parts and the number of characters consumed (through the newline of its last line).
-- The first line is scanned as transactionp parses it: a date, an optional secondary date,
-- then whitespace or the end of the line, an optional status mark, an optional code, the
-- description (whitespace-stripped), and an optional comment; then any following indented
-- comment lines continue the comment (as transactioncommentp parses them). Then, as postingsp
-- does, each following indented line is taken as a posting (with its own following comment
-- lines), until a line that is not indented, or the end of the text. Since a decline must
-- consume nothing, one posting the scanner does not handle declines the whole transaction.
scanSimpleTransaction :: Journal -> Text -> Either Text (SimpleTransaction, Int)
scanSimpleTransaction :: Journal -> Text -> Either Text (SimpleTransaction, Int)
scanSimpleTransaction Journal
j Text
s0 = do
  (line1, s1, n1) <- Text -> Maybe (Text, Text, Int) -> Either Text (Text, Text, Int)
forall a. Text -> Maybe a -> Either Text a
orDecline Text
"CR line ending" (Maybe (Text, Text, Int) -> Either Text (Text, Text, Int))
-> Maybe (Text, Text, Int) -> Either Text (Text, Text, Int)
forall a b. (a -> b) -> a -> b
$ Text -> Maybe (Text, Text, Int)
scanSimpleLine Text
s0  -- (the text is not empty: it begins with a digit)
  (date, r1) <- orDecline "unusual date form" $ scanSimpleDate (jparsedefaultyear j) line1
  -- an optional secondary date, as secondarydatep parses it: = and a date, partial ones
  -- taking the primary date's year
  (mdate2, r2) <- case T.uncons r1 of
    Just (Char
'=', Text
r) -> do
      (date2, r') <- Text -> Maybe (Day, Text) -> Either Text (Day, Text)
forall a. Text -> Maybe a -> Either Text a
orDecline Text
"unusual secondary date form" (Maybe (Day, Text) -> Either Text (Day, Text))
-> Maybe (Day, Text) -> Either Text (Day, Text)
forall a b. (a -> b) -> a -> b
$ Maybe Integer -> Text -> Maybe (Day, Text)
scanSimpleDate (Integer -> Maybe Integer
forall a. a -> Maybe a
Just (Integer -> Maybe Integer) -> Integer -> Maybe Integer
forall a b. (a -> b) -> a -> b
$ (Integer, Int, Int) -> Integer
forall {a} {b} {c}. (a, b, c) -> a
first3 ((Integer, Int, Int) -> Integer) -> (Integer, Int, Int) -> Integer
forall a b. (a -> b) -> a -> b
$ Day -> (Integer, Int, Int)
toGregorian Day
date) Text
r
      Right (Just date2, r')
    Maybe (Char, Text)
_ -> (Maybe Day, Text) -> Either Text (Maybe Day, Text)
forall a b. b -> Either a b
Right (Maybe Day
forall a. Maybe a
Nothing, Text
r1)
  -- then whitespace or the end of the line, as transactionp requires (anything else is an error)
  r3 <- case T.uncons r2 of
    Maybe (Char, Text)
Nothing -> Text -> Either Text Text
forall a b. b -> Either a b
Right Text
r2
    Just (Char
c, Text
_) | Char -> Bool
isNonNewlineSpace Char
c -> Text -> Either Text Text
forall a b. b -> Either a b
Right (Text -> Either Text Text) -> Text -> Either Text Text
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
r2
    Maybe (Char, Text)
_ -> Text -> Either Text Text
forall a b. a -> Either a b
Left Text
"unexpected text after the date"
  let (status, r4) = case T.uncons r3 of
        Just (Char
'*', Text
r) -> (Status
Cleared, Text
r)
        Just (Char
'!', Text
r) -> (Status
Pending, Text
r)
        Maybe (Char, Text)
_             -> (Status
Unmarked, Text
r3)
      r5 = (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
r4
      -- codep requires at least one space before the code's ( : after the status mark if
      -- there is one, otherwise the whitespace after the date will do
      spacedbeforecode = Status
status Status -> Status -> Bool
forall a. Eq a => a -> a -> Bool
== Status
Unmarked Bool -> Bool -> Bool
|| Text -> Bool
startsWithSpace Text
r4
  -- an optional code in parentheses, as codep parses it
  (code, r6) <- case T.uncons r5 of
    Just (Char
'(', Text
r) | Bool
spacedbeforecode -> do
      let (Text
c, Text
r') = (Char -> Bool) -> Text -> Tag
T.break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
')') Text
r
      r'' <- Text -> Maybe Text -> Either Text Text
forall a. Text -> Maybe a -> Either Text a
orDecline Text
"unclosed transaction code" (Maybe Text -> Either Text Text) -> Maybe Text -> Either Text Text
forall a b. (a -> b) -> a -> b
$ Text -> Text -> Maybe Text
T.stripPrefix Text
")" Text
r'
      Right (c, r'')
    Maybe (Char, Text)
_ -> Tag -> Either Text Tag
forall a b. b -> Either a b
Right (Text
"", Text
r5)
  -- the description ends at a semicolon, which begins a same-line comment; following indented
  -- comment lines continue the comment (transactioncommentp); a tag in any of it: decline
  let (desc, r7) = T.break (== ';') r6
      msameline = Text -> Text -> Maybe Text
T.stripPrefix Text
";" Text
r7
      !(commentlines, s2, n2) = scanCommentLines s1
      year = (Integer, Int, Int) -> Integer
forall {a} {b} {c}. (a, b, c) -> a
first3 ((Integer, Int, Int) -> Integer) -> (Integer, Int, Int) -> Integer
forall a b. (a -> b) -> a -> b
$ Day -> (Integer, Int, Int)
toGregorian Day
date  -- the default year for partial dates in the postings' date tags
  (sps, n) <- scanPostings year (1 + length commentlines) s2 (n1 + n2) []
  Right (SimpleTransaction{stDate=date, stDate2=mdate2, stStatus=status, stCode=code, stDescription=T.strip desc
                          ,stComment=commentText msameline commentlines
                          ,stTags=concatMap scanTransactionTags $ maybeToList msameline ++ commentlines
                          ,stPostings=sps}, n)
  where
    modifyacct :: Text -> Either String Text
modifyacct = [AccountAlias]
-> Text -> [AccountAlias] -> Text -> Either String Text
accountNameApplyModifiers (Journal -> [AccountAlias]
jparsealiases Journal
j) ([Text] -> Text
concatAccountNames ([Text] -> Text) -> [Text] -> Text
forall a b. (a -> b) -> a -> b
$ [Text] -> [Text]
forall a. [a] -> [a]
reverse ([Text] -> [Text]) -> [Text] -> [Text]
forall a b. (a -> b) -> a -> b
$ Journal -> [Text]
jparseparentaccounts Journal
j) (Journal -> [AccountAlias]
jparseoptaliases Journal
j)
    scanPostings :: Integer
-> Int
-> Text
-> Int
-> [SimplePosting]
-> Either Text ([SimplePosting], Int)
scanPostings Integer
year !Int
lineoffset Text
s !Int
n [SimplePosting]
acc = case Text -> Maybe (Text, Text, Int)
scanSimpleLine Text
s of
      Just (Text
line, Text
s', Int
k)
        | Text -> Bool
isIndented Text
line -> do
            -- a posting line, and any following indented comment lines (its comment's continuation)
            let !([Text]
commentlines, Text
s'', Int
k') = Text -> ([Text], Text, Int)
scanCommentLines Text
s'
            p <- Journal
-> Integer
-> Int
-> (Text -> Either String Text)
-> Text
-> [Text]
-> Either Text SimplePosting
scanSimplePosting Journal
j Integer
year Int
lineoffset Text -> Either String Text
modifyacct Text
line [Text]
commentlines
            scanPostings year (lineoffset + 1 + length commentlines) s'' (n + k + k') (p : acc)
        | Bool
otherwise -> ([SimplePosting], Int) -> Either Text ([SimplePosting], Int)
forall a b. b -> Either a b
Right ([SimplePosting] -> [SimplePosting]
forall a. [a] -> [a]
reverse [SimplePosting]
acc, Int
n)
      -- the end of the text, or a line with a CR: in an indented (posting) line that declines,
      -- since the general parser would accept the posting; any other line just ends the postings
      Maybe (Text, Text, Int)
Nothing
        | Text -> Bool
isIndented ((Char -> Bool) -> Text -> Text
T.takeWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\n') Text
s) -> Text -> Either Text ([SimplePosting], Int)
forall a b. a -> Either a b
Left Text
"CR line ending"
        | Bool
otherwise -> ([SimplePosting], Int) -> Either Text ([SimplePosting], Int)
forall a b. b -> Either a b
Right ([SimplePosting] -> [SimplePosting]
forall a. [a] -> [a]
reverse [SimplePosting]
acc, Int
n)
    -- does the line begin with whitespace followed by something ? (like postingsp's nextlineisindented)
    isIndented :: Text -> Bool
isIndented Text
line = case Text -> Maybe (Char, Text)
T.uncons Text
line of
      Just (Char
c, Text
_) -> Char -> Bool
isNonNewlineSpace Char
c Bool -> Bool -> Bool
&& Bool -> Bool
not (Text -> Bool
T.null (Text -> Bool) -> Text -> Bool
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
line)
      Maybe (Char, Text)
Nothing     -> Bool
False

-- | The next line of the text (without its newline), the text after it, and the number of
-- characters consumed (including the newline, if there was one); or Nothing if the text is
-- empty, or if the line contains a CR. (The general parser treats CR as whitespace; rather than
-- mirror that in every scanner, files with CRLF line endings are left to it.)
scanSimpleLine :: Text -> Maybe (Text, Text, Int)
scanSimpleLine :: Text -> Maybe (Text, Text, Int)
scanSimpleLine Text
s
  | Text -> Bool
T.null Text
s = Maybe (Text, Text, Int)
forall a. Maybe a
Nothing
  | Bool
otherwise =
      let (Text
line, Text
rest) = (Char -> Bool) -> Text -> Tag
T.break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'\n') Text
s
          !rest' :: Text
rest' = Int -> Text -> Text
T.drop Int
1 Text
rest
          !n :: Int
n = Text -> Int
T.length Text
line Int -> Int -> Int
forall a. Num a => a -> a -> a
+ (if Text -> Bool
T.null Text
rest then Int
0 else Int
1)
      in if (Char -> Bool) -> Text -> Bool
T.any (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'\r') Text
line
         then Maybe (Text, Text, Int)
forall a. Maybe a
Nothing
         else (Text, Text, Int) -> Maybe (Text, Text, Int)
forall a. a -> Maybe a
Just (Text
line, Text
rest', Int
n)

-- | Consume any following comment lines (indented lines beginning with a semicolon, as
-- followingcommentpWith recognises them), returning their texts after the semicolon, the text
-- after them, and the number of characters consumed. (The next line is usually a posting,
-- so it is checked before being split off.)
scanCommentLines :: Text -> ([Text], Text, Int)
scanCommentLines :: Text -> ([Text], Text, Int)
scanCommentLines = [Text] -> Int -> Text -> ([Text], Text, Int)
go [] Int
0
  where
    go :: [Text] -> Int -> Text -> ([Text], Text, Int)
go [Text]
acc !Int
n Text
s
      | Text -> Bool
startsWithSpace Text
s, Just Text
r <- Text -> Text -> Maybe Text
T.stripPrefix Text
";" ((Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
s)
      , Just (Text
_, Text
s', Int
k) <- Text -> Maybe (Text, Text, Int)
scanSimpleLine Text
s
      = [Text] -> Int -> Text -> ([Text], Text, Int)
go ((Char -> Bool) -> Text -> Text
T.takeWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\n') Text
r Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: [Text]
acc) (Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
k) Text
s'
      | Bool
otherwise = ([Text] -> [Text]
forall a. [a] -> [a]
reverse [Text]
acc, Text
s, Int
n)

-- | A date as datep parses it, given the default year, and the text after it. A full date has a
-- four-digit year (datep also allows longer ones; those decline), a - / or . separator, a one-
-- or two-digit month, the same separator again, and a one- or two-digit day. A partial date has
-- just a one- or two-digit month, a separator and a one- or two-digit day, and takes the default
-- year. Declines if the date has another shape, is not a valid calendar date (datep reports an
-- error for that), or is partial when there is no default year (likewise).
scanSimpleDate :: Maybe Year -> Text -> Maybe (Day, Text)
scanSimpleDate :: Maybe Integer -> Text -> Maybe (Day, Text)
scanSimpleDate Maybe Integer
mdefaultyear Text
t = do
  let (Text
n1, Text
r1) = (Char -> Bool) -> Text -> Tag
T.span Char -> Bool
isDigit Text
t
  (sep, r2) <- Text -> Maybe (Char, Text)
T.uncons Text
r1
  guard $ sep == '-' || sep == '/' || sep == '.'
  let (n2, r3) = T.span isDigit r2
  guard $ T.length n2 == 1 || T.length n2 == 2
  if T.length n1 == 4
  then do  -- a full date: year, month, day
    (sep2, r4) <- T.uncons r3
    guard $ sep2 == sep
    let (n3, r5) = T.span isDigit r4
    guard $ T.length n3 == 1 || T.length n3 == 2
    date <- fromGregorianValid (readDecimal n1) (fromInteger $ readDecimal n2) (fromInteger $ readDecimal n3)
    Just (date, r5)
  else do  -- a partial date: month, day, in the default year
    guard $ T.length n1 == 1 || T.length n1 == 2
    y <- mdefaultyear
    date <- fromGregorianValid y (fromInteger $ readDecimal n1) (fromInteger $ readDecimal n2)
    Just (date, r3)

-- | Skip a time of day as timeofdayp parses it (two-digit hour and minute, optionally a
-- two-digit second, optionally a +HHMM or -HHMM time zone), returning the text after it;
-- or Nothing if the text does not begin with a valid one.
scanTimeOfDay :: Text -> Maybe Text
scanTimeOfDay :: Text -> Maybe Text
scanTimeOfDay Text
t0 = do
  (h, r1) <- Text -> Maybe (Integer, Text)
twoDigits Text
t0
  guard $ h <= 23
  r2 <- T.stripPrefix ":" r1
  (m, r3) <- twoDigits r2
  guard $ m <= 59
  r4 <- case T.stripPrefix ":" r3 of
    Just Text
r  -> do (sec, r') <- Text -> Maybe (Integer, Text)
twoDigits Text
r; guard (sec <= 59); Just r'
    Maybe Text
Nothing -> Text -> Maybe Text
forall a. a -> Maybe a
Just Text
r3
  Just $ fromMaybe r4 $ do  -- an optional time zone
    (c, r5) <- T.uncons r4
    guard $ c == '+' || c == '-'
    let (ds, r6) = T.span isDigit r5
    guard $ T.length ds == 4
    Just r6
  where
    twoDigits :: Text -> Maybe (Integer, Text)
twoDigits Text
t = let (Text
ds, Text
r) = (Char -> Bool) -> Text -> Tag
T.span Char -> Bool
isDigit Text
t in if Text -> Int
T.length Text
ds Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
2 then (Integer, Text) -> Maybe (Integer, Text)
forall a. a -> Maybe a
Just (Text -> Integer
readDecimal Text
ds, Text
r) else Maybe (Integer, Text)
forall a. Maybe a
Nothing

-- | Does the text begin with a non-newline space ?
startsWithSpace :: Text -> Bool
startsWithSpace :: Text -> Bool
startsWithSpace = Bool -> ((Char, Text) -> Bool) -> Maybe (Char, Text) -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (Char -> Bool
isNonNewlineSpace (Char -> Bool) -> ((Char, Text) -> Char) -> (Char, Text) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Char, Text) -> Char
forall a b. (a, b) -> a
fst) (Maybe (Char, Text) -> Bool)
-> (Text -> Maybe (Char, Text)) -> Text -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Maybe (Char, Text)
T.uncons

-- | A simple posting line (see fasttransactionp), scanned as postingp parses it: indentation,
-- an optional status mark, the account name, optionally an amount with cost, optionally a balance
-- assertion or assignment, and optionally a same-line comment; and given the line's position within
-- the transaction, and the texts of its following comment lines (see scanCommentLines).
-- Returns the status, the account name (with aliases and the parent account applied by the
-- given function, as modifiedaccountnamep does, and virtual posting brackets removed, as postingp does), the
-- posting type, the amount and balance assertion if any, the comment text, and the comment's tags and posting dates
-- (the transaction's year is given for partial dates in those). Declines on a bracketed date
-- in the comment (which postingcommentp would interpret), a date tag whose value is not a
-- simple date, a balance assertion it does not handle, or anything else after the amount.
scanSimplePosting :: Journal -> Year -> Int -> (AccountName -> Either RegexError AccountName) -> Text -> [Text] -> Either Text SimplePosting
scanSimplePosting :: Journal
-> Integer
-> Int
-> (Text -> Either String Text)
-> Text
-> [Text]
-> Either Text SimplePosting
scanSimplePosting Journal
j Integer
year Int
lineoffset Text -> Either String Text
modifyacct Text
line [Text]
commentlines = do
  -- an optional status mark, as statusp parses it, then spaces
  let (Status
status, Text
body) = case Text -> Maybe (Char, Text)
T.uncons (Text -> Maybe (Char, Text)) -> Text -> Maybe (Char, Text)
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
line of
        Just (Char
'*', Text
r) -> (Status
Cleared, (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
r)
        Just (Char
'!', Text
r) -> (Status
Pending, (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
r)
        Just (Char, Text)
_        -> (Status
Unmarked, (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
line)
        Maybe (Char, Text)
Nothing       -> (Status
Unmarked, Text
"")
  let (Text
name, Text
r1) = Text -> Tag
scanSimpleAccountName Text
body
      r2 :: Text
r2 = (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
r1
  -- a status mark and nothing else is an error (accountnamep needs at least one character)
  Bool -> Text -> Either Text ()
declineIf (Text -> Bool
T.null Text
name) Text
"malformed posting"
  -- an empty account name part is an error, reported by accountnamep
  Bool -> Text -> Either Text ()
declineIf (Text -> Bool
accountNameHasEmptyPart Text
name) Text
"account name with an empty part"
  (mamt, r3) <-
    -- no amount (a following = begins a balance assignment)
    if Text -> Bool
T.null Text
r2 Bool -> Bool -> Bool
|| Text -> Text -> Bool
T.isPrefixOf Text
";" Text
r2 Bool -> Bool -> Bool
|| Text -> Text -> Bool
T.isPrefixOf Text
"=" Text
r2
    then (Maybe Amount, Text) -> Either Text (Maybe Amount, Text)
forall a b. b -> Either a b
Right (Maybe Amount
forall a. Maybe a
Nothing, Text
r2)
    else do (a, r) <- Journal -> Text -> Either Text (Amount, Text)
scanSimpleAmountAndCost Journal
j Text
r2; Right (Just a, r)
  -- then an optional balance assertion or assignment
  let r4 = (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
r3
  (massertion, r5) <-
    if T.isPrefixOf "=" r4
    then do (a, r) <- scanSimpleAssertion j lineoffset line r4; Right (Just a, r)
    else Right (Nothing, r4)
  -- then an optional same-line comment; anything else is an error
  msameline <- case T.uncons r5 of
    Maybe (Char, Text)
Nothing       -> Maybe Text -> Either Text (Maybe Text)
forall a b. b -> Either a b
Right Maybe Text
forall a. Maybe a
Nothing
    Just (Char
';', Text
r) -> Maybe Text -> Either Text (Maybe Text)
forall a b. b -> Either a b
Right (Text -> Maybe Text
forall a. a -> Maybe a
Just Text
r)
    Maybe (Char, Text)
_             -> Text -> Either Text (Maybe Text)
forall a b. a -> Either a b
Left Text
"unexpected text after the amount"
  -- the comment's tags and posting dates, as postingcommentp parses them; a bracketed date
  -- (which it would also interpret) declines, as does a date tag with an unusual value
  let comments = Maybe Text -> [Text]
forall a. Maybe a -> [a]
maybeToList Maybe Text
msameline [Text] -> [Text] -> [Text]
forall a. [a] -> [a] -> [a]
++ [Text]
commentlines
  declineIf (any (T.any (== '[')) comments) "posting comment with bracketed date"
  tagsanddates <- orDecline "unusual date tag value" $ mapM (scanPostingTags year) comments
  let dates = (([Tag], [(Text, Day)]) -> [(Text, Day)])
-> [([Tag], [(Text, Day)])] -> [(Text, Day)]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap ([Tag], [(Text, Day)]) -> [(Text, Day)]
forall a b. (a, b) -> b
snd [([Tag], [(Text, Day)])]
tagsanddates
  -- as modifiedaccountnamep and postingp do (an alias error declines, to be reported there)
  full <- either (const $ Left "account alias error") Right $ modifyacct name
  Right SimplePosting{spStatus=status, spAccount=textUnbracket full, spRealness=accountNamePostingType full, spAmount=mamt, spAssertion=massertion
                     ,spComment=commentText msameline commentlines, spTags=concatMap fst tagsanddates
                     ,spDate=lookup "date" dates, spDate2=lookup "date2" dates}

-- | A balance assertion or assignment as balanceassertionp parses it, and the text after it,
-- given the posting's line offset within the transaction, the whole line, and the part of the
-- line beginning with the first =. That is =, ==, =* or ==*, optional spaces, and an amount with
-- an optional cost. Declines if a tab precedes the = on the line, rather than copy megaparsec's
-- tab stop rule for calculating its column; and on anything scanSimpleAmountAndCost declines.
scanSimpleAssertion :: Journal -> Int -> Text -> Text -> Either Text (SimpleAssertion, Text)
scanSimpleAssertion :: Journal
-> Int -> Text -> Text -> Either Text (SimpleAssertion, Text)
scanSimpleAssertion Journal
j Int
lineoffset Text
line Text
t = do
  let before :: Int
before = Text -> Int
T.length Text
line Int -> Int -> Int
forall a. Num a => a -> a -> a
- Text -> Int
T.length Text
t
  Bool -> Text -> Either Text ()
declineIf ((Char -> Bool) -> Text -> Bool
T.any (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'\t') (Text -> Bool) -> Text -> Bool
forall a b. (a -> b) -> a -> b
$ Int -> Text -> Text
T.take Int
before Text
line) Text
"balance assertion after a tab"
  let r1 :: Text
r1 = Int -> Text -> Text
T.drop Int
1 Text
t
      (Bool
istotal, Text
r2)     = (Bool, Text)
-> (Text -> (Bool, Text)) -> Maybe Text -> (Bool, Text)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Bool
False, Text
r1) (Bool
True,) (Maybe Text -> (Bool, Text)) -> Maybe Text -> (Bool, Text)
forall a b. (a -> b) -> a -> b
$ Text -> Text -> Maybe Text
T.stripPrefix Text
"=" Text
r1
      (Bool
isinclusive, Text
r3) = (Bool, Text)
-> (Text -> (Bool, Text)) -> Maybe Text -> (Bool, Text)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Bool
False, Text
r2) (Bool
True,) (Maybe Text -> (Bool, Text)) -> Maybe Text -> (Bool, Text)
forall a b. (a -> b) -> a -> b
$ Text -> Text -> Maybe Text
T.stripPrefix Text
"*" Text
r2
  (a, r4) <- Journal -> Text -> Either Text (Amount, Text)
scanSimpleAmountAndCost Journal
j (Text -> Either Text (Amount, Text))
-> Text -> Either Text (Amount, Text)
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
r3
  Right (SimpleAssertion{saAmount=a, saTotal=istotal, saInclusive=isinclusive, saLineOffset=lineoffset, saColumn=before + 1}, r4)

-- | An account name as accountnamep parses it, and the text after it: one or more
-- non-whitespace parts, separated by single spaces (a single tab also separates parts, and
-- becomes a space; two or more whitespace characters end the name, as does a newline).
scanSimpleAccountName :: Text -> (Text, Text)
scanSimpleAccountName :: Text -> Tag
scanSimpleAccountName Text
t = [Text] -> Text -> Tag
go [Text
part1] Text
r1
  where
    (Text
part1, Text
r1) = (Char -> Bool) -> Text -> Tag
T.span (Bool -> Bool
not (Bool -> Bool) -> (Char -> Bool) -> Char -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> Bool
isSpace) Text
t
    go :: [Text] -> Text -> Tag
go [Text]
parts Text
r = case Text -> Maybe (Char, Text)
T.uncons Text
r of
      Just (Char
c1, Text
r') | Char -> Bool
isNonNewlineSpace Char
c1, Just (Char
c2, Text
_) <- Text -> Maybe (Char, Text)
T.uncons Text
r', Bool -> Bool
not (Char -> Bool
isSpace Char
c2) ->
        let (Text
part, Text
r'') = (Char -> Bool) -> Text -> Tag
T.span (Bool -> Bool
not (Bool -> Bool) -> (Char -> Bool) -> Char -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> Bool
isSpace) Text
r' in [Text] -> Text -> Tag
go (Text
part Text -> [Text] -> [Text]
forall a. a -> [a] -> [a]
: [Text]
parts) Text
r''
      Maybe (Char, Text)
_ -> ([Text] -> Text
T.unwords ([Text] -> [Text]
forall a. [a] -> [a]
reverse [Text]
parts), Text
r)

-- | An amount with an optional @ or @@ cost, as amountp' parses simple ones, and the text after
-- it. A total cost's sign follows the amount's, as in costp. Declines on a second cost, a
-- parenthesised cost, a valuation expression or a lot annotation (anything beginning with
-- @ ( { or [ after the amount or the cost).
scanSimpleAmountAndCost :: Journal -> Text -> Either Text (Amount, Text)
scanSimpleAmountAndCost :: Journal -> Text -> Either Text (Amount, Text)
scanSimpleAmountAndCost Journal
j Text
t = do
  (a, r1) <- Journal -> Text -> Either Text (Amount, Text)
scanSimpleAmount Journal
j Text
t
  let r2 = (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
r1
  case T.uncons r2 of
    Just (Char
'@', Text
r3) -> do
      let (Bool
total, Text
r4) = case Text -> Maybe (Char, Text)
T.uncons Text
r3 of
            Just (Char
'@', Text
r) -> (Bool
True, Text
r)
            Maybe (Char, Text)
_             -> (Bool
False, Text
r3)
      (ca, r5) <- Journal -> Text -> Either Text (Amount, Text)
scanSimpleAmount Journal
j (Text -> Either Text (Amount, Text))
-> Text -> Either Text (Amount, Text)
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
r4
      let r6 = (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
r5
      -- another cost, or a lot annotation: decline
      declineIf (maybe False (\(Char
c, Text
_) -> Char
c Char -> String -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` (String
"@({[" :: String)) $ T.uncons r6) "annotation after the cost"
      let amtsign = case Quantity -> Quantity
forall a. Num a => a -> a
signum (Amount -> Quantity
aquantity Amount
a) of Quantity
0 -> Quantity
1; Quantity
sgn -> Quantity
sgn
          cost | Bool
total     = Amount -> AmountCost
TotalCost Amount
ca{aquantity = amtsign * aquantity ca}
               | Bool
otherwise = Amount -> AmountCost
UnitCost Amount
ca
      Right (a{acost = Just cost}, r6)
    Just (Char
c, Text
_) | Char
c Char -> String -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` (String
"({[" :: String) -> Text -> Either Text (Amount, Text)
forall a b. a -> Either a b
Left Text
"lot or valuation annotation"
    Maybe (Char, Text)
_ -> (Amount, Text) -> Either Text (Amount, Text)
forall a b. b -> Either a b
Right (Amount
a, Text
r2)

-- | An amount without cost, as simpleamountp parses simple ones, and the text after it: an
-- optional sign, then either a commodity symbol, optional spaces, an optional second
-- sign and a number; or a number, optional spaces and an optional symbol. The number
-- is interpreted by interpretRawNumber with the same suggested style and required decimal mark
-- that simpleamountp would use, so decimal-mark and commodity directives have their usual effect,
-- and the amount's style is built as there. Declines on an exponent, and
-- on a symbol-less amount when a default commodity (D) directive is in effect (simpleamountp
-- would apply that commodity and its style).
scanSimpleAmount :: Journal -> Text -> Either Text (Amount, Text)
scanSimpleAmount :: Journal -> Text -> Either Text (Amount, Text)
scanSimpleAmount Journal
j Text
t0 = do
  let (Quantity -> Quantity
sign1, Text
t1) = Text -> (Quantity -> Quantity, Text)
scanSign Text
t0
  (c, _) <- Text -> Maybe (Char, Text) -> Either Text (Char, Text)
forall a. Text -> Maybe a -> Either Text a
orDecline Text
malformed (Maybe (Char, Text) -> Either Text (Char, Text))
-> Maybe (Char, Text) -> Either Text (Char, Text)
forall a b. (a -> b) -> a -> b
$ Text -> Maybe (Char, Text)
T.uncons Text
t1
  -- in a posting, (... is an amount expression, which postingamountp evaluates
  declineIf (c == '(') "possible amount expression"
  if c == '"' || not (isNonsimpleCommodityChar c)
  then do  -- symbol on the left
    (sym, t2) <- orDecline malformed $ scanCommoditySymbol t1
    let (spaced, t3) = scanSpaces t2
        (sign2, t4) = scanSign t3
    (raw, t5) <- orDecline malformed $ scanSimpleNumber t4
    (q, p, mdec, mgrps) <- interpret (suggestedStyle sym) raw
    Right (nullamt{acommodity=sym, aquantity=sign1 (sign2 q), acost=Nothing
                  ,astyle=amountstyle{ascommodityside=L, ascommodityspaced=spaced, asprecision=Precision p, asdecimalmark=mdec, asdigitgroups=mgrps}}
          ,t5)
  else do
    (raw, t2) <- orDecline malformed $ scanSimpleNumber t1
    let (spaced, t3) = scanSpaces t2
    case T.uncons t3 of
                   -- in a posting, 10 /2 is a division, which postingamountp evaluates
      Just (Char
c2, Text
_) | Char
c2 Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'/' -> Text -> Either Text (Amount, Text)
forall a b. a -> Either a b
Left Text
"possible amount expression"
                   | Char
c2 Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'"' Bool -> Bool -> Bool
|| Bool -> Bool
not (Char -> Bool
isNonsimpleCommodityChar Char
c2) -> do  -- symbol on the right
        (sym, t4) <- Text -> Maybe Tag -> Either Text Tag
forall a. Text -> Maybe a -> Either Text a
orDecline Text
malformed (Maybe Tag -> Either Text Tag) -> Maybe Tag -> Either Text Tag
forall a b. (a -> b) -> a -> b
$ Text -> Maybe Tag
scanCommoditySymbol Text
t3
        (q, p, mdec, mgrps) <- interpret (suggestedStyle sym) raw
        Right (nullamt{acommodity=sym, aquantity=sign1 q, acost=Nothing
                      ,astyle=amountstyle{ascommodityside=R, ascommodityspaced=spaced, asprecision=Precision p, asdecimalmark=mdec, asdigitgroups=mgrps}}
              ,t4)
      Maybe (Char, Text)
_ -> do  -- no symbol (and no default commodity directive, which would apply: decline)
        Bool -> Text -> Either Text ()
declineIf (Maybe (Text, AmountStyle) -> Bool
forall a. Maybe a -> Bool
isJust (Maybe (Text, AmountStyle) -> Bool)
-> Maybe (Text, AmountStyle) -> Bool
forall a b. (a -> b) -> a -> b
$ Journal -> Maybe (Text, AmountStyle)
jparsedefaultcommodity Journal
j) Text
"default commodity directive in effect"
        (q, p, mdec, mgrps) <- Maybe AmountStyle
-> Either AmbiguousNumber RawNumber
-> Either Text (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
forall {a}.
IsString a =>
Maybe AmountStyle
-> Either AmbiguousNumber RawNumber
-> Either a (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
interpret (Text -> Maybe AmountStyle
suggestedStyle Text
"") Either AmbiguousNumber RawNumber
raw
        Right (nullamt{acommodity="", aquantity=sign1 q, acost=Nothing
                      ,astyle=amountstyle{asprecision=Precision p, asdecimalmark=mdec, asdigitgroups=mgrps}}
              ,t2)
  where
    -- a number scanSimpleNumber does not handle, or text which is not an amount at all (an error, usually)
    malformed :: Text
malformed = Text
"malformed amount, or number with an exponent"
    suggestedStyle :: Text -> Maybe AmountStyle
suggestedStyle Text
sym = Journal -> Maybe AmountStyle
journalDecimalMarkStyle Journal
j Maybe AmountStyle -> Maybe AmountStyle -> Maybe AmountStyle
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Journal -> Text -> Maybe AmountStyle
journalAmountStyleFor Journal
j Text
sym
    interpret :: Maybe AmountStyle
-> Either AmbiguousNumber RawNumber
-> Either a (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
interpret Maybe AmountStyle
msuggested Either AmbiguousNumber RawNumber
raw = (String
 -> Either a (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle))
-> ((Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
    -> Either a (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle))
-> Either
     String (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> Either a (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Either a (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> String
-> Either a (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
forall a b. a -> b -> a
const (Either a (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
 -> String
 -> Either a (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle))
-> Either a (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> String
-> Either a (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
forall a b. (a -> b) -> a -> b
$ a -> Either a (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
forall a b. a -> Either a b
Left a
"invalid number") (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> Either a (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
forall a b. b -> Either a b
Right (Either String (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
 -> Either a (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle))
-> Either
     String (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> Either a (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
forall a b. (a -> b) -> a -> b
$ Maybe Char
-> Maybe AmountStyle
-> Either AmbiguousNumber RawNumber
-> Maybe Integer
-> Either
     String (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
interpretRawNumber (Journal -> Maybe Char
jparsedecimalmark Journal
j) Maybe AmountStyle
msuggested Either AmbiguousNumber RawNumber
raw Maybe Integer
forall a. Maybe a
Nothing

-- | A commodity symbol as commoditysymbolp parses it, and the text after it: a double-quoted symbol
-- (returned without the quotes, and which may be empty, but can't contain a semicolon or newline),
-- or one or more simple commodity symbol characters. Or Nothing, if neither of those is here.
scanCommoditySymbol :: Text -> Maybe (CommoditySymbol, Text)
scanCommoditySymbol :: Text -> Maybe Tag
scanCommoditySymbol Text
t = case Text -> Maybe (Char, Text)
T.uncons Text
t of
  Just (Char
'"', Text
r) -> do
    let (Text
sym, Text
r') = (Char -> Bool) -> Text -> Tag
T.span (\Char
c -> Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
';' Bool -> Bool -> Bool
&& Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\n' Bool -> Bool -> Bool
&& Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'"') Text
r
    (Text
sym,) (Text -> Tag) -> Maybe Text -> Maybe Tag
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Text -> Text -> Maybe Text
T.stripPrefix Text
"\"" Text
r'
  Maybe (Char, Text)
_ -> case (Char -> Bool) -> Text -> Tag
T.span (Bool -> Bool
not (Bool -> Bool) -> (Char -> Bool) -> Char -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> Bool
isNonsimpleCommodityChar) Text
t of
    (Text
sym, Text
r) | Text -> Bool
T.null Text
sym -> Maybe Tag
forall a. Maybe a
Nothing
             | Bool
otherwise  -> Tag -> Maybe Tag
forall a. a -> Maybe a
Just (Text
sym, Text
r)

-- | An optional sign, as signp parses it (a - or +, then optional spaces), as a function to
-- apply to the quantity; and the text after it.
scanSign :: Text -> (Quantity -> Quantity, Text)
scanSign :: Text -> (Quantity -> Quantity, Text)
scanSign Text
t = case Text -> Maybe (Char, Text)
T.uncons Text
t of
  Just (Char
'-', Text
r) -> (Quantity -> Quantity
forall a. Num a => a -> a
negate, (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
r)
  Just (Char
'+', Text
r) -> (Quantity -> Quantity
forall a. a -> a
id, (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
r)
  Maybe (Char, Text)
_             -> (Quantity -> Quantity
forall a. a -> a
id, Text
t)

-- | Skip any spaces, also saying whether there were any (like skipNonNewlineSpaces', which
-- simpleamountp uses to record whether the commodity symbol was separated from the number).
scanSpaces :: Text -> (Bool, Text)
scanSpaces :: Text -> (Bool, Text)
scanSpaces Text
t = (Bool -> ((Char, Text) -> Bool) -> Maybe (Char, Text) -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (Char -> Bool
isNonNewlineSpace (Char -> Bool) -> ((Char, Text) -> Char) -> (Char, Text) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Char, Text) -> Char
forall a b. (a, b) -> a
fst) (Maybe (Char, Text) -> Bool) -> Maybe (Char, Text) -> Bool
forall a b. (a -> b) -> a -> b
$ Text -> Maybe (Char, Text)
T.uncons Text
t, (Char -> Bool) -> Text -> Text
T.dropWhile Char -> Bool
isNonNewlineSpace Text
t)

-- | A number, classified as rawnumberp would, and the text after it: digits, possibly in groups
-- separated by one repeated digit group mark (which can be a space), possibly with a decimal
-- mark and decimal digits, or with just a leading or trailing decimal mark. The classification
-- records the marks and digit groups seen (each group as its digit count and value, as
-- digitgroupp does); interpretRawNumber turns that into a quantity, precision and style.
-- As in rawnumberp, a number with a single mark between digits is ambiguous, since the mark
-- could be a decimal mark or a digit group mark; that is left for interpretRawNumber to decide,
-- from the suggested style (with none, a single mark is a decimal mark). Eg:
--
-- > 1234       Right (NoSeparators 1234 Nothing)
-- > .56        Right (NoSeparators mempty (Just ('.', 56)))
-- > 1234.      Right (NoSeparators 1234 (Just ('.', mempty)))
-- > 1234.56    Left (AmbiguousNumber 1234 '.' 56)
-- > 1,234,567  Right (WithSeparators ',' [1,234,567] Nothing)
-- > 1,234.56   Right (WithSeparators ',' [1,234] (Just ('.', 56)))
-- > 1 234,56   Right (WithSeparators ' ' [1,234] (Just (',', 56)))
--
-- Declines when the number is followed by an exponent (which rawnumberp allows; rarely used),
-- or by another decimal mark, or by a space and a digit (errors, which rawnumberp reports).
scanSimpleNumber :: Text -> Maybe (Either AmbiguousNumber RawNumber, Text)
scanSimpleNumber :: Text -> Maybe (Either AmbiguousNumber RawNumber, Text)
scanSimpleNumber Text
t0 = do
  (raw, r) <- case Text -> Maybe (Char, Text)
T.uncons Text
t0 of
    -- a leading decimal mark, then digits: .5
    Just (Char
c, Text
t1) | Char -> Bool
isDecimalMark Char
c -> do
      (grp, r) <- Text -> Maybe (DigitGrp, Text)
digits Text
t1
      Just (Right $ NoSeparators mempty (Just (c, grp)), r)
    Maybe (Char, Text)
_ -> do
      (grp1, r1) <- Text -> Maybe (DigitGrp, Text)
digits Text
t0
      case T.uncons r1 of
        -- a digit group mark (which might be a decimal mark), then a digit: more digit groups
        Just (Char
sep, Text
r2) | Char -> Bool
isDigitSeparatorChar Char
sep, Bool -> ((Char, Text) -> Bool) -> Maybe (Char, Text) -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (Char -> Bool
isDigit (Char -> Bool) -> ((Char, Text) -> Char) -> (Char, Text) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Char, Text) -> Char
forall a b. (a, b) -> a
fst) (Text -> Maybe (Char, Text)
T.uncons Text
r2) -> do
          (grp2, r3) <- Text -> Maybe (DigitGrp, Text)
digits Text
r2
          let (grps, r4) = moreGroups sep r3
          case T.uncons r4 of
            -- then a decimal mark (not the digit group mark), and maybe decimal digits
            Just (Char
dm, Text
r5) | Char -> Bool
isDecimalMark Char
dm, Char
dm Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
sep ->
              let (DigitGrp
dgrp, Text
r6) = (DigitGrp, Text) -> Maybe (DigitGrp, Text) -> (DigitGrp, Text)
forall a. a -> Maybe a -> a
fromMaybe (DigitGrp
forall a. Monoid a => a
mempty, Text
r5) (Maybe (DigitGrp, Text) -> (DigitGrp, Text))
-> Maybe (DigitGrp, Text) -> (DigitGrp, Text)
forall a b. (a -> b) -> a -> b
$ Text -> Maybe (DigitGrp, Text)
digits Text
r5
              in (Either AmbiguousNumber RawNumber, Text)
-> Maybe (Either AmbiguousNumber RawNumber, Text)
forall a. a -> Maybe a
Just (RawNumber -> Either AmbiguousNumber RawNumber
forall a b. b -> Either a b
Right (RawNumber -> Either AmbiguousNumber RawNumber)
-> RawNumber -> Either AmbiguousNumber RawNumber
forall a b. (a -> b) -> a -> b
$ Char -> [DigitGrp] -> Maybe (Char, DigitGrp) -> RawNumber
WithSeparators Char
sep (DigitGrp
grp1 DigitGrp -> [DigitGrp] -> [DigitGrp]
forall a. a -> [a] -> [a]
: DigitGrp
grp2 DigitGrp -> [DigitGrp] -> [DigitGrp]
forall a. a -> [a] -> [a]
: [DigitGrp]
grps) ((Char, DigitGrp) -> Maybe (Char, DigitGrp)
forall a. a -> Maybe a
Just (Char
dm, DigitGrp
dgrp)), Text
r6)
            Maybe (Char, Text)
_ | [DigitGrp] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [DigitGrp]
grps Bool -> Bool -> Bool
&& Char -> Bool
isDecimalMark Char
sep -> (Either AmbiguousNumber RawNumber, Text)
-> Maybe (Either AmbiguousNumber RawNumber, Text)
forall a. a -> Maybe a
Just (AmbiguousNumber -> Either AmbiguousNumber RawNumber
forall a b. a -> Either a b
Left (AmbiguousNumber -> Either AmbiguousNumber RawNumber)
-> AmbiguousNumber -> Either AmbiguousNumber RawNumber
forall a b. (a -> b) -> a -> b
$ DigitGrp -> Char -> DigitGrp -> AmbiguousNumber
AmbiguousNumber DigitGrp
grp1 Char
sep DigitGrp
grp2, Text
r4)
              | Bool
otherwise -> (Either AmbiguousNumber RawNumber, Text)
-> Maybe (Either AmbiguousNumber RawNumber, Text)
forall a. a -> Maybe a
Just (RawNumber -> Either AmbiguousNumber RawNumber
forall a b. b -> Either a b
Right (RawNumber -> Either AmbiguousNumber RawNumber)
-> RawNumber -> Either AmbiguousNumber RawNumber
forall a b. (a -> b) -> a -> b
$ Char -> [DigitGrp] -> Maybe (Char, DigitGrp) -> RawNumber
WithSeparators Char
sep (DigitGrp
grp1 DigitGrp -> [DigitGrp] -> [DigitGrp]
forall a. a -> [a] -> [a]
: DigitGrp
grp2 DigitGrp -> [DigitGrp] -> [DigitGrp]
forall a. a -> [a] -> [a]
: [DigitGrp]
grps) Maybe (Char, DigitGrp)
forall a. Maybe a
Nothing, Text
r4)
        -- a trailing decimal mark: 1.
        Just (Char
dm, Text
r2) | Char -> Bool
isDecimalMark Char
dm -> (Either AmbiguousNumber RawNumber, Text)
-> Maybe (Either AmbiguousNumber RawNumber, Text)
forall a. a -> Maybe a
Just (RawNumber -> Either AmbiguousNumber RawNumber
forall a b. b -> Either a b
Right (RawNumber -> Either AmbiguousNumber RawNumber)
-> RawNumber -> Either AmbiguousNumber RawNumber
forall a b. (a -> b) -> a -> b
$ DigitGrp -> Maybe (Char, DigitGrp) -> RawNumber
NoSeparators DigitGrp
grp1 ((Char, DigitGrp) -> Maybe (Char, DigitGrp)
forall a. a -> Maybe a
Just (Char
dm, DigitGrp
forall a. Monoid a => a
mempty)), Text
r2)
        Maybe (Char, Text)
_ -> (Either AmbiguousNumber RawNumber, Text)
-> Maybe (Either AmbiguousNumber RawNumber, Text)
forall a. a -> Maybe a
Just (RawNumber -> Either AmbiguousNumber RawNumber
forall a b. b -> Either a b
Right (RawNumber -> Either AmbiguousNumber RawNumber)
-> RawNumber -> Either AmbiguousNumber RawNumber
forall a b. (a -> b) -> a -> b
$ DigitGrp -> Maybe (Char, DigitGrp) -> RawNumber
NoSeparators DigitGrp
grp1 Maybe (Char, DigitGrp)
forall a. Maybe a
Nothing, Text
r1)
  guard $ numberEnds r
  Just (raw, r)
  where
    digits :: Text -> Maybe (DigitGrp, Text)
digits Text
t = let (Text
ds, Text
r) = (Char -> Bool) -> Text -> Tag
T.span Char -> Bool
isDigit Text
t in if Text -> Bool
T.null Text
ds then Maybe (DigitGrp, Text)
forall a. Maybe a
Nothing else (DigitGrp, Text) -> Maybe (DigitGrp, Text)
forall a. a -> Maybe a
Just (Text -> DigitGrp
digitGroup Text
ds, Text
r)
    moreGroups :: Char -> Text -> ([DigitGrp], Text)
moreGroups Char
sep Text
t = case Text -> Maybe (Char, Text)
T.uncons Text
t of
      Just (Char
c, Text
t') | Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
sep, Just (DigitGrp
g, Text
t'') <- Text -> Maybe (DigitGrp, Text)
digits Text
t' -> let ([DigitGrp]
gs, Text
r) = Char -> Text -> ([DigitGrp], Text)
moreGroups Char
sep Text
t'' in (DigitGrp
g DigitGrp -> [DigitGrp] -> [DigitGrp]
forall a. a -> [a] -> [a]
: [DigitGrp]
gs, Text
r)
      Maybe (Char, Text)
_ -> ([], Text
t)
    digitGroup :: Text -> DigitGrp
digitGroup Text
ds = Word -> Integer -> DigitGrp
DigitGrp (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int -> Word) -> Int -> Word
forall a b. (a -> b) -> a -> b
$ Text -> Int
T.length Text
ds) (Text -> Integer
readDecimal Text
ds)
    -- the number must not be followed by another decimal mark, an exponent, or a digit group
    -- mark (which can be a space) and a digit; those are errors, or more complex numbers
    numberEnds :: Text -> Bool
numberEnds Text
r = case Text -> Maybe (Char, Text)
T.uncons Text
r of
      Just (Char
c, Text
r') | Char -> Bool
isDecimalMark Char
c -> Bool
False
                   | Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'e' Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'E' -> Bool
False
                   | Char -> Bool
isDigitSeparatorChar Char
c, Just (Char
d, Text
_) <- Text -> Maybe (Char, Text)
T.uncons Text
r', Char -> Bool
isDigit Char
d -> Bool
False
      Maybe (Char, Text)
_ -> Bool
True

--- *** postings

-- Parse the following whitespace-beginning lines as postings, posting
-- tags, and/or comments (inferring year, if needed, from the given date).
postingsp :: Maybe Year -> JournalParser m [Posting]
postingsp :: forall (m :: * -> *). Maybe Integer -> JournalParser m [Posting]
postingsp Maybe Integer
mTransactionYear = StateT Journal (ParsecT HledgerParseErrorData Text m) Bool
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Posting
-> StateT Journal (ParsecT HledgerParseErrorData Text m) [Posting]
forall (m :: * -> *) a. MonadPlus m => m Bool -> m a -> m [a]
manyWhile StateT Journal (ParsecT HledgerParseErrorData Text m) Bool
nextlineisindented (Maybe Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Posting
forall (m :: * -> *). Maybe Integer -> JournalParser m Posting
postingp Maybe Integer
mTransactionYear) StateT Journal (ParsecT HledgerParseErrorData Text m) [Posting]
-> String
-> StateT Journal (ParsecT HledgerParseErrorData Text m) [Posting]
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"postings"
  where
    -- does the next line begin with whitespace followed by something ? (a cheap check before trying to parse a posting)
    nextlineisindented :: StateT Journal (ParsecT HledgerParseErrorData Text m) Bool
nextlineisindented = do
      (spaced, mc) <- ParsecT HledgerParseErrorData Text m (Bool, Maybe Char)
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Bool, Maybe Char)
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m (Bool, Maybe Char)
forall (m :: * -> *). TextParser m (Bool, Maybe Char)
peekAfterSpaces
      pure $ spaced && maybe False (not . isNewline) mc

-- linebeginningwithspaces :: JournalParser m String
-- linebeginningwithspaces = do
--   sp <- lift skipNonNewlineSpaces1
--   c <- nonspace
--   cs <- lift restofline
--   return $ sp ++ (c:cs) ++ "\n"

postingp :: Maybe Year -> JournalParser m Posting
postingp :: forall (m :: * -> *). Maybe Integer -> JournalParser m Posting
postingp = ((Posting, Bool) -> Posting)
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Posting, Bool)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Posting
forall a b.
(a -> b)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Posting, Bool) -> Posting
forall a b. (a, b) -> a
fst (StateT
   Journal (ParsecT HledgerParseErrorData Text m) (Posting, Bool)
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) Posting)
-> (Maybe Integer
    -> StateT
         Journal (ParsecT HledgerParseErrorData Text m) (Posting, Bool))
-> Maybe Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Posting
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool
-> Maybe Integer
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Posting, Bool)
forall (m :: * -> *).
Bool -> Maybe Integer -> JournalParser m (Posting, Bool)
postingphelper Bool
False

-- Parse the following whitespace-beginning lines as transaction posting rules, posting
-- tags, and/or comments (inferring year, if needed, from the given date).
tmpostingrulesp :: Maybe Year -> JournalParser m [TMPostingRule]
tmpostingrulesp :: forall (m :: * -> *).
Maybe Integer -> JournalParser m [TMPostingRule]
tmpostingrulesp Maybe Integer
mTransactionYear = StateT Journal (ParsecT HledgerParseErrorData Text m) TMPostingRule
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) [TMPostingRule]
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
many (Maybe Integer
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) TMPostingRule
forall (m :: * -> *).
Maybe Integer -> JournalParser m TMPostingRule
tmpostingrulep Maybe Integer
mTransactionYear) StateT
  Journal (ParsecT HledgerParseErrorData Text m) [TMPostingRule]
-> String
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) [TMPostingRule]
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"posting rules"

-- Amounts calculated with * or / are rounded to their own precision, as in periodic transactions (#2648).
tmpostingrulep :: Maybe Year -> JournalParser m TMPostingRule
tmpostingrulep :: forall (m :: * -> *).
Maybe Integer -> JournalParser m TMPostingRule
tmpostingrulep = ((Posting, Bool) -> TMPostingRule)
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Posting, Bool)
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) TMPostingRule
forall a b.
(a -> b)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((Posting -> Bool -> TMPostingRule)
-> (Posting, Bool) -> TMPostingRule
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry Posting -> Bool -> TMPostingRule
TMPostingRule ((Posting, Bool) -> TMPostingRule)
-> ((Posting, Bool) -> (Posting, Bool))
-> (Posting, Bool)
-> TMPostingRule
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Posting -> Posting) -> (Posting, Bool) -> (Posting, Bool)
forall a b c. (a -> b) -> (a, c) -> (b, c)
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first ((Posting, Bool) -> Posting
forall a b. (a, b) -> a
fst ((Posting, Bool) -> Posting)
-> (Posting -> (Posting, Bool)) -> Posting -> Posting
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Map Text AmountStyle -> Posting -> (Posting, Bool)
postingRoundCalculatedAmounts Map Text AmountStyle
forall a. Monoid a => a
mempty)) (StateT
   Journal (ParsecT HledgerParseErrorData Text m) (Posting, Bool)
 -> StateT
      Journal (ParsecT HledgerParseErrorData Text m) TMPostingRule)
-> (Maybe Integer
    -> StateT
         Journal (ParsecT HledgerParseErrorData Text m) (Posting, Bool))
-> Maybe Integer
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) TMPostingRule
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool
-> Maybe Integer
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Posting, Bool)
forall (m :: * -> *).
Bool -> Maybe Integer -> JournalParser m (Posting, Bool)
postingphelper Bool
True

-- Parse a Posting, and return a flag with whether a multiplier has been detected.
-- The multiplier is used in TMPostingRules.
postingphelper :: Bool -> Maybe Year -> JournalParser m (Posting, Bool)
postingphelper :: forall (m :: * -> *).
Bool -> Maybe Integer -> JournalParser m (Posting, Bool)
postingphelper Bool
isPostingRule Maybe Integer
mTransactionYear = do
    -- lift $ dbgparse 0 "postingp"
    -- backtrack if this is not a posting line; but once an account name begins,
    -- its errors (eg an empty part) are reported
    status <- StateT Journal (ParsecT HledgerParseErrorData Text m) Status
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Status
forall a.
StateT Journal (ParsecT HledgerParseErrorData Text m) a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (StateT Journal (ParsecT HledgerParseErrorData Text m) Status
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) Status)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Status
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Status
forall a b. (a -> b) -> a -> b
$ do
      ParsecT HledgerParseErrorData Text m ()
-> StateT Journal (ParsecT HledgerParseErrorData Text m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
      status <- ParsecT HledgerParseErrorData Text m Status
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Status
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text m Status
forall (m :: * -> *). TextParser m Status
statusp
      lift skipNonNewlineSpaces
      _ <- lookAhead $ satisfy (not . isSpace)
      return status
    account <- modifiedaccountnamep True
    let preal = Text -> PostingRealness
accountNamePostingType Text
account
    account' <- shareText $ textUnbracket account
    lift skipNonNewlineSpaces
    mult <- if isPostingRule then multiplierp else pure False
    -- an auto posting rule's *AMT multiplier can't be an expression; other posting amounts can (#2648)
    amt <- optional $ if mult then amountp' MultiplierAmount else postingamountp OrdinaryAmount
    lift skipNonNewlineSpaces
    mc <- lift peekChar
    massertion <- if mc == Just '=' then optional balanceassertionp else pure Nothing
    lift skipNonNewlineSpaces
    (comment,tags,mdate,mdate2) <- lift $ postingcommentp mTransactionYear
    let p = Posting
posting
            { pdate=mdate
            , pdate2=mdate2
            , pstatus=status
            , paccount=account'
            , pamount=maybe missingmixedamt mixedAmount amt
            , pcomment=comment
            , preal=preal
            , ptags=tags
            , pbalanceassertion=massertion
            }
    -- Build the posting now (its fields are strict, so this also evaluates the
    -- amount), rather than leaving a thunk holding the parser's intermediate
    -- values until finalisation, which inflates peak memory use on large journals.
    p `seq` return (p, mult)
  where
    multiplierp :: StateT Journal (ParsecT HledgerParseErrorData Text m) Bool
multiplierp = Bool
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Bool
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Bool
forall (m :: * -> *) a. Alternative m => a -> m a -> m a
option Bool
False (StateT Journal (ParsecT HledgerParseErrorData Text m) Bool
 -> StateT Journal (ParsecT HledgerParseErrorData Text m) Bool)
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Bool
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Bool
forall a b. (a -> b) -> a -> b
$ Bool
True Bool
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Char
-> StateT Journal (ParsecT HledgerParseErrorData Text m) Bool
forall a b.
a
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Token Text
-> StateT
     Journal (ParsecT HledgerParseErrorData Text m) (Token Text)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token Text
'*'

--- ** tests

tests_JournalReader :: TestTree
tests_JournalReader = String -> [TestTree] -> TestTree
testGroup String
"JournalReader" [

   let p :: JournalParser IO Text
p = ParsecT HledgerParseErrorData Text IO Text -> JournalParser IO Text
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData Text IO Text
forall (m :: * -> *). TextParser m Text
accountnamep :: JournalParser IO AccountName in
   String -> [TestTree] -> TestTree
testGroup String
"accountnamep" [
     String -> Assertion -> TestTree
testCase String
"basic" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO Text -> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse JournalParser IO Text
p Text
"a:b:c"
    ,String -> Assertion -> TestTree
testCase String
"single space is part of the account name" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO Text -> Text -> Text -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq JournalParser IO Text
p Text
"a b:c" Text
"a b:c"
    ,String -> Assertion -> TestTree
testCase String
"empty inner component" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO Text -> Text -> String -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> String -> Assertion
assertParseError JournalParser IO Text
p Text
"a::c" String
"has an empty part"
    ,String -> Assertion -> TestTree
testCase String
"empty leading component" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO Text -> Text -> String -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> String -> Assertion
assertParseError JournalParser IO Text
p Text
":b:c" String
"has an empty part"
    ,String -> Assertion -> TestTree
testCase String
"empty trailing component" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO Text -> Text -> String -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> String -> Assertion
assertParseError JournalParser IO Text
p Text
"a:b:" String
"has an empty part"
    ]

  -- "Parse a date in YYYY/MM/DD format.
  -- Hyphen (-) and period (.) are also allowed as separators.
  -- The year may be omitted if a default year has been set.
  -- Leading zeroes may be omitted."
  ,String -> [TestTree] -> TestTree
testGroup String
"datep" [
     String -> Assertion -> TestTree
testCase String
"YYYY/MM/DD" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Day
-> Text -> Day -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq StateT Journal (ParsecT HledgerParseErrorData Text IO) Day
forall (m :: * -> *). JournalParser m Day
datep Text
"2018/01/01" (Integer -> Int -> Int -> Day
fromGregorian Integer
2018 Int
1 Int
1)
    ,String -> Assertion -> TestTree
testCase String
"YYYY-MM-DD" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Day
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT Journal (ParsecT HledgerParseErrorData Text IO) Day
forall (m :: * -> *). JournalParser m Day
datep Text
"2018-01-01"
    ,String -> Assertion -> TestTree
testCase String
"YYYY.MM.DD" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Day
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT Journal (ParsecT HledgerParseErrorData Text IO) Day
forall (m :: * -> *). JournalParser m Day
datep Text
"2018.01.01"
    ,String -> Assertion -> TestTree
testCase String
"yearless date with no default year" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Day
-> Text -> String -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> String -> Assertion
assertParseError StateT Journal (ParsecT HledgerParseErrorData Text IO) Day
forall (m :: * -> *). JournalParser m Day
datep Text
"1/1" String
"current year is unknown"
    ,String -> Assertion -> TestTree
testCase String
"yearless date with default year" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
      let s :: Text
s = Text
"1/1"
      ep <- Journal
-> StateT Journal (ParsecT HledgerParseErrorData Text IO) Day
-> Text
-> IO (Either HledgerParseErrors Day)
forall (m :: * -> *) st a.
Monad m =>
st
-> StateT st (ParsecT HledgerParseErrorData Text m) a
-> Text
-> m (Either HledgerParseErrors a)
parseWithState Journal
nulljournal{jparsedefaultyear=Just 2018} StateT Journal (ParsecT HledgerParseErrorData Text IO) Day
forall (m :: * -> *). JournalParser m Day
datep Text
s
      either (assertFailure . ("parse error at "++) . customErrorBundlePretty) (const $ return ()) ep
    ,String -> Assertion -> TestTree
testCase String
"no leading zero" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Day
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT Journal (ParsecT HledgerParseErrorData Text IO) Day
forall (m :: * -> *). JournalParser m Day
datep Text
"2018/1/1"
    ]
  ,String -> Assertion -> TestTree
testCase String
"datetimep" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     let
       good :: Text -> Assertion
good  = StateT Journal (ParsecT HledgerParseErrorData Text IO) LocalTime
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT Journal (ParsecT HledgerParseErrorData Text IO) LocalTime
forall (m :: * -> *). JournalParser m LocalTime
datetimep
       bad :: Text -> Assertion
bad Text
t = StateT Journal (ParsecT HledgerParseErrorData Text IO) LocalTime
-> Text -> String -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> String -> Assertion
assertParseError StateT Journal (ParsecT HledgerParseErrorData Text IO) LocalTime
forall (m :: * -> *). JournalParser m LocalTime
datetimep Text
t String
""
     Text -> Assertion
good Text
"2011/1/1 00:00"
     Text -> Assertion
good Text
"2011/1/1 23:59:59"
     Text -> Assertion
bad Text
"2011/1/1"
     Text -> Assertion
bad Text
"2011/1/1 24:00:00"
     Text -> Assertion
bad Text
"2011/1/1 00:60:00"
     Text -> Assertion
bad Text
"2011/1/1 00:00:60"
     Text -> Assertion
bad Text
"2011/1/1 3:5:7"
     -- timezone is parsed but ignored
     let t :: LocalTime
t = Day -> TimeOfDay -> LocalTime
LocalTime (Integer -> Int -> Int -> Day
fromGregorian Integer
2018 Int
1 Int
1) (Int -> Int -> Pico -> TimeOfDay
TimeOfDay Int
0 Int
0 Pico
0)
     StateT Journal (ParsecT HledgerParseErrorData Text IO) LocalTime
-> Text -> LocalTime -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq StateT Journal (ParsecT HledgerParseErrorData Text IO) LocalTime
forall (m :: * -> *). JournalParser m LocalTime
datetimep Text
"2018/1/1 00:00-0800" LocalTime
t
     StateT Journal (ParsecT HledgerParseErrorData Text IO) LocalTime
-> Text -> LocalTime -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq StateT Journal (ParsecT HledgerParseErrorData Text IO) LocalTime
forall (m :: * -> *). JournalParser m LocalTime
datetimep Text
"2018/1/1 00:00+1234" LocalTime
t

  ,String -> [TestTree] -> TestTree
testGroup String
"periodictransactionp" [

    String -> Assertion -> TestTree
testCase String
"more period text in comment after one space" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData Text IO) PeriodicTransaction
-> Text -> PeriodicTransaction -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq StateT
  Journal (ParsecT HledgerParseErrorData Text IO) PeriodicTransaction
forall (m :: * -> *).
MonadIO m =>
JournalParser m PeriodicTransaction
periodictransactionp
      Text
"~ monthly from 2018/6 ;In 2019 we will change this\n"
      PeriodicTransaction
nullperiodictransaction {
         ptperiodexpr  = "monthly from 2018/6"
        ,ptinterval    = Months 1
        ,ptspan        = DateSpan (Just $ Flex $ fromGregorian 2018 6 1) Nothing
        ,ptsourcepos   = (SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 2) (mkPos 1))
        ,ptdescription = ""
        ,ptcomment     = "In 2019 we will change this\n"
        }

    ,String -> Assertion -> TestTree
testCase String
"more period text in description after two spaces" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData Text IO) PeriodicTransaction
-> Text -> PeriodicTransaction -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq StateT
  Journal (ParsecT HledgerParseErrorData Text IO) PeriodicTransaction
forall (m :: * -> *).
MonadIO m =>
JournalParser m PeriodicTransaction
periodictransactionp
      Text
"~ monthly from 2018/6   In 2019 we will change this\n"
      PeriodicTransaction
nullperiodictransaction {
         ptperiodexpr  = "monthly from 2018/6"
        ,ptinterval    = Months 1
        ,ptspan        = DateSpan (Just $ Flex $ fromGregorian 2018 6 1) Nothing
        ,ptsourcepos   = (SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 2) (mkPos 1))
        ,ptdescription = "In 2019 we will change this"
        ,ptcomment     = ""
        }

    ,String -> Assertion -> TestTree
testCase String
"Next year in description" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData Text IO) PeriodicTransaction
-> Text -> PeriodicTransaction -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq StateT
  Journal (ParsecT HledgerParseErrorData Text IO) PeriodicTransaction
forall (m :: * -> *).
MonadIO m =>
JournalParser m PeriodicTransaction
periodictransactionp
      Text
"~ monthly  Next year blah blah\n"
      PeriodicTransaction
nullperiodictransaction {
         ptperiodexpr  = "monthly"
        ,ptinterval    = Months 1
        ,ptspan        = DateSpan Nothing Nothing
        ,ptsourcepos   = (SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 2) (mkPos 1))
        ,ptdescription = "Next year blah blah"
        ,ptcomment     = ""
        }

    ,String -> Assertion -> TestTree
testCase String
"Just date, no description" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData Text IO) PeriodicTransaction
-> Text -> PeriodicTransaction -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq StateT
  Journal (ParsecT HledgerParseErrorData Text IO) PeriodicTransaction
forall (m :: * -> *).
MonadIO m =>
JournalParser m PeriodicTransaction
periodictransactionp
      Text
"~ 2019-01-04\n"
      PeriodicTransaction
nullperiodictransaction {
         ptperiodexpr  = "2019-01-04"
        ,ptinterval    = NoInterval
        ,ptspan        = DateSpan (Just $ Exact $ fromGregorian 2019 1 4) (Just $ Exact $ fromGregorian 2019 1 5)
        ,ptsourcepos   = (SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 2) (mkPos 1))
        ,ptdescription = ""
        ,ptcomment     = ""
        }

    ,String -> Assertion -> TestTree
testCase String
"Just date, no description + empty transaction comment" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData Text IO) PeriodicTransaction
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT
  Journal (ParsecT HledgerParseErrorData Text IO) PeriodicTransaction
forall (m :: * -> *).
MonadIO m =>
JournalParser m PeriodicTransaction
periodictransactionp
      Text
"~ 2019-01-04\n  ;\n  a  1\n  b\n"

    ]

  ,String -> [TestTree] -> TestTree
testGroup String
"postingp" [
     String -> Assertion -> TestTree
testCase String
"basic" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
-> Text -> Posting -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq (Maybe Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
forall (m :: * -> *). Maybe Integer -> JournalParser m Posting
postingp Maybe Integer
forall a. Maybe a
Nothing)
      Text
"  expenses:food:dining  $10.00   ; a: a a \n   ; b: b b \n"
      Posting
posting{
        paccount="expenses:food:dining",
        pamount=mixedAmount (usd 10),
        pcomment="a: a a\nb: b b\n",
        ptags=[("a","a a"), ("b","b b")]
        }

    ,String -> Assertion -> TestTree
testCase String
"posting dates" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
-> Text -> Posting -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq (Maybe Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
forall (m :: * -> *). Maybe Integer -> JournalParser m Posting
postingp Maybe Integer
forall a. Maybe a
Nothing)
      Text
" a  1. ; date:2012/11/28, date2=2012/11/29,b:b\n"
      Posting
nullposting{
         paccount="a"
        ,pamount=mixedAmount (num 1)
        ,pcomment="date:2012/11/28, date2=2012/11/29,b:b\n"
        ,ptags=[("date", "2012/11/28"), ("date2=2012/11/29,b", "b")] -- TODO tag name parsed too greedily
        ,pdate=Just $ fromGregorian 2012 11 28
        ,pdate2=Nothing  -- Just $ fromGregorian 2012 11 29
        }

    ,String -> Assertion -> TestTree
testCase String
"posting dates bracket syntax" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
-> Text -> Posting -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq (Maybe Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
forall (m :: * -> *). Maybe Integer -> JournalParser m Posting
postingp Maybe Integer
forall a. Maybe a
Nothing)
      Text
" a  1. ; [2012/11/28=2012/11/29]\n"
      Posting
nullposting{
         paccount="a"
        ,pamount=mixedAmount (num 1)
        ,pcomment="[2012/11/28=2012/11/29]\n"
        ,ptags=[]
        ,pdate= Just $ fromGregorian 2012 11 28
        ,pdate2=Just $ fromGregorian 2012 11 29
        }

    ,String -> Assertion -> TestTree
testCase String
"quoted commodity symbol with digits" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse (Maybe Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
forall (m :: * -> *). Maybe Integer -> JournalParser m Posting
postingp Maybe Integer
forall a. Maybe a
Nothing) Text
"  a  1 \"DE123\"\n"

    ,String -> Assertion -> TestTree
testCase String
"only lot price" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse (Maybe Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
forall (m :: * -> *). Maybe Integer -> JournalParser m Posting
postingp Maybe Integer
forall a. Maybe a
Nothing) Text
"  a  1A {1B}\n"
    ,String -> Assertion -> TestTree
testCase String
"fixed lot price" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse (Maybe Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
forall (m :: * -> *). Maybe Integer -> JournalParser m Posting
postingp Maybe Integer
forall a. Maybe a
Nothing) Text
"  a  1A {=1B}\n"
    ,String -> Assertion -> TestTree
testCase String
"total lot price" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse (Maybe Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
forall (m :: * -> *). Maybe Integer -> JournalParser m Posting
postingp Maybe Integer
forall a. Maybe a
Nothing) Text
"  a  1A {{1B}}\n"
    ,String -> Assertion -> TestTree
testCase String
"fixed total lot price, and spaces" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse (Maybe Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
forall (m :: * -> *). Maybe Integer -> JournalParser m Posting
postingp Maybe Integer
forall a. Maybe a
Nothing) Text
"  a  1A {{  =  1B }}\n"
    ,String -> Assertion -> TestTree
testCase String
"lot price before transaction price" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse (Maybe Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
forall (m :: * -> *). Maybe Integer -> JournalParser m Posting
postingp Maybe Integer
forall a. Maybe a
Nothing) Text
"  a  1A {1B} @ 1B\n"
    ,String -> Assertion -> TestTree
testCase String
"lot price after transaction price" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse (Maybe Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
forall (m :: * -> *). Maybe Integer -> JournalParser m Posting
postingp Maybe Integer
forall a. Maybe a
Nothing) Text
"  a  1A @ 1B {1B}\n"
    ,String -> Assertion -> TestTree
testCase String
"lot price after balance assertion not allowed" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
-> Text -> String -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> String -> Assertion
assertParseError (Maybe Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
forall (m :: * -> *). Maybe Integer -> JournalParser m Posting
postingp Maybe Integer
forall a. Maybe a
Nothing) Text
"  a  1A @ 1B = 1A {1B}\n" String
"unexpected '{'"
    ,String -> Assertion -> TestTree
testCase String
"only lot date" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse (Maybe Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
forall (m :: * -> *). Maybe Integer -> JournalParser m Posting
postingp Maybe Integer
forall a. Maybe a
Nothing) Text
"  a  1A [2000-01-01]\n"
    ,String -> Assertion -> TestTree
testCase String
"transaction price, lot price, lot date" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse (Maybe Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
forall (m :: * -> *). Maybe Integer -> JournalParser m Posting
postingp Maybe Integer
forall a. Maybe a
Nothing) Text
"  a  1A @ 1B {1B} [2000-01-01]\n"
    ,String -> Assertion -> TestTree
testCase String
"lot date, lot price, transaction price" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse (Maybe Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
forall (m :: * -> *). Maybe Integer -> JournalParser m Posting
postingp Maybe Integer
forall a. Maybe a
Nothing) Text
"  a  1A [2000-01-01] {1B} @ 1B\n"

    ,String -> Assertion -> TestTree
testCase String
"balance assertion over entire contents of account" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse (Maybe Integer
-> StateT Journal (ParsecT HledgerParseErrorData Text IO) Posting
forall (m :: * -> *). Maybe Integer -> JournalParser m Posting
postingp Maybe Integer
forall a. Maybe a
Nothing) Text
"  a  $1 == $1\n"
    ]

  ,String -> [TestTree] -> TestTree
testGroup String
"transactionmodifierp" [

    String -> Assertion -> TestTree
testCase String
"basic" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData Text IO) TransactionModifier
-> Text -> TransactionModifier -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq StateT
  Journal (ParsecT HledgerParseErrorData Text IO) TransactionModifier
forall (m :: * -> *). JournalParser m TransactionModifier
transactionmodifierp
      Text
"= (some value expr)\n some:postings  1.\n"
      TransactionModifier
nulltransactionmodifier {
        tmquerytxt = "(some value expr)"
       ,tmpostingrules = [TMPostingRule nullposting{paccount="some:postings", pamount=mixedAmount (num 1)} False]
      }
    ]

  ,String -> [TestTree] -> TestTree
testGroup String
"transactionp" [

     String -> Assertion -> TestTree
testCase String
"just a date" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Transaction
-> Text -> Transaction -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq StateT Journal (ParsecT HledgerParseErrorData Text IO) Transaction
forall (m :: * -> *). JournalParser m Transaction
transactionp Text
"2015/1/1\n" Transaction
nulltransaction{tdate=fromGregorian 2015 1 1}

    ,String -> Assertion -> TestTree
testCase String
"more complex" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) Transaction
-> Text -> Transaction -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq StateT Journal (ParsecT HledgerParseErrorData Text IO) Transaction
forall (m :: * -> *). JournalParser m Transaction
transactionp
      ([Text] -> Text
T.unlines [
        Text
"2012/05/14=2012/05/15 (code) desc  ; tcomment1",
        Text
"    ; tcomment2",
        Text
"    ; ttag1: val1",
        Text
"    * a         $1.00  ; pcomment1",
        Text
"    ; pcomment2",
        Text
"    ; ptag1: val1",
        Text
"    ; ptag2: val2"
        ])
      Transaction
nulltransaction{
        tsourcepos=(SourcePos "" (mkPos 1) (mkPos 1), SourcePos "" (mkPos 8) (mkPos 1)),  -- 8 because there are 7 lines
        tprecedingcomment="",
        tdate=fromGregorian 2012 5 14,
        tdate2=Just $ fromGregorian 2012 5 15,
        tstatus=Unmarked,
        tcode="code",
        tdescription="desc",
        tcomment="tcomment1\ntcomment2\nttag1: val1\n",
        ttags=[("ttag1","val1")],
        tpostings=[
          nullposting{
            pdate=Nothing,
            pstatus=Cleared,
            paccount="a",
            pamount=mixedAmount (usd 1),
            pcomment="pcomment1\npcomment2\nptag1: val1\nptag2: val2\n",
            preal=RealPosting,
            ptags=[("ptag1","val1"),("ptag2","val2")],
            ptransaction=Nothing
            }
          ]
      }

    ,String -> Assertion -> TestTree
testCase String
"parses a well-formed transaction" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
      HasCallStack => String -> Bool -> Assertion
String -> Bool -> Assertion
assertBool String
"" (Bool -> Assertion) -> Bool -> Assertion
forall a b. (a -> b) -> a -> b
$ Either (ZonkAny 0) (Either HledgerParseErrors Transaction) -> Bool
forall a b. Either a b -> Bool
isRight (Either (ZonkAny 0) (Either HledgerParseErrors Transaction)
 -> Bool)
-> Either (ZonkAny 0) (Either HledgerParseErrors Transaction)
-> Bool
forall a b. (a -> b) -> a -> b
$ JournalParser (Either (ZonkAny 0)) Transaction
-> Text
-> Either (ZonkAny 0) (Either HledgerParseErrors Transaction)
forall (m :: * -> *) a.
Monad m =>
JournalParser m a -> Text -> m (Either HledgerParseErrors a)
rjp JournalParser (Either (ZonkAny 0)) Transaction
forall (m :: * -> *). JournalParser m Transaction
transactionp (Text
 -> Either (ZonkAny 0) (Either HledgerParseErrors Transaction))
-> Text
-> Either (ZonkAny 0) (Either HledgerParseErrors Transaction)
forall a b. (a -> b) -> a -> b
$ [Text] -> Text
T.unlines
        [Text
"2007/01/28 coopportunity"
        ,Text
"    expenses:food:groceries                   $47.18"
        ,Text
"    assets:checking                          $-47.18"
        ,Text
""
        ]

    ,String -> Assertion -> TestTree
testCase String
"does not parse a following comment as part of the description" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
      StateT Journal (ParsecT HledgerParseErrorData Text IO) Transaction
-> Text -> (Transaction -> Text) -> Text -> Assertion
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (a -> b) -> b -> Assertion
assertParseEqOn StateT Journal (ParsecT HledgerParseErrorData Text IO) Transaction
forall (m :: * -> *). JournalParser m Transaction
transactionp Text
"2009/1/1 a ;comment\n b 1\n" Transaction -> Text
tdescription Text
"a"

    ,String -> Assertion -> TestTree
testCase String
"parses a following whitespace line" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
      HasCallStack => String -> Bool -> Assertion
String -> Bool -> Assertion
assertBool String
"" (Bool -> Assertion) -> Bool -> Assertion
forall a b. (a -> b) -> a -> b
$ Either (ZonkAny 1) (Either HledgerParseErrors Transaction) -> Bool
forall a b. Either a b -> Bool
isRight (Either (ZonkAny 1) (Either HledgerParseErrors Transaction)
 -> Bool)
-> Either (ZonkAny 1) (Either HledgerParseErrors Transaction)
-> Bool
forall a b. (a -> b) -> a -> b
$ JournalParser (Either (ZonkAny 1)) Transaction
-> Text
-> Either (ZonkAny 1) (Either HledgerParseErrors Transaction)
forall (m :: * -> *) a.
Monad m =>
JournalParser m a -> Text -> m (Either HledgerParseErrors a)
rjp JournalParser (Either (ZonkAny 1)) Transaction
forall (m :: * -> *). JournalParser m Transaction
transactionp (Text
 -> Either (ZonkAny 1) (Either HledgerParseErrors Transaction))
-> Text
-> Either (ZonkAny 1) (Either HledgerParseErrors Transaction)
forall a b. (a -> b) -> a -> b
$ [Text] -> Text
T.unlines
        [Text
"2012/1/1"
        ,Text
"  a  1"
        ,Text
"  b"
        ,Text
" "
        ]

    ,String -> Assertion -> TestTree
testCase String
"parses an empty transaction comment following whitespace line" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
      HasCallStack => String -> Bool -> Assertion
String -> Bool -> Assertion
assertBool String
"" (Bool -> Assertion) -> Bool -> Assertion
forall a b. (a -> b) -> a -> b
$ Either (ZonkAny 2) (Either HledgerParseErrors Transaction) -> Bool
forall a b. Either a b -> Bool
isRight (Either (ZonkAny 2) (Either HledgerParseErrors Transaction)
 -> Bool)
-> Either (ZonkAny 2) (Either HledgerParseErrors Transaction)
-> Bool
forall a b. (a -> b) -> a -> b
$ JournalParser (Either (ZonkAny 2)) Transaction
-> Text
-> Either (ZonkAny 2) (Either HledgerParseErrors Transaction)
forall (m :: * -> *) a.
Monad m =>
JournalParser m a -> Text -> m (Either HledgerParseErrors a)
rjp JournalParser (Either (ZonkAny 2)) Transaction
forall (m :: * -> *). JournalParser m Transaction
transactionp (Text
 -> Either (ZonkAny 2) (Either HledgerParseErrors Transaction))
-> Text
-> Either (ZonkAny 2) (Either HledgerParseErrors Transaction)
forall a b. (a -> b) -> a -> b
$ [Text] -> Text
T.unlines
        [Text
"2012/1/1"
        ,Text
"  ;"
        ,Text
"  a  1"
        ,Text
"  b"
        ,Text
" "
        ]

    ,String -> Assertion -> TestTree
testCase String
"comments everywhere, two postings parsed" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
      StateT Journal (ParsecT HledgerParseErrorData Text IO) Transaction
-> Text -> (Transaction -> Int) -> Int -> Assertion
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (a -> b) -> b -> Assertion
assertParseEqOn StateT Journal (ParsecT HledgerParseErrorData Text IO) Transaction
forall (m :: * -> *). JournalParser m Transaction
transactionp
        ([Text] -> Text
T.unlines
          [Text
"2009/1/1 x  ; transaction comment"
          ,Text
" a  1  ; posting 1 comment"
          ,Text
" ; posting 1 comment 2"
          ,Text
" b"
          ,Text
" ; posting 2 comment"
          ])
        ([Posting] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([Posting] -> Int)
-> (Transaction -> [Posting]) -> Transaction -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> [Posting]
tpostings)
        Int
2

    ]

  ,let amts :: [Posting] -> [([(Quantity, AmountPrecision)], Bool)]
amts = (Posting -> ([(Quantity, AmountPrecision)], Bool))
-> [Posting] -> [([(Quantity, AmountPrecision)], Bool)]
forall a b. (a -> b) -> [a] -> [b]
map (\Posting
p -> ((Amount -> (Quantity, AmountPrecision))
-> [Amount] -> [(Quantity, AmountPrecision)]
forall a b. (a -> b) -> [a] -> [b]
map (\Amount
a -> (Amount -> Quantity
aquantity Amount
a, AmountStyle -> AmountPrecision
asprecision (AmountStyle -> AmountPrecision) -> AmountStyle -> AmountPrecision
forall a b. (a -> b) -> a -> b
$ Amount -> AmountStyle
astyle Amount
a)) ([Amount] -> [(Quantity, AmountPrecision)])
-> [Amount] -> [(Quantity, AmountPrecision)]
forall a b. (a -> b) -> a -> b
$ MixedAmount -> [Amount]
amountsRaw (MixedAmount -> [Amount]) -> MixedAmount -> [Amount]
forall a b. (a -> b) -> a -> b
$ Posting -> MixedAmount
pamount Posting
p, Text -> Posting -> Bool
postingHasTag Text
roundedPostingTagName Posting
p))
   in String -> [TestTree] -> TestTree
testGroup String
"amount expressions are rounded" [
     String -> Assertion -> TestTree
testCase String
"to the entry's precision, after all postings are read" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
      StateT Journal (ParsecT HledgerParseErrorData Text IO) Transaction
-> Text
-> (Transaction -> [([(Quantity, AmountPrecision)], Bool)])
-> [([(Quantity, AmountPrecision)], Bool)]
-> Assertion
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (a -> b) -> b -> Assertion
assertParseEqOn StateT Journal (ParsecT HledgerParseErrorData Text IO) Transaction
forall (m :: * -> *). JournalParser m Transaction
transactionp ([Text] -> Text
T.unlines [Text
"2026-01-01", Text
" a  $100/3", Text
" b  $10 * 0.15", Text
" c  $-100.00"]) ([Posting] -> [([(Quantity, AmountPrecision)], Bool)]
amts ([Posting] -> [([(Quantity, AmountPrecision)], Bool)])
-> (Transaction -> [Posting])
-> Transaction
-> [([(Quantity, AmountPrecision)], Bool)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> [Posting]
tpostings)
        [([(Quantity
33.33, Word8 -> AmountPrecision
Precision Word8
2)], Bool
True), ([(Quantity
1.5, Word8 -> AmountPrecision
Precision Word8
2)], Bool
False), ([(-Quantity
100, Word8 -> AmountPrecision
Precision Word8
2)], Bool
False)]
    ,String -> Assertion -> TestTree
testCase String
"with banker's rounding" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
      StateT Journal (ParsecT HledgerParseErrorData Text IO) Transaction
-> Text
-> (Transaction -> [([(Quantity, AmountPrecision)], Bool)])
-> [([(Quantity, AmountPrecision)], Bool)]
-> Assertion
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (a -> b) -> b -> Assertion
assertParseEqOn StateT Journal (ParsecT HledgerParseErrorData Text IO) Transaction
forall (m :: * -> *). JournalParser m Transaction
transactionp ([Text] -> Text
T.unlines [Text
"2026-01-01", Text
" a  $0.25 / 2", Text
" b  $0.35 / 2", Text
" c  $-0.30"]) ([Posting] -> [([(Quantity, AmountPrecision)], Bool)]
amts ([Posting] -> [([(Quantity, AmountPrecision)], Bool)])
-> (Transaction -> [Posting])
-> Transaction
-> [([(Quantity, AmountPrecision)], Bool)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> [Posting]
tpostings)
        [([(Quantity
0.12, Word8 -> AmountPrecision
Precision Word8
2)], Bool
True), ([(Quantity
0.18, Word8 -> AmountPrecision
Precision Word8
2)], Bool
True), ([(-Quantity
0.3, Word8 -> AmountPrecision
Precision Word8
2)], Bool
False)]
    ,String -> Assertion -> TestTree
testCase String
"not counting cost amounts" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
      StateT Journal (ParsecT HledgerParseErrorData Text IO) Transaction
-> Text
-> (Transaction -> [([(Quantity, AmountPrecision)], Bool)])
-> [([(Quantity, AmountPrecision)], Bool)]
-> Assertion
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (a -> b) -> b -> Assertion
assertParseEqOn StateT Journal (ParsecT HledgerParseErrorData Text IO) Transaction
forall (m :: * -> *). JournalParser m Transaction
transactionp ([Text] -> Text
T.unlines [Text
"2026-01-01", Text
" a  10 X / 3 @ $1.2345", Text
" b  $-4"]) ([Posting] -> [([(Quantity, AmountPrecision)], Bool)]
amts ([Posting] -> [([(Quantity, AmountPrecision)], Bool)])
-> (Transaction -> [Posting])
-> Transaction
-> [([(Quantity, AmountPrecision)], Bool)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> [Posting]
tpostings)
        [([(Quantity
3, Word8 -> AmountPrecision
Precision Word8
0)], Bool
True), ([(-Quantity
4, Word8 -> AmountPrecision
Precision Word8
0)], Bool
False)]
    ,String -> Assertion -> TestTree
testCase String
"to their own precision in periodic transactions" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
      StateT
  Journal (ParsecT HledgerParseErrorData Text IO) PeriodicTransaction
-> Text
-> (PeriodicTransaction -> [([(Quantity, AmountPrecision)], Bool)])
-> [([(Quantity, AmountPrecision)], Bool)]
-> Assertion
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (a -> b) -> b -> Assertion
assertParseEqOn StateT
  Journal (ParsecT HledgerParseErrorData Text IO) PeriodicTransaction
forall (m :: * -> *).
MonadIO m =>
JournalParser m PeriodicTransaction
periodictransactionp ([Text] -> Text
T.unlines [Text
"~ monthly", Text
" a  $100/3", Text
" b  $-100.00"]) ([Posting] -> [([(Quantity, AmountPrecision)], Bool)]
amts ([Posting] -> [([(Quantity, AmountPrecision)], Bool)])
-> (PeriodicTransaction -> [Posting])
-> PeriodicTransaction
-> [([(Quantity, AmountPrecision)], Bool)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PeriodicTransaction -> [Posting]
ptpostings)
        [([(Quantity
33, Word8 -> AmountPrecision
Precision Word8
0)], Bool
False), ([(-Quantity
100, Word8 -> AmountPrecision
Precision Word8
2)], Bool
False)]
    ,String -> Assertion -> TestTree
testCase String
"to their own precision in auto posting rules" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$
      StateT
  Journal (ParsecT HledgerParseErrorData Text IO) TransactionModifier
-> Text
-> (TransactionModifier -> [([(Quantity, AmountPrecision)], Bool)])
-> [([(Quantity, AmountPrecision)], Bool)]
-> Assertion
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (a -> b) -> b -> Assertion
assertParseEqOn StateT
  Journal (ParsecT HledgerParseErrorData Text IO) TransactionModifier
forall (m :: * -> *). JournalParser m TransactionModifier
transactionmodifierp ([Text] -> Text
T.unlines [Text
"= a", Text
" (b)  $100/3", Text
" (c)  $-100.00"]) ([Posting] -> [([(Quantity, AmountPrecision)], Bool)]
amts ([Posting] -> [([(Quantity, AmountPrecision)], Bool)])
-> (TransactionModifier -> [Posting])
-> TransactionModifier
-> [([(Quantity, AmountPrecision)], Bool)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (TMPostingRule -> Posting) -> [TMPostingRule] -> [Posting]
forall a b. (a -> b) -> [a] -> [b]
map TMPostingRule -> Posting
tmprPosting ([TMPostingRule] -> [Posting])
-> (TransactionModifier -> [TMPostingRule])
-> TransactionModifier
-> [Posting]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TransactionModifier -> [TMPostingRule]
tmpostingrules)
        [([(Quantity
33, Word8 -> AmountPrecision
Precision Word8
0)], Bool
False), ([(-Quantity
100, Word8 -> AmountPrecision
Precision Word8
2)], Bool
False)]
    ]

  -- directives

  ,let p :: JournalParser IO AssertDirective
p = Day -> JournalParser IO AssertDirective
forall (m :: * -> *).
Monad m =>
Day -> JournalParser m AssertDirective
assertdirectivep (Integer -> Int -> Int -> Day
fromGregorian Integer
2026 Int
11 Int
8)
       summary :: AssertDirective -> (AssertQuantifier, Maybe Interval, Text)
summary AssertDirective
ad = (AssertDirective -> AssertQuantifier
adQuantifier AssertDirective
ad, ((Interval, DateSpan) -> Interval)
-> Maybe (Interval, DateSpan) -> Maybe Interval
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Interval, DateSpan) -> Interval
forall a b. (a, b) -> a
fst (AssertDirective -> Maybe (Interval, DateSpan)
adPeriod AssertDirective
ad), AssertDirective -> Text
adQueryText AssertDirective
ad)
   in String -> [TestTree] -> TestTree
testGroup String
"assertdirectivep" [
     String -> Assertion -> TestTree
testCase String
"no period, comment" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO AssertDirective
-> Text
-> (AssertDirective -> (AssertQuantifier, Maybe Interval, Text))
-> (AssertQuantifier, Maybe Interval, Text)
-> Assertion
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (a -> b) -> b -> Assertion
assertParseEqOn JournalParser IO AssertDirective
p Text
"assert none  expenses:petty amt:>+500  ; a comment\n" AssertDirective -> (AssertQuantifier, Maybe Interval, Text)
summary
       (AssertQuantifier
AssertNone, Maybe Interval
forall a. Maybe a
Nothing, Text
"expenses:petty amt:>+500")
    ,String -> Assertion -> TestTree
testCase String
"no period, empty query" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO AssertDirective
-> Text
-> (AssertDirective -> (AssertQuantifier, Maybe Interval, Text))
-> (AssertQuantifier, Maybe Interval, Text)
-> Assertion
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (a -> b) -> b -> Assertion
assertParseEqOn JournalParser IO AssertDirective
p Text
"assert some\n" AssertDirective -> (AssertQuantifier, Maybe Interval, Text)
summary
       (AssertQuantifier
AssertSome, Maybe Interval
forall a. Maybe a
Nothing, Text
"")
    ,String -> Assertion -> TestTree
testCase String
"no period, empty query, comment" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO AssertDirective
-> Text
-> (AssertDirective -> (AssertQuantifier, Maybe Interval, Text))
-> (AssertQuantifier, Maybe Interval, Text)
-> Assertion
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (a -> b) -> b -> Assertion
assertParseEqOn JournalParser IO AssertDirective
p Text
"assert some ; a comment\n" AssertDirective -> (AssertQuantifier, Maybe Interval, Text)
summary
       (AssertQuantifier
AssertSome, Maybe Interval
forall a. Maybe a
Nothing, Text
"")
    ,String -> Assertion -> TestTree
testCase String
"no period, balance: term" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO AssertDirective
-> Text
-> (AssertDirective -> (AssertQuantifier, Maybe Interval, Text))
-> (AssertQuantifier, Maybe Interval, Text)
-> Assertion
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (a -> b) -> b -> Assertion
assertParseEqOn JournalParser IO AssertDirective
p Text
"assert none  type:A balance:<0\n" AssertDirective -> (AssertQuantifier, Maybe Interval, Text)
summary
       (AssertQuantifier
AssertNone, Maybe Interval
forall a. Maybe a
Nothing, Text
"type:A balance:<0")
    ,String -> Assertion -> TestTree
testCase String
"no period, double space inside the query" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO AssertDirective
-> Text
-> (AssertDirective -> (AssertQuantifier, Maybe Interval, Text))
-> (AssertQuantifier, Maybe Interval, Text)
-> Assertion
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (a -> b) -> b -> Assertion
assertParseEqOn JournalParser IO AssertDirective
p Text
"assert none  desc:'a  b'\n" AssertDirective -> (AssertQuantifier, Maybe Interval, Text)
summary
       (AssertQuantifier
AssertNone, Maybe Interval
forall a. Maybe a
Nothing, Text
"desc:'a  b'")
    ,String -> Assertion -> TestTree
testCase String
"period with interval" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO AssertDirective
-> Text
-> (AssertDirective -> (AssertQuantifier, Maybe Interval, Text))
-> (AssertQuantifier, Maybe Interval, Text)
-> Assertion
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (a -> b) -> b -> Assertion
assertParseEqOn JournalParser IO AssertDirective
p Text
"assert none daily  type:A balance:<0\n" AssertDirective -> (AssertQuantifier, Maybe Interval, Text)
summary
       (AssertQuantifier
AssertNone, Interval -> Maybe Interval
forall a. a -> Maybe a
Just (Int -> Interval
Days Int
1), Text
"type:A balance:<0")
    ,String -> Assertion -> TestTree
testCase String
"period with span only" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO AssertDirective
-> Text
-> (AssertDirective -> (AssertQuantifier, Maybe Interval, Text))
-> (AssertQuantifier, Maybe Interval, Text)
-> Assertion
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (a -> b) -> b -> Assertion
assertParseEqOn JournalParser IO AssertDirective
p Text
"assert some in 2025  income:salary\n" AssertDirective -> (AssertQuantifier, Maybe Interval, Text)
summary
       (AssertQuantifier
AssertSome, Interval -> Maybe Interval
forall a. a -> Maybe a
Just Interval
NoInterval, Text
"income:salary")
    ,String -> Assertion -> TestTree
testCase String
"period, empty query" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO AssertDirective
-> Text
-> (AssertDirective -> (AssertQuantifier, Maybe Interval, Text))
-> (AssertQuantifier, Maybe Interval, Text)
-> Assertion
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (a -> b) -> b -> Assertion
assertParseEqOn JournalParser IO AssertDirective
p Text
"assert some monthly\n" AssertDirective -> (AssertQuantifier, Maybe Interval, Text)
summary
       (AssertQuantifier
AssertSome, Interval -> Maybe Interval
forall a. a -> Maybe a
Just (Int -> Interval
Months Int
1), Text
"")
    ,String -> Assertion -> TestTree
testCase String
"period, empty query, comment" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO AssertDirective
-> Text
-> (AssertDirective -> (AssertQuantifier, Maybe Interval, Text))
-> (AssertQuantifier, Maybe Interval, Text)
-> Assertion
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (a -> b) -> b -> Assertion
assertParseEqOn JournalParser IO AssertDirective
p Text
"assert some monthly  ; a comment\n" AssertDirective -> (AssertQuantifier, Maybe Interval, Text)
summary
       (AssertQuantifier
AssertSome, Interval -> Maybe Interval
forall a. a -> Maybe a
Just (Int -> Interval
Months Int
1), Text
"")
    ,String -> Assertion -> TestTree
testCase String
"a query starting with the word balance" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO AssertDirective
-> Text
-> (AssertDirective -> (AssertQuantifier, Maybe Interval, Text))
-> (AssertQuantifier, Maybe Interval, Text)
-> Assertion
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (a -> b) -> b -> Assertion
assertParseEqOn JournalParser IO AssertDirective
p Text
"assert none  balance\n" AssertDirective -> (AssertQuantifier, Maybe Interval, Text)
summary
       (AssertQuantifier
AssertNone, Maybe Interval
forall a. Maybe a
Nothing, Text
"balance")
    ,String -> Assertion -> TestTree
testCase String
"bad quantifier" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO AssertDirective -> Text -> String -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> String -> Assertion
assertParseError JournalParser IO AssertDirective
p Text
"assert never  expenses\n" String
"should be followed by none or some"
    ,String -> Assertion -> TestTree
testCase String
"period expression not parseable" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO AssertDirective -> Text -> String -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> String -> Assertion
assertParseError JournalParser IO AssertDirective
p Text
"assert none dialy  expenses\n" String
"as a period expression"
    ,String -> Assertion -> TestTree
testCase String
"query needs two spaces" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO AssertDirective -> Text -> String -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> String -> Assertion
assertParseError JournalParser IO AssertDirective
p Text
"assert some desc:'opening balances'\n" String
"as a period expression"
    ,String -> Assertion -> TestTree
testCase String
"period expression needs a double space" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO AssertDirective -> Text -> String -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> String -> Assertion
assertParseError JournalParser IO AssertDirective
p Text
"assert none daily type:A\n" String
"terminate the period expression with a double space"
    ,String -> Assertion -> TestTree
testCase String
"bad query" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO AssertDirective -> Text -> String -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> String -> Assertion
assertParseError JournalParser IO AssertDirective
p Text
"assert none  amt:>x\n" String
""
    ,String -> Assertion -> TestTree
testCase String
"row terms inside or" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ JournalParser IO AssertDirective -> Text -> String -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> String -> Assertion
assertParseError JournalParser IO AssertDirective
p Text
"assert none monthly  expr:'a or change:>0'\n" String
"can only be combined"
    ]

  ,String -> [TestTree] -> TestTree
testGroup String
"directivep" [
    String -> Assertion -> TestTree
testCase String
"supports !" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
        StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO))
  ()
-> Text -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT
  st
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO))
  a
-> Text -> Assertion
assertParseE (InputOpts
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO))
     ()
forall (m :: * -> *).
MonadIO m =>
InputOpts -> ErroringJournalParser m ()
directivep InputOpts
definputopts) Text
"!account a\n"
        StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO))
  ()
-> Text -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT
  st
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO))
  a
-> Text -> Assertion
assertParseE (InputOpts
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO))
     ()
forall (m :: * -> *).
MonadIO m =>
InputOpts -> ErroringJournalParser m ()
directivep InputOpts
definputopts) Text
"!D 1.0\n"
     ]

  ,String -> [TestTree] -> TestTree
testGroup String
"accountdirectivep" [
       String -> Assertion -> TestTree
testCase String
"with-comment"       (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
accountdirectivep Text
"account a:b  ; a comment\n"
      ,String -> Assertion -> TestTree
testCase String
"does-not-support-!" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
-> Text -> String -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> String -> Assertion
assertParseError StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
accountdirectivep Text
"!account a:b\n" String
""
      ,String -> Assertion -> TestTree
testCase String
"account-type-code"  (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
accountdirectivep Text
"account a:b  ; type:A\n"
      ,String -> Assertion -> TestTree
testCase String
"account-type-tag"   (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
-> Text
-> (Journal -> [(Text, AccountDeclarationInfo)])
-> [(Text, AccountDeclarationInfo)]
-> Assertion
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (st -> b) -> b -> Assertion
assertParseStateOn StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
accountdirectivep Text
"account a:b  ; type:asset\n"
        Journal -> [(Text, AccountDeclarationInfo)]
jdeclaredaccounts
        [(Text
"a:b", AccountDeclarationInfo{adicomment :: Text
adicomment          = Text
"type:asset\n"
                                       ,aditags :: [Tag]
aditags             = [(Text
"type",Text
"asset")]
                                       ,adideclarationorder :: Int
adideclarationorder = Int
1
                                       ,adisourcepos :: SourcePos
adisourcepos        = SourcePos
nullsourcepos
                                       })
        ]
      ]

  ,String -> Assertion -> TestTree
testCase String
"commodityconversiondirectivep" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
commodityconversiondirectivep Text
"C 1h = $50.00\n"

  ,String -> Assertion -> TestTree
testCase String
"defaultcommoditydirectivep" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
      StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
defaultcommoditydirectivep Text
"D $1,000.0\n"
      StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
-> Text -> String -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> String -> Assertion
assertParseError StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
defaultcommoditydirectivep Text
"D $1000\n" String
"Please include a decimal point or decimal comma"

  ,String -> [TestTree] -> TestTree
testGroup String
"defaultyeardirectivep" [
      String -> Assertion -> TestTree
testCase String
"1000" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
defaultyeardirectivep Text
"Y 1000" -- XXX no \n like the others
     -- ,testCase "999" $ assertParseError defaultyeardirectivep "Y 999" "bad year number"
     ,String -> Assertion -> TestTree
testCase String
"12345" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
defaultyeardirectivep Text
"Y 12345"
     ]

  ,String -> Assertion -> TestTree
testCase String
"ignoredpricecommoditydirectivep" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
ignoredpricecommoditydirectivep Text
"N $\n"

  ,String -> [TestTree] -> TestTree
testGroup String
"includedirectivep" [
      String -> Assertion -> TestTree
testCase String
"include" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO))
  ()
-> Text -> String -> Assertion
forall st a.
(Default st, Eq a, Show a, HasCallStack) =>
StateT
  st
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO))
  a
-> Text -> String -> Assertion
assertParseErrorE (InputOpts
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO))
     ()
forall (m :: * -> *).
MonadIO m =>
InputOpts -> ErroringJournalParser m ()
includedirectivep InputOpts
definputopts) Text
"include nosuchfile\n" String
"No files were matched by: nosuchfile"
     ,String -> Assertion -> TestTree
testCase String
"glob" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO))
  ()
-> Text -> String -> Assertion
forall st a.
(Default st, Eq a, Show a, HasCallStack) =>
StateT
  st
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO))
  a
-> Text -> String -> Assertion
assertParseErrorE (InputOpts
-> StateT
     Journal
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO))
     ()
forall (m :: * -> *).
MonadIO m =>
InputOpts -> ErroringJournalParser m ()
includedirectivep InputOpts
definputopts) Text
"include nosuchfile*\n" String
"No files were matched by: nosuchfile*"
     ]

  ,String -> Assertion -> TestTree
testCase String
"marketpricedirectivep" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData Text IO) PriceDirective
-> Text -> PriceDirective -> Assertion
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq StateT
  Journal (ParsecT HledgerParseErrorData Text IO) PriceDirective
forall (m :: * -> *). JournalParser m PriceDirective
marketpricedirectivep
    Text
"P 2017/01/30 BTC $922.83\n"
    PriceDirective{
      pdsourcepos :: SourcePos
pdsourcepos = SourcePos
nullsourcepos,
      pddate :: Day
pddate      = Integer -> Int -> Int -> Day
fromGregorian Integer
2017 Int
1 Int
30,
      pdcommodity :: Text
pdcommodity = Text
"BTC",
      pdamount :: Amount
pdamount    = Quantity -> Amount
usd Quantity
922.83
      }

  ,String -> [TestTree] -> TestTree
testGroup String
"payeedirectivep" [
        String -> Assertion -> TestTree
testCase String
"simple"             (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
payeedirectivep Text
"payee foo\n"
       ,String -> Assertion -> TestTree
testCase String
"with-comment"       (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
payeedirectivep Text
"payee foo ; comment\n"
       ,String -> Assertion -> TestTree
testCase String
"double-quoted"      (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
payeedirectivep Text
"payee \"a b\"\n"
       ,String -> Assertion -> TestTree
testCase String
"empty        "      (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
payeedirectivep Text
"payee \"\"\n"
       ]

  ,String -> Assertion -> TestTree
testCase String
"tagdirectivep" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
tagdirectivep Text
"tag foo \n"

  ,String -> Assertion -> TestTree
testCase String
"endtagdirectivep" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
      StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
endtagdirectivep Text
"end tag \n"
      StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
-> Text -> Assertion
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse StateT Journal (ParsecT HledgerParseErrorData Text IO) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData Text m) ()
endtagdirectivep Text
"end apply tag \n"

  ,String -> [TestTree] -> TestTree
testGroup String
"journalp" [
    String -> Assertion -> TestTree
testCase String
"empty file" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ ErroringJournalParser IO Journal -> Text -> Journal -> Assertion
forall st a.
(Default st, Eq a, Show a, HasCallStack) =>
StateT
  st
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError IO))
  a
-> Text -> a -> Assertion
assertParseEqE (InputOpts -> ErroringJournalParser IO Journal
forall (m :: * -> *).
MonadIO m =>
InputOpts -> ErroringJournalParser m Journal
journalp InputOpts
definputopts) Text
"" Journal
nulljournal
    ]

   -- these are defined here rather than in Common so they can use journalp
  ,String -> Assertion -> TestTree
testCase String
"parseAndFinaliseJournal" (Assertion -> TestTree) -> Assertion -> TestTree
forall a b. (a -> b) -> a -> b
$ do
      ej <- ExceptT String IO Journal -> IO (Either String Journal)
forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT (ExceptT String IO Journal -> IO (Either String Journal))
-> ExceptT String IO Journal -> IO (Either String Journal)
forall a b. (a -> b) -> a -> b
$ ErroringJournalParser IO Journal
-> InputOpts -> String -> Text -> ExceptT String IO Journal
parseAndFinaliseJournal (InputOpts -> ErroringJournalParser IO Journal
forall (m :: * -> *).
MonadIO m =>
InputOpts -> ErroringJournalParser m Journal
journalp InputOpts
definputopts) InputOpts
definputopts String
"" Text
"2019-1-1\n"
      let Right j = ej
      assertEqual "" [""] $ journalFilePaths j

  ]