--- * -*- 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/MANUAL.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 #-}

--- ** 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

  -- * Tests
  ,tests_JournalReader
)
where

--- ** imports
import qualified Control.Monad.Fail as Fail (fail)
import qualified Control.Exception as C
import Control.Monad (forM_, when, void, unless)
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.Char (toLower)
import Data.Either (isRight)
import qualified Data.Map.Strict as M
import Data.Text (Text)
import Data.String
import Data.List
import Data.Maybe
import qualified Data.Text as T
import Data.Time.Calendar
import Data.Time.LocalTime
import Safe
import Text.Megaparsec hiding (parse)
import Text.Megaparsec.Char
import Text.Megaparsec.Custom
import Text.Printf
import System.FilePath
import "Glob" System.FilePath.Glob hiding (match)

import Hledger.Data
import Hledger.Read.Common
import Hledger.Utils

import qualified Hledger.Read.TimedotReader as TimedotReader (reader)
import qualified Hledger.Read.TimeclockReader as TimeclockReader (reader)
import qualified Hledger.Read.CsvReader as CsvReader (reader)

--- ** 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 = forall (m :: * -> *) e s a.
Monad m =>
ParsecT e s m a
-> [Char] -> s -> m (Either (ParseErrorBundle s e) a)
runParserT (forall (m :: * -> *) s a. Monad m => StateT s m a -> s -> m a
evalStateT JournalParser m a
p Journal
nulljournal) [Char]
""
rjp :: forall (m :: * -> *) a.
Monad m =>
JournalParser m a -> Text -> m (Either HledgerParseErrors a)
rjp = 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 =
  forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) e s a.
Monad m =>
ParsecT e s m a
-> [Char] -> s -> m (Either (ParseErrorBundle s e) a)
runParserT (forall (m :: * -> *) s a. Monad m => StateT s m a -> s -> m a
evalStateT ErroringJournalParser m a
p Journal
nulljournal) [Char]
"" Text
t
rejp :: forall (m :: * -> *) a.
Monad m =>
ErroringJournalParser m a
-> Text -> m (Either FinalParseError (Either HledgerParseErrors a))
rejp = 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' = [
  forall (m :: * -> *). MonadIO m => Reader m
reader
 ,forall (m :: * -> *). MonadIO m => Reader m
TimeclockReader.reader
 ,forall (m :: * -> *). MonadIO m => Reader m
TimedotReader.reader
 ,forall (m :: * -> *). MonadIO m => Reader m
CsvReader.reader
--  ,LedgerReader.reader
 ]

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

-- | @findReader mformat mpath@
--
-- Find the reader named by @mformat@, if provided.
-- 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 [Char] -> Maybe [Char] -> Maybe (Reader m)
findReader Maybe [Char]
Nothing Maybe [Char]
Nothing     = forall a. Maybe a
Nothing
findReader (Just [Char]
fmt) Maybe [Char]
_        = forall a. [a] -> Maybe a
headMay [Reader m
r | Reader m
r <- forall (m :: * -> *). MonadIO m => [Reader m]
readers', forall (m :: * -> *). Reader m -> [Char]
rFormat Reader m
r forall a. Eq a => a -> a -> Bool
== [Char]
fmt]
findReader Maybe [Char]
Nothing (Just [Char]
path) =
  case Maybe [Char]
prefix of
    Just [Char]
fmt -> forall a. [a] -> Maybe a
headMay [Reader m
r | Reader m
r <- forall (m :: * -> *). MonadIO m => [Reader m]
readers', forall (m :: * -> *). Reader m -> [Char]
rFormat Reader m
r forall a. Eq a => a -> a -> Bool
== [Char]
fmt]
    Maybe [Char]
Nothing  -> forall a. [a] -> Maybe a
headMay [Reader m
r | Reader m
r <- forall (m :: * -> *). MonadIO m => [Reader m]
readers', [Char]
ext forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` forall (m :: * -> *). Reader m -> [[Char]]
rExtensions Reader m
r]
  where
    (Maybe [Char]
prefix,[Char]
path') = [Char] -> (Maybe [Char], [Char])
splitReaderPrefix [Char]
path
    ext :: [Char]
ext            = forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower forall a b. (a -> b) -> a -> b
$ forall a. Int -> [a] -> [a]
drop Int
1 forall a b. (a -> b) -> a -> b
$ [Char] -> [Char]
takeExtension [Char]
path'

-- | A file path optionally prefixed by a reader name and colon
-- (journal:, csv:, timedot:, etc.).
type PrefixedFilePath = FilePath

-- | If a filepath is prefixed by one of the reader names and a colon,
-- split that off. Eg "csv:-" -> (Just "csv", "-").
splitReaderPrefix :: PrefixedFilePath -> (Maybe String, FilePath)
splitReaderPrefix :: [Char] -> (Maybe [Char], [Char])
splitReaderPrefix [Char]
f =
  forall a. a -> [a] -> a
headDef (forall a. Maybe a
Nothing, [Char]
f)
  [(forall a. a -> Maybe a
Just [Char]
r, forall a. Int -> [a] -> [a]
drop (forall (t :: * -> *) a. Foldable t => t a -> Int
length [Char]
r forall a. Num a => a -> a -> a
+ Int
1) [Char]
f) | [Char]
r <- [[Char]]
readerNames, ([Char]
rforall a. [a] -> [a] -> [a]
++[Char]
":") forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf` [Char]
f]

--- ** reader

reader :: MonadIO m => Reader m
reader :: forall (m :: * -> *). MonadIO m => Reader m
reader = Reader
  {rFormat :: [Char]
rFormat     = [Char]
"journal"
  ,rExtensions :: [[Char]]
rExtensions = [[Char]
"journal", [Char]
"j", [Char]
"hledger", [Char]
"ledger"]
  ,rReadFn :: InputOpts -> [Char] -> Text -> ExceptT [Char] IO Journal
rReadFn     = InputOpts -> [Char] -> Text -> ExceptT [Char] IO Journal
parse
  ,rParser :: MonadIO m => ErroringJournalParser m Journal
rParser    = forall (m :: * -> *). MonadIO m => 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 -> [Char] -> Text -> ExceptT [Char] IO Journal
parse InputOpts
iopts [Char]
f = ErroringJournalParser IO Journal
-> InputOpts -> [Char] -> Text -> ExceptT [Char] IO Journal
parseAndFinaliseJournal ErroringJournalParser IO Journal
journalp' InputOpts
iopts [Char]
f
  where
    journalp' :: ErroringJournalParser IO Journal
journalp' = do
      -- reverse parsed aliases to ensure that they are applied in order given on commandline
      forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ forall (m :: * -> *). MonadState Journal m => AccountAlias -> m ()
addAccountAlias (forall a. [a] -> [a]
reverse forall a b. (a -> b) -> a -> b
$ InputOpts -> [AccountAlias]
aliasesFromOpts InputOpts
iopts)
      forall (m :: * -> *). MonadIO m => ErroringJournalParser m Journal
journalp

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

-- | A journal parser. Accumulates and returns a "ParsedJournal",
-- which should be finalised/validated before use.
--
-- >>> rejp (journalp <* eof) "2015/1/1\n a  0\n"
-- Right (Right Journal (unknown) with 1 transactions, 1 accounts)
--
journalp :: MonadIO m => ErroringJournalParser m ParsedJournal
journalp :: forall (m :: * -> *). MonadIO m => ErroringJournalParser m Journal
journalp = do
  forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
many forall (m :: * -> *). MonadIO m => ErroringJournalParser m ()
addJournalItemP
  forall e s (m :: * -> *). MonadParsec e s m => m ()
eof
  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.
addJournalItemP :: MonadIO m => ErroringJournalParser m ()
addJournalItemP :: forall (m :: * -> *). MonadIO m => ErroringJournalParser m ()
addJournalItemP =
  -- all journal line types can be distinguished by the first
  -- character, can use choice without backtracking
  forall (f :: * -> *) (m :: * -> *) a.
(Foldable f, Alternative m) =>
f (m a) -> m a
choice [
      forall (m :: * -> *). MonadIO m => ErroringJournalParser m ()
directivep
    , forall (m :: * -> *). JournalParser m Transaction
transactionp          forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> Journal -> Journal
addTransaction
    , forall (m :: * -> *). JournalParser m TransactionModifier
transactionmodifierp  forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' forall b c a. (b -> c) -> (a -> b) -> a -> c
. TransactionModifier -> Journal -> Journal
addTransactionModifier
    , forall (m :: * -> *).
MonadIO m =>
JournalParser m PeriodicTransaction
periodictransactionp  forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' forall b c a. (b -> c) -> (a -> b) -> a -> c
. PeriodicTransaction -> Journal -> Journal
addPeriodicTransaction
    , forall (m :: * -> *). JournalParser m PriceDirective
marketpricedirectivep forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' forall b c a. (b -> c) -> (a -> b) -> a -> c
. PriceDirective -> Journal -> Journal
addPriceDirective
    , forall (f :: * -> *) a. Functor f => f a -> f ()
void (forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m ()
emptyorcommentlinep)
    , forall (f :: * -> *) a. Functor f => f a -> f ()
void (forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m ()
multilinecommentp)
    ] forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"transaction or directive"

--- *** directives

-- | Parse any journal directive and update the parse state accordingly.
-- Cf http://hledger.org/manual.html#directives,
-- http://ledger-cli.org/3.0/doc/ledger3.html#Command-Directives
directivep :: MonadIO m => ErroringJournalParser m ()
directivep :: forall (m :: * -> *). MonadIO m => ErroringJournalParser m ()
directivep = (do
  forall (f :: * -> *) a. Alternative f => f a -> f (Maybe a)
optional forall a b. (a -> b) -> a -> b
$ forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
'!'
  forall (f :: * -> *) (m :: * -> *) a.
(Foldable f, Alternative m) =>
f (m a) -> m a
choice [
    forall (m :: * -> *). MonadIO m => ErroringJournalParser m ()
includedirectivep
   ,forall (m :: * -> *). JournalParser m ()
aliasdirectivep
   ,forall (m :: * -> *). JournalParser m ()
endaliasesdirectivep
   ,forall (m :: * -> *). JournalParser m ()
accountdirectivep
   ,forall (m :: * -> *). JournalParser m ()
applyaccountdirectivep
   ,forall (m :: * -> *). JournalParser m ()
commoditydirectivep
   ,forall (m :: * -> *). JournalParser m ()
endapplyaccountdirectivep
   ,forall (m :: * -> *). JournalParser m ()
payeedirectivep
   ,forall (m :: * -> *). JournalParser m ()
tagdirectivep
   ,forall (m :: * -> *). JournalParser m ()
endtagdirectivep
   ,forall (m :: * -> *). JournalParser m ()
defaultyeardirectivep
   ,forall (m :: * -> *). JournalParser m ()
defaultcommoditydirectivep
   ,forall (m :: * -> *). JournalParser m ()
commodityconversiondirectivep
   ,forall (m :: * -> *). JournalParser m ()
ignoredpricecommoditydirectivep
   ,forall (m :: * -> *). JournalParser m ()
decimalmarkdirectivep
   ]
  ) forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"directive"

-- | Parse an include directive. include's argument is an optionally
-- file-format-prefixed file path or glob pattern. In the latter case,
-- the prefix is applied to each matched path. Examples:
-- foo.j, foo/bar.j, timedot:foo/2020*.md
includedirectivep :: MonadIO m => ErroringJournalParser m ()
includedirectivep :: forall (m :: * -> *). MonadIO m => ErroringJournalParser m ()
includedirectivep = do
  forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"include"
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  [Char]
prefixedglob <- Text -> [Char]
T.unpack forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe [Char] -> (Token s -> Bool) -> m (Tokens s)
takeWhileP forall a. Maybe a
Nothing (forall a. Eq a => a -> a -> Bool
/= Char
'\n') -- don't consume newline yet
  Int
parentoff <- forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
  SourcePos
parentpos <- forall s e (m :: * -> *).
(TraversableStream s, MonadParsec e s m) =>
m SourcePos
getSourcePos
  let (Maybe [Char]
mprefix,[Char]
glb) = [Char] -> (Maybe [Char], [Char])
splitReaderPrefix [Char]
prefixedglob
  [[Char]]
paths <- forall (m :: * -> *).
MonadIO m =>
Int -> SourcePos -> [Char] -> JournalParser m [[Char]]
getFilePaths Int
parentoff SourcePos
parentpos [Char]
glb
  let prefixedpaths :: [[Char]]
prefixedpaths = case Maybe [Char]
mprefix of
        Maybe [Char]
Nothing  -> [[Char]]
paths
        Just [Char]
fmt -> forall a b. (a -> b) -> [a] -> [b]
map (([Char]
fmtforall a. [a] -> [a] -> [a]
++[Char]
":")forall a. [a] -> [a] -> [a]
++) [[Char]]
paths
  forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [[Char]]
prefixedpaths forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *).
MonadIO m =>
SourcePos -> [Char] -> ErroringJournalParser m ()
parseChild SourcePos
parentpos
  forall (f :: * -> *) a. Functor f => f a -> f ()
void forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m (Token s)
newline

  where
    getFilePaths
      :: MonadIO m => Int -> SourcePos -> FilePath -> JournalParser m [FilePath]
    getFilePaths :: forall (m :: * -> *).
MonadIO m =>
Int -> SourcePos -> [Char] -> JournalParser m [[Char]]
getFilePaths Int
parseroff SourcePos
parserpos [Char]
filename = do
        let curdir :: [Char]
curdir = [Char] -> [Char]
takeDirectory (SourcePos -> [Char]
sourceName SourcePos
parserpos)
        [Char]
filename' <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall a b. (a -> b) -> a -> b
$ [Char] -> IO [Char]
expandHomePath [Char]
filename
                         forall (m :: * -> *) a.
MonadIO m =>
IO a -> [Char] -> TextParser m a
`orRethrowIOError` (forall a. Show a => a -> [Char]
show SourcePos
parserpos forall a. [a] -> [a] -> [a]
++ [Char]
" locating " forall a. [a] -> [a] -> [a]
++ [Char]
filename)
        -- Compiling filename as a glob pattern works even if it is a literal
        Pattern
fileglob <- case CompOptions -> [Char] -> Either [Char] Pattern
tryCompileWith CompOptions
compDefault{errorRecovery :: Bool
errorRecovery=Bool
False} [Char]
filename' of
            Right Pattern
x -> forall (f :: * -> *) a. Applicative f => a -> f a
pure Pattern
x
            Left [Char]
e -> forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure forall a b. (a -> b) -> a -> b
$
                        Int -> [Char] -> HledgerParseErrorData
parseErrorAt Int
parseroff forall a b. (a -> b) -> a -> b
$ [Char]
"Invalid glob pattern: " forall a. [a] -> [a] -> [a]
++ [Char]
e
        -- Get all matching files in the current working directory, sorting in
        -- lexicographic order to simulate the output of 'ls'.
        [[Char]]
filepaths <- forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall a b. (a -> b) -> a -> b
$ forall a. Ord a => [a] -> [a]
sort forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Pattern -> [Char] -> IO [[Char]]
globDir1 Pattern
fileglob [Char]
curdir
        if (Bool -> Bool
not forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall (t :: * -> *) a. Foldable t => t a -> Bool
null) [[Char]]
filepaths
            then forall (f :: * -> *) a. Applicative f => a -> f a
pure [[Char]]
filepaths
            else forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure forall a b. (a -> b) -> a -> b
$ Int -> [Char] -> HledgerParseErrorData
parseErrorAt Int
parseroff forall a b. (a -> b) -> a -> b
$
                   [Char]
"No existing files match pattern: " forall a. [a] -> [a] -> [a]
++ [Char]
filename

    parseChild :: MonadIO m => SourcePos -> PrefixedFilePath -> ErroringJournalParser m ()
    parseChild :: forall (m :: * -> *).
MonadIO m =>
SourcePos -> [Char] -> ErroringJournalParser m ()
parseChild SourcePos
parentpos [Char]
prefixedpath = do
      let (Maybe [Char]
_mprefix,[Char]
filepath) = [Char] -> (Maybe [Char], [Char])
splitReaderPrefix [Char]
prefixedpath

      Journal
parentj <- forall s (m :: * -> *). MonadState s m => m s
get
      let parentfilestack :: [[Char]]
parentfilestack = Journal -> [[Char]]
jincludefilestack Journal
parentj
      forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when ([Char]
filepath forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [[Char]]
parentfilestack) forall a b. (a -> b) -> a -> b
$
        forall (m :: * -> *) a. MonadFail m => [Char] -> m a
Fail.fail ([Char]
"Cyclic include: " forall a. [a] -> [a] -> [a]
++ [Char]
filepath)

      Text
childInput <-
        forall a. Int -> [Char] -> a -> a
traceOrLogAt Int
6 ([Char]
"parseChild: "forall a. [a] -> [a] -> [a]
++[Char] -> [Char]
takeFileName [Char]
filepath) forall a b. (a -> b) -> a -> b
$
        forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall a b. (a -> b) -> a -> b
$ [Char] -> IO Text
readFilePortably [Char]
filepath
          forall (m :: * -> *) a.
MonadIO m =>
IO a -> [Char] -> TextParser m a
`orRethrowIOError` (forall a. Show a => a -> [Char]
show SourcePos
parentpos forall a. [a] -> [a] -> [a]
++ [Char]
" reading " forall a. [a] -> [a] -> [a]
++ [Char]
filepath)
      let initChildj :: Journal
initChildj = [Char] -> Journal -> Journal
newJournalWithParseStateFrom [Char]
filepath Journal
parentj

      -- Choose a reader/parser based on the file path prefix or file extension,
      -- defaulting to JournalReader. Duplicating readJournal a bit here.
      let r :: Reader m
r = forall a. a -> Maybe a -> a
fromMaybe forall (m :: * -> *). MonadIO m => Reader m
reader forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *).
MonadIO m =>
Maybe [Char] -> Maybe [Char] -> Maybe (Reader m)
findReader forall a. Maybe a
Nothing (forall a. a -> Maybe a
Just [Char]
prefixedpath)
          parser :: ErroringJournalParser m Journal
parser = forall (m :: * -> *).
Reader m -> MonadIO m => ErroringJournalParser m Journal
rParser Reader m
r
      forall (m :: * -> *) a. (MonadIO m, Show a) => [Char] -> a -> m ()
dbg6IO [Char]
"parseChild: trying reader" (forall (m :: * -> *). Reader m -> [Char]
rFormat Reader m
r)

      -- Parse the file (of whichever format) to a Journal, with file path and source text attached.
      Journal
updatedChildj <- ([Char], Text) -> Journal -> Journal
journalAddFile ([Char]
filepath, Text
childInput) forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$>
                        forall (m :: * -> *) st a.
Monad m =>
StateT
  st
  (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
  a
-> st
-> [Char]
-> Text
-> StateT
     st
     (ParsecT HledgerParseErrorData Text (ExceptT FinalParseError m))
     a
parseIncludeFile ErroringJournalParser m Journal
parser Journal
initChildj [Char]
filepath Text
childInput

      -- Merge this child journal into the parent journal
      -- (with debug logging for troubleshooting account display order).
      -- 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' :: Journal
parentj' =
          [Char] -> Journal -> Journal
dbgJournalAcctDeclOrder ([Char]
"parseChild: child " forall a. Semigroup a => a -> a -> a
<> [Char]
childfilename forall a. Semigroup a => a -> a -> a
<> [Char]
" acct decls: ") Journal
updatedChildj
          Journal -> Journal -> Journal
`journalConcat`
          [Char] -> Journal -> Journal
dbgJournalAcctDeclOrder ([Char]
"parseChild: parent " forall a. Semigroup a => a -> a -> a
<> [Char]
parentfilename forall a. Semigroup a => a -> a -> a
<> [Char]
" acct decls: ") Journal
parentj

          where
            childfilename :: [Char]
childfilename = [Char] -> [Char]
takeFileName [Char]
filepath
            parentfilename :: [Char]
parentfilename = forall b a. b -> (a -> b) -> Maybe a -> b
maybe [Char]
"(unknown)" [Char] -> [Char]
takeFileName forall a b. (a -> b) -> a -> b
$ forall a. [a] -> Maybe a
headMay forall a b. (a -> b) -> a -> b
$ Journal -> [[Char]]
jincludefilestack Journal
parentj  -- XXX more accurate than journalFilePath for some reason

      -- Update the parse state.
      forall s (m :: * -> *). MonadState s m => s -> m ()
put Journal
parentj'

    newJournalWithParseStateFrom :: FilePath -> Journal -> Journal
    newJournalWithParseStateFrom :: [Char] -> Journal -> Journal
newJournalWithParseStateFrom [Char]
filepath Journal
j = Journal
nulljournal{
      jparsedefaultyear :: Maybe Year
jparsedefaultyear      = Journal -> Maybe Year
jparsedefaultyear Journal
j
      ,jparsedefaultcommodity :: Maybe (Text, AmountStyle)
jparsedefaultcommodity = Journal -> Maybe (Text, AmountStyle)
jparsedefaultcommodity Journal
j
      ,jparseparentaccounts :: [Text]
jparseparentaccounts   = Journal -> [Text]
jparseparentaccounts Journal
j
      ,jparsedecimalmark :: Maybe Char
jparsedecimalmark      = Journal -> Maybe Char
jparsedecimalmark Journal
j
      ,jparsealiases :: [AccountAlias]
jparsealiases          = Journal -> [AccountAlias]
jparsealiases Journal
j
      ,jcommodities :: Map Text Commodity
jcommodities           = Journal -> Map Text Commodity
jcommodities Journal
j
      -- ,jparsetransactioncount = jparsetransactioncount j
      ,jparsetimeclockentries :: [TimeclockEntry]
jparsetimeclockentries = Journal -> [TimeclockEntry]
jparsetimeclockentries Journal
j
      ,jincludefilestack :: [[Char]]
jincludefilestack      = [Char]
filepath forall a. a -> [a] -> [a]
: Journal -> [[Char]]
jincludefilestack Journal
j
      }

-- | Lift an IO action into the exception monad, rethrowing any IO
-- error with the given message prepended.
orRethrowIOError :: MonadIO m => IO a -> String -> TextParser m a
orRethrowIOError :: forall (m :: * -> *) a.
MonadIO m =>
IO a -> [Char] -> TextParser m a
orRethrowIOError IO a
io [Char]
msg = do
  Either [Char] a
eResult <- forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall a b. (a -> b) -> a -> b
$ (forall a b. b -> Either a b
Right forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO a
io) forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`C.catch` \(IOException
e::C.IOException) -> forall (f :: * -> *) a. Applicative f => a -> f a
pure forall a b. (a -> b) -> a -> b
$ forall a b. a -> Either a b
Left forall a b. (a -> b) -> a -> b
$ forall r. PrintfType r => [Char] -> r
printf [Char]
"%s:\n%s" [Char]
msg (forall a. Show a => a -> [Char]
show IOException
e)
  case Either [Char] a
eResult of
    Right a
res -> forall (f :: * -> *) a. Applicative f => a -> f a
pure a
res
    Left [Char]
errMsg -> forall (m :: * -> *) a. MonadFail m => [Char] -> m a
Fail.fail [Char]
errMsg

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

  forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"account"
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1

  -- the account name, possibly modified by preceding alias or apply account directives
  Text
acct <- forall (m :: * -> *). JournalParser m Text
modifiedaccountnamep

  -- maybe a comment, on this and/or following lines
  (Text
cmt, [Tag]
tags) <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m (Text, [Tag])
transactioncommentp

  -- maybe Ledger-style subdirectives (ignored)
  forall (m :: * -> *) a. MonadPlus m => m a -> m ()
skipMany forall (m :: * -> *). JournalParser m [Char]
indentedlinep

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

  -- update the journal
  forall (m :: * -> *).
(Text, Text, [Tag], SourcePos) -> JournalParser m ()
addAccountDeclaration (Text
acct, Text
cmt, [Tag]
tags, SourcePos
pos)
  forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Tag]
tags) forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *). Text -> [Tag] -> JournalParser m ()
addDeclaredAccountTags Text
acct [Tag]
tags
  case Maybe (Either [Char] AccountType)
metype of
    Maybe (Either [Char] AccountType)
Nothing         -> forall (m :: * -> *) a. Monad m => a -> m a
return ()
    Just (Right AccountType
t)  -> forall (m :: * -> *). Text -> AccountType -> JournalParser m ()
addDeclaredAccountType Text
acct AccountType
t
    Just (Left [Char]
err) -> forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure forall a b. (a -> b) -> a -> b
$ Int -> [Char] -> HledgerParseErrorData
parseErrorAt Int
off [Char]
err

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

parseAccountTypeCode :: Text -> Either String AccountType
parseAccountTypeCode :: Text -> Either [Char] AccountType
parseAccountTypeCode Text
s =
  case Text -> Text
T.toLower Text
s of
    Text
"asset"      -> forall a b. b -> Either a b
Right AccountType
Asset
    Text
"a"          -> forall a b. b -> Either a b
Right AccountType
Asset
    Text
"liability"  -> forall a b. b -> Either a b
Right AccountType
Liability
    Text
"l"          -> forall a b. b -> Either a b
Right AccountType
Liability
    Text
"equity"     -> forall a b. b -> Either a b
Right AccountType
Equity
    Text
"e"          -> forall a b. b -> Either a b
Right AccountType
Equity
    Text
"revenue"    -> forall a b. b -> Either a b
Right AccountType
Revenue
    Text
"r"          -> forall a b. b -> Either a b
Right AccountType
Revenue
    Text
"expense"    -> forall a b. b -> Either a b
Right AccountType
Expense
    Text
"x"          -> forall a b. b -> Either a b
Right AccountType
Expense
    Text
"cash"       -> forall a b. b -> Either a b
Right AccountType
Cash
    Text
"c"          -> forall a b. b -> Either a b
Right AccountType
Cash
    Text
"conversion" -> forall a b. b -> Either a b
Right AccountType
Conversion
    Text
"v"          -> forall a b. b -> Either a b
Right AccountType
Conversion
    Text
_            -> forall a b. a -> Either a b
Left [Char]
err
  where
    err :: [Char]
err = Text -> [Char]
T.unpack forall a b. (a -> b) -> a -> b
$ Text
"invalid account type code "forall a. Semigroup a => a -> a -> a
<>Text
sforall a. Semigroup a => a -> a -> a
<>Text
", should be one of " forall a. Semigroup a => a -> a -> a
<>
            Text -> [Text] -> Text
T.intercalate Text
", " [Text
"A",Text
"L",Text
"E",Text
"R",Text
"X",Text
"C",Text
"V",Text
"Asset",Text
"Liability",Text
"Equity",Text
"Revenue",Text
"Expense",Text
"Cash",Text
"Conversion"]

-- 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
  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 :: Text
adicomment          = Text
cmt
                             ,aditags :: [Tag]
aditags             = [Tag]
tags
                             ,adideclarationorder :: Int
adideclarationorder = forall (t :: * -> *) a. Foldable t => t a -> Int
length [(Text, AccountDeclarationInfo)]
decls forall a. Num a => a -> a -> a
+ Int
1  -- gets renumbered when Journals are finalised or merged
                             ,adisourcepos :: SourcePos
adisourcepos        = SourcePos
pos
                             })
             in
               Journal
j{jdeclaredaccounts :: [(Text, AccountDeclarationInfo)]
jdeclaredaccounts = (Text, AccountDeclarationInfo)
dforall a. a -> [a] -> [a]
:[(Text, AccountDeclarationInfo)]
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) =
  forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' (\j :: Journal
j@Journal{[(Text, PayeeDeclarationInfo)]
jdeclaredpayees :: Journal -> [(Text, PayeeDeclarationInfo)]
jdeclaredpayees :: [(Text, PayeeDeclarationInfo)]
jdeclaredpayees} -> Journal
j{jdeclaredpayees :: [(Text, PayeeDeclarationInfo)]
jdeclaredpayees=(Text, PayeeDeclarationInfo)
dforall a. a -> [a] -> [a]
:[(Text, PayeeDeclarationInfo)]
jdeclaredpayees})
             where
               d :: (Text, PayeeDeclarationInfo)
d = (Text
p
                   ,PayeeDeclarationInfo
nullpayeedeclarationinfo{
                     pdicomment :: Text
pdicomment = Text
cmt
                    ,pditags :: [Tag]
pditags    = [Tag]
tags
                    })

indentedlinep :: JournalParser m String
indentedlinep :: forall (m :: * -> *). JournalParser m [Char]
indentedlinep = forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1 forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ([Char] -> [Char]
rstrip forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m [Char]
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 :: * -> *). JournalParser m ()
commoditydirectivep = forall (m :: * -> *). JournalParser m ()
commoditydirectiveonelinep forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> forall (m :: * -> *). JournalParser 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 :: * -> *). JournalParser m ()
commoditydirectiveonelinep = do
  (Int
off, Amount{Text
acommodity :: Amount -> Text
acommodity :: Text
acommodity,AmountStyle
astyle :: Amount -> AmountStyle
astyle :: AmountStyle
astyle}) <- forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try forall a b. (a -> b) -> a -> b
$ do
    forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"commodity"
    forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
    Int
off <- forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
    Amount
amt <- forall (m :: * -> *). JournalParser m Amount
amountp
    forall (f :: * -> *) a. Applicative f => a -> f a
pure forall a b. (a -> b) -> a -> b
$ (Int
off, Amount
amt)
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  Text
_ <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m Text
followingcommentp
  let comm :: Commodity
comm = Commodity{csymbol :: Text
csymbol=Text
acommodity, cformat :: Maybe AmountStyle
cformat=forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$ forall a. Show a => [Char] -> a -> a
dbg6 [Char]
"style from commodity directive" AmountStyle
astyle}
  if forall a. Maybe a -> Bool
isNothing forall a b. (a -> b) -> a -> b
$ AmountStyle -> Maybe Char
asdecimalpoint AmountStyle
astyle
  then forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure forall a b. (a -> b) -> a -> b
$ Int -> [Char] -> HledgerParseErrorData
parseErrorAt Int
off [Char]
pleaseincludedecimalpoint
  else forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' (\Journal
j -> Journal
j{jcommodities :: Map Text Commodity
jcommodities=forall k a. Ord k => k -> a -> Map k a -> Map k a
M.insert Text
acommodity Commodity
comm forall a b. (a -> b) -> a -> b
$ Journal -> Map Text Commodity
jcommodities Journal
j})

pleaseincludedecimalpoint :: String
pleaseincludedecimalpoint :: [Char]
pleaseincludedecimalpoint = [Char] -> [Char]
chomp forall a b. (a -> b) -> a -> b
$ [[Char]] -> [Char]
unlines [
   [Char]
"Please include a decimal point or decimal comma in commodity directives,"
  ,[Char]
"to help us parse correctly. It may be followed by zero or more decimal digits."
  ,[Char]
"Examples:"
  ,[Char]
"commodity $1000.            ; no thousands mark, decimal period, no decimals"
  ,[Char]
"commodity 1.234,00 ARS      ; period at thousands, decimal comma, 2 decimals"
  ,[Char]
"commodity EUR 1 000,000     ; space at thousands, decimal comma, 3 decimals"
  ,[Char]
"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 :: * -> *). JournalParser m ()
commoditydirectivemultilinep = do
  forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"commodity"
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  Text
sym <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m Text
commoditysymbolp
  Text
_ <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m Text
followingcommentp
  Maybe AmountStyle
mfmt <- forall a. [a] -> Maybe a
lastMay forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
many (forall {b}.
StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
indented forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *). Text -> JournalParser m AmountStyle
formatdirectivep Text
sym)
  let comm :: Commodity
comm = Commodity{csymbol :: Text
csymbol=Text
sym, cformat :: Maybe AmountStyle
cformat=Maybe AmountStyle
mfmt}
  forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' (\Journal
j -> Journal
j{jcommodities :: Map Text Commodity
jcommodities=forall k a. Ord k => k -> a -> Map k a -> Map k a
M.insert Text
sym Commodity
comm forall a b. (a -> b) -> a -> b
$ Journal -> Map Text Commodity
jcommodities Journal
j})
  where
    indented :: StateT Journal (ParsecT HledgerParseErrorData Text m) b
-> StateT Journal (ParsecT HledgerParseErrorData Text m) b
indented = (forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1 forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>>)

-- | 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
  forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"format"
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  Int
off <- forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
  Amount{Text
acommodity :: Text
acommodity :: Amount -> Text
acommodity,AmountStyle
astyle :: AmountStyle
astyle :: Amount -> AmountStyle
astyle} <- forall (m :: * -> *). JournalParser m Amount
amountp
  Text
_ <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m Text
followingcommentp
  if Text
acommodityforall a. Eq a => a -> a -> Bool
==Text
expectedsym
    then
      if forall a. Maybe a -> Bool
isNothing forall a b. (a -> b) -> a -> b
$ AmountStyle -> Maybe Char
asdecimalpoint AmountStyle
astyle
      then forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure forall a b. (a -> b) -> a -> b
$ Int -> [Char] -> HledgerParseErrorData
parseErrorAt Int
off [Char]
pleaseincludedecimalpoint
      else forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ forall a. Show a => [Char] -> a -> a
dbg6 [Char]
"style from format subdirective" AmountStyle
astyle
    else forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure forall a b. (a -> b) -> a -> b
$ Int -> [Char] -> HledgerParseErrorData
parseErrorAt Int
off forall a b. (a -> b) -> a -> b
$
         forall r. PrintfType r => [Char] -> r
printf [Char]
"commodity directive symbol \"%s\" and format directive symbol \"%s\" should be the same" Text
expectedsym Text
acommodity

keywordp :: String -> JournalParser m ()
keywordp :: forall (m :: * -> *). [Char] -> JournalParser m ()
keywordp = forall (f :: * -> *) a. Functor f => f a -> f ()
void forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. IsString a => [Char] -> a
fromString

spacesp :: JournalParser m ()
spacesp :: forall (m :: * -> *). JournalParser m ()
spacesp = forall (f :: * -> *) a. Functor f => f a -> f ()
void forall a b. (a -> b) -> a -> b
$ forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift 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 :: * -> *). [Char] -> JournalParser m ()
keywordsp = forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall (t :: * -> *) (m :: * -> *) a.
(Foldable t, Monad m) =>
t (m a) -> m ()
sequence_ forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a. a -> [a] -> [a]
intersperse forall (m :: * -> *). JournalParser m ()
spacesp forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b. (a -> b) -> [a] -> [b]
map forall (m :: * -> *). [Char] -> JournalParser m ()
keywordp forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> [[Char]]
words

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

endapplyaccountdirectivep :: JournalParser m ()
endapplyaccountdirectivep :: forall (m :: * -> *). JournalParser m ()
endapplyaccountdirectivep = do
  forall (m :: * -> *). [Char] -> JournalParser m ()
keywordsp [Char]
"end apply account" forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"end apply account directive"
  forall (m :: * -> *). JournalParser m ()
popParentAccount

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

endaliasesdirectivep :: JournalParser m ()
endaliasesdirectivep :: forall (m :: * -> *). JournalParser m ()
endaliasesdirectivep = do
  forall (m :: * -> *). [Char] -> JournalParser m ()
keywordsp [Char]
"end aliases" forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"end aliases directive"
  forall (m :: * -> *). MonadState Journal m => m ()
clearAccountAliases

tagdirectivep :: JournalParser m ()
tagdirectivep :: forall (m :: * -> *). JournalParser m ()
tagdirectivep = do
  forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"tag" forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"tag directive"
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  [Char]
_ <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
some forall (m :: * -> *). TextParser m Char
nonspace
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m [Char]
restofline
  forall (m :: * -> *) a. Monad m => a -> m a
return ()

endtagdirectivep :: JournalParser m ()
endtagdirectivep :: forall (m :: * -> *). JournalParser m ()
endtagdirectivep = do
  (forall (m :: * -> *). [Char] -> JournalParser m ()
keywordsp [Char]
"end tag" forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> forall (m :: * -> *). [Char] -> JournalParser m ()
keywordp [Char]
"pop") forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"end tag or pop directive"
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m [Char]
restofline
  forall (m :: * -> *) a. Monad m => a -> m a
return ()

payeedirectivep :: JournalParser m ()
payeedirectivep :: forall (m :: * -> *). JournalParser m ()
payeedirectivep = do
  forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"payee" forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"payee directive"
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  Text
payee <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall a b. (a -> b) -> a -> b
$ Text -> Text
T.strip forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall (m :: * -> *). TextParser m Text
noncommenttext1p
  (Text
comment, [Tag]
tags) <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m (Text, [Tag])
transactioncommentp
  forall (m :: * -> *). (Text, Text, [Tag]) -> JournalParser m ()
addPayeeDeclaration (Text
payee, Text
comment, [Tag]
tags)
  forall (m :: * -> *) a. Monad m => a -> m a
return ()

defaultyeardirectivep :: JournalParser m ()
defaultyeardirectivep :: forall (m :: * -> *). JournalParser m ()
defaultyeardirectivep = do
  forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
'Y' forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"default year"
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  forall (m :: * -> *). Year -> JournalParser m ()
setYear forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m Year
yearp

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

marketpricedirectivep :: JournalParser m PriceDirective
marketpricedirectivep :: forall (m :: * -> *). JournalParser m PriceDirective
marketpricedirectivep = do
  forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
'P' forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"market price"
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  Day
date <- forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (do {LocalTime Day
d TimeOfDay
_ <- forall (m :: * -> *). JournalParser m LocalTime
datetimep; forall (m :: * -> *) a. Monad m => a -> m a
return Day
d}) forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> forall (m :: * -> *). JournalParser m Day
datep -- a time is ignored
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  Text
symbol <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m Text
commoditysymbolp
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  Amount
price <- forall (m :: * -> *). JournalParser m Amount
amountp
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m [Char]
restofline
  forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ Day -> Text -> Amount -> PriceDirective
PriceDirective Day
date Text
symbol Amount
price

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

commodityconversiondirectivep :: JournalParser m ()
commodityconversiondirectivep :: forall (m :: * -> *). JournalParser m ()
commodityconversiondirectivep = do
  forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
'C' forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"commodity conversion"
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  forall (m :: * -> *). JournalParser m Amount
amountp
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
'='
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  forall (m :: * -> *). JournalParser m Amount
amountp
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m [Char]
restofline
  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 :: * -> *). JournalParser m ()
decimalmarkdirectivep = do
  forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens Text
"decimal-mark" forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"decimal mark"
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
  Char
mark <- forall e s (m :: * -> *).
MonadParsec e s m =>
(Token s -> Bool) -> m (Token s)
satisfy Char -> Bool
isDecimalMark
  forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' forall a b. (a -> b) -> a -> b
$ \Journal
j -> Journal
j{jparsedecimalmark :: Maybe Char
jparsedecimalmark=forall a. a -> Maybe a
Just Char
mark}
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m [Char]
restofline
  forall (m :: * -> *) a. Monad m => a -> m a
return ()

--- *** transactions

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

  -- first line
  forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
'~' forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"periodic transaction"
  forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall a b. (a -> b) -> a -> b
$ forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  -- a period expression
  Int
off <- forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset

  -- if there's a default year in effect, use Y/1/1 as base for partial/relative dates
  Day
today <- forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO IO Day
getCurrentDay
  Maybe Year
mdefaultyear <- forall (m :: * -> *). JournalParser m (Maybe Year)
getYear
  let refdate :: Day
refdate = case Maybe Year
mdefaultyear of
                  Maybe Year
Nothing -> Day
today
                  Just Year
y  -> Year -> Int -> Int -> Day
fromGregorian Year
y Int
1 Int
1
  SourceExcerpt
periodExcerpt <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a.
MonadParsec HledgerParseErrorData Text m =>
m a -> m SourceExcerpt
excerpt_ forall a b. (a -> b) -> a -> b
$
                    forall (m :: * -> *). (Char -> Bool) -> TextParser m Text
singlespacedtextsatisfying1p (\Char
c -> Char
c forall a. Eq a => a -> a -> Bool
/= Char
';' Bool -> Bool -> Bool
&& Char
c forall a. Eq a => a -> a -> Bool
/= Char
'\n')
  let periodtxt :: Text
periodtxt = Text -> Text
T.strip 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
interval, DateSpan
spn) <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a.
Monad m =>
SourceExcerpt
-> ParsecT HledgerParseErrorData Text m a
-> ParsecT HledgerParseErrorData Text m a
reparseExcerpt SourceExcerpt
periodExcerpt forall a b. (a -> b) -> a -> b
$ do
    (Interval, DateSpan)
pexp <- forall (m :: * -> *). Day -> TextParser m (Interval, DateSpan)
periodexprp Day
refdate
    forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
(<|>) forall e s (m :: * -> *). MonadParsec e s m => m ()
eof forall a b. (a -> b) -> a -> b
$ do
      Int
offset1 <- forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
      forall (f :: * -> *) a. Functor f => f a -> f ()
void forall e s (m :: * -> *). MonadParsec e s m => m (Tokens s)
takeRest
      Int
offset2 <- forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
      forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure forall a b. (a -> b) -> a -> b
$ Int -> Int -> [Char] -> HledgerParseErrorData
parseErrorAtRegion Int
offset1 Int
offset2 forall a b. (a -> b) -> a -> b
$
           [Char]
"remainder of period expression cannot be parsed"
        forall a. Semigroup a => a -> a -> a
<> [Char]
"\nperhaps you need to terminate the period expression with a double space?"
        forall a. Semigroup a => a -> a -> a
<> [Char]
"\na double space is required between period expression and description/comment"
    forall (f :: * -> *) a. Applicative f => a -> f a
pure (Interval, DateSpan)
pexp

  -- In periodic transactions, the period expression has an additional constraint:
  case Interval -> DateSpan -> Text -> Maybe [Char]
checkPeriodicTransactionStartDate Interval
interval DateSpan
spn Text
periodtxt of
    Just [Char]
e -> forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure forall a b. (a -> b) -> a -> b
$ Int -> [Char] -> HledgerParseErrorData
parseErrorAt Int
off [Char]
e
    Maybe [Char]
Nothing -> forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

  Status
status <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m Status
statusp forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"cleared status"
  Text
code <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m Text
codep forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"transaction code"
  Text
description <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall a b. (a -> b) -> a -> b
$ Text -> Text
T.strip forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall (m :: * -> *). TextParser m Text
descriptionp
  (Text
comment, [Tag]
tags) <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m (Text, [Tag])
transactioncommentp
  -- next lines; use same year determined above
  [Posting]
postings <- forall (m :: * -> *). Maybe Year -> JournalParser m [Posting]
postingsp (forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$ forall {a} {b} {c}. (a, b, c) -> a
first3 forall a b. (a -> b) -> a -> b
$ Day -> (Year, Int, Int)
toGregorian Day
refdate)

  forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ PeriodicTransaction
nullperiodictransaction{
     ptperiodexpr :: Text
ptperiodexpr=Text
periodtxt
    ,ptinterval :: Interval
ptinterval=Interval
interval
    ,ptspan :: DateSpan
ptspan=DateSpan
spn
    ,ptstatus :: Status
ptstatus=Status
status
    ,ptcode :: Text
ptcode=Text
code
    ,ptdescription :: Text
ptdescription=Text
description
    ,ptcomment :: Text
ptcomment=Text
comment
    ,pttags :: [Tag]
pttags=[Tag]
tags
    ,ptpostings :: [Posting]
ptpostings=[Posting]
postings
    }

-- | Parse a (possibly unbalanced) transaction.
transactionp :: JournalParser m Transaction
transactionp :: forall (m :: * -> *). JournalParser m Transaction
transactionp = do
  -- dbgparse 0 "transactionp"
  SourcePos
startpos <- forall s e (m :: * -> *).
(TraversableStream s, MonadParsec e s m) =>
m SourcePos
getSourcePos
  Day
date <- forall (m :: * -> *). JournalParser m Day
datep forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"transaction"
  Maybe Day
edate <- forall (f :: * -> *) a. Alternative f => f a -> f (Maybe a)
optional (forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *). Day -> TextParser m Day
secondarydatep Day
date) forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"secondary date"
  forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
lookAhead (forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Char ~ Token s) =>
ParsecT HledgerParseErrorData s m Char
spacenonewline forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m (Token s)
newline) forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"whitespace or newline"
  Status
status <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m Status
statusp forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"cleared status"
  Text
code <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m Text
codep forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"transaction code"
  Text
description <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall a b. (a -> b) -> a -> b
$ Text -> Text
T.strip forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall (m :: * -> *). TextParser m Text
descriptionp
  (Text
comment, [Tag]
tags) <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m (Text, [Tag])
transactioncommentp
  let year :: Year
year = forall {a} {b} {c}. (a, b, c) -> a
first3 forall a b. (a -> b) -> a -> b
$ Day -> (Year, Int, Int)
toGregorian Day
date
  [Posting]
postings <- forall (m :: * -> *). Maybe Year -> JournalParser m [Posting]
postingsp (forall a. a -> Maybe a
Just Year
year)
  SourcePos
endpos <- forall s e (m :: * -> *).
(TraversableStream s, MonadParsec e s m) =>
m SourcePos
getSourcePos
  let sourcepos :: (SourcePos, SourcePos)
sourcepos = (SourcePos
startpos, SourcePos
endpos)
  forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ Transaction -> Transaction
txnTieKnot forall a b. (a -> b) -> a -> b
$ Year
-> Text
-> (SourcePos, SourcePos)
-> Day
-> Maybe Day
-> Status
-> Text
-> Text
-> Text
-> [Tag]
-> [Posting]
-> Transaction
Transaction Year
0 Text
"" (SourcePos, SourcePos)
sourcepos Day
date Maybe Day
edate Status
status Text
code Text
description Text
comment [Tag]
tags [Posting]
postings

--- *** 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 Year -> JournalParser m [Posting]
postingsp Maybe Year
mTransactionYear = forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
many (forall (m :: * -> *). Maybe Year -> JournalParser m Posting
postingp Maybe Year
mTransactionYear) forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"postings"

-- 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 Year -> JournalParser m Posting
postingp = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap forall a b. (a, b) -> a
fst forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall (m :: * -> *).
Bool -> Maybe Year -> 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 Year -> JournalParser m [TMPostingRule]
tmpostingrulesp Maybe Year
mTransactionYear = forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
many (forall (m :: * -> *). Maybe Year -> JournalParser m TMPostingRule
tmpostingrulep Maybe Year
mTransactionYear) forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> [Char] -> m a
<?> [Char]
"posting rules"

tmpostingrulep :: Maybe Year -> JournalParser m TMPostingRule
tmpostingrulep :: forall (m :: * -> *). Maybe Year -> JournalParser m TMPostingRule
tmpostingrulep = forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry Posting -> Bool -> TMPostingRule
TMPostingRule) forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall (m :: * -> *).
Bool -> Maybe Year -> 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 Year -> JournalParser m (Posting, Bool)
postingphelper Bool
isPostingRule Maybe Year
mTransactionYear = do
    -- lift $ dbgparse 0 "postingp"
    (Status
status, Text
account) <- forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try forall a b. (a -> b) -> a -> b
$ do
      forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
      Status
status <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m Status
statusp
      forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
      Text
account <- forall (m :: * -> *). JournalParser m Text
modifiedaccountnamep
      forall (m :: * -> *) a. Monad m => a -> m a
return (Status
status, Text
account)
    let (PostingType
ptype, Text
account') = (Text -> PostingType
accountNamePostingType Text
account, Text -> Text
textUnbracket Text
account)
    forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
    Bool
mult <- if Bool
isPostingRule then StateT Journal (ParsecT HledgerParseErrorData Text m) Bool
multiplierp else forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
False
    Maybe Amount
amt <- forall (f :: * -> *) a. Alternative f => f a -> f (Maybe a)
optional forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *). Bool -> JournalParser m Amount
amountpwithmultiplier Bool
mult
    forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
    Maybe BalanceAssertion
massertion <- forall (f :: * -> *) a. Alternative f => f a -> f (Maybe a)
optional forall (m :: * -> *). JournalParser m BalanceAssertion
balanceassertionp
    forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
    (Text
comment,[Tag]
tags,Maybe Day
mdate,Maybe Day
mdate2) <- forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *).
Maybe Year -> TextParser m (Text, [Tag], Maybe Day, Maybe Day)
postingcommentp Maybe Year
mTransactionYear
    let p :: Posting
p = Posting
posting
            { pdate :: Maybe Day
pdate=Maybe Day
mdate
            , pdate2 :: Maybe Day
pdate2=Maybe Day
mdate2
            , pstatus :: Status
pstatus=Status
status
            , paccount :: Text
paccount=Text
account'
            , pamount :: MixedAmount
pamount=forall b a. b -> (a -> b) -> Maybe a -> b
maybe MixedAmount
missingmixedamt Amount -> MixedAmount
mixedAmount Maybe Amount
amt
            , pcomment :: Text
pcomment=Text
comment
            , ptype :: PostingType
ptype=PostingType
ptype
            , ptags :: [Tag]
ptags=[Tag]
tags
            , pbalanceassertion :: Maybe BalanceAssertion
pbalanceassertion=Maybe BalanceAssertion
massertion
            }
    forall (m :: * -> *) a. Monad m => a -> m a
return (Posting
p, Bool
mult)
  where
    multiplierp :: StateT Journal (ParsecT HledgerParseErrorData Text m) Bool
multiplierp = forall (m :: * -> *) a. Alternative m => a -> m a -> m a
option Bool
False forall a b. (a -> b) -> a -> b
$ Bool
True forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
'*'

--- ** tests

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

   let p :: JournalParser IO Text
p = forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift forall (m :: * -> *). TextParser m Text
accountnamep :: JournalParser IO AccountName in
   [Char] -> [TestTree] -> TestTree
testGroup [Char]
"accountnamep" [
     [Char] -> Assertion -> TestTree
testCase [Char]
"basic" forall a b. (a -> b) -> a -> b
$ forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse JournalParser IO Text
p Text
"a:b:c"
    -- ,testCase "empty inner component" $ assertParseError p "a::c" ""  -- TODO
    -- ,testCase "empty leading component" $ assertParseError p ":b:c" "x"
    -- ,testCase "empty trailing component" $ assertParseError p "a:b:" "x"
    ]

  -- "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."
  ,[Char] -> [TestTree] -> TestTree
testGroup [Char]
"datep" [
     [Char] -> Assertion -> TestTree
testCase [Char]
"YYYY/MM/DD" forall a b. (a -> b) -> a -> b
$ forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq forall (m :: * -> *). JournalParser m Day
datep Text
"2018/01/01" (Year -> Int -> Int -> Day
fromGregorian Year
2018 Int
1 Int
1)
    ,[Char] -> Assertion -> TestTree
testCase [Char]
"YYYY-MM-DD" forall a b. (a -> b) -> a -> b
$ forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse forall (m :: * -> *). JournalParser m Day
datep Text
"2018-01-01"
    ,[Char] -> Assertion -> TestTree
testCase [Char]
"YYYY.MM.DD" forall a b. (a -> b) -> a -> b
$ forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse forall (m :: * -> *). JournalParser m Day
datep Text
"2018.01.01"
    ,[Char] -> Assertion -> TestTree
testCase [Char]
"yearless date with no default year" forall a b. (a -> b) -> a -> b
$ forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> [Char] -> Assertion
assertParseError forall (m :: * -> *). JournalParser m Day
datep Text
"1/1" [Char]
"current year is unknown"
    ,[Char] -> Assertion -> TestTree
testCase [Char]
"yearless date with default year" forall a b. (a -> b) -> a -> b
$ do
      let s :: Text
s = Text
"1/1"
      Either HledgerParseErrors Day
ep <- forall (m :: * -> *) st a.
Monad m =>
st
-> StateT st (ParsecT HledgerParseErrorData Text m) a
-> Text
-> m (Either HledgerParseErrors a)
parseWithState Journal
nulljournal{jparsedefaultyear :: Maybe Year
jparsedefaultyear=forall a. a -> Maybe a
Just Year
2018} forall (m :: * -> *). JournalParser m Day
datep Text
s
      forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (forall a. HasCallStack => [Char] -> IO a
assertFailure forall b c a. (b -> c) -> (a -> b) -> a -> c
. ([Char]
"parse error at "forall a. [a] -> [a] -> [a]
++) forall b c a. (b -> c) -> (a -> b) -> a -> c
. HledgerParseErrors -> [Char]
customErrorBundlePretty) (forall a b. a -> b -> a
const forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a. Monad m => a -> m a
return ()) Either HledgerParseErrors Day
ep
    ,[Char] -> Assertion -> TestTree
testCase [Char]
"no leading zero" forall a b. (a -> b) -> a -> b
$ forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse forall (m :: * -> *). JournalParser m Day
datep Text
"2018/1/1"
    ]
  ,[Char] -> Assertion -> TestTree
testCase [Char]
"datetimep" forall a b. (a -> b) -> a -> b
$ do
     let
       good :: Text -> Assertion
good  = forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse forall (m :: * -> *). JournalParser m LocalTime
datetimep
       bad :: Text -> Assertion
bad Text
t = forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> [Char] -> Assertion
assertParseError forall (m :: * -> *). JournalParser m LocalTime
datetimep Text
t [Char]
""
     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 (Year -> Int -> Int -> Day
fromGregorian Year
2018 Int
1 Int
1) (Int -> Int -> Pico -> TimeOfDay
TimeOfDay Int
0 Int
0 Pico
0)
     forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq forall (m :: * -> *). JournalParser m LocalTime
datetimep Text
"2018/1/1 00:00-0800" LocalTime
t
     forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq forall (m :: * -> *). JournalParser m LocalTime
datetimep Text
"2018/1/1 00:00+1234" LocalTime
t

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

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

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

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

    ,[Char] -> Assertion -> TestTree
testCase [Char]
"Just date, no description" forall a b. (a -> b) -> a -> b
$ forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq forall (m :: * -> *).
MonadIO m =>
JournalParser m PeriodicTransaction
periodictransactionp
      Text
"~ 2019-01-04\n"
      PeriodicTransaction
nullperiodictransaction {
         ptperiodexpr :: Text
ptperiodexpr  = Text
"2019-01-04"
        ,ptinterval :: Interval
ptinterval    = Interval
NoInterval
        ,ptspan :: DateSpan
ptspan        = Maybe Day -> Maybe Day -> DateSpan
DateSpan (forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$ Year -> Int -> Int -> Day
fromGregorian Year
2019 Int
1 Int
4) (forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$ Year -> Int -> Int -> Day
fromGregorian Year
2019 Int
1 Int
5)
        ,ptdescription :: Text
ptdescription = Text
""
        ,ptcomment :: Text
ptcomment     = Text
""
        }

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

    ]

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

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

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

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

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

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

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

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

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

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

    ,[Char] -> Assertion -> TestTree
testCase [Char]
"more complex" forall a b. (a -> b) -> a -> b
$ forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> a -> Assertion
assertParseEq 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, SourcePos)
tsourcepos=([Char] -> Pos -> Pos -> SourcePos
SourcePos [Char]
"" (Int -> Pos
mkPos Int
1) (Int -> Pos
mkPos Int
1), [Char] -> Pos -> Pos -> SourcePos
SourcePos [Char]
"" (Int -> Pos
mkPos Int
8) (Int -> Pos
mkPos Int
1)),  -- 8 because there are 7 lines
        tprecedingcomment :: Text
tprecedingcomment=Text
"",
        tdate :: Day
tdate=Year -> Int -> Int -> Day
fromGregorian Year
2012 Int
5 Int
14,
        tdate2 :: Maybe Day
tdate2=forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$ Year -> Int -> Int -> Day
fromGregorian Year
2012 Int
5 Int
15,
        tstatus :: Status
tstatus=Status
Unmarked,
        tcode :: Text
tcode=Text
"code",
        tdescription :: Text
tdescription=Text
"desc",
        tcomment :: Text
tcomment=Text
"tcomment1\ntcomment2\nttag1: val1\n",
        ttags :: [Tag]
ttags=[(Text
"ttag1",Text
"val1")],
        tpostings :: [Posting]
tpostings=[
          Posting
nullposting{
            pdate :: Maybe Day
pdate=forall a. Maybe a
Nothing,
            pstatus :: Status
pstatus=Status
Cleared,
            paccount :: Text
paccount=Text
"a",
            pamount :: MixedAmount
pamount=Amount -> MixedAmount
mixedAmount (DecimalRaw Year -> Amount
usd DecimalRaw Year
1),
            pcomment :: Text
pcomment=Text
"pcomment1\npcomment2\nptag1: val1\nptag2: val2\n",
            ptype :: PostingType
ptype=PostingType
RegularPosting,
            ptags :: [Tag]
ptags=[(Text
"ptag1",Text
"val1"),(Text
"ptag2",Text
"val2")],
            ptransaction :: Maybe Transaction
ptransaction=forall a. Maybe a
Nothing
            }
          ]
      }

    ,[Char] -> Assertion -> TestTree
testCase [Char]
"parses a well-formed transaction" forall a b. (a -> b) -> a -> b
$
      HasCallStack => [Char] -> Bool -> Assertion
assertBool [Char]
"" forall a b. (a -> b) -> a -> b
$ forall a b. Either a b -> Bool
isRight forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a.
Monad m =>
JournalParser m a -> Text -> m (Either HledgerParseErrors a)
rjp forall (m :: * -> *). JournalParser m Transaction
transactionp 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
""
        ]

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

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

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

    ,[Char] -> Assertion -> TestTree
testCase [Char]
"comments everywhere, two postings parsed" forall a b. (a -> b) -> a -> b
$
      forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (a -> b) -> b -> Assertion
assertParseEqOn 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"
          ])
        (forall (t :: * -> *) a. Foldable t => t a -> Int
length forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> [Posting]
tpostings)
        Int
2

    ]

  -- directives

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

  ,[Char] -> [TestTree] -> TestTree
testGroup [Char]
"accountdirectivep" [
       [Char] -> Assertion -> TestTree
testCase [Char]
"with-comment"       forall a b. (a -> b) -> a -> b
$ forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse forall (m :: * -> *). JournalParser m ()
accountdirectivep Text
"account a:b  ; a comment\n"
      ,[Char] -> Assertion -> TestTree
testCase [Char]
"does-not-support-!" forall a b. (a -> b) -> a -> b
$ forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> [Char] -> Assertion
assertParseError forall (m :: * -> *). JournalParser m ()
accountdirectivep Text
"!account a:b\n" [Char]
""
      ,[Char] -> Assertion -> TestTree
testCase [Char]
"account-type-code"  forall a b. (a -> b) -> a -> b
$ forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse forall (m :: * -> *). JournalParser m ()
accountdirectivep Text
"account a:b  ; type:A\n"
      ,[Char] -> Assertion -> TestTree
testCase [Char]
"account-type-tag"   forall a b. (a -> b) -> a -> b
$ forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> (st -> b) -> b -> Assertion
assertParseStateOn forall (m :: * -> *). JournalParser 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        = forall a b. (a, b) -> a
fst (SourcePos, SourcePos)
nullsourcepos
                                       })
        ]
      ]

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

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

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

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

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

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

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

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

  ,[Char] -> Assertion -> TestTree
testCase [Char]
"endtagdirectivep" forall a b. (a -> b) -> a -> b
$ do
      forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse forall (m :: * -> *). JournalParser m ()
endtagdirectivep Text
"end tag \n"
      forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData Text IO) a
-> Text -> Assertion
assertParse forall (m :: * -> *). JournalParser m ()
endtagdirectivep Text
"pop \n"

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

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

  ]