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

File reading/parsing utilities used by multiple readers, and a good
amount of the parsers for journal format, to avoid import cycles
when JournalReader imports other readers.

Some of these might belong in Hledger.Read.JournalReader or Hledger.Read.

-}

--- ** language
{-# LANGUAGE BangPatterns        #-}
{-# LANGUAGE CPP                 #-}
{-# LANGUAGE FlexibleContexts    #-}
{-# LANGUAGE LambdaCase          #-}
{-# LANGUAGE NamedFieldPuns      #-}
{-# LANGUAGE NoMonoLocalBinds    #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE Rank2Types          #-}
{-# LANGUAGE RecordWildCards     #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections       #-}
{-# LANGUAGE TypeFamilies        #-}
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
{-# HLINT ignore "Functor law" #-}

--- ** exports
module Hledger.Read.Common (
  Reader (..),
  readerReadsOwnInput,
  includeFileParser,
  PrefixedFilePath,
  isStdin,
  InputOpts(..),
  HasInputOpts(..),
  definputopts,
  rawOptsToInputOpts,
  handleReadFnToTextReadFn,

  -- * parsing utilities
  parseAndFinaliseJournal,
  initialiseAndParseJournal,
  journalFinalise,
  journalAddForecast,
  journalAddAutoPostings,
  journalCheckAssertsWith,
  setYear,
  getYear,
  getSourcePos',
  setDefaultCommodityAndStyle,
  getDefaultCommodityAndStyle,
  getDefaultAmountStyle,
  getAmountStyle,
  journalDecimalMarkStyle,
  journalAmountStyleFor,
  shareText,
  shareAmountStyle,
  addDeclaredAccountTags,
  addDeclaredAccountType,
  pushParentAccount,
  getParentAccount,
  addAccountAlias,
  getAccountAliases,
  journalAddFile,

  -- * parsers
  -- ** transaction bits
  statusp,
  codep,
  descriptionp,

  -- ** dates
  datep,
  datetimep,
  timeofdayp,
  secondarydatep,

  -- ** account names
  modifiedaccountnamep,
  aliasedaccountnamep,
  applyParentAndOptionAliases,
  accountNameApplyModifiers,
  accountnamep,
  accountnamenosemicolonp,
  parentaccountnamep,

  -- ** account aliases
  accountaliasp,

  -- ** amounts
  spaceandamountormissingp,
  amountp,
  AmountParseKind(..),
  amountp',
  postingamountp,
  simpleamountp,
  commoditysymbolp,
  costp,
  balanceassertionp,
  lotcostp,
  numberp,
  fromRawNumber,
  rawnumberp,
  interpretRawNumber,
  RawNumber(..),
  AmbiguousNumber(..),
  DigitGrp(..),
  isDigitSeparatorChar,
  parseamount,
  parseamountWithStyles,
  parseamount',
  parsemixedamount,
  parsemixedamount',

  -- ** comments
  isLineCommentStart,
  isSameLineCommentStart,
  multilinecommentp,
  emptyorcommentlinep,
  emptyorcommentlinep2,
  followingcommentp,
  transactioncommentp,
  commentlinetagsp,
  postingcommentp,

  -- ** bracketed dates
  bracketeddatetagsp,

  -- ** misc
  doublequotedtextp,
  noncommenttextp,
  noncommenttext1p,
  singlespacedtext1p,
  singlespacednoncommenttext1p,
  singlespacedtextsatisfying1p,
  singlespacep,
  skipNonNewlineSpaces,
  skipNonNewlineSpaces1,
  aliasesFromOpts,

  -- * tests
  tests_Common,
)
where

--- ** imports
import Control.Monad (foldM, forM_, liftM2, when, unless, (>=>), (<=<))
import Control.Monad.Fail qualified as Fail (fail)
import Control.Exception (evaluate)
import Control.Exception.Safe (tryIO)
import Control.Monad.Except (ExceptT(..), liftEither, runExceptT, withExceptT)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.State.Strict (MonadState, evalStateT, modify', get)
import Control.Monad.Trans.Class (lift)
import Data.Bifunctor (bimap, first, second)
import Data.Char (digitToInt, isDigit, isSpace)
import Data.Decimal (DecimalRaw (Decimal), Decimal)
import Data.Either (rights)
import Data.Function ((&))
import Data.Functor ((<&>), ($>), void)
import Data.List (find, genericReplicate, intercalate, sortOn, union)
import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, listToMaybe)
import Data.Map qualified as M
import Data.Set qualified as S
import Data.Semigroup qualified as Sem
import Data.Text (Text, stripEnd)
import Data.Text qualified as T
import Data.Time.Calendar (Day, fromGregorianValid, toGregorian)
import Data.Time.Clock.POSIX (getPOSIXTime)
import Data.Time.LocalTime (LocalTime(..), TimeOfDay(..))
import Data.Word (Word8)
import System.Directory (canonicalizePath)
import System.FilePath (takeFileName)
import System.IO (Handle)
import Text.Megaparsec
import Text.Megaparsec.Char (char, char', digitChar, newline, string)
import Text.Megaparsec.Char.Lexer (decimal)
import Text.Printf (printf)

import Hledger.Data
import Hledger.Query (Query(..), filterQuery, parseQueryTerm, queryEndDate, queryStartDate, queryIsDate, simplifyQuery)
import Hledger.Reports.ReportOptions (ReportOpts(..), queryFromFlags, rawOptsToReportOpts)
import Hledger.Utils
import Hledger.Read.InputOptions


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

--- ** types

-- main types; a few more below

-- | A hledger journal reader is a storage format name,
-- a list of file extensions assumed to be in this format,
-- and an IO action that reads data in this format, returning a Journal.
--
-- The journal parser used by the latter is also stored separately for direct use
-- by the journal reader's includedirectivep to parse included files.
-- The type variable m is needed for this parser.
-- Lately it requires an InputOpts, basically to support --old-timeclock.
data Reader m = Reader {
    -- The canonical name of the format handled by this reader. "journal", "timedot", "csv" etc.
   forall (m :: * -> *). Reader m -> StorageFormat
rFormat :: StorageFormat
    -- The file extensions recognised as containing this format.
  ,forall (m :: * -> *). Reader m -> [String]
rExtensions :: [String]
    -- An IO action for reading this format, producing a journal or an error message.
    -- It accepts input options, a file path to show in error messages, and a handle to read data from.
  ,forall (m :: * -> *).
Reader m
-> InputOpts -> String -> Handle -> ExceptT String IO Journal
rReadFn :: InputOpts -> FilePath -> Handle -> ExceptT String IO Journal
    -- The megaparsec parser called by the above, provided separately for parsing included files.
    -- It is given the included file's text as input, or empty text if the reader reads its own input
    -- (see readerReadsOwnInput).
  ,forall (m :: * -> *).
Reader m
-> MonadIO m => InputOpts -> ErroringJournalParser m Journal
rParser :: MonadIO m => InputOpts -> ErroringJournalParser m ParsedJournal
  }

instance Show (Reader m) where show :: Reader m -> String
show Reader m
r = StorageFormat -> String
forall a. Show a => a -> String
show (Reader m -> StorageFormat
forall (m :: * -> *). Reader m -> StorageFormat
rFormat Reader m
r) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" reader"

-- | Does this reader's rParser read the included file itself, ignoring the text it is given ?
-- The CSV and rules readers do, since their data may be in a non-UTF-8 encoding declared by
-- the rules file, or (for rules files) in a separate data file.
readerReadsOwnInput :: Reader m -> Bool
readerReadsOwnInput :: forall (m :: * -> *). Reader m -> Bool
readerReadsOwnInput Reader m
r = case Reader m -> StorageFormat
forall (m :: * -> *). Reader m -> StorageFormat
rFormat Reader m
r of
  Sep SepFormat
_ -> Bool
True
  StorageFormat
Rules -> Bool
True
  StorageFormat
_     -> Bool
False

-- | Make an include file parser (see rParser) from an IO action which reads the file
-- at the given path and converts it to an unfinalised journal, with lists in reverse order
-- as journalFinalise expects. This is for readers of non-journal formats like CSV.
-- The megaparsec input is ignored; the file path is taken from the parse state's include file stack.
-- The account aliases in effect (from alias directives, then --alias options) are applied to the result,
-- as they would be for inlined journal entries (but not the parent account from apply account directives;
-- see 'accountNameApplyModifiers').
-- Any error, including an IO error, is rethrown as a final parse error showing the include file stack.
includeFileParser :: MonadIO m => (FilePath -> ExceptT String IO ParsedJournal) -> ErroringJournalParser m ParsedJournal
includeFileParser :: forall (m :: * -> *).
MonadIO m =>
(String -> ExceptT String IO Journal)
-> ErroringJournalParser m Journal
includeFileParser String -> ExceptT String IO Journal
readfn = do
  j <- StateT
  Journal
  (ParsecT
     HledgerParseErrorData CommoditySymbol (ExceptT FinalParseError m))
  Journal
forall s (m :: * -> *). MonadState s m => m s
get
  f <- maybe (finalMessageFailure "includeFileParser: no include file in parse state") (pure . fst) $
       listToMaybe $ jparseincludefilestack j
  ej <- liftIO $ tryIO $ runExceptT $ readfn f >>= liftEither . journalApplyAliases (jparsealiases j ++ jparseoptaliases j)
  either (finalMessageFailure . show) (either finalMessageFailure pure) ej

-- | A file path optionally prefixed by a reader name and colon (journal:, csv:, timedot:, etc.).
-- The file path part can also be - meaning standard input.
type PrefixedFilePath = FilePath

-- | Is this the special file path meaning standard input ? (-, possibly prefixed)
isStdin :: PrefixedFilePath -> Bool
isStdin :: String -> Bool
isStdin String
f = case Char -> String -> [String]
forall a. Eq a => a -> [a] -> [[a]]
splitAtElement Char
':' String
f of
  [String
_,String
"-"] -> Bool
True
  [String
"-"] -> Bool
True
  [String]
_ -> Bool
False

-- | Parse an InputOpts from a RawOpts and a provided date.
-- This will fail with a usage error if the forecast period expression cannot be parsed.
rawOptsToInputOpts :: Day -> Bool -> RawOpts -> InputOpts
rawOptsToInputOpts :: Day -> Bool -> RawOpts -> InputOpts
rawOptsToInputOpts Day
day Bool
usecoloronstdout RawOpts
rawopts =

    let
        -- Allow/disallow implicit-cost conversion transactions, according to policy in Check.md.
        -- Disallow them if we see the --strict flag, or if we see a "balanced" argument with the "check" command,
        -- which we assume means the user is running "hledger check balanced".
        -- XXX #2377 The check was originally named "balancednoautoconversion",
        -- but later it was renamed, so this is no longer good; any command with "balanced"
        -- as an argument will also enable this check, normally enabled only in strict mode.
        noinferbalancingcosts :: Bool
noinferbalancingcosts =  -- keep synced with Check.*
             String -> RawOpts -> Bool
boolopt String
"strict" RawOpts
rawopts 
          Bool -> Bool -> Bool
|| (String -> RawOpts -> String
stringopt String
"args" RawOpts
rawopts String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
"balanced" Bool -> Bool -> Bool
&& String -> RawOpts -> String
stringopt String
"command" RawOpts
rawopts String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
"check")

        -- Do we really need to do all this work just to get the requested end date? This is duplicating
        -- much of reportOptsToSpec.
        ropts :: ReportOpts
ropts = Day -> Bool -> RawOpts -> ReportOpts
rawOptsToReportOpts Day
day Bool
usecoloronstdout RawOpts
rawopts
        argsquery :: [Query]
argsquery = ((Query, [QueryOpt]) -> Query) -> [(Query, [QueryOpt])] -> [Query]
forall a b. (a -> b) -> [a] -> [b]
map (Query, [QueryOpt]) -> Query
forall a b. (a, b) -> a
fst ([(Query, [QueryOpt])] -> [Query])
-> ([CommoditySymbol] -> [(Query, [QueryOpt])])
-> [CommoditySymbol]
-> [Query]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Either String (Query, [QueryOpt])] -> [(Query, [QueryOpt])]
forall a b. [Either a b] -> [b]
rights ([Either String (Query, [QueryOpt])] -> [(Query, [QueryOpt])])
-> ([CommoditySymbol] -> [Either String (Query, [QueryOpt])])
-> [CommoditySymbol]
-> [(Query, [QueryOpt])]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (CommoditySymbol -> Either String (Query, [QueryOpt]))
-> [CommoditySymbol] -> [Either String (Query, [QueryOpt])]
forall a b. (a -> b) -> [a] -> [b]
map (Day -> CommoditySymbol -> Either String (Query, [QueryOpt])
parseQueryTerm Day
day) ([CommoditySymbol] -> [Query]) -> [CommoditySymbol] -> [Query]
forall a b. (a -> b) -> a -> b
$ ReportOpts -> [CommoditySymbol]
querystring_ ReportOpts
ropts
        datequery :: Query
datequery = Query -> Query
simplifyQuery (Query -> Query) -> ([Query] -> Query) -> [Query] -> Query
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Query -> Bool) -> Query -> Query
filterQuery Query -> Bool
queryIsDate (Query -> Query) -> ([Query] -> Query) -> [Query] -> Query
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Query] -> Query
And ([Query] -> Query) -> [Query] -> Query
forall a b. (a -> b) -> a -> b
$ ReportOpts -> Query
queryFromFlags ReportOpts
ropts Query -> [Query] -> [Query]
forall a. a -> [a] -> [a]
: [Query]
argsquery

        txnbalancingprecision :: TransactionBalancingPrecision
txnbalancingprecision = (String -> TransactionBalancingPrecision)
-> (TransactionBalancingPrecision -> TransactionBalancingPrecision)
-> Either String TransactionBalancingPrecision
-> TransactionBalancingPrecision
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either String -> TransactionBalancingPrecision
forall {b}. String -> b
err TransactionBalancingPrecision -> TransactionBalancingPrecision
forall a. a -> a
id (Either String TransactionBalancingPrecision
 -> TransactionBalancingPrecision)
-> Either String TransactionBalancingPrecision
-> TransactionBalancingPrecision
forall a b. (a -> b) -> a -> b
$ RawOpts -> Either String TransactionBalancingPrecision
transactionBalancingPrecisionFromOpts RawOpts
rawopts
          where err :: String -> b
err String
e = String -> b
forall {b}. String -> b
error' (String -> b) -> String -> b
forall a b. (a -> b) -> a -> b
$ String
"could not parse --txn-tolerance: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
e  -- PARTIAL:

        styles :: Map CommoditySymbol AmountStyle
styles = (String -> Map CommoditySymbol AmountStyle)
-> (Map CommoditySymbol AmountStyle
    -> Map CommoditySymbol AmountStyle)
-> Either String (Map CommoditySymbol AmountStyle)
-> Map CommoditySymbol AmountStyle
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either String -> Map CommoditySymbol AmountStyle
forall {b}. String -> b
err Map CommoditySymbol AmountStyle -> Map CommoditySymbol AmountStyle
forall a. a -> a
id (Either String (Map CommoditySymbol AmountStyle)
 -> Map CommoditySymbol AmountStyle)
-> Either String (Map CommoditySymbol AmountStyle)
-> Map CommoditySymbol AmountStyle
forall a b. (a -> b) -> a -> b
$ RawOpts -> Either String (Map CommoditySymbol AmountStyle)
commodityStyleFromRawOpts RawOpts
rawopts
          where err :: String -> b
err String
e = String -> b
forall {b}. String -> b
error' (String -> b) -> String -> b
forall a b. (a -> b) -> a -> b
$ String
"could not parse --commodity-style: '" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
e String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"'"  -- PARTIAL:

    in InputOpts
definputopts{
       -- files_             = listofstringopt "file" rawopts
       mformat_           = Nothing
      ,mrules_file_       = maybestringopt "rules" rawopts
      ,aliases_           = listofstringopt "alias" rawopts
      ,anon_              = boolopt "obfuscate" rawopts
      ,new_               = boolopt "new" rawopts
      ,new_save_          = True
      ,pivot_             = stringopt "pivot" rawopts
      ,forecast_          = forecastPeriodFromRawOpts day rawopts
      ,verbose_tags_      = boolopt "verbose-tags" rawopts
      ,reportspan_        = DateSpan (Exact <$> queryStartDate False datequery) (Exact <$> queryEndDate False datequery)
      ,auto_              = boolopt "auto" rawopts
      ,infer_equity_      = boolopt "infer-equity" rawopts && conversionop_ ropts /= Just ToCost
      ,infer_costs_       = boolopt "infer-costs" rawopts
      ,ignore_lots_       = boolopt "ignore-lots" rawopts
      ,balancingopts_     = defbalancingopts{
                                 ignore_assertions_     = boolopt "ignore-assertions" rawopts
                               , infer_balancing_costs_ = not noinferbalancingcosts
                               , txn_balancing_         = txnbalancingprecision
                               , infer_imbalance_       = boolopt "infer-imbalance" rawopts
                               , commodity_styles_      = Just styles
                               }
      ,strict_            = boolopt "strict" rawopts
      ,_ioDay             = day
      ,_oldtimeclock      = boolopt "oldtimeclock" rawopts
      }

handleReadFnToTextReadFn :: (InputOpts -> FilePath -> Text -> ExceptT String IO Journal) -> InputOpts -> FilePath -> Handle -> ExceptT String IO Journal
handleReadFnToTextReadFn :: (InputOpts
 -> String -> CommoditySymbol -> ExceptT String IO Journal)
-> InputOpts -> String -> Handle -> ExceptT String IO Journal
handleReadFnToTextReadFn InputOpts -> String -> CommoditySymbol -> ExceptT String IO Journal
p InputOpts
iopts String
fp =
  InputOpts -> String -> CommoditySymbol -> ExceptT String IO Journal
p InputOpts
iopts String
fp (CommoditySymbol -> ExceptT String IO Journal)
-> (Handle -> ExceptT String IO CommoditySymbol)
-> Handle
-> ExceptT String IO Journal
forall (m :: * -> *) b c a.
Monad m =>
(b -> m c) -> (a -> m b) -> a -> m c
<=< Int
-> String -> CommoditySymbol -> ExceptT String IO CommoditySymbol
forall (m :: * -> *) a.
(MonadIO m, NFData a) =>
Int -> String -> a -> m a
dbgTimeIO Int
1 (String
"read " String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String -> String
takeFileName String
fp) (CommoditySymbol -> ExceptT String IO CommoditySymbol)
-> (Handle -> ExceptT String IO CommoditySymbol)
-> Handle
-> ExceptT String IO CommoditySymbol
forall (m :: * -> *) b c a.
Monad m =>
(b -> m c) -> (a -> m b) -> a -> m c
<=< IO CommoditySymbol -> ExceptT String IO CommoditySymbol
forall (m :: * -> *) a. Monad m => m a -> ExceptT String m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (IO CommoditySymbol -> ExceptT String IO CommoditySymbol)
-> (Handle -> IO CommoditySymbol)
-> Handle
-> ExceptT String IO CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Maybe DynEncoding -> Handle -> IO CommoditySymbol
hGetContentsPortably Maybe DynEncoding
forall a. Maybe a
Nothing

-- | Get the date span from --forecast's PERIODEXPR argument, if any.
-- This will fail with a usage error if the period expression cannot be parsed,
-- or if it contains a report interval.
forecastPeriodFromRawOpts :: Day -> RawOpts -> Maybe DateSpan
forecastPeriodFromRawOpts :: Day -> RawOpts -> Maybe DateSpan
forecastPeriodFromRawOpts Day
d RawOpts
rawopts = do
    arg <- String -> RawOpts -> Maybe String
maybestringopt String
"forecast" RawOpts
rawopts
    let period = Day
-> CommoditySymbol
-> Either HledgerParseErrors (Interval, DateSpan)
parsePeriodExpr Day
d (CommoditySymbol -> Either HledgerParseErrors (Interval, DateSpan))
-> (CommoditySymbol -> CommoditySymbol)
-> CommoditySymbol
-> Either HledgerParseErrors (Interval, DateSpan)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CommoditySymbol -> CommoditySymbol
textStripQuotes (CommoditySymbol -> Either HledgerParseErrors (Interval, DateSpan))
-> CommoditySymbol
-> Either HledgerParseErrors (Interval, DateSpan)
forall a b. (a -> b) -> a -> b
$ String -> CommoditySymbol
T.pack String
arg
    return $ if null arg then nulldatespan else either badParse (getSpan arg) period
  where
    badParse :: HledgerParseErrors -> b
badParse HledgerParseErrors
e = String -> b
forall {b}. String -> b
usageError (String -> b) -> String -> b
forall a b. (a -> b) -> a -> b
$ String
"could not parse forecast period: "String -> String -> String
forall a. [a] -> [a] -> [a]
++HledgerParseErrors -> String
customErrorBundlePretty HledgerParseErrors
e
    getSpan :: String -> (Interval, b) -> b
getSpan String
arg (Interval
interval, b
requestedspan) = case Interval
interval of
        Interval
NoInterval -> b
requestedspan
        Interval
_          -> String -> b
forall {b}. String -> b
usageError (String -> b) -> String -> b
forall a b. (a -> b) -> a -> b
$ String
"--forecast's argument should not contain a report interval ("
                                 String -> String -> String
forall a. [a] -> [a] -> [a]
++ Interval -> String
forall a. Show a => a -> String
show Interval
interval String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" in \"" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
arg String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\")"

-- | Given the raw options, return either
-- * if all options were successfully parsed: a map of successfully parsed commodity styles,
-- * if one or more options failed to parse: the first option which failed to parse
commodityStyleFromRawOpts :: RawOpts -> Either String (M.Map CommoditySymbol AmountStyle)
commodityStyleFromRawOpts :: RawOpts -> Either String (Map CommoditySymbol AmountStyle)
commodityStyleFromRawOpts RawOpts
rawOpts =
  (Map CommoditySymbol AmountStyle
 -> String -> Either String (Map CommoditySymbol AmountStyle))
-> Map CommoditySymbol AmountStyle
-> [String]
-> Either String (Map CommoditySymbol AmountStyle)
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM (\Map CommoditySymbol AmountStyle
r -> ((CommoditySymbol, AmountStyle) -> Map CommoditySymbol AmountStyle)
-> Either String (CommoditySymbol, AmountStyle)
-> Either String (Map CommoditySymbol AmountStyle)
forall a b. (a -> b) -> Either String a -> Either String b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\(CommoditySymbol
c,AmountStyle
a) -> CommoditySymbol
-> AmountStyle
-> Map CommoditySymbol AmountStyle
-> Map CommoditySymbol AmountStyle
forall k a. Ord k => k -> a -> Map k a -> Map k a
M.insert CommoditySymbol
c AmountStyle
a Map CommoditySymbol AmountStyle
r) (Either String (CommoditySymbol, AmountStyle)
 -> Either String (Map CommoditySymbol AmountStyle))
-> (String -> Either String (CommoditySymbol, AmountStyle))
-> String
-> Either String (Map CommoditySymbol AmountStyle)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Either String (CommoditySymbol, AmountStyle)
parseCommodity) Map CommoditySymbol AmountStyle
forall a. Monoid a => a
mempty [String]
optList
  where
    optList :: [String]
optList = String -> RawOpts -> [String]
listofstringopt String
"commodity-style" RawOpts
rawOpts
    parseCommodity :: String -> Either String (CommoditySymbol, AmountStyle)
parseCommodity String
optStr = case String -> Either HledgerParseErrors Amount
parseamount String
optStr of
      Left HledgerParseErrors
_ -> String -> Either String (CommoditySymbol, AmountStyle)
forall a b. a -> Either a b
Left String
optStr
      Right (Amount CommoditySymbol
acommodity Quantity
_ AmountStyle
astyle Maybe AmountCost
_ Maybe CostBasis
_) -> (CommoditySymbol, AmountStyle)
-> Either String (CommoditySymbol, AmountStyle)
forall a b. b -> Either a b
Right (CommoditySymbol
acommodity, AmountStyle
astyle)

-- | Get the --txn-tolerance option's value.
-- (The deprecated --txn-balancing flag sets this too; see hiddenflagsformainmode.)
transactionBalancingPrecisionFromOpts :: RawOpts -> Either String TransactionBalancingPrecision
transactionBalancingPrecisionFromOpts :: RawOpts -> Either String TransactionBalancingPrecision
transactionBalancingPrecisionFromOpts RawOpts
rawopts =
  case String -> RawOpts -> Maybe String
maybestringopt String
"txn-tolerance" RawOpts
rawopts of
    Maybe String
Nothing        -> TransactionBalancingPrecision
-> Either String TransactionBalancingPrecision
forall a b. b -> Either a b
Right TransactionBalancingPrecision
TBPEntry
    Just String
"entry"   -> TransactionBalancingPrecision
-> Either String TransactionBalancingPrecision
forall a b. b -> Either a b
Right TransactionBalancingPrecision
TBPEntry
    Just String
"display" -> TransactionBalancingPrecision
-> Either String TransactionBalancingPrecision
forall a b. b -> Either a b
Right TransactionBalancingPrecision
TBPDisplay
    Just String
s         -> String -> Either String TransactionBalancingPrecision
forall a b. a -> Either a b
Left (String -> Either String TransactionBalancingPrecision)
-> String -> Either String TransactionBalancingPrecision
forall a b. (a -> b) -> a -> b
$ String
"'"String -> String -> String
forall a. Semigroup a => a -> a -> a
<>String
sString -> String -> String
forall a. Semigroup a => a -> a -> a
<>String
"', should be one of: entry, display"

-- | Given a parser to ParsedJournal, input options, file path and
-- content: run the parser on the content, and finalise the result to
-- get a Journal; or throw an error.
parseAndFinaliseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts
                           -> FilePath -> Text -> ExceptT String IO Journal
parseAndFinaliseJournal :: ErroringJournalParser IO Journal
-> InputOpts
-> String
-> CommoditySymbol
-> ExceptT String IO Journal
parseAndFinaliseJournal ErroringJournalParser IO Journal
parser InputOpts
iopts String
f CommoditySymbol
txt =
    ErroringJournalParser IO Journal
-> InputOpts
-> String
-> CommoditySymbol
-> ExceptT String IO Journal
initialiseAndParseJournal ErroringJournalParser IO Journal
parser InputOpts
iopts String
f CommoditySymbol
txt ExceptT String IO Journal
-> (Journal -> ExceptT String IO Journal)
-> ExceptT String IO Journal
forall a b.
ExceptT String IO a
-> (a -> ExceptT String IO b) -> ExceptT String IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= InputOpts
-> String
-> CommoditySymbol
-> Journal
-> ExceptT String IO Journal
journalFinalise InputOpts
iopts String
f CommoditySymbol
txt

-- | Given a parser to ParsedJournal, input options, file path and
-- content: run the parser on the content. This is all steps of
-- 'parseAndFinaliseJournal' without the finalisation step, and is used when
-- you need to perform other actions before finalisatison, as in parsing
-- Timeclock and Timedot files.
initialiseAndParseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts
                          -> FilePath -> Text -> ExceptT String IO Journal
initialiseAndParseJournal :: ErroringJournalParser IO Journal
-> InputOpts
-> String
-> CommoditySymbol
-> ExceptT String IO Journal
initialiseAndParseJournal ErroringJournalParser IO Journal
parser InputOpts
iopts String
f CommoditySymbol
txt = do
    cf <- IO String -> ExceptT String IO String
forall a. IO a -> ExceptT String IO a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String -> ExceptT String IO String)
-> IO String -> ExceptT String IO String
forall a b. (a -> b) -> a -> b
$ String -> IO String
canonicalizePath String
f
    prettyParseErrors (runParserT (evalStateT parser (initJournal cf)) f txt)
      >>= dbgTimeIO 1 ("parse " <> takeFileName f)
      >>= \Journal
j -> Journal
j Journal -> ExceptT String IO () -> ExceptT String IO Journal
forall a b. a -> ExceptT String IO b -> ExceptT String IO a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ FastPathStats -> ExceptT String IO ()
forall (m :: * -> *). MonadIO m => FastPathStats -> m ()
dbgFastPathStats (Journal -> FastPathStats
jparsefastpathstats Journal
j)
  where
    y :: Integer
y = (Integer, Int, Int) -> Integer
forall {a} {b} {c}. (a, b, c) -> a
first3 ((Integer, Int, Int) -> Integer)
-> (Day -> (Integer, Int, Int)) -> Day -> Integer
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Day -> (Integer, Int, Int)
toGregorian (Day -> Integer) -> Day -> Integer
forall a b. (a -> b) -> a -> b
$ InputOpts -> Day
_ioDay InputOpts
iopts
    initJournal :: String -> Journal
initJournal String
cf = Journal
nulljournal{jparsedefaultyear = Just y, jparseincludefilestack = [(f, cf)]}
    -- Flatten parse errors and final parse errors, and output each as a pretty String.
    prettyParseErrors :: ExceptT FinalParseError IO (Either (ParseErrorBundle Text HledgerParseErrorData) a)
                      -> ExceptT String IO a
    prettyParseErrors :: forall a.
ExceptT FinalParseError IO (Either HledgerParseErrors a)
-> ExceptT String IO a
prettyParseErrors = (HledgerParseErrors -> String)
-> ExceptT HledgerParseErrors IO a -> ExceptT String IO a
forall (m :: * -> *) e e' a.
Functor m =>
(e -> e') -> ExceptT e m a -> ExceptT e' m a
withExceptT HledgerParseErrors -> String
customErrorBundlePretty (ExceptT HledgerParseErrors IO a -> ExceptT String IO a)
-> (Either HledgerParseErrors a -> ExceptT HledgerParseErrors IO a)
-> Either HledgerParseErrors a
-> ExceptT String IO a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Either HledgerParseErrors a -> ExceptT HledgerParseErrors IO a
forall e (m :: * -> *) a. MonadError e m => Either e a -> m a
liftEither
                    (Either HledgerParseErrors a -> ExceptT String IO a)
-> (ExceptT FinalParseError IO (Either HledgerParseErrors a)
    -> ExceptT String IO (Either HledgerParseErrors a))
-> ExceptT FinalParseError IO (Either HledgerParseErrors a)
-> ExceptT String IO a
forall (m :: * -> *) b c a.
Monad m =>
(b -> m c) -> (a -> m b) -> a -> m c
<=< (FinalParseError -> String)
-> ExceptT FinalParseError IO (Either HledgerParseErrors a)
-> ExceptT String IO (Either HledgerParseErrors a)
forall (m :: * -> *) e e' a.
Functor m =>
(e -> e') -> ExceptT e m a -> ExceptT e' m a
withExceptT (FinalParseErrorBundle' HledgerParseErrorData -> String
finalErrorBundlePretty (FinalParseErrorBundle' HledgerParseErrorData -> String)
-> (FinalParseError
    -> FinalParseErrorBundle' HledgerParseErrorData)
-> FinalParseError
-> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String
-> CommoditySymbol
-> FinalParseError
-> FinalParseErrorBundle' HledgerParseErrorData
forall e.
String
-> CommoditySymbol
-> FinalParseError' e
-> FinalParseErrorBundle' e
attachSource String
f CommoditySymbol
txt)

-- | With --debug, report what share of a parsed file's entries (including its included files')
-- the journal parser's fast path accepted, and why it declined the others; see the fast path
-- section of Hledger.Read.JournalReader. Nothing is reported for files with no such entries.
dbgFastPathStats :: MonadIO m => FastPathStats -> m ()
dbgFastPathStats :: forall (m :: * -> *). MonadIO m => FastPathStats -> m ()
dbgFastPathStats FastPathStats{Int
Map CommoditySymbol Int
fpsTxnsFast :: Int
fpsTxnsGeneral :: Int
fpsPricesFast :: Int
fpsPricesGeneral :: Int
fpsDeclines :: Map CommoditySymbol Int
fpsDeclines :: FastPathStats -> Map CommoditySymbol Int
fpsPricesGeneral :: FastPathStats -> Int
fpsPricesFast :: FastPathStats -> Int
fpsTxnsGeneral :: FastPathStats -> Int
fpsTxnsFast :: FastPathStats -> Int
..}
  | Int
debugLevel Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
1 Bool -> Bool -> Bool
|| [String] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [String]
shares = () -> m ()
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
  | Bool
otherwise = Int -> String -> m ()
forall (m :: * -> *). MonadIO m => Int -> String -> m ()
dbgMsgIO Int
1 (String -> m ()) -> String -> m ()
forall a b. (a -> b) -> a -> b
$ String
"fast path was used for " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
", " [String]
shares String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
declined
  where
    shares :: [String]
shares = [Int -> Int -> String -> String
forall {a}. (Show a, Integral a) => a -> a -> String -> String
share Int
fpsTxnsFast   Int
fpsTxnsGeneral   String
"transactions" | Int
fpsTxnsFast   Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
fpsTxnsGeneral   Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0]
          [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [Int -> Int -> String -> String
forall {a}. (Show a, Integral a) => a -> a -> String -> String
share Int
fpsPricesFast Int
fpsPricesGeneral String
"prices"       | Int
fpsPricesFast Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
fpsPricesGeneral Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0]
    -- eg "51% of 900 transactions" (the percentage rounded)
    share :: a -> a -> String -> String
share a
fast a
general String
what = a -> String
forall a. Show a => a -> String
show ((a
200 a -> a -> a
forall a. Num a => a -> a -> a
* a
fast a -> a -> a
forall a. Num a => a -> a -> a
+ a
total) a -> a -> a
forall a. Integral a => a -> a -> a
`div` (a
2 a -> a -> a
forall a. Num a => a -> a -> a
* a
total)) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"% of " String -> String -> String
forall a. [a] -> [a] -> [a]
++ a -> String
forall a. Show a => a -> String
show a
total String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
what
      where total :: a
total = a
fast a -> a -> a
forall a. Num a => a -> a -> a
+ a
general
    declined :: String
declined
      | Map CommoditySymbol Int -> Bool
forall k a. Map k a -> Bool
M.null Map CommoditySymbol Int
fpsDeclines = String
""
      | Bool
otherwise = String
"; declined: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
", "
          [Int -> String
forall a. Show a => a -> String
show Int
n String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack CommoditySymbol
reason | (CommoditySymbol
reason, Int
n) <- ((CommoditySymbol, Int) -> Int)
-> [(CommoditySymbol, Int)] -> [(CommoditySymbol, Int)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (Int -> Int
forall a. Num a => a -> a
negate (Int -> Int)
-> ((CommoditySymbol, Int) -> Int) -> (CommoditySymbol, Int) -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (CommoditySymbol, Int) -> Int
forall a b. (a, b) -> b
snd) ([(CommoditySymbol, Int)] -> [(CommoditySymbol, Int)])
-> [(CommoditySymbol, Int)] -> [(CommoditySymbol, Int)]
forall a b. (a -> b) -> a -> b
$ Map CommoditySymbol Int -> [(CommoditySymbol, Int)]
forall k a. Map k a -> [(k, a)]
M.toList Map CommoditySymbol Int
fpsDeclines]

{- HLINT ignore journalFinalise "Redundant <&>" -} -- silence this warning, the code is clearer as is
--  note this activates TH, may slow compilation ? https://github.com/ndmitchell/hlint/blob/master/README.md#customizing-the-hints
--
-- | Post-process a parsed Journal: infer missing information, check validity,
-- and enrich postings with computed metadata.
-- See doc\/SPEC-finalising.md for the full pipeline specification.
maxExpectedForecastTxns :: Int
maxExpectedForecastTxns :: Int
maxExpectedForecastTxns = Int
100000

journalFinalise :: InputOpts -> FilePath -> Text -> ParsedJournal -> ExceptT String IO Journal
journalFinalise :: InputOpts
-> String
-> CommoditySymbol
-> Journal
-> ExceptT String IO Journal
journalFinalise InputOpts{_scanfiles :: InputOpts -> Bool
_scanfiles=Bool
True} String
f CommoditySymbol
txt Journal
pj =
  -- just finding the files read: record the main file's info, put lists in parse order, and stop
  Journal -> ExceptT String IO Journal
forall a. a -> ExceptT String IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Journal -> ExceptT String IO Journal)
-> Journal -> ExceptT String IO Journal
forall a b. (a -> b) -> a -> b
$ Journal
pj Journal -> (Journal -> Journal) -> Journal
forall a b. a -> (a -> b) -> b
& JournalFile -> Journal -> Journal
journalAddFile (String -> CommoditySymbol -> Int -> JournalFile
JournalFile String
f CommoditySymbol
txt Int
0) Journal -> (Journal -> Journal) -> Journal
forall a b. a -> (a -> b) -> b
& Journal -> Journal
journalReverse
journalFinalise iopts :: InputOpts
iopts@InputOpts{Bool
auto_ :: InputOpts -> Bool
auto_ :: Bool
auto_,BalancingOpts
balancingopts_ :: InputOpts -> BalancingOpts
balancingopts_ :: BalancingOpts
balancingopts_,Bool
ignore_lots_ :: InputOpts -> Bool
ignore_lots_ :: Bool
ignore_lots_,Bool
infer_costs_ :: InputOpts -> Bool
infer_costs_ :: Bool
infer_costs_,Bool
infer_equity_ :: InputOpts -> Bool
infer_equity_ :: Bool
infer_equity_,Bool
strict_ :: InputOpts -> Bool
strict_ :: Bool
strict_,Bool
verbose_tags_ :: InputOpts -> Bool
verbose_tags_ :: Bool
verbose_tags_,Day
_ioDay :: InputOpts -> Day
_ioDay :: Day
_ioDay} String
f CommoditySymbol
txt Journal
pj = do
  let
    BalancingOpts{Maybe (Map CommoditySymbol AmountStyle)
commodity_styles_ :: BalancingOpts -> Maybe (Map CommoditySymbol AmountStyle)
commodity_styles_ :: Maybe (Map CommoditySymbol AmountStyle)
commodity_styles_, Bool
ignore_assertions_ :: BalancingOpts -> Bool
ignore_assertions_ :: Bool
ignore_assertions_} = BalancingOpts
balancingopts_
    -- Hack: peek at the command line to know if certain checks were requested.
    checking :: String -> Bool
checking String
checkname = String
"check" String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [String]
args Bool -> Bool -> Bool
&& String
checkname String -> [String] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [String]
args where args :: [String]
args = [String]
progArgs
    checkordereddates :: Bool
checkordereddates = String -> Bool
checking String
"ordereddates"
    checkassertions :: Bool
checkassertions = Bool -> Bool
not Bool
ignore_assertions_ Bool -> Bool -> Bool
|| Bool
strict_ Bool -> Bool -> Bool
|| String -> Bool
checking String
"assertions"
    lotschecking :: Bool
lotschecking    = Bool -> Bool
not Bool
ignore_lots_       Bool -> Bool -> Bool
|| Bool
strict_ Bool -> Bool -> Bool
|| String -> Bool
checking String
"lots"  -- are lot checks wanted ?
    lenientlots :: Bool
lenientlots     = Bool -> Bool
not Bool
lotschecking
    haslots :: Bool
haslots         = Journal -> Bool
journalHasLotFeatures Journal
pj  -- does the journal use lots at all ? if not, the lot stages are skipped, they would do nothing
    checklots :: Bool
checklots       = Bool
haslots Bool -> Bool -> Bool
&& Bool
lotschecking   -- run the lot classification, calculation and checking stages ?
    -- With --debug, report each stage's run time and memory allocation (dbgTime forces the stage's result to measure it).
    timed :: String -> (a -> c) -> a -> c
timed  String
name a -> c
stage = Int -> String -> c -> c
forall a. NFData a => Int -> String -> a -> a
dbgTime Int
1 String
name (c -> c) -> (a -> c) -> a -> c
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> c
stage          -- a stage returning a Journal
    timedE :: String -> (a -> f b) -> a -> f b
timedE String
name a -> f b
stage = (b -> b) -> f b -> f b
forall a b. (a -> b) -> f a -> f b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Int -> String -> b -> b
forall a. NFData a => Int -> String -> a -> a
dbgTime Int
1 String
name) (f b -> f b) -> (a -> f b) -> a -> f b
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> f b
stage   -- a stage returning an Either error Journal

  t <- IO POSIXTime -> ExceptT String IO POSIXTime
forall a. IO a -> ExceptT String IO a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO IO POSIXTime
getPOSIXTime
  -- Warn before generating an implausible number of forecast transactions
  -- (in practice, a mistyped date in a periodic rule or --forecast period), so the user can cancel (#1683).
  -- They are counted without being generated, in constant memory.
  forM_ (forecastPeriod iopts pj) $ \DateSpan
forecastspan -> do
    let n :: Int
n = [Int] -> Int
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [ [Day] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([Day] -> Int) -> [Day] -> Int
forall a b. (a -> b) -> a -> b
$ PeriodicTransaction -> DateSpan -> [Day]
periodicTransactionDates PeriodicTransaction
pt DateSpan
forecastspan | PeriodicTransaction
pt <- Journal -> [PeriodicTransaction]
jperiodictxns Journal
pj ]
    Bool -> ExceptT String IO () -> ExceptT String IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
maxExpectedForecastTxns) (ExceptT String IO () -> ExceptT String IO ())
-> ExceptT String IO () -> ExceptT String IO ()
forall a b. (a -> b) -> a -> b
$ String -> ExceptT String IO ()
forall (m :: * -> *). MonadIO m => String -> m ()
warnIO (String -> ExceptT String IO ()) -> String -> ExceptT String IO ()
forall a b. (a -> b) -> a -> b
$ String -> Int -> CommoditySymbol -> String
forall r. PrintfType r => String -> r
printf
      (String
"--forecast would generate %d transactions (forecast period %s),\n"
      String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
"using a lot of memory. If not intended, press control-C now, and check for a mistyped date.")
      Int
n (DateSpan -> CommoditySymbol
showDateSpan DateSpan
forecastspan)
  j <- liftEither $
    pj{jglobalcommoditystyles=fromMaybe mempty commodity_styles_}

      -- Setup
      &   timed  "journalSetLastReadTime" (journalSetLastReadTime t)              -- save the last read time
      &   timed  "journalAddFile" (journalAddFile (JournalFile f txt 0))                    -- save the main file's info
      &   timed  "journalReverse" journalReverse                                  -- convert all lists to the order they were parsed

      -- Account types and amount styles
      &   timed  "journalAddAccountTypes" journalAddAccountTypes                  -- build a map of all known account types
            -- XXX does not see conversion accounts generated by journalInferEquityFromCosts below, requiring a workaround in journalCheckAccounts. Do it later ?
      &   timedE "journalStyleAmounts" journalStyleAmounts                        -- infer and apply commodity styles (but don't round) - should be done early
      >>= timedE "journalApplyCommodityAliases" journalApplyCommodityAliases      -- convert amounts in commodity aliases to their commodity

      -- Forecast and account tags
      <&> timed  "journalAddForecast" (journalAddForecast verbose_tags_ (forecastPeriod iopts pj))  -- add forecast transactions if enabled
      <&> timed  "journalPostingsAddAccountTags" journalPostingsAddAccountTags    -- propagate account tags to postings (queryable but hidden)

      -- Pre-balancing cost/equity tagging
      >>= timedE "journalTagCostsAndEquityAndMaybeInferCosts" (journalTagCostsAndEquityAndMaybeInferCosts verbose_tags_ False)  -- tag equity conversion postings and redundant costs, to help the transaction balancer ignore them

      -- Lot cost basis and transacted cost inference, and gain posting tagging
      -- These enrichment stages always run, so lot entries balance the same
      -- with or without --ignore-lots; with --ignore-lots (unless overridden
      -- by --strict or `hledger check lots`) they are lenient, skipping their
      -- errors and leaving the affected postings/transactions unchanged.
      -- They run before auto postings, whose preliminary balancing needs them too.
      >>= (if haslots then timedE "journalInferBasisFromAccountNames" (journalInferBasisFromAccountNames lenientlots) else pure)  -- infer cost basis from lot subaccount names (validating them, unless lenient)
      <&> (if haslots then timed  "journalInferPostingsTransactedCost" journalInferPostingsTransactedCost else id)              -- in acquire-shaped postings, infer a transacted cost from cost basis
      >>= (if checklots then timedE "journalCheckAcquireBasis" journalCheckAcquireBasis else pure)                              -- error if an acquire-shaped posting's written cost basis and transacted cost differ (before balancing, so this is reported rather than an unbalanced entry)
      >>= (if haslots then timedE "journalTagGainPostings" (journalTagGainPostings lenientlots verbose_tags_) else pure)        -- in disposals, tag user-written gain postings so the balancer sets them aside

      -- Auto postings
      >>= (if auto_ && not (null $ jtxnmodifiers pj)
            then timedE "journalAddAutoPostings" $ journalAddAutoPostings verbose_tags_ _ioDay  -- add auto postings if enabled; does preliminary transaction balancing
                  balancingopts_{lotful_commodities_ = journalLotfulCommodities pj
                                ,account_lots_tags_ = journalAccountLotsTags pj
                                ,lenient_lots_ = lenientlots
                                ,verbose_balancing_tags_ = verbose_tags_}
            else pure)

      -- Transaction balancing
      >>= (\Journal
j -> if Bool
checkordereddates then Journal -> Either String ()
journalCheckOrdereddates Journal
j Either String () -> Journal -> Either String Journal
forall (f :: * -> *) a b. Functor f => f a -> b -> f b
$> Journal
j else Journal -> Either String Journal
forall a b. b -> Either a b
Right Journal
j)     -- maybe check that journal entries are in date order
      >>= (\Journal
j -> do
        -- Infer balance assignments/amounts, and maybe check balance assertions.
        -- An assertion failure is not raised immediately: it is deferred until
        -- the stages below have run without error, so lot errors (usually the
        -- more fundamental problem) are reported first.
        (j2, massertionerr) <- String
-> (Journal -> Either String (Journal, Maybe String))
-> Journal
-> Either String (Journal, Maybe String)
forall {f :: * -> *} {b} {a}.
(Functor f, NFData b) =>
String -> (a -> f b) -> a -> f b
timedE String
"journalBalanceTransactionsAndDeferAssertions"
              (BalancingOpts -> Journal -> Either String (Journal, Maybe String)
journalBalanceTransactionsAndDeferAssertions
                BalancingOpts
balancingopts_{ignore_assertions_=not checkassertions, account_types_ = jaccounttypes j
                              ,lotful_commodities_ = journalLotfulCommodities j
                              ,account_lots_tags_ = journalAccountLotsTags j
                              ,lenient_lots_ = lenientlots
                              ,verbose_balancing_tags_ = verbose_tags_
                              ,imbalance_account_ = journalAccountForType defaultImbalanceAccount Imbalance j}) Journal
j
        j3 <- Right j2

          -- Lot classification
          -- Runs after balancing, when all posting amounts are known (inferred
          -- amounts included), so every entry shape classifies the same way as
          -- if its amounts had been written explicitly (#2686, #2690, #2692).
          <&> (if checklots then timed "journalClassifyLotPostings" (journalClassifyLotPostings verbose_tags_) else id)  -- detect and classify lot postings (acquire/dispose/transfer..), maybe with visible tags

          -- Post-balancing enrichment
          >>= timedE "journalInferCommodityStyles" journalInferCommodityStyles          -- infer commodity styles once more now that all posting amounts are present
          <&> timed  "journalPostingsAddCommodityTags" journalPostingsAddCommodityTags  -- propagate amounts' commodity tags to postings (queryable but hidden)

          -- Cost inference
          >>= (if infer_costs_  then timedE "journalTagCostsAndEquityAndMaybeInferCosts" (journalTagCostsAndEquityAndMaybeInferCosts verbose_tags_ True) else pure)  -- maybe infer costs from equity postings

          -- Market prices and renumbering
          <&> timed  "journalInferMarketPricesFromTransactions" journalInferMarketPricesFromTransactions  -- infer market prices from commodity-exchanging transactions
          <&> timed  "journalRenumberAccountDeclarations" journalRenumberAccountDeclarations              -- renumber account declarations for consistent ordering

          -- Lot and capital gains calculation/checking
          -- (skipped by --ignore-lots or -I; forced back on by --strict or `hledger check lots`)
          >>= (if checklots  then timedE "journalCheckLotsTagValues" journalCheckLotsTagValues                       else pure)  -- validate lots: tag values on commodity/account declarations
          >>= (if checklots  then timedE "journalCheckLotsMethodCoherence" journalCheckLotsMethodCoherence           else pure)  -- reject a global (*ALL) method mixed with other methods for one commodity
          >>= (if checklots  then timedE "journalCalculateLots" (journalCalculateLots verbose_tags_)                 else pure)  -- evaluate lot selectors, calculate lot balances, add lot subaccounts
          >>= (if checklots  then timedE "journalAddOrCheckGainPostings" (journalAddOrCheckGainPostings verbose_tags_) else pure)  -- in disposal transactions, add the realised-gain posting, or check a user-written one
          <&> (if haslots    then timed  "journalStripBalancerCopiedBases" journalStripBalancerCopiedBases           else id)    -- remove balancer-copied basis annotations, kept until now as classification evidence

          -- Equity inference
          <&> (if infer_equity_ then timed  "journalInferEquityFromCosts" (journalInferEquityFromCosts verbose_tags_) else id)  -- maybe infer equity postings from costs; after lot processing, so lot disposals convert at cost basis

        -- Now report any balance assertion failure detected above,
        -- then check any assert directives (on the finalised journal, so lot subaccounts are seen).
        maybe (Right j3) Left massertionerr
          >>= (if checkassertions && not (null $ jasserts j3)
                then timedE "journalCheckAsserts" (\Journal
j4 -> InputOpts -> Journal -> Either String ()
journalCheckAssertsWith InputOpts
iopts Journal
j4 Either String () -> Journal -> Either String Journal
forall (f :: * -> *) a b. Functor f => f a -> b -> f b
$> Journal
j4)
                else pure))

  -- The last stage's timing line appears when its result is forced; with --debug, do that now.
  when (debugLevel > 0) $ liftIO $ void $ evaluate j
  return j

-- | Check a finalised journal's assert rules, as journal loading does, with these input options:
-- resolving relative dates with their today's date, and ignoring forecast transactions
-- if they were generated only for display (see '_forecastOnlyForDisplay').
-- Also used by hledger-ui to recheck the rules in memory.
journalCheckAssertsWith :: InputOpts -> Journal -> Either String ()
journalCheckAssertsWith :: InputOpts -> Journal -> Either String ()
journalCheckAssertsWith InputOpts{Bool
_forecastOnlyForDisplay :: InputOpts -> Bool
_forecastOnlyForDisplay :: Bool
_forecastOnlyForDisplay, Day
_ioDay :: InputOpts -> Day
_ioDay :: Day
_ioDay} Journal
j =
  Day -> Journal -> Either String ()
journalCheckAsserts Day
_ioDay (Journal -> Either String ()) -> Journal -> Either String ()
forall a b. (a -> b) -> a -> b
$
    if Bool
_forecastOnlyForDisplay then Journal
j{jtxns = filter (not . isForecast) $ jtxns j} else Journal
j
  where isForecast :: Transaction -> Bool
isForecast = Maybe CommoditySymbol -> Bool
forall a. Maybe a -> Bool
isJust (Maybe CommoditySymbol -> Bool)
-> (Transaction -> Maybe CommoditySymbol) -> Transaction -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CommoditySymbol
-> [(CommoditySymbol, CommoditySymbol)] -> Maybe CommoditySymbol
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup CommoditySymbol
generatedTransactionTagName ([(CommoditySymbol, CommoditySymbol)] -> Maybe CommoditySymbol)
-> (Transaction -> [(CommoditySymbol, CommoditySymbol)])
-> Transaction
-> Maybe CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> [(CommoditySymbol, CommoditySymbol)]
ttags

-- | Apply any auto posting rules to generate extra postings on this journal's transactions.
-- With a true first argument, adds visible tags to generated postings and modified transactions.
journalAddAutoPostings :: Bool -> Day -> BalancingOpts -> Journal -> Either String Journal
journalAddAutoPostings :: Bool -> Day -> BalancingOpts -> Journal -> Either String Journal
journalAddAutoPostings Bool
verbosetags Day
d BalancingOpts
bopts =
    -- Balance all transactions without checking balance assertions,
    BalancingOpts -> Journal -> Either String Journal
journalBalanceTransactions BalancingOpts
bopts{ignore_assertions_=True}
    -- then add the auto postings
    -- (Note adding auto postings after balancing means #893b fails;
    -- adding them before balancing probably means #893a, #928, #938 fail.)
    (Journal -> Either String Journal)
-> (Journal -> Either String Journal)
-> Journal
-> Either String Journal
forall (m :: * -> *) a b c.
Monad m =>
(a -> m b) -> (b -> m c) -> a -> m c
>=> Bool -> Day -> Journal -> Either String Journal
journalModifyTransactions Bool
verbosetags Day
d

-- | Generate periodic transactions from all periodic transaction rules in the journal.
-- These transactions are added to the in-memory Journal (but not the on-disk file).
--
-- The start & end date for generated periodic transactions are determined in
-- a somewhat complicated way; see the hledger manual -> Periodic transactions.
journalAddForecast :: Bool -> Maybe DateSpan -> Journal -> Journal
journalAddForecast :: Bool -> Maybe DateSpan -> Journal -> Journal
journalAddForecast Bool
_ Maybe DateSpan
Nothing Journal
j = Journal
j
journalAddForecast Bool
verbosetags (Just DateSpan
forecastspan) Journal
j = Journal
j{jtxns = jtxns j ++ forecasttxns}
  where
    {-# HLINT ignore "Move concatMap out" #-}
    forecasttxns :: [Transaction]
forecasttxns =
        (Transaction -> Transaction) -> [Transaction] -> [Transaction]
forall a b. (a -> b) -> [a] -> [b]
map (Transaction -> Transaction
txnTieKnot (Transaction -> Transaction)
-> (Transaction -> Transaction) -> Transaction -> Transaction
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Posting -> Posting) -> Transaction -> Transaction
transactionTransformPostings (Map CommoditySymbol AmountStyle -> Posting -> Posting
forall a. HasAmounts a => Map CommoditySymbol AmountStyle -> a -> a
styleAmounts (Map CommoditySymbol AmountStyle -> Posting -> Posting)
-> Map CommoditySymbol AmountStyle -> Posting -> Posting
forall a b. (a -> b) -> a -> b
$ Journal -> Map CommoditySymbol AmountStyle
journalCommodityStyles Journal
j))
      ([Transaction] -> [Transaction])
-> ([PeriodicTransaction] -> [Transaction])
-> [PeriodicTransaction]
-> [Transaction]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Transaction -> Bool) -> [Transaction] -> [Transaction]
forall a. (a -> Bool) -> [a] -> [a]
filter (DateSpan -> Day -> Bool
spanContainsDate DateSpan
forecastspan (Day -> Bool) -> (Transaction -> Day) -> Transaction -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> Day
tdate)
      ([Transaction] -> [Transaction])
-> ([PeriodicTransaction] -> [Transaction])
-> [PeriodicTransaction]
-> [Transaction]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (PeriodicTransaction -> [Transaction])
-> [PeriodicTransaction] -> [Transaction]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (\PeriodicTransaction
pt -> Bool -> PeriodicTransaction -> DateSpan -> [Transaction]
runPeriodicTransaction Bool
verbosetags PeriodicTransaction
pt DateSpan
forecastspan)
      ([PeriodicTransaction] -> [Transaction])
-> [PeriodicTransaction] -> [Transaction]
forall a b. (a -> b) -> a -> b
$ Journal -> [PeriodicTransaction]
jperiodictxns Journal
j

-- | For each posting whose account name contains a lot subaccount (e.g.
-- @assets:broker:{2026-01-15, $50}@), parse the cost basis from the subaccount
-- name and set or merge it into the posting's amounts' @acostbasis@.
-- This allows users to write lot subaccounts explicitly without redundant @{...}@
-- amount annotations.
--
-- With a true first argument (lenient mode, used by --ignore-lots), a posting
-- whose lot subaccount name is invalid or conflicting is left unchanged
-- (treated as an ordinary subaccount) instead of raising an error.
journalInferBasisFromAccountNames :: Bool -> Journal -> Either String Journal
journalInferBasisFromAccountNames :: Bool -> Journal -> Either String Journal
journalInferBasisFromAccountNames Bool
lenient Journal
j = do
  txns' <- (Transaction -> Either String Transaction)
-> [Transaction] -> Either String [Transaction]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM Transaction -> Either String Transaction
processTransaction (Journal -> [Transaction]
jtxns Journal
j)
  Right j{jtxns = txns'}
  where
    parseAmt :: String -> Maybe Amount
parseAmt String
s = case String -> Either HledgerParseErrors Amount
parseamount String
s of
      Right Amount
a  -> Amount -> Maybe Amount
forall a. a -> Maybe a
Just Amount
a
      Left HledgerParseErrors
_   -> Maybe Amount
forall a. Maybe a
Nothing

    processTransaction :: Transaction -> Either String Transaction
processTransaction Transaction
t = do
      ps' <- (Posting -> Either String Posting)
-> [Posting] -> Either String [Posting]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM Posting -> Either String Posting
processPosting (Transaction -> [Posting]
tpostings Transaction
t)
      Right t{tpostings = ps'}

    processPosting :: Posting -> Either String Posting
processPosting Posting
p
      | Bool
lenient   = Posting -> Either String Posting
forall a b. b -> Either a b
Right (Posting -> Either String Posting)
-> Posting -> Either String Posting
forall a b. (a -> b) -> a -> b
$ (String -> Posting)
-> (Posting -> Posting) -> Either String Posting -> Posting
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Posting -> String -> Posting
forall a b. a -> b -> a
const Posting
p) Posting -> Posting
forall a. a -> a
id (Either String Posting -> Posting)
-> Either String Posting -> Posting
forall a b. (a -> b) -> a -> b
$ Posting -> Either String Posting
inferPosting Posting
p
      | Bool
otherwise = Posting -> Either String Posting
inferPosting Posting
p

    inferPosting :: Posting -> Either String Posting
inferPosting Posting
p = case CommoditySymbol -> Maybe CommoditySymbol
lotSubaccountName (Posting -> CommoditySymbol
paccount Posting
p) of
      Maybe CommoditySymbol
Nothing   -> Posting -> Either String Posting
forall a b. b -> Either a b
Right Posting
p
      Just CommoditySymbol
name -> do
        cb <- (String -> String)
-> Either String CostBasis -> Either String CostBasis
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first (Posting -> String -> String
lotErr Posting
p) (Either String CostBasis -> Either String CostBasis)
-> Either String CostBasis -> Either String CostBasis
forall a b. (a -> b) -> a -> b
$ (String -> Maybe Amount)
-> CommoditySymbol -> Either String CostBasis
parseLotName String -> Maybe Amount
parseAmt CommoditySymbol
name
        when (isNothing (cbDate cb) || isNothing (cbCost cb)) $
          Left $ lotErr p $ "lot subaccount name must contain a date and cost: " ++ T.unpack name
        let updateAmt Amount
a = case Amount -> Maybe CostBasis
acostbasis Amount
a of
              Maybe CostBasis
Nothing -> Amount -> Either String Amount
forall a b. b -> Either a b
Right Amount
a{acostbasis = Just cb}
              Just CostBasis
existing -> do
                merged <- (String -> String)
-> Either String CostBasis -> Either String CostBasis
forall a b c. (a -> b) -> Either a c -> Either b c
forall (p :: * -> * -> *) a b c.
Bifunctor p =>
(a -> b) -> p a c -> p b c
first (Posting -> String -> String
lotConflictErr Posting
p) (Either String CostBasis -> Either String CostBasis)
-> Either String CostBasis -> Either String CostBasis
forall a b. (a -> b) -> a -> b
$ CostBasis -> CostBasis -> Either String CostBasis
mergeCostBasis CostBasis
cb CostBasis
existing
                Right a{acostbasis = Just merged}
        amts' <- mapM updateAmt (amountsRaw (pamount p))
        Right p{pamount = foldMap mixedAmount amts'}

    -- Wrap a lot-subaccount parse error with a verbose source-position excerpt
    -- highlighting the posting's account name, and remind the reader that final
    -- @:{...}@ components are reserved for lot subaccount syntax.
    lotErr :: Posting -> String -> String
lotErr Posting
p String
msg = Posting -> String -> String
lotPosErr Posting
p (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ String
msg
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\n\nA final account name part enclosed in { } must be a valid lot subaccount name."
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\nPlease adjust the account name, or use --ignore-lots/-I."

    -- Likewise for a lot subaccount name which disagrees with the amount's lot annotation.
    lotConflictErr :: Posting -> String -> String
lotConflictErr Posting
p String
msg = Posting -> String -> String
lotPosErr Posting
p (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ String
msg
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\n\nThe lot subaccount name and the amount's lot annotation must agree."
      String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\nPlease make them match, or remove one of them."

    lotPosErr :: Posting -> String -> String
    lotPosErr :: Posting -> String -> String
lotPosErr Posting
p String
msg = String -> String -> Int -> CommoditySymbol -> String -> String
forall r. PrintfType r => String -> r
printf String
"%s:%d:\n%s\n%s" String
f Int
line CommoditySymbol
ex String
msg
      where (String
f, Int
line, Maybe (Int, Maybe Int)
_, CommoditySymbol
ex) = Posting -> (String, Int, Maybe (Int, Maybe Int), CommoditySymbol)
makePostingAccountErrorExcerpt Posting
p

setYear :: Year -> JournalParser m ()
setYear :: forall (m :: * -> *). Integer -> JournalParser m ()
setYear Integer
y = (Journal -> Journal)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' (\Journal
j -> Journal
j{jparsedefaultyear=Just y})

getYear :: JournalParser m (Maybe Year)
getYear :: forall (m :: * -> *). JournalParser m (Maybe Integer)
getYear = (Journal -> Maybe Integer)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Journal
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe Integer)
forall a b.
(a -> b)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Journal -> Maybe Integer
jparsedefaultyear StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Journal
forall s (m :: * -> *). MonadState s m => m s
get

dp :: String -> TextParser m ()
dp :: forall (m :: * -> *). String -> TextParser m ()
dp = TextParser m () -> String -> TextParser m ()
forall a b. a -> b -> a
const (TextParser m () -> String -> TextParser m ())
-> TextParser m () -> String -> TextParser m ()
forall a b. (a -> b) -> a -> b
$ () -> TextParser m ()
forall a. a -> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (m :: * -> *) a. Monad m => a -> m a
return ()  -- no-op
-- dp = dbgparse 0  -- trace parse state at this --debug level

-- | Get the decimal mark that has been specified for parsing, if any
-- (eg by the CSV decimal-mark rule, or possibly a future journal directive).
-- Return it as an AmountStyle that amount parsers can use.
getDecimalMarkStyle :: JournalParser m (Maybe AmountStyle)
getDecimalMarkStyle :: forall (m :: * -> *). JournalParser m (Maybe AmountStyle)
getDecimalMarkStyle = Journal -> Maybe AmountStyle
journalDecimalMarkStyle (Journal -> Maybe AmountStyle)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Journal
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe AmountStyle)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Journal
forall s (m :: * -> *). MonadState s m => m s
get

-- | The amount style implied by a decimal-mark directive or CSV rule in effect, if any.
journalDecimalMarkStyle :: Journal -> Maybe AmountStyle
journalDecimalMarkStyle :: Journal -> Maybe AmountStyle
journalDecimalMarkStyle Journal{Maybe Char
jparsedecimalmark :: Maybe Char
jparsedecimalmark :: Journal -> Maybe Char
jparsedecimalmark} = (\Char
c -> AmountStyle
amountstyle{asdecimalmark=Just c}) (Char -> AmountStyle) -> Maybe Char -> Maybe AmountStyle
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe Char
jparsedecimalmark

setDefaultCommodityAndStyle :: (CommoditySymbol,AmountStyle) -> JournalParser m ()
setDefaultCommodityAndStyle :: forall (m :: * -> *).
(CommoditySymbol, AmountStyle) -> JournalParser m ()
setDefaultCommodityAndStyle (CommoditySymbol, AmountStyle)
cs = (Journal -> Journal)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' (\Journal
j -> Journal
j{jparsedefaultcommodity=Just cs})

getDefaultCommodityAndStyle :: JournalParser m (Maybe (CommoditySymbol,AmountStyle))
getDefaultCommodityAndStyle :: forall (m :: * -> *).
JournalParser m (Maybe (CommoditySymbol, AmountStyle))
getDefaultCommodityAndStyle = Journal -> Maybe (CommoditySymbol, AmountStyle)
jparsedefaultcommodity (Journal -> Maybe (CommoditySymbol, AmountStyle))
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Journal
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe (CommoditySymbol, AmountStyle))
forall a b.
(a -> b)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
`fmap` StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Journal
forall s (m :: * -> *). MonadState s m => m s
get

-- | Get amount style associated with default currency.
--
-- Returns 'AmountStyle' used to defined by a latest default commodity directive
-- prior to current position within this file or its parents.
getDefaultAmountStyle :: JournalParser m (Maybe AmountStyle)
getDefaultAmountStyle :: forall (m :: * -> *). JournalParser m (Maybe AmountStyle)
getDefaultAmountStyle = ((CommoditySymbol, AmountStyle) -> AmountStyle)
-> Maybe (CommoditySymbol, AmountStyle) -> Maybe AmountStyle
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (CommoditySymbol, AmountStyle) -> AmountStyle
forall a b. (a, b) -> b
snd (Maybe (CommoditySymbol, AmountStyle) -> Maybe AmountStyle)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe (CommoditySymbol, AmountStyle))
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe AmountStyle)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol m)
  (Maybe (CommoditySymbol, AmountStyle))
forall (m :: * -> *).
JournalParser m (Maybe (CommoditySymbol, AmountStyle))
getDefaultCommodityAndStyle

-- | Get the 'AmountStyle' declared by the most recently parsed (in the current or parent files,
-- prior to the current position) commodity directive for the given commodity, if any.
getAmountStyle :: CommoditySymbol -> JournalParser m (Maybe AmountStyle)
getAmountStyle :: forall (m :: * -> *).
CommoditySymbol -> JournalParser m (Maybe AmountStyle)
getAmountStyle CommoditySymbol
commodity = (Journal -> CommoditySymbol -> Maybe AmountStyle)
-> CommoditySymbol -> Journal -> Maybe AmountStyle
forall a b c. (a -> b -> c) -> b -> a -> c
flip Journal -> CommoditySymbol -> Maybe AmountStyle
journalAmountStyleFor CommoditySymbol
commodity (Journal -> Maybe AmountStyle)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Journal
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe AmountStyle)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Journal
forall s (m :: * -> *). MonadState s m => m s
get

-- | The 'AmountStyle' declared by the most recently parsed commodity directive for the given
-- commodity, or failing that by the most recent default commodity directive, if any.
journalAmountStyleFor :: Journal -> CommoditySymbol -> Maybe AmountStyle
journalAmountStyleFor :: Journal -> CommoditySymbol -> Maybe AmountStyle
journalAmountStyleFor Journal{Map CommoditySymbol Commodity
jdeclaredcommodities :: Map CommoditySymbol Commodity
jdeclaredcommodities :: Journal -> Map CommoditySymbol Commodity
jdeclaredcommodities, Maybe (CommoditySymbol, AmountStyle)
jparsedefaultcommodity :: Journal -> Maybe (CommoditySymbol, AmountStyle)
jparsedefaultcommodity :: Maybe (CommoditySymbol, AmountStyle)
jparsedefaultcommodity} CommoditySymbol
commodity =
  [AmountStyle] -> Maybe AmountStyle
forall a. [a] -> Maybe a
listToMaybe ([AmountStyle] -> Maybe AmountStyle)
-> [AmountStyle] -> Maybe AmountStyle
forall a b. (a -> b) -> a -> b
$ [Maybe AmountStyle] -> [AmountStyle]
forall a. [Maybe a] -> [a]
catMaybes [CommoditySymbol -> Map CommoditySymbol Commodity -> Maybe Commodity
forall k a. Ord k => k -> Map k a -> Maybe a
M.lookup CommoditySymbol
commodity Map CommoditySymbol Commodity
jdeclaredcommodities Maybe Commodity
-> (Commodity -> Maybe AmountStyle) -> Maybe AmountStyle
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Commodity -> Maybe AmountStyle
cformat, (CommoditySymbol, AmountStyle) -> AmountStyle
forall a b. (a, b) -> b
snd ((CommoditySymbol, AmountStyle) -> AmountStyle)
-> Maybe (CommoditySymbol, AmountStyle) -> Maybe AmountStyle
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe (CommoditySymbol, AmountStyle)
jparsedefaultcommodity]

-- | Return an identical amount style parsed earlier, if there is one, so that amounts share it;
-- otherwise remember and return this one. Journals use few distinct styles, so this saves memory.
shareAmountStyle :: AmountStyle -> JournalParser m AmountStyle
shareAmountStyle :: forall (m :: * -> *). AmountStyle -> JournalParser m AmountStyle
shareAmountStyle AmountStyle
s = do
  styles <- Journal -> Set AmountStyle
jparseamountstyles (Journal -> Set AmountStyle)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Journal
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Set AmountStyle)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Journal
forall s (m :: * -> *). MonadState s m => m s
get
  case S.lookupLE s styles of
    Just AmountStyle
s' | AmountStyle
s' AmountStyle -> AmountStyle -> Bool
forall a. Eq a => a -> a -> Bool
== AmountStyle
s -> AmountStyle
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     AmountStyle
forall a.
a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (m :: * -> *) a. Monad m => a -> m a
return AmountStyle
s'
    Maybe AmountStyle
_ -> do
      (Journal -> Journal)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' ((Journal -> Journal)
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ())
-> (Journal -> Journal)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall a b. (a -> b) -> a -> b
$ \Journal
j -> Journal
j{jparseamountstyles = S.insert s styles}
      AmountStyle
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     AmountStyle
forall a.
a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (m :: * -> *) a. Monad m => a -> m a
return AmountStyle
s

-- | Return an identical text parsed earlier (an account name or commodity symbol), if there is one,
-- so that they share one copy; otherwise remember (a compact copy of) this one and return that.
-- Journals use relatively few distinct account names and commodity symbols, so this saves memory.
shareText :: Text -> JournalParser m Text
shareText :: forall (m :: * -> *).
CommoditySymbol -> JournalParser m CommoditySymbol
shareText CommoditySymbol
t = do
  texts <- Journal -> Set CommoditySymbol
jparsetexts (Journal -> Set CommoditySymbol)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Journal
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Set CommoditySymbol)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Journal
forall s (m :: * -> *). MonadState s m => m s
get
  case S.lookupLE t texts of
    Just CommoditySymbol
t' | CommoditySymbol
t' CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
== CommoditySymbol
t -> CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
forall a.
a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (m :: * -> *) a. Monad m => a -> m a
return CommoditySymbol
t'
    Maybe CommoditySymbol
_ -> do
      let t' :: CommoditySymbol
t' = CommoditySymbol -> CommoditySymbol
T.copy CommoditySymbol
t  -- don't retain the whole input text this is a slice of
      (Journal -> Journal)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' ((Journal -> Journal)
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ())
-> (Journal -> Journal)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall a b. (a -> b) -> a -> b
$ \Journal
j -> Journal
j{jparsetexts = S.insert t' texts}
      CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
forall a.
a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (m :: * -> *) a. Monad m => a -> m a
return CommoditySymbol
t'

addDeclaredAccountTags :: AccountName -> [Tag] -> JournalParser m ()
addDeclaredAccountTags :: forall (m :: * -> *).
CommoditySymbol
-> [(CommoditySymbol, CommoditySymbol)] -> JournalParser m ()
addDeclaredAccountTags CommoditySymbol
acct [(CommoditySymbol, CommoditySymbol)]
atags =
  (Journal -> Journal)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' (\Journal
j -> Journal
j{jdeclaredaccounttags = M.insertWith (flip union) acct atags (jdeclaredaccounttags j)})

addDeclaredAccountType :: AccountName -> AccountType -> JournalParser m ()
addDeclaredAccountType :: forall (m :: * -> *).
CommoditySymbol -> AccountType -> JournalParser m ()
addDeclaredAccountType CommoditySymbol
acct AccountType
atype =
  (Journal -> Journal)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' (\Journal
j -> Journal
j{jdeclaredaccounttypes = M.insertWith (++) atype [acct] (jdeclaredaccounttypes j)})

pushParentAccount :: AccountName -> JournalParser m ()
pushParentAccount :: forall (m :: * -> *). CommoditySymbol -> JournalParser m ()
pushParentAccount CommoditySymbol
acct = (Journal -> Journal)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' (\Journal
j -> Journal
j{jparseparentaccounts = acct : jparseparentaccounts j})

getParentAccount :: JournalParser m AccountName
getParentAccount :: forall (m :: * -> *). JournalParser m CommoditySymbol
getParentAccount = (Journal -> CommoditySymbol)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Journal
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
forall a b.
(a -> b)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ([CommoditySymbol] -> CommoditySymbol
concatAccountNames ([CommoditySymbol] -> CommoditySymbol)
-> (Journal -> [CommoditySymbol]) -> Journal -> CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [CommoditySymbol] -> [CommoditySymbol]
forall a. [a] -> [a]
reverse ([CommoditySymbol] -> [CommoditySymbol])
-> (Journal -> [CommoditySymbol]) -> Journal -> [CommoditySymbol]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Journal -> [CommoditySymbol]
jparseparentaccounts) StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Journal
forall s (m :: * -> *). MonadState s m => m s
get

-- | Get the current source position, like megaparsec's getSourcePos but
-- cheaper on large inputs. megaparsec walks every character since the last
-- position it calculated, checking each one's width; this instead starts
-- from the most recently calculated position kept in the parse state (see
-- 'ParsePos'), counts the newlines since then with a fast scan, and walks
-- only the current line, using megaparsec's column rules. The journal
-- parsers should use this rather than getSourcePos. On the first call, or
-- if the parser has somehow moved backwards, it falls back to getSourcePos.
-- (Though, measured in 2026 on a 100k-transaction journal, this saved only
-- about 4% of total run time: the per-character walk is cheap in optimised code,
-- and this still scans the text, just faster.)
getSourcePos' :: JournalParser m SourcePos
getSourcePos' :: forall (m :: * -> *). JournalParser m SourcePos
getSourcePos' = do
  o <- StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
  manchor <- jparsepos <$> get
  pos <- case manchor of
    Just (ParsePos anchor :: SourcePos
anchor@(SourcePos String
f Pos
l Pos
_) Int
o0 CommoditySymbol
s0) | Int
o Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
o0 -> do
      let
        consumed :: CommoditySymbol
consumed = Int -> CommoditySymbol -> CommoditySymbol
T.take (Int
o Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
o0) CommoditySymbol
s0  -- the text between the anchor and here
        newlines :: Int
newlines = HasCallStack => CommoditySymbol -> CommoditySymbol -> Int
CommoditySymbol -> CommoditySymbol -> Int
T.count CommoditySymbol
"\n" CommoditySymbol
consumed
        -- walk the current line only: from the anchor if that is on this line, else from the line's start
        (SourcePos
startpos, CommoditySymbol
lineprefix)
          | Int
newlines Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
0 = (SourcePos
anchor, CommoditySymbol
consumed)
          | Bool
otherwise     = (String -> Pos -> Pos -> SourcePos
SourcePos String
f (Int -> Pos
mkPos (Int -> Pos) -> Int -> Pos
forall a b. (a -> b) -> a -> b
$ Pos -> Int
unPos Pos
l Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
newlines) Pos
pos1, (Char -> Bool) -> CommoditySymbol -> CommoditySymbol
T.takeWhileEnd (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\n') CommoditySymbol
consumed)
      SourcePos
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) SourcePos
forall a.
a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (m :: * -> *) a. Monad m => a -> m a
return (SourcePos
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData CommoditySymbol m)
      SourcePos)
-> SourcePos
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) SourcePos
forall a b. (a -> b) -> a -> b
$ PosState CommoditySymbol -> SourcePos
forall s. PosState s -> SourcePos
pstateSourcePos (PosState CommoditySymbol -> SourcePos)
-> PosState CommoditySymbol -> SourcePos
forall a b. (a -> b) -> a -> b
$ Int -> PosState CommoditySymbol -> PosState CommoditySymbol
forall s. TraversableStream s => Int -> PosState s -> PosState s
reachOffsetNoLine (CommoditySymbol -> Int
T.length CommoditySymbol
lineprefix) PosState
        { pstateInput :: CommoditySymbol
pstateInput = CommoditySymbol
lineprefix, pstateOffset :: Int
pstateOffset = Int
0, pstateSourcePos :: SourcePos
pstateSourcePos = SourcePos
startpos
        , pstateTabWidth :: Pos
pstateTabWidth = Pos
defaultTabWidth, pstateLinePrefix :: String
pstateLinePrefix = String
"" }
    Maybe ParsePos
_ -> StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) SourcePos
forall s e (m :: * -> *).
(TraversableStream s, MonadParsec e s m) =>
m SourcePos
getSourcePos
  s <- getInput
  modify' $ \Journal
j -> Journal
j{jparsepos = Just $ ParsePos pos o s}
  return pos

addAccountAlias :: MonadState Journal m => AccountAlias -> m ()
addAccountAlias :: forall (m :: * -> *). MonadState Journal m => AccountAlias -> m ()
addAccountAlias AccountAlias
a = (Journal -> Journal) -> m ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' (\(j :: Journal
j@Journal{[Maybe Integer]
[(String, String)]
[(String, [String])]
[(CommoditySymbol, AccountDeclarationInfo)]
[(CommoditySymbol, TagDeclarationInfo)]
[(CommoditySymbol, PayeeDeclarationInfo)]
[CommoditySymbol]
[JournalFile]
[JournalItem]
[MarketPrice]
[PriceDirective]
[TimeclockEntry]
[AssertDirective]
[PeriodicTransaction]
[TransactionModifier]
[Transaction]
[AccountAlias]
Maybe Char
Maybe Integer
Maybe (CommoditySymbol, AmountStyle)
Maybe ParsePos
Map CommoditySymbol [(CommoditySymbol, CommoditySymbol)]
Map CommoditySymbol Commodity
Map CommoditySymbol AmountStyle
Map CommoditySymbol AccountType
Map AccountType [CommoditySymbol]
Set CommoditySymbol
Set AmountStyle
POSIXTime
FastPathStats
jparseincludefilestack :: Journal -> [(String, String)]
jparsealiases :: Journal -> [AccountAlias]
jparseoptaliases :: Journal -> [AccountAlias]
jparsefastpathstats :: Journal -> FastPathStats
jparsedefaultyear :: Journal -> Maybe Integer
jperiodictxns :: Journal -> [PeriodicTransaction]
jglobalcommoditystyles :: Journal -> Map CommoditySymbol AmountStyle
jtxnmodifiers :: Journal -> [TransactionModifier]
jaccounttypes :: Journal -> Map CommoditySymbol AccountType
jasserts :: Journal -> [AssertDirective]
jtxns :: Journal -> [Transaction]
jparsedecimalmark :: Journal -> Maybe Char
jparsedefaultcommodity :: Journal -> Maybe (CommoditySymbol, AmountStyle)
jdeclaredcommodities :: Journal -> Map CommoditySymbol Commodity
jparseamountstyles :: Journal -> Set AmountStyle
jparsetexts :: Journal -> Set CommoditySymbol
jdeclaredaccounttags :: Journal -> Map CommoditySymbol [(CommoditySymbol, CommoditySymbol)]
jdeclaredaccounttypes :: Journal -> Map AccountType [CommoditySymbol]
jparseparentaccounts :: Journal -> [CommoditySymbol]
jparsepos :: Journal -> Maybe ParsePos
jparsedefaultyear :: Maybe Integer
jparseapplyyears :: [Maybe Integer]
jparsedefaultcommodity :: Maybe (CommoditySymbol, AmountStyle)
jparsedecimalmark :: Maybe Char
jparseparentaccounts :: [CommoditySymbol]
jparsealiases :: [AccountAlias]
jparseoptaliases :: [AccountAlias]
jparsetimeclockentries :: [TimeclockEntry]
jparseincludefilestack :: [(String, String)]
jparsepos :: Maybe ParsePos
jparseamountstyles :: Set AmountStyle
jparsetexts :: Set CommoditySymbol
jparsefastpathstats :: FastPathStats
jdeclaredpayees :: [(CommoditySymbol, PayeeDeclarationInfo)]
jdeclaredtags :: [(CommoditySymbol, TagDeclarationInfo)]
jdeclaredaccounts :: [(CommoditySymbol, AccountDeclarationInfo)]
jdeclaredaccounttags :: Map CommoditySymbol [(CommoditySymbol, CommoditySymbol)]
jdeclaredaccounttypes :: Map AccountType [CommoditySymbol]
jaccounttypes :: Map CommoditySymbol AccountType
jdeclaredcommodities :: Map CommoditySymbol Commodity
jdeclaredcommoditytags :: Map CommoditySymbol [(CommoditySymbol, CommoditySymbol)]
jinferredcommoditystyles :: Map CommoditySymbol AmountStyle
jglobalcommoditystyles :: Map CommoditySymbol AmountStyle
jpricedirectives :: [PriceDirective]
jinferredmarketprices :: [MarketPrice]
jtxnmodifiers :: [TransactionModifier]
jperiodictxns :: [PeriodicTransaction]
jasserts :: [AssertDirective]
jtxns :: [Transaction]
jitems :: [JournalItem]
jfiles :: [JournalFile]
jauxfiles :: [(String, [String])]
jlastreadtime :: POSIXTime
jlastreadtime :: Journal -> POSIXTime
jauxfiles :: Journal -> [(String, [String])]
jfiles :: Journal -> [JournalFile]
jitems :: Journal -> [JournalItem]
jinferredmarketprices :: Journal -> [MarketPrice]
jpricedirectives :: Journal -> [PriceDirective]
jinferredcommoditystyles :: Journal -> Map CommoditySymbol AmountStyle
jdeclaredcommoditytags :: Journal -> Map CommoditySymbol [(CommoditySymbol, CommoditySymbol)]
jdeclaredaccounts :: Journal -> [(CommoditySymbol, AccountDeclarationInfo)]
jdeclaredtags :: Journal -> [(CommoditySymbol, TagDeclarationInfo)]
jdeclaredpayees :: Journal -> [(CommoditySymbol, PayeeDeclarationInfo)]
jparsetimeclockentries :: Journal -> [TimeclockEntry]
jparseapplyyears :: Journal -> [Maybe Integer]
..}) -> Journal
j{jparsealiases=a:jparsealiases})

getAccountAliases :: MonadState Journal m => m [AccountAlias]
getAccountAliases :: forall (m :: * -> *). MonadState Journal m => m [AccountAlias]
getAccountAliases = (Journal -> [AccountAlias]) -> m Journal -> m [AccountAlias]
forall a b. (a -> b) -> m a -> m b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Journal -> [AccountAlias]
jparsealiases m Journal
forall s (m :: * -> *). MonadState s m => m s
get

-- getTransactionCount :: MonadState Journal m =>  m Integer
-- getTransactionCount = fmap jparsetransactioncount get
--
-- setTransactionCount :: MonadState Journal m => Integer -> m ()
-- setTransactionCount i = modify' (\j -> j{jparsetransactioncount=i})
--
-- -- | Increment the transaction index by one and return the new value.
-- incrementTransactionCount :: MonadState Journal m => m Integer
-- incrementTransactionCount = do
--   modify' (\j -> j{jparsetransactioncount=jparsetransactioncount j + 1})
--   getTransactionCount

journalAddFile :: JournalFile -> Journal -> Journal
journalAddFile :: JournalFile -> Journal -> Journal
journalAddFile JournalFile
f j :: Journal
j@Journal{jfiles :: Journal -> [JournalFile]
jfiles=[JournalFile]
fs} = Journal
j{jfiles=fs++[f]}
  -- append, unlike the other fields, even though we do a final reverse,
  -- to compensate for additional reversal due to including/monoid-concatting

-- A version of `match` that is strict in the returned text
match' :: TextParser m a -> TextParser m (Text, a)
match' :: forall (m :: * -> *) a.
TextParser m a -> TextParser m (CommoditySymbol, a)
match' TextParser m a
p = do
  (!txt, p') <- TextParser m a
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol, a)
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> m (Tokens s, a)
match TextParser m a
p
  pure (txt, p')

--- ** parsers
--- *** transaction bits

statusp :: TextParser m Status
statusp :: forall (m :: * -> *). TextParser m Status
statusp = do
  -- a status mark may follow, after optional spaces; check cheaply, since usually there is none
  (_, mc) <- TextParser m (Bool, Maybe Char)
forall (m :: * -> *). TextParser m (Bool, Maybe Char)
peekAfterSpaces
  case mc of
    Just Char
'*' -> Status
Cleared Status
-> ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m Status
forall a b.
a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ (ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m Char
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'*')
    Just Char
'!' -> Status
Pending Status
-> ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m Status
forall a b.
a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ (ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m Char
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'!')
    Maybe Char
_        -> Status -> ParsecT HledgerParseErrorData CommoditySymbol m Status
forall a. a -> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Status
Unmarked

codep :: TextParser m Text
codep :: forall (m :: * -> *). TextParser m CommoditySymbol
codep = do
  -- a code in parentheses may follow, after spaces; check cheaply, since usually there is none
  (spaced, mc) <- TextParser m (Bool, Maybe Char)
forall (m :: * -> *). TextParser m (Bool, Maybe Char)
peekAfterSpaces
  if spaced && mc == Just '('
  then do
    skipNonNewlineSpaces1
    char '('
    code <- takeWhileP Nothing $ \Token CommoditySymbol
c -> Char
Token CommoditySymbol
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
')' Bool -> Bool -> Bool
&& Char
Token CommoditySymbol
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\n'
    char ')' <?> "closing bracket ')' for transaction code"
    pure code
  else pure ""

-- | Parse possibly empty text until a semicolon or newline.
-- Whitespace is preserved (for now - perhaps helps preserve alignment 
-- of same-line comments ?).
descriptionp :: TextParser m Text
descriptionp :: forall (m :: * -> *). TextParser m CommoditySymbol
descriptionp = TextParser m CommoditySymbol
forall (m :: * -> *). TextParser m CommoditySymbol
noncommenttextp TextParser m CommoditySymbol
-> String -> TextParser m CommoditySymbol
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"description"

--- *** dates

-- | Parse a date in YYYY-MM-DD format.
-- Slash (/) and period (.) are also allowed as separators.
-- The year may be omitted if a default year has been set.
-- Leading zeroes may be omitted.
datep :: JournalParser m Day
datep :: forall (m :: * -> *). JournalParser m Day
datep = do
  mYear <- JournalParser m (Maybe Integer)
forall (m :: * -> *). JournalParser m (Maybe Integer)
getYear
  lift $ datep' mYear

datep' :: Maybe Year -> TextParser m Day
datep' :: forall (m :: * -> *). Maybe Integer -> TextParser m Day
datep' Maybe Integer
mYear = do
    startOffset <- ParsecT HledgerParseErrorData CommoditySymbol m Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
    d1 <- yearorintp <?> "year or month"
    sep <- datesepchar <?> "date separator"
    d2 <- decimal <?> "month or day"
    case d1 of
      Left Integer
y  -> Int
-> Integer
-> Char
-> Int
-> ParsecT HledgerParseErrorData CommoditySymbol m Day
forall (m :: * -> *).
Int -> Integer -> Char -> Int -> TextParser m Day
fullDate Int
startOffset Integer
y Char
sep Int
d2
      Right Int
m -> Int
-> Maybe Integer
-> Int
-> Int
-> ParsecT HledgerParseErrorData CommoditySymbol m Day
forall (m :: * -> *).
Int -> Maybe Integer -> Int -> Int -> TextParser m Day
partialDate Int
startOffset Maybe Integer
mYear Int
m Int
d2
    ParsecT HledgerParseErrorData CommoditySymbol m Day
-> String -> ParsecT HledgerParseErrorData CommoditySymbol m Day
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"full or partial date"
  where
    fullDate :: Int -> Year -> Char -> Month -> TextParser m Day
    fullDate :: forall (m :: * -> *).
Int -> Integer -> Char -> Int -> TextParser m Day
fullDate Int
startOffset Integer
year Char
sep Int
month = do
      sep2 <- (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
(Token s -> Bool) -> m (Token s)
satisfy Char -> Bool
Token CommoditySymbol -> Bool
isDateSepChar ParsecT HledgerParseErrorData CommoditySymbol m Char
-> String -> ParsecT HledgerParseErrorData CommoditySymbol m Char
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"date separator"
      day <- decimal <?> "day"
      endOffset <- getOffset
      when (sep /= sep2) $ 
        customFailure $ parseErrorAtRegion startOffset endOffset $
          "This date has different separators, please use consistent separators."
      case fromGregorianValid year month day of
        Maybe Day
Nothing -> 
          HledgerParseErrorData
-> ParsecT HledgerParseErrorData CommoditySymbol m Day
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData
 -> ParsecT HledgerParseErrorData CommoditySymbol m Day)
-> HledgerParseErrorData
-> ParsecT HledgerParseErrorData CommoditySymbol m Day
forall a b. (a -> b) -> a -> b
$ Int -> Int -> String -> HledgerParseErrorData
parseErrorAtRegion Int
startOffset Int
endOffset (String -> HledgerParseErrorData)
-> String -> HledgerParseErrorData
forall a b. (a -> b) -> a -> b
$
            String
"This is not a valid date, please fix it."
        Just Day
date -> Day -> ParsecT HledgerParseErrorData CommoditySymbol m Day
forall a. a -> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Day -> ParsecT HledgerParseErrorData CommoditySymbol m Day)
-> Day -> ParsecT HledgerParseErrorData CommoditySymbol m Day
forall a b. (a -> b) -> a -> b
$! Day
date

    partialDate :: Int -> Maybe Year -> Month -> MonthDay -> TextParser m Day
    partialDate :: forall (m :: * -> *).
Int -> Maybe Integer -> Int -> Int -> TextParser m Day
partialDate Int
startOffset Maybe Integer
myr Int
month Int
day = do
      endOffset <- ParsecT HledgerParseErrorData CommoditySymbol m Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
      case myr of
        Just Integer
year ->
          case Integer -> Int -> Int -> Maybe Day
fromGregorianValid Integer
year Int
month Int
day of
            Maybe Day
Nothing -> 
              HledgerParseErrorData
-> ParsecT HledgerParseErrorData CommoditySymbol m Day
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData
 -> ParsecT HledgerParseErrorData CommoditySymbol m Day)
-> HledgerParseErrorData
-> ParsecT HledgerParseErrorData CommoditySymbol m Day
forall a b. (a -> b) -> a -> b
$ Int -> Int -> String -> HledgerParseErrorData
parseErrorAtRegion Int
startOffset Int
endOffset (String -> HledgerParseErrorData)
-> String -> HledgerParseErrorData
forall a b. (a -> b) -> a -> b
$
                String
"This is not a valid date, please fix it."
            Just Day
date -> Day -> ParsecT HledgerParseErrorData CommoditySymbol m Day
forall a. a -> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Day -> ParsecT HledgerParseErrorData CommoditySymbol m Day)
-> Day -> ParsecT HledgerParseErrorData CommoditySymbol m Day
forall a b. (a -> b) -> a -> b
$! Day
date

        Maybe Integer
Nothing ->
          HledgerParseErrorData
-> ParsecT HledgerParseErrorData CommoditySymbol m Day
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData
 -> ParsecT HledgerParseErrorData CommoditySymbol m Day)
-> HledgerParseErrorData
-> ParsecT HledgerParseErrorData CommoditySymbol m Day
forall a b. (a -> b) -> a -> b
$ Int -> Int -> String -> HledgerParseErrorData
parseErrorAtRegion Int
startOffset Int
endOffset (String -> HledgerParseErrorData)
-> String -> HledgerParseErrorData
forall a b. (a -> b) -> a -> b
$
            String
"This partial date can not be parsed because the current year is unknown.\n"
            String -> String -> String
forall a. [a] -> [a] -> [a]
++String
"Please make it a full date, or add a default year directive."

{-# INLINABLE datep' #-}

-- | Parse a date and time in YYYY-MM-DD HH:MM[:SS][+-ZZZZ] format.
-- Slash (/) and period (.) are also allowed as date separators.
-- The year may be omitted if a default year has been set.
-- Seconds are optional.
-- The timezone is optional and ignored (the time is always interpreted as a local time).
-- Leading zeroes may be omitted (except in a timezone).
datetimep :: JournalParser m LocalTime
datetimep :: forall (m :: * -> *). JournalParser m LocalTime
datetimep = do
  mYear <- JournalParser m (Maybe Integer)
forall (m :: * -> *). JournalParser m (Maybe Integer)
getYear
  lift $ datetimep' mYear

datetimep' :: Maybe Year -> TextParser m LocalTime
datetimep' :: forall (m :: * -> *). Maybe Integer -> TextParser m LocalTime
datetimep' Maybe Integer
mYear = do
  day <- Maybe Integer -> TextParser m Day
forall (m :: * -> *). Maybe Integer -> TextParser m Day
datep' Maybe Integer
mYear
  skipNonNewlineSpaces1
  time <- timeofdayp
  pure $ LocalTime day time

-- | Parse a time of day (HH:MM[:SS]), and skip any time zone suffix (like +0100) following it.
timeofdayp :: TextParser m TimeOfDay
timeofdayp :: forall (m :: * -> *). TextParser m TimeOfDay
timeofdayp = do
  time <- TextParser m TimeOfDay
forall (m :: * -> *). TextParser m TimeOfDay
timeOfDay
  optional timeZone -- ignoring time zones
  pure time

  where
    timeOfDay :: TextParser m TimeOfDay
    timeOfDay :: forall (m :: * -> *). TextParser m TimeOfDay
timeOfDay = do
      off1 <- ParsecT HledgerParseErrorData CommoditySymbol m Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
      h' <- twoDigitDecimal <?> "hour"
      off2 <- getOffset
      unless (h' >= 0 && h' <= 23) $ customFailure $
        parseErrorAtRegion off1 off2 "invalid time (bad hour)"

      char ':' <?> "':' (hour-minute separator)"
      off3 <- getOffset
      m' <- twoDigitDecimal <?> "minute"
      off4 <- getOffset
      unless (m' >= 0 && m' <= 59) $ customFailure $
        parseErrorAtRegion off3 off4 "invalid time (bad minute)"

      s' <- option 0 $ do
        char ':' <?> "':' (minute-second separator)"
        off5 <- getOffset
        s' <- twoDigitDecimal <?> "second"
        off6 <- getOffset
        unless (s' >= 0 && s' <= 59) $ customFailure $
          parseErrorAtRegion off5 off6 "invalid time (bad second)"
          -- we do not support leap seconds
        pure s'

      pure $ TimeOfDay h' m' (fromIntegral s')

    twoDigitDecimal :: TextParser m Int
    twoDigitDecimal :: forall (m :: * -> *). TextParser m Int
twoDigitDecimal = do
      d1 <- Char -> Int
digitToInt (Char -> Int)
-> ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m Int
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ParsecT HledgerParseErrorData CommoditySymbol m Char
ParsecT
  HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m (Token s)
digitChar
      d2 <- digitToInt <$> (digitChar <?> "a second digit")
      pure $ d1*10 + d2

    timeZone :: TextParser m String
    timeZone :: forall (m :: * -> *). TextParser m String
timeZone = do
      plusminus <- (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
(Token s -> Bool) -> m (Token s)
satisfy ((Token CommoditySymbol -> Bool)
 -> ParsecT
      HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol))
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall a b. (a -> b) -> a -> b
$ \Token CommoditySymbol
c -> Char
Token CommoditySymbol
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'-' Bool -> Bool -> Bool
|| Char
Token CommoditySymbol
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'+'
      fourDigits <- count 4 (digitChar <?> "a digit (for a time zone)")
      pure $ plusminus:fourDigits

secondarydatep :: Day -> TextParser m Day
secondarydatep :: forall (m :: * -> *). Day -> TextParser m Day
secondarydatep Day
primaryDate = Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'=' ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m Day
-> ParsecT HledgerParseErrorData CommoditySymbol m Day
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> Maybe Integer
-> ParsecT HledgerParseErrorData CommoditySymbol m Day
forall (m :: * -> *). Maybe Integer -> TextParser m Day
datep' (Integer -> Maybe Integer
forall a. a -> Maybe a
Just Integer
primaryYear)
  where primaryYear :: Integer
primaryYear = (Integer, Int, Int) -> Integer
forall {a} {b} {c}. (a, b, c) -> a
first3 ((Integer, Int, Int) -> Integer) -> (Integer, Int, Int) -> Integer
forall a b. (a -> b) -> a -> b
$ Day -> (Integer, Int, Int)
toGregorian Day
primaryDate

-- | Parse a year number or an Int. Years must contain at least four
-- digits.
yearorintp :: TextParser m (Either Year Int)
yearorintp :: forall (m :: * -> *). TextParser m (Either Integer Int)
yearorintp = do
    yearOrMonth <- Maybe String
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhile1P (String -> Maybe String
forall a. a -> Maybe a
Just String
"digit") Char -> Bool
Token CommoditySymbol -> Bool
isDigit
    let n = CommoditySymbol -> Integer
readDecimal CommoditySymbol
yearOrMonth
    return $ if T.length yearOrMonth >= 4 then Left n else Right (fromInteger n)

--- *** account names

-- | Parse an account name plus one following space if present (see accountnamep);
-- then apply the alias directives, parent account prefix and --alias options currently in effect,
-- in that order (see 'accountNameApplyModifiers', which explains this).
-- This calls error if any account alias with an invalid regular expression exists.
-- The flag says whether account names may include semicolons; currently account names
-- in journal format may, but account names in timeclock/timedot formats may not.
modifiedaccountnamep :: Bool -> JournalParser m AccountName
modifiedaccountnamep :: forall (m :: * -> *). Bool -> JournalParser m CommoditySymbol
modifiedaccountnamep Bool
allowsemicolon = Bool -> JournalParser m CommoditySymbol
forall (m :: * -> *). Bool -> JournalParser m CommoditySymbol
aliasedaccountnamep Bool
allowsemicolon JournalParser m CommoditySymbol
-> (CommoditySymbol -> JournalParser m CommoditySymbol)
-> JournalParser m CommoditySymbol
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> (a
    -> StateT
         Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= CommoditySymbol -> JournalParser m CommoditySymbol
forall (m :: * -> *).
CommoditySymbol -> JournalParser m CommoditySymbol
applyParentAndOptionAliases

-- | Parse an account name like modifiedaccountnamep, but apply only the alias directives,
-- not the parent account prefix or --alias options (see 'accountNameApplyModifiers').
aliasedaccountnamep :: Bool -> JournalParser m AccountName
aliasedaccountnamep :: forall (m :: * -> *). Bool -> JournalParser m CommoditySymbol
aliasedaccountnamep Bool
allowsemicolon = do
  als <- StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol m)
  [AccountAlias]
forall (m :: * -> *). MonadState Journal m => m [AccountAlias]
getAccountAliases
  a   <- lift $ if allowsemicolon then accountnamep else accountnamenosemicolonp
  -- XXX or accountNameApplyAliasesMemo ? doesn't seem to make a difference (retest that function)
  orAliasError a $ accountNameApplyAliases als a

-- | Add the parent account prefix to an account name (with alias directives already applied),
-- then apply the --alias options (see 'accountNameApplyModifiers').
-- This calls error if an --alias option has an invalid regular expression.
applyParentAndOptionAliases :: AccountName -> JournalParser m AccountName
applyParentAndOptionAliases :: forall (m :: * -> *).
CommoditySymbol -> JournalParser m CommoditySymbol
applyParentAndOptionAliases CommoditySymbol
a = do
  parent <- JournalParser m CommoditySymbol
forall (m :: * -> *). JournalParser m CommoditySymbol
getParentAccount
  optals <- jparseoptaliases <$> get
  orAliasError a $ accountNameApplyAliases optals $ joinAccountNames parent a

-- | Return an aliased account name, or call error with the alias problem.
-- This should not happen, regexaliasp will have displayed a better error already.
-- (XXX why does customFailure cause error to be displayed there, but not here ?)
orAliasError :: AccountName -> Either RegexError AccountName -> JournalParser m AccountName
orAliasError :: forall (m :: * -> *).
CommoditySymbol
-> Either String CommoditySymbol -> JournalParser m CommoditySymbol
orAliasError CommoditySymbol
_ (Right CommoditySymbol
a') = CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
forall a.
a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (m :: * -> *) a. Monad m => a -> m a
return (CommoditySymbol
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData CommoditySymbol m)
      CommoditySymbol)
-> CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
forall a b. (a -> b) -> a -> b
$! CommoditySymbol
a'
orAliasError CommoditySymbol
a (Left String
e)   = String
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
forall {b}. String -> b
error' (String
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData CommoditySymbol m)
      CommoditySymbol)
-> String
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
forall a b. (a -> b) -> a -> b
$ String
"problem in account alias applied to "String -> String -> String
forall a. [a] -> [a] -> [a]
++CommoditySymbol -> String
T.unpack CommoditySymbol
aString -> String -> String
forall a. [a] -> [a] -> [a]
++String
": "String -> String -> String
forall a. [a] -> [a] -> [a]
++String
e  -- PARTIAL:

-- | Rewrite an account name as written in a journal entry, using the given alias directives
-- (most recent first), parent account (from apply account directives) and --alias options.
-- Can fail with a bad replacement pattern in a regular expression alias.
--
-- This is the reference for how account names are modified during parsing. There are three modifiers,
-- applied in this order:
--
-- 1. alias directives and account directives' alias: tags (kept in 'jparsealiases'),
--    applied to the name as written. This is as in Ledger, and it means a file's aliases keep working
--    when the file is included under apply account (#2733). Before hledger 2, these were applied after step 2.
--
-- 2. the parent account from apply account directives ('jparseparentaccounts'), prepended.
--
-- 3. --alias options ('jparseoptaliases'), applied to the full account name,
--    since that is the name users see in reports. These are kept separately from 1,
--    so that end aliases can forget alias directives without forgetting them.
--
-- The code is split up because of a few special cases:
--
-- - The parsers apply these in two parts: 'aliasedaccountnamep' does step 1, and
--   'applyParentAndOptionAliases' does steps 2 and 3. Normally both are used ('modifiedaccountnamep').
--   But accountdirectivep also needs the name after step 1 only: it is the target of the directive's
--   alias: tags, which (like alias directives) are applied before step 2, so a target which already
--   included the parent account would get it added twice.
--
-- - The journal reader's fast path for simple transactions (fasttransactionp) does all three steps
--   with this function, since it works on text rather than in the parser.
--
-- - Entries from included CSV/rules files get steps 1 and 3, but not 2 ('includeFileParser').
--   (Included timeclock/timedot files are parsed with 'modifiedaccountnamep', so they get all three.)
--
-- - When a non-journal file is read directly, 'jparseoptaliases' is empty, and its reader
--   applies step 3 itself after parsing.
accountNameApplyModifiers :: [AccountAlias] -> AccountName -> [AccountAlias] -> AccountName -> Either RegexError AccountName
accountNameApplyModifiers :: [AccountAlias]
-> CommoditySymbol
-> [AccountAlias]
-> CommoditySymbol
-> Either String CommoditySymbol
accountNameApplyModifiers [AccountAlias]
als CommoditySymbol
parent [AccountAlias]
optals CommoditySymbol
a =
  [AccountAlias] -> CommoditySymbol -> Either String CommoditySymbol
accountNameApplyAliases [AccountAlias]
optals (CommoditySymbol -> Either String CommoditySymbol)
-> (CommoditySymbol -> CommoditySymbol)
-> CommoditySymbol
-> Either String CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CommoditySymbol -> CommoditySymbol -> CommoditySymbol
joinAccountNames CommoditySymbol
parent (CommoditySymbol -> Either String CommoditySymbol)
-> Either String CommoditySymbol -> Either String CommoditySymbol
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< [AccountAlias] -> CommoditySymbol -> Either String CommoditySymbol
accountNameApplyAliases [AccountAlias]
als CommoditySymbol
a

-- | Parse an account name, plus one following space if present.
-- Account names have one or more parts separated by the account separator character,
-- and are terminated by two or more whitespace characters (spaces or tabs), or end of input.
-- Each part is at least one character long, may have single spaces inside it, and starts with a non-whitespace.
-- (We should have required them to start with an alphanumeric, but didn't.)
-- An empty part (from a leading, trailing or repeated separator) is an error.
-- Note, this means account names can contain all kinds of punctuation, including ; which usually starts a following comment.
-- Parent parsers usually remove the following comment before using this parser.
accountnamep :: TextParser m AccountName
accountnamep :: forall (m :: * -> *). TextParser m CommoditySymbol
accountnamep = (CommoditySymbol -> CommoditySymbol)
-> TextParser m CommoditySymbol -> TextParser m CommoditySymbol
forall (m :: * -> *).
(CommoditySymbol -> CommoditySymbol)
-> TextParser m CommoditySymbol -> TextParser m CommoditySymbol
nonemptypartsp CommoditySymbol -> CommoditySymbol
forall a. a -> a
id TextParser m CommoditySymbol
forall (m :: * -> *). TextParser m CommoditySymbol
singlespacedtext1p

-- Like accountnamep, but stops parsing if it reaches a semicolon.
accountnamenosemicolonp :: TextParser m AccountName
accountnamenosemicolonp :: forall (m :: * -> *). TextParser m CommoditySymbol
accountnamenosemicolonp = (CommoditySymbol -> CommoditySymbol)
-> TextParser m CommoditySymbol -> TextParser m CommoditySymbol
forall (m :: * -> *).
(CommoditySymbol -> CommoditySymbol)
-> TextParser m CommoditySymbol -> TextParser m CommoditySymbol
nonemptypartsp CommoditySymbol -> CommoditySymbol
forall a. a -> a
id TextParser m CommoditySymbol
forall (m :: * -> *). TextParser m CommoditySymbol
singlespacednoncommenttext1p

-- | Parse the parent account name of an apply account directive.
-- Like accountnamep, but one trailing account separator is allowed, and dropped (as in Ledger, #2858).
parentaccountnamep :: TextParser m AccountName
parentaccountnamep :: forall (m :: * -> *). TextParser m CommoditySymbol
parentaccountnamep = (CommoditySymbol -> CommoditySymbol)
-> TextParser m CommoditySymbol -> TextParser m CommoditySymbol
forall (m :: * -> *).
(CommoditySymbol -> CommoditySymbol)
-> TextParser m CommoditySymbol -> TextParser m CommoditySymbol
nonemptypartsp (\CommoditySymbol
a -> CommoditySymbol -> Maybe CommoditySymbol -> CommoditySymbol
forall a. a -> Maybe a -> a
fromMaybe CommoditySymbol
a (Maybe CommoditySymbol -> CommoditySymbol)
-> Maybe CommoditySymbol -> CommoditySymbol
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> CommoditySymbol -> Maybe CommoditySymbol
T.stripSuffix CommoditySymbol
acctsep CommoditySymbol
a) TextParser m CommoditySymbol
forall (m :: * -> *). TextParser m CommoditySymbol
singlespacedtext1p

-- | Run an account name parser, and normalise its result with the given function;
-- fail with an error highlighting the name if the result has an empty part.
nonemptypartsp :: (AccountName -> AccountName) -> TextParser m AccountName -> TextParser m AccountName
nonemptypartsp :: forall (m :: * -> *).
(CommoditySymbol -> CommoditySymbol)
-> TextParser m CommoditySymbol -> TextParser m CommoditySymbol
nonemptypartsp CommoditySymbol -> CommoditySymbol
f TextParser m CommoditySymbol
p = do
  off1 <- ParsecT HledgerParseErrorData CommoditySymbol m Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
  a <- p
  off2 <- getOffset
  let a' = CommoditySymbol -> CommoditySymbol
f CommoditySymbol
a
  when (accountNameHasEmptyPart a') $ customFailure $ parseErrorAtRegion off1 off2 $
    "account name \"" ++ T.unpack a ++ "\" has an empty part.\n"
    ++ "Account names can't begin or end with " ++ sep ++ ", or contain " ++ sep ++ sep ++ "."
  return a'
  where sep :: String
sep = [Char
acctsepchar]

-- | Parse a single line of possibly empty text enclosed in double quotes.
doublequotedtextp :: TextParser m Text
doublequotedtextp :: forall (m :: * -> *). TextParser m CommoditySymbol
doublequotedtextp = ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
forall (m :: * -> *) open close a.
Applicative m =>
m open -> m close -> m a -> m a
between (Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'"') (Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'"') (ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
 -> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol)
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
forall a b. (a -> b) -> a -> b
$
  Maybe String
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhileP Maybe String
forall a. Maybe a
Nothing ((Token CommoditySymbol -> Bool)
 -> ParsecT
      HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol))
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall a b. (a -> b) -> a -> b
$ \Token CommoditySymbol
c -> Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Char -> Bool
isNewline Char
Token CommoditySymbol
c Bool -> Bool -> Bool
|| Char
Token CommoditySymbol
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'"'

-- | Parse possibly empty text, including whitespace, 
-- until a comment start (semicolon) or newline.
noncommenttextp :: TextParser m T.Text
noncommenttextp :: forall (m :: * -> *). TextParser m CommoditySymbol
noncommenttextp = Maybe String
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhileP Maybe String
forall a. Maybe a
Nothing (\Token CommoditySymbol
c -> Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Char -> Bool
isSameLineCommentStart Char
Token CommoditySymbol
c Bool -> Bool -> Bool
|| Char -> Bool
isNewline Char
Token CommoditySymbol
c)

-- | Parse non-empty text, including whitespace, 
-- until a comment start (semicolon) or newline.
noncommenttext1p :: TextParser m T.Text
noncommenttext1p :: forall (m :: * -> *). TextParser m CommoditySymbol
noncommenttext1p = Maybe String
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhile1P Maybe String
forall a. Maybe a
Nothing (\Token CommoditySymbol
c -> Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Char -> Bool
isSameLineCommentStart Char
Token CommoditySymbol
c Bool -> Bool -> Bool
|| Char -> Bool
isNewline Char
Token CommoditySymbol
c)

-- | Parse non-empty, single-spaced text starting and ending with non-whitespace,
-- until a double space or newline.
singlespacedtext1p :: TextParser m T.Text
singlespacedtext1p :: forall (m :: * -> *). TextParser m CommoditySymbol
singlespacedtext1p = (Char -> Bool) -> TextParser m CommoditySymbol
forall (m :: * -> *).
(Char -> Bool) -> TextParser m CommoditySymbol
singlespacedtextsatisfying1p (Bool -> Char -> Bool
forall a b. a -> b -> a
const Bool
True)

-- | Parse non-empty, single-spaced text starting and ending with non-whitespace,
-- until a comment start (semicolon), double space, or newline.
singlespacednoncommenttext1p :: TextParser m T.Text
singlespacednoncommenttext1p :: forall (m :: * -> *). TextParser m CommoditySymbol
singlespacednoncommenttext1p = (Char -> Bool) -> TextParser m CommoditySymbol
forall (m :: * -> *).
(Char -> Bool) -> TextParser m CommoditySymbol
singlespacedtextsatisfying1p (Bool -> Bool
not (Bool -> Bool) -> (Char -> Bool) -> Char -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> Bool
isSameLineCommentStart)

-- | Parse non-empty, single-spaced text starting and ending with non-whitespace,
-- where all characters satisfy the given predicate.
singlespacedtextsatisfying1p :: (Char -> Bool) -> TextParser m T.Text
singlespacedtextsatisfying1p :: forall (m :: * -> *).
(Char -> Bool) -> TextParser m CommoditySymbol
singlespacedtextsatisfying1p Char -> Bool
f = do
  firstPart <- ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
ParsecT
  HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
partp
  otherParts <- manyWhile nextissinglespaceandpart $ try $ singlespacep *> partp
  pure $! T.unwords $ firstPart : otherParts
  where
    partp :: ParsecT
  HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
partp = Maybe String
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhile1P Maybe String
forall a. Maybe a
Nothing (\Token CommoditySymbol
c -> Char -> Bool
f Char
Token CommoditySymbol
c Bool -> Bool -> Bool
&& Bool -> Bool
not (Char -> Bool
isSpace Char
Token CommoditySymbol
c))
    -- is the next part separated from here by exactly one space ? (checked cheaply before parsing)
    nextissinglespaceandpart :: ParsecT HledgerParseErrorData CommoditySymbol m Bool
nextissinglespaceandpart = do
      next2 <- TextParser m (Maybe Char, Maybe Char)
forall (m :: * -> *). TextParser m (Maybe Char, Maybe Char)
peekChars2
      pure $ case next2 of
        (Just Char
c1, Just Char
c2) -> Char -> Bool
isNonNewlineSpace Char
c1 Bool -> Bool -> Bool
&& Char -> Bool
f Char
c2 Bool -> Bool -> Bool
&& Bool -> Bool
not (Char -> Bool
isSpace Char
c2)
        (Maybe Char, Maybe Char)
_                  -> Bool
False

-- | Parse one non-newline whitespace character that is not followed by another one.
-- (A single tab is not a separator, unlike in Ledger; hledger 1 and 2 agree on this.)
singlespacep :: TextParser m ()
singlespacep :: forall (m :: * -> *). TextParser m ()
singlespacep = ParsecT HledgerParseErrorData CommoditySymbol m Char
forall s (m :: * -> *).
(Stream s, Char ~ Token s) =>
ParsecT HledgerParseErrorData s m Char
spacenonewline ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m ()
notFollowedBy ParsecT HledgerParseErrorData CommoditySymbol m Char
forall s (m :: * -> *).
(Stream s, Char ~ Token s) =>
ParsecT HledgerParseErrorData s m Char
spacenonewline

--- *** amounts

-- | Parse whitespace then an amount, or return the special "missing" marker amount.
spaceandamountormissingp :: JournalParser m MixedAmount
spaceandamountormissingp :: forall (m :: * -> *). JournalParser m MixedAmount
spaceandamountormissingp =
  MixedAmount
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     MixedAmount
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     MixedAmount
forall (m :: * -> *) a. Alternative m => a -> m a -> m a
option MixedAmount
missingmixedamt (StateT
   Journal
   (ParsecT HledgerParseErrorData CommoditySymbol m)
   MixedAmount
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData CommoditySymbol m)
      MixedAmount)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     MixedAmount
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     MixedAmount
forall a b. (a -> b) -> a -> b
$ StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol m)
  MixedAmount
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     MixedAmount
forall a.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (StateT
   Journal
   (ParsecT HledgerParseErrorData CommoditySymbol m)
   MixedAmount
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData CommoditySymbol m)
      MixedAmount)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     MixedAmount
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     MixedAmount
forall a b. (a -> b) -> a -> b
$ do
    ParsecT HledgerParseErrorData CommoditySymbol m ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (ParsecT HledgerParseErrorData CommoditySymbol m ()
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ())
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall a b. (a -> b) -> a -> b
$ ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces1
    Amount -> MixedAmount
mixedAmount (Amount -> MixedAmount)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     MixedAmount
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall (m :: * -> *). JournalParser m Amount
amountp

-- | Parse a single-commodity amount, applying the default commodity if there is no commodity symbol;
-- optionally followed by, in any order:
-- a Ledger-style cost, Ledger-style valuation expression, and/or Ledger-style cost basis, which is one or more of
-- lot cost, lot date, and/or lot note (we loosely call this triple the lot's cost basis).
-- The cost basis makes it a lot rather than just an amount. Both cost basis info and valuation expression
-- are discarded for now.
-- The main amount's sign is significant; here are the possibilities and their interpretation.
-- Also imagine an optional VALUATIONEXPR added to any of these (omitted for clarity):
-- @
--
--   AMT                         -- acquiring an amount
--   AMT COST                    -- acquiring an amount at some cost
--   AMT COST COSTBASIS          -- acquiring a lot at some cost, saving its cost basis
--   AMT COSTBASIS COST          -- like the above
--   AMT COSTBASIS               -- like the above with cost same as the cost basis
--
--  -AMT                         -- releasing an amount
--  -AMT SELLPRICE               -- releasing an amount at some selling price
--  -AMT SELLPRICE COSTBASISSEL  -- releasing a lot at some selling price, selecting it by its cost basis
--  -AMT COSTBASISSEL SELLPRICE  -- like the above
--  -AMT COSTBASISSEL            -- like the above with selling price same as the selected lot's cost basis amount
--
-- COST/SELLPRICE can be @ UNITAMT, @@ TOTALAMT, (@) UNITAMT, or (@@) TOTALAMT. The () are ignored.
-- COSTBASIS    is one or more of {LOTCOST}, [LOTDATE], (LOTNOTE), in any order, with LOTCOST defaulting to COST.
-- COSTBASISSEL is one or more of {LOTCOST}, [LOTDATE], (LOTNOTE), in any order.
-- {LOTCOST} can be {UNITAMT}, {{TOTALAMT}}, {=UNITAMT}, or {{=TOTALAMT}}. The = is ignored.
-- VALUATIONEXPR can be ((VALUE AMOUNT)) or ((VALUE FUNCTION)).
--
-- @
-- Ledger amount syntax is really complex.
-- Rule of thumb: curly braces, parentheses, and/or square brackets
-- in an amount means a Ledger-style cost basis is involved.
--
-- To parse an amount's numeric quantity we need to know which character 
-- represents a decimal mark. We find it in one of three ways:
--
-- 1. If a decimal mark has been set explicitly in the journal parse state
--    (by a decimal-mark directive or CSV rule), we use that, strictly
--
-- 2. Or if the journal has a commodity declaration for the amount's commodity,
--    we get the decimal mark from that, and use it only to interpret ambiguous numbers
--    (see AmountParseKind for details)
--
-- 3. Otherwise we will parse any valid decimal mark appearing in the
--    number, as long as the number appears well formed.
--    (This means we handle files with any supported decimal mark without configuration,
--    but it also allows different decimal marks in  different amounts,
--    which is a bit too loose. There's an open issue.)
--
amountp :: JournalParser m Amount
amountp :: forall (m :: * -> *). JournalParser m Amount
amountp = AmountParseKind -> JournalParser m Amount
forall (m :: * -> *). AmountParseKind -> JournalParser m Amount
amountp' AmountParseKind
OrdinaryAmount

-- | The kinds of amount which are parsed a little differently.
--
-- A decimal-mark directive (or CSV rule) declares how numbers are written in the data,
-- and data amounts (OrdinaryAmount, MultiplierAmount) must obey it strictly;
-- violations are parse errors, reported at the number.
-- A commodity or D directive declares a display style, given as a sample amount (StyleAmount),
-- which may use a different decimal mark from the data.
-- When there's no decimal-mark directive, a commodity's display style is also used
-- to interpret ambiguous numbers like 1,000, but it is not enforced.
data AmountParseKind
  = OrdinaryAmount
    -- ^ An amount in the data: in a posting, cost, balance assertion, price directive, CSV record, etc.
    --   If a decimal-mark directive is in effect, the number must use only that decimal mark:
    --   1,000.00 is rejected when , is declared, and 1.2.34 when . is declared.
  | MultiplierAmount
    -- ^ A multiplier in an auto posting rule (*AMT). The default commodity is not applied to it.
    --   Otherwise it's parsed like an OrdinaryAmount.
  | StyleAmount
    -- ^ The sample amount in a commodity directive (or its format subdirective) or a D directive,
    --   declaring a display style. Its decimal mark may differ from the one declared by decimal-mark,
    --   so that is not enforced; but it is still used to interpret ambiguous numbers like 1,000.
  deriving (AmountParseKind -> AmountParseKind -> Bool
(AmountParseKind -> AmountParseKind -> Bool)
-> (AmountParseKind -> AmountParseKind -> Bool)
-> Eq AmountParseKind
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: AmountParseKind -> AmountParseKind -> Bool
== :: AmountParseKind -> AmountParseKind -> Bool
$c/= :: AmountParseKind -> AmountParseKind -> Bool
/= :: AmountParseKind -> AmountParseKind -> Bool
Eq, Int -> AmountParseKind -> String -> String
[AmountParseKind] -> String -> String
AmountParseKind -> String
(Int -> AmountParseKind -> String -> String)
-> (AmountParseKind -> String)
-> ([AmountParseKind] -> String -> String)
-> Show AmountParseKind
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> AmountParseKind -> String -> String
showsPrec :: Int -> AmountParseKind -> String -> String
$cshow :: AmountParseKind -> String
show :: AmountParseKind -> String
$cshowList :: [AmountParseKind] -> String -> String
showList :: [AmountParseKind] -> String -> String
Show)

-- An amount with optional cost, valuation, and/or cost basis, as described above.
amountp' :: AmountParseKind -> JournalParser m Amount
amountp' :: forall (m :: * -> *). AmountParseKind -> JournalParser m Amount
amountp' AmountParseKind
kind =
  -- dbg "amountp'" $
  String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a.
String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall e s (m :: * -> *) a.
MonadParsec e s m =>
String -> m a -> m a
label String
"amount" (StateT
   Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a b. (a -> b) -> a -> b
$ do
  amt <- AmountParseKind
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall (m :: * -> *). AmountParseKind -> JournalParser m Amount
simpleamountp AmountParseKind
kind StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* ParsecT HledgerParseErrorData CommoditySymbol m ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  amountannotationsp amt

-- | A posting amount. Like amountp', except that the amount may also be written as a simple
-- arithmetic expression, which is evaluated to a single amount (see amountexprp) (#2648).
-- Any cost, valuation or lot annotations come after the expression, and apply to its result.
postingamountp :: AmountParseKind -> JournalParser m Amount
postingamountp :: forall (m :: * -> *). AmountParseKind -> JournalParser m Amount
postingamountp AmountParseKind
kind =
  String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a.
String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall e s (m :: * -> *) a.
MonadParsec e s m =>
String -> m a -> m a
label String
"amount" (StateT
   Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a b. (a -> b) -> a -> b
$ do
  amt <- AmountParseKind
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall (m :: * -> *). AmountParseKind -> JournalParser m Amount
amountexprp AmountParseKind
kind StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* ParsecT HledgerParseErrorData CommoditySymbol m ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  amountannotationsp amt

-- | The cost, valuation and lot annotations which may follow an amount
-- (and any spaces after it). Returns the amount with its cost and cost basis set.
amountannotationsp :: Amount -> JournalParser m Amount
amountannotationsp :: forall (m :: * -> *). Amount -> JournalParser m Amount
amountannotationsp Amount
amt = do
  let spaces :: StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
spaces = ParsecT HledgerParseErrorData CommoditySymbol m ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (ParsecT HledgerParseErrorData CommoditySymbol m ()
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ())
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall a b. (a -> b) -> a -> b
$ ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  -- A cost, valuation expression or lot annotation may follow, in any order, each at most once.
  -- Each begins with a distinctive character or two, so look at those and run just the right
  -- parser, stopping at anything else or at a repeated kind. (A permutation parser was used before,
  -- but its failed attempts at the other alternatives made each cost cost ~3x as much as a posting.)
  -- costp, valuationexprp and lotnotep all begin with a parenthesis; costp is tried first,
  -- and backtracks if no @ follows, so that errors within a cost's amount are reported.
  let annotations :: Maybe AmountCost
-> Maybe ()
-> Maybe CostBasis
-> Maybe Day
-> Maybe CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
      Maybe CommoditySymbol)
annotations Maybe AmountCost
mcost Maybe ()
mval Maybe CostBasis
mcb Maybe Day
mdate Maybe CommoditySymbol
mnote = do
        (mc1, mc2) <- ParsecT
  HledgerParseErrorData CommoditySymbol m (Maybe Char, Maybe Char)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe Char, Maybe Char)
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT
  HledgerParseErrorData CommoditySymbol m (Maybe Char, Maybe Char)
forall (m :: * -> *). TextParser m (Maybe Char, Maybe Char)
peekChars2
        case (mc1, mc2) of
          (Just Char
'@', Maybe Char
_)        | Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isNothing Maybe AmountCost
mcost -> Amount -> JournalParser m AmountCost
forall (m :: * -> *). Amount -> JournalParser m AmountCost
costp Amount
amt JournalParser m AmountCost
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> JournalParser m AmountCost
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
spaces          JournalParser m AmountCost
-> (AmountCost
    -> StateT
         Journal
         (ParsecT HledgerParseErrorData CommoditySymbol m)
         (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
          Maybe CommoditySymbol))
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
      Maybe CommoditySymbol)
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> (a
    -> StateT
         Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \AmountCost
x -> Maybe AmountCost
-> Maybe ()
-> Maybe CostBasis
-> Maybe Day
-> Maybe CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
      Maybe CommoditySymbol)
annotations (AmountCost -> Maybe AmountCost
forall a. a -> Maybe a
Just AmountCost
x) Maybe ()
mval Maybe CostBasis
mcb Maybe Day
mdate Maybe CommoditySymbol
mnote
          (Just Char
'(', Just Char
'@') | Maybe AmountCost -> Bool
forall a. Maybe a -> Bool
isNothing Maybe AmountCost
mcost -> Amount -> JournalParser m AmountCost
forall (m :: * -> *). Amount -> JournalParser m AmountCost
costp Amount
amt JournalParser m AmountCost
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> JournalParser m AmountCost
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
spaces          JournalParser m AmountCost
-> (AmountCost
    -> StateT
         Journal
         (ParsecT HledgerParseErrorData CommoditySymbol m)
         (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
          Maybe CommoditySymbol))
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
      Maybe CommoditySymbol)
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> (a
    -> StateT
         Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \AmountCost
x -> Maybe AmountCost
-> Maybe ()
-> Maybe CostBasis
-> Maybe Day
-> Maybe CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
      Maybe CommoditySymbol)
annotations (AmountCost -> Maybe AmountCost
forall a. a -> Maybe a
Just AmountCost
x) Maybe ()
mval Maybe CostBasis
mcb Maybe Day
mdate Maybe CommoditySymbol
mnote
          (Just Char
'(', Just Char
'(') | Maybe () -> Bool
forall a. Maybe a -> Bool
isNothing Maybe ()
mval  -> StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
valuationexprp StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
spaces     StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> (()
    -> StateT
         Journal
         (ParsecT HledgerParseErrorData CommoditySymbol m)
         (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
          Maybe CommoditySymbol))
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
      Maybe CommoditySymbol)
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> (a
    -> StateT
         Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \()
x -> Maybe AmountCost
-> Maybe ()
-> Maybe CostBasis
-> Maybe Day
-> Maybe CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
      Maybe CommoditySymbol)
annotations Maybe AmountCost
mcost (() -> Maybe ()
forall a. a -> Maybe a
Just ()
x) Maybe CostBasis
mcb Maybe Day
mdate Maybe CommoditySymbol
mnote
          (Just Char
'{', Maybe Char
_)        | Maybe CostBasis -> Bool
forall a. Maybe a -> Bool
isNothing Maybe CostBasis
mcb   -> Quantity -> JournalParser m CostBasis
forall (m :: * -> *). Quantity -> JournalParser m CostBasis
lotcostp (Amount -> Quantity
aquantity Amount
amt) JournalParser m CostBasis
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> JournalParser m CostBasis
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
spaces JournalParser m CostBasis
-> (CostBasis
    -> StateT
         Journal
         (ParsecT HledgerParseErrorData CommoditySymbol m)
         (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
          Maybe CommoditySymbol))
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
      Maybe CommoditySymbol)
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> (a
    -> StateT
         Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \CostBasis
x -> Maybe AmountCost
-> Maybe ()
-> Maybe CostBasis
-> Maybe Day
-> Maybe CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
      Maybe CommoditySymbol)
annotations Maybe AmountCost
mcost Maybe ()
mval (CostBasis -> Maybe CostBasis
forall a. a -> Maybe a
Just CostBasis
x) Maybe Day
mdate Maybe CommoditySymbol
mnote
          (Just Char
'[', Maybe Char
_)        | Maybe Day -> Bool
forall a. Maybe a -> Bool
isNothing Maybe Day
mdate -> JournalParser m Day
forall (m :: * -> *). JournalParser m Day
lotdatep JournalParser m Day
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> JournalParser m Day
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
spaces           JournalParser m Day
-> (Day
    -> StateT
         Journal
         (ParsecT HledgerParseErrorData CommoditySymbol m)
         (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
          Maybe CommoditySymbol))
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
      Maybe CommoditySymbol)
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> (a
    -> StateT
         Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \Day
x -> Maybe AmountCost
-> Maybe ()
-> Maybe CostBasis
-> Maybe Day
-> Maybe CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
      Maybe CommoditySymbol)
annotations Maybe AmountCost
mcost Maybe ()
mval Maybe CostBasis
mcb (Day -> Maybe Day
forall a. a -> Maybe a
Just Day
x) Maybe CommoditySymbol
mnote
          (Just Char
'(', Maybe Char
_)        | Maybe CommoditySymbol -> Bool
forall a. Maybe a -> Bool
isNothing Maybe CommoditySymbol
mnote -> JournalParser m CommoditySymbol
forall (m :: * -> *). JournalParser m CommoditySymbol
lotnotep JournalParser m CommoditySymbol
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> JournalParser m CommoditySymbol
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
spaces           JournalParser m CommoditySymbol
-> (CommoditySymbol
    -> StateT
         Journal
         (ParsecT HledgerParseErrorData CommoditySymbol m)
         (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
          Maybe CommoditySymbol))
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
      Maybe CommoditySymbol)
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> (a
    -> StateT
         Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \CommoditySymbol
x -> Maybe AmountCost
-> Maybe ()
-> Maybe CostBasis
-> Maybe Day
-> Maybe CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
      Maybe CommoditySymbol)
annotations Maybe AmountCost
mcost Maybe ()
mval Maybe CostBasis
mcb Maybe Day
mdate (CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
Just CommoditySymbol
x)
          (Maybe Char, Maybe Char)
_ -> (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
 Maybe CommoditySymbol)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
      Maybe CommoditySymbol)
forall a.
a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Maybe AmountCost
mcost, Maybe ()
mval, Maybe CostBasis
mcb, Maybe Day
mdate, Maybe CommoditySymbol
mnote)
  (mcost, _valuationexpr, mlotcb, mlotdate, mlotnote) <- Maybe AmountCost
-> Maybe ()
-> Maybe CostBasis
-> Maybe Day
-> Maybe CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe AmountCost, Maybe (), Maybe CostBasis, Maybe Day,
      Maybe CommoditySymbol)
annotations Maybe AmountCost
forall a. Maybe a
Nothing Maybe ()
forall a. Maybe a
Nothing Maybe CostBasis
forall a. Maybe a
Nothing Maybe Day
forall a. Maybe a
Nothing Maybe CommoditySymbol
forall a. Maybe a
Nothing
  -- Reject mixing consolidated {DATE,...} or {"LABEL",...} with ledger-style [DATE] or (NOTE)
  let isConsolidated = case Maybe CostBasis
mlotcb of
        Just CostBasis
cb | Maybe Day -> Bool
forall a. Maybe a -> Bool
isJust (CostBasis -> Maybe Day
cbDate CostBasis
cb) Bool -> Bool -> Bool
|| Maybe CommoditySymbol -> Bool
forall a. Maybe a -> Bool
isJust (CostBasis -> Maybe CommoditySymbol
cbLabel CostBasis
cb) -> Bool
True
        Maybe CostBasis
_ -> Bool
False
  when (isConsolidated && (isJust mlotdate || isJust mlotnote)) $
    Fail.fail "hledger lot syntax {...} cannot be combined with ledger-style [DATE] or (NOTE)"
  let mcostbasis =
        case (Maybe CostBasis
mlotcb, Maybe Day
mlotdate, Maybe CommoditySymbol
mlotnote) of
          (Maybe CostBasis
Nothing, Maybe Day
Nothing, Maybe CommoditySymbol
Nothing) -> Maybe CostBasis
forall a. Maybe a
Nothing
          (Maybe CostBasis, Maybe Day, Maybe CommoditySymbol)
_ -> CostBasis -> Maybe CostBasis
forall a. a -> Maybe a
Just (CostBasis -> Maybe CostBasis) -> CostBasis -> Maybe CostBasis
forall a b. (a -> b) -> a -> b
$ CostBasis
                 { cbCost :: Maybe Amount
cbCost  = Maybe CostBasis
mlotcb Maybe CostBasis -> (CostBasis -> Maybe Amount) -> Maybe Amount
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= CostBasis -> Maybe Amount
cbCost
                 , cbDate :: Maybe Day
cbDate  = (Maybe CostBasis
mlotcb Maybe CostBasis -> (CostBasis -> Maybe Day) -> Maybe Day
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= CostBasis -> Maybe Day
cbDate) Maybe Day -> Maybe Day -> Maybe Day
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe Day
mlotdate
                 , cbLabel :: Maybe CommoditySymbol
cbLabel = (Maybe CostBasis
mlotcb Maybe CostBasis
-> (CostBasis -> Maybe CommoditySymbol) -> Maybe CommoditySymbol
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= CostBasis -> Maybe CommoditySymbol
cbLabel) Maybe CommoditySymbol
-> Maybe CommoditySymbol -> Maybe CommoditySymbol
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe CommoditySymbol
mlotnote
                 }
  pure $ amt { acost = mcost, acostbasis = mcostbasis }

-- An amount with optional cost, but no cost basis.
amountnobasisp :: JournalParser m Amount
amountnobasisp :: forall (m :: * -> *). JournalParser m Amount
amountnobasisp =
  -- dbg "amountnobasisp" $ 
  String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a.
String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall e s (m :: * -> *) a.
MonadParsec e s m =>
String -> m a -> m a
label String
"amount" (StateT
   Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a b. (a -> b) -> a -> b
$ do
  let spaces :: StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
spaces = ParsecT HledgerParseErrorData CommoditySymbol m ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (ParsecT HledgerParseErrorData CommoditySymbol m ()
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ())
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall a b. (a -> b) -> a -> b
$ ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  amt <- AmountParseKind
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall (m :: * -> *). AmountParseKind -> JournalParser m Amount
simpleamountp AmountParseKind
OrdinaryAmount
  spaces
  mprice <- optional $ costp amt <* spaces
  pure $ amt { acost = mprice }

-- An amount with no cost or cost basis.
-- A commodity-less amount will have the default commodity applied to it, unless it's a multiplier.
simpleamountp :: AmountParseKind -> JournalParser m Amount
simpleamountp :: forall (m :: * -> *). AmountParseKind -> JournalParser m Amount
simpleamountp = Maybe Int -> AmountParseKind -> JournalParser m Amount
forall (m :: * -> *).
Maybe Int -> AmountParseKind -> JournalParser m Amount
simpleamountp' Maybe Int
forall a. Maybe a
Nothing

-- | Like simpleamountp, but when given a nesting depth, parses an operand of an amount expression
-- (see amountexprp), inside that many parentheses. There, an unquoted commodity symbol written
-- after the number can't begin with /, and inside parentheses can't contain ),
-- so that 10 EUR / 4 and (10 EUR + 5 EUR) are read as expressions.
simpleamountp' :: Maybe Int -> AmountParseKind -> JournalParser m Amount
simpleamountp' :: forall (m :: * -> *).
Maybe Int -> AmountParseKind -> JournalParser m Amount
simpleamountp' Maybe Int
mdepth AmountParseKind
kind =
  -- dbg "simpleamountp" $
  do
  sign <- ParsecT
  HledgerParseErrorData CommoditySymbol m (Quantity -> Quantity)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Quantity -> Quantity)
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT
  HledgerParseErrorData CommoditySymbol m (Quantity -> Quantity)
forall a (m :: * -> *). Num a => TextParser m (a -> a)
signp
  -- A symbol-first amount starts with a quote or a simple commodity symbol character;
  -- anything else (a digit or decimal mark, usually) is parsed as a number-first amount.
  -- Checking cheaply avoids a failed parse attempt for the latter, the common case.
  mc <- lift peekChar
  if maybe False startsCommoditySymbol mc then leftsymbolamountp sign else rightornosymbolamountp sign

  where
  startsCommoditySymbol :: Char -> Bool
startsCommoditySymbol Char
c = Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'"' Bool -> Bool -> Bool
|| Bool -> Bool
not (Char -> Bool
isNonsimpleCommodityChar Char
c)

  isoperand :: Bool
isoperand = Maybe Int -> Bool
forall a. Maybe a -> Bool
isJust Maybe Int
mdepth
  inparens :: Bool
inparens  = Bool -> (Int -> Bool) -> Maybe Int -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
0) Maybe Int
mdepth
  rightsymbolp :: TextParser n CommoditySymbol
  rightsymbolp :: forall (m :: * -> *). TextParser m CommoditySymbol
rightsymbolp
    | Bool
inparens  = TextParser n CommoditySymbol
forall (m :: * -> *). TextParser m CommoditySymbol
quotedcommoditysymbolp TextParser n CommoditySymbol
-> TextParser n CommoditySymbol -> TextParser n CommoditySymbol
forall a.
ParsecT HledgerParseErrorData CommoditySymbol n a
-> ParsecT HledgerParseErrorData CommoditySymbol n a
-> ParsecT HledgerParseErrorData CommoditySymbol n a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe String
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol n (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhile1P Maybe String
forall a. Maybe a
Nothing (\Token CommoditySymbol
c -> Bool -> Bool
not (Char -> Bool
isNonsimpleCommodityChar Char
Token CommoditySymbol
c) Bool -> Bool -> Bool
&& Char
Token CommoditySymbol
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
')')
    | Bool
otherwise = TextParser n CommoditySymbol
forall (m :: * -> *). TextParser m CommoditySymbol
commoditysymbolp

  -- An amount with commodity symbol on the left.
  leftsymbolamountp :: (Decimal -> Decimal) -> JournalParser m Amount
  leftsymbolamountp :: forall (m :: * -> *).
(Quantity -> Quantity) -> JournalParser m Amount
leftsymbolamountp Quantity -> Quantity
sign = String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a.
String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall e s (m :: * -> *) a.
MonadParsec e s m =>
String -> m a -> m a
label String
"amount" (StateT
   Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a b. (a -> b) -> a -> b
$ do
    c <- CommoditySymbol -> JournalParser m CommoditySymbol
forall (m :: * -> *).
CommoditySymbol -> JournalParser m CommoditySymbol
shareText (CommoditySymbol -> JournalParser m CommoditySymbol)
-> JournalParser m CommoditySymbol
-> JournalParser m CommoditySymbol
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
-> JournalParser m CommoditySymbol
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
forall (m :: * -> *). TextParser m CommoditySymbol
commoditysymbolp
    mdecmarkStyle <- getDecimalMarkStyle
    mcommodityStyle <- getAmountStyle c
    -- XXX amounts of this commodity in periodic transaction rules and auto posting rules ? #1461
    let suggestedStyle = Maybe AmountStyle
mdecmarkStyle Maybe AmountStyle -> Maybe AmountStyle -> Maybe AmountStyle
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe AmountStyle
mcommodityStyle
    commodityspaced <- lift skipNonNewlineSpaces'
    sign2 <- lift $ signp
    offBeforeNum <- getOffset
    ambiguousRawNum <- lift rawnumberp
    mExponent <- lift optionalexponentp
    offAfterNum <- getOffset
    let numRegion = (Int
offBeforeNum, Int
offAfterNum)
    (q,prec,mdec,mgrps) <- interpretNumber numRegion suggestedStyle ambiguousRawNum mExponent
    s <- shareAmountStyle amountstyle{ascommodityside=L, ascommodityspaced=commodityspaced, asprecision=prec, asdecimalmark=mdec, asdigitgroups=mgrps}
    return nullamt{acommodity=c, aquantity=sign (sign2 q), astyle=s, acost=Nothing}

  -- An amount with commodity symbol on the right or no commodity symbol.
  -- A no-symbol amount will have the default commodity applied to it
  -- unless we are parsing a multiplier amount (*AMT).
  rightornosymbolamountp :: (Decimal -> Decimal) -> JournalParser m Amount
  rightornosymbolamountp :: forall (m :: * -> *).
(Quantity -> Quantity) -> JournalParser m Amount
rightornosymbolamountp Quantity -> Quantity
sign = String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a.
String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall e s (m :: * -> *) a.
MonadParsec e s m =>
String -> m a -> m a
label String
"amount" (StateT
   Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a b. (a -> b) -> a -> b
$ do
    offBeforeNum <- StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
    ambiguousRawNum <- lift rawnumberp
    mExponent <- lift optionalexponentp
    offAfterNum <- getOffset
    let numRegion = (Int
offBeforeNum, Int
offAfterNum)
    -- A commodity symbol may follow the number, possibly after spaces; check cheaply first.
    (_, mnext) <- lift peekAfterSpaces
    mSpaceAndCommodity <- lift $
      if maybe False (\Char
c -> Char -> Bool
startsCommoditySymbol Char
c Bool -> Bool -> Bool
&& Bool -> Bool
not (Bool
isoperand Bool -> Bool -> Bool
&& Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'/') Bool -> Bool -> Bool
&& Bool -> Bool
not (Bool
inparens Bool -> Bool -> Bool
&& Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
')')) mnext
      then optional $ try $ (,) <$> skipNonNewlineSpaces' <*> rightsymbolp
      else pure Nothing
    case mSpaceAndCommodity of
      -- right symbol amount
      Just (Bool
commodityspaced, CommoditySymbol
c0) -> do
        c <- CommoditySymbol -> JournalParser m CommoditySymbol
forall (m :: * -> *).
CommoditySymbol -> JournalParser m CommoditySymbol
shareText CommoditySymbol
c0
        mdecmarkStyle <- getDecimalMarkStyle
        mcommodityStyle <- getAmountStyle c
        -- XXX amounts of this commodity in periodic transaction rules and auto posting rules ? #1461
        let msuggestedStyle = Maybe AmountStyle
mdecmarkStyle Maybe AmountStyle -> Maybe AmountStyle -> Maybe AmountStyle
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe AmountStyle
mcommodityStyle
        (q,prec,mdec,mgrps) <- interpretNumber numRegion msuggestedStyle ambiguousRawNum mExponent
        s <- shareAmountStyle amountstyle{ascommodityside=R, ascommodityspaced=commodityspaced, asprecision=prec, asdecimalmark=mdec, asdigitgroups=mgrps}
        return nullamt{acommodity=c, aquantity=sign q, astyle=s, acost=Nothing}
      -- no symbol amount
      Maybe (Bool, CommoditySymbol)
Nothing -> do
        -- look for a number style to use when parsing, based on
        -- these things we've already parsed, in this order of preference:
        mdecmarkStyle   <- JournalParser m (Maybe AmountStyle)
forall (m :: * -> *). JournalParser m (Maybe AmountStyle)
getDecimalMarkStyle   -- a decimal-mark CSV rule
        mcommodityStyle <- getAmountStyle ""     -- a commodity directive for the no-symbol commodity
        mdefaultStyle   <- getDefaultAmountStyle -- a D default commodity directive
        -- XXX no-symbol amounts in periodic transaction rules and auto posting rules ? #1461
        let msuggestedStyle = Maybe AmountStyle
mdecmarkStyle Maybe AmountStyle -> Maybe AmountStyle -> Maybe AmountStyle
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe AmountStyle
mcommodityStyle Maybe AmountStyle -> Maybe AmountStyle -> Maybe AmountStyle
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe AmountStyle
mdefaultStyle
        (q,prec,mdec,mgrps) <- interpretNumber numRegion msuggestedStyle ambiguousRawNum mExponent
        -- if a default commodity has been set, apply it and its style to this amount
        -- (unless it's a multiplier in an automated posting);
        -- the number's own decimal mark and digit groups are kept where the default style has none
        defcs <- getDefaultCommodityAndStyle
        let (c,s) = case defcs of
              Just (CommoditySymbol
defc,AmountStyle
defs) | AmountParseKind
kind AmountParseKind -> AmountParseKind -> Bool
forall a. Eq a => a -> a -> Bool
/= AmountParseKind
MultiplierAmount ->
                (CommoditySymbol
defc, AmountStyle
defs{asprecision=max (asprecision defs) prec
                           ,asdecimalmark=asdecimalmark defs <|> mdec
                           ,asdigitgroups=asdigitgroups defs <|> mgrps})
              Maybe (CommoditySymbol, AmountStyle)
_ -> (CommoditySymbol
"", AmountStyle
amountstyle{asprecision=prec, asdecimalmark=mdec, asdigitgroups=mgrps})
        s' <- shareAmountStyle s
        return nullamt{acommodity=c, aquantity=sign q, astyle=s', acost=Nothing}

  -- For reducing code duplication. Doesn't parse anything. Has the type
  -- of a parser only in order to read the parse state and throw parse errors (for convenience).
  interpretNumber
    :: (Int, Int) -- offsets
    -> Maybe AmountStyle
    -> Either AmbiguousNumber RawNumber
    -> Maybe Integer
    -> JournalParser m (Quantity, AmountPrecision, Maybe Char, Maybe DigitGroupStyle)
  interpretNumber :: forall (m :: * -> *).
(Int, Int)
-> Maybe AmountStyle
-> Either AmbiguousNumber RawNumber
-> Maybe Integer
-> JournalParser
     m (Quantity, AmountPrecision, Maybe Char, Maybe DigitGroupStyle)
interpretNumber (Int, Int)
posRegion Maybe AmountStyle
msuggestedStyle Either AmbiguousNumber RawNumber
ambiguousNum Maybe Integer
mExp = do
    -- The decimal mark declared by a decimal-mark directive or CSV rule, which all numbers must use,
    -- except those declaring a display style.
    mrequiredmark <- if AmountParseKind
kind AmountParseKind -> AmountParseKind -> Bool
forall a. Eq a => a -> a -> Bool
== AmountParseKind
StyleAmount then Maybe Char
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe Char)
forall a.
a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe Char
forall a. Maybe a
Nothing else Journal -> Maybe Char
jparsedecimalmark (Journal -> Maybe Char)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Journal
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe Char)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Journal
forall s (m :: * -> *). MonadState s m => m s
get
    case interpretRawNumber mrequiredmark msuggestedStyle ambiguousNum mExp of
      Left String
errMsg -> HledgerParseErrorData
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Quantity, AmountPrecision, Maybe Char, Maybe DigitGroupStyle)
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData CommoditySymbol m)
      (Quantity, AmountPrecision, Maybe Char, Maybe DigitGroupStyle))
-> HledgerParseErrorData
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Quantity, AmountPrecision, Maybe Char, Maybe DigitGroupStyle)
forall a b. (a -> b) -> a -> b
$
                       (Int -> Int -> String -> HledgerParseErrorData)
-> (Int, Int) -> String -> HledgerParseErrorData
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry Int -> Int -> String -> HledgerParseErrorData
parseErrorAtRegion (Int, Int)
posRegion String
errMsg
      Right (Quantity
q,Word8
p,Maybe Char
d,Maybe DigitGroupStyle
g) -> (Quantity, AmountPrecision, Maybe Char, Maybe DigitGroupStyle)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Quantity, AmountPrecision, Maybe Char, Maybe DigitGroupStyle)
forall a.
a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Quantity
q, Word8 -> AmountPrecision
Precision Word8
p, Maybe Char
d, Maybe DigitGroupStyle
g)

-- | A simple arithmetic expression involving amounts, evaluated to a single amount (#2648). Eg:
--
-- > $-21.60 + $-27.68 + $-5.03
-- > 10 EUR - 2.50 EUR
-- > $47.97 * 0.05
-- > ($200 + $15.75) / 3
-- > $10 + 5
-- > 1 / 1.14 EUR
--
-- The operands are simple amounts (see simpleamountp), or parenthesised expressions.
-- The operators are + - * and /. * and / are applied before + and -; otherwise, left to right.
-- Spaces around operators are optional, except before a / which follows a commodity symbol (10 EUR / 4).
-- A - or + directly before an operand or parenthesis is its sign.
--
-- + and - combine amounts of the same commodity; a number with no commodity symbol takes the
-- other side's commodity. The result has the larger of their precisions.
-- * and / take a plain number (with no commodity symbol) on at least one side.
-- Their result has the commodity and display style of the other side's amount
-- (with two plain numbers, the left one). So 1 / 1.14 EUR is 0.877.. EUR, as in Ledger.
-- So a result's precision is the most decimal places written in the amounts it was calculated from
-- (not counting plain numbers used with * or /).
-- The results of * and / are exact here, and so may have more decimal places than their precision.
-- They are rounded once the whole entry has been read, since the number of decimal places
-- depends on the other amounts in the entry (see transactionRoundCalculatedAmounts in
-- Hledger.Read.JournalReader). In a cost, they are kept exact (see costp).
-- Anything else (eg adding different commodities, or dividing by zero) is a parse error.
--
-- The operands are parsed without applying the default commodity (D), so that a number can
-- take its commodity from the expression; if the result has no commodity, the default commodity
-- is applied to it, as for a simple amount (unless it's a multiplier amount).
--
-- An amount with no operators is parsed the same as by simpleamountp.
amountexprp :: AmountParseKind -> JournalParser m Amount
amountexprp :: forall (m :: * -> *). AmountParseKind -> JournalParser m Amount
amountexprp AmountParseKind
kind = do
  a <- Int
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
sump (Int
0 :: Int)
  if kind /= MultiplierAmount && T.null (acommodity a) then withDefaultCommodity a else pure a
  where
    spaces :: StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
spaces = ParsecT HledgerParseErrorData CommoditySymbol m ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces

    -- if a default commodity has been set, apply it and its style (like simpleamountp)
    withDefaultCommodity :: Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
withDefaultCommodity Amount
a = do
      defcs <- JournalParser m (Maybe (CommoditySymbol, AmountStyle))
forall (m :: * -> *).
JournalParser m (Maybe (CommoditySymbol, AmountStyle))
getDefaultCommodityAndStyle
      case defcs of
        Just (CommoditySymbol
defc, AmountStyle
defs) -> do
          s <- AmountStyle -> JournalParser m AmountStyle
forall (m :: * -> *). AmountStyle -> JournalParser m AmountStyle
shareAmountStyle AmountStyle
defs{asprecision = max (asprecision defs) (asprecision $ astyle a)
                                    ,asdecimalmark = asdecimalmark defs <|> asdecimalmark (astyle a)
                                    ,asdigitgroups = asdigitgroups defs <|> asdigitgroups (astyle a)}
          pure a{acommodity = defc, astyle = s}
        Maybe (CommoditySymbol, AmountStyle)
Nothing -> Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a.
a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Amount
a

    -- a sum or difference of products (depth is the number of enclosing parentheses)
    sump :: Int
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
sump Int
depth = Int
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
productp Int
depth StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> (Amount
    -> StateT
         Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> (a
    -> StateT
         Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Int
-> Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
sumrestp Int
depth
    sumrestp :: Int
-> Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
sumrestp Int
depth Amount
a = do
      mop <- ParsecT HledgerParseErrorData CommoditySymbol m (Maybe Char)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe Char)
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData CommoditySymbol m (Maybe Char)
forall (m :: * -> *). TextParser m (Maybe Char)
peekChar
      case mop of
        Just Char
op | Char
op Char -> String -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Char
'+',Char
'-'] -> do
          off <- StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
          b <- char op *> spaces *> productp depth
          off' <- getOffset
          c <- addAmounts (off, off') op a b
          sumrestp depth c
        Maybe Char
_ -> Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a.
a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Amount
a

    -- a product or quotient of factors
    productp :: Int
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
productp Int
depth = Int
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
factorp Int
depth StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> (Amount
    -> StateT
         Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> (a
    -> StateT
         Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Int
-> Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
productrestp Int
depth
    productrestp :: Int
-> Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
productrestp Int
depth Amount
a = do
      mop <- ParsecT HledgerParseErrorData CommoditySymbol m (Maybe Char)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe Char)
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData CommoditySymbol m (Maybe Char)
forall (m :: * -> *). TextParser m (Maybe Char)
peekChar
      case mop of
        Just Char
op | Char
op Char -> String -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Char
'*',Char
'/'] -> do
          off <- StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
          b <- char op *> spaces *> factorp depth
          off' <- getOffset
          c <- multiplyAmounts (off, off') op a b
          productrestp depth c
        Maybe Char
_ -> Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a.
a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Amount
a

    -- a simple amount, or a parenthesised expression with an optional sign; and any following spaces.
    -- (Look ahead cheaply, so that ordinary amounts are parsed without backtracking.)
    -- Operands are parsed as multiplier amounts, ie without applying the default commodity.
    factorp :: Int
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
factorp Int
depth = do
      s <- StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol m)
  CommoditySymbol
forall e s (m :: * -> *). MonadParsec e s m => m s
getInput
      case T.uncons s of
        Just (Char
'(', CommoditySymbol
_) -> Int
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
parensp Int
depth
        Just (Char
c, CommoditySymbol
rest) | Char
c Char -> String -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Char
'-',Char
'+'], CommoditySymbol
"(" CommoditySymbol -> CommoditySymbol -> Bool
`T.isPrefixOf` (Char -> Bool) -> CommoditySymbol -> CommoditySymbol
T.dropWhile Char -> Bool
isNonNewlineSpace CommoditySymbol
rest -> do
          a <- StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol m)
  (Token CommoditySymbol)
forall e s (m :: * -> *). MonadParsec e s m => m (Token s)
anySingle StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol m)
  (Token CommoditySymbol)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
spaces StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> Int
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
parensp Int
depth
          pure $ if c == '-' then a{aquantity = negate $ aquantity a} else a
        Maybe (Char, CommoditySymbol)
_ -> do
          a <- Maybe Int
-> AmountParseKind
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall (m :: * -> *).
Maybe Int -> AmountParseKind -> JournalParser m Amount
simpleamountp' (Int -> Maybe Int
forall a. a -> Maybe a
Just Int
depth) AmountParseKind
MultiplierAmount
          -- In 10 EUR/4, the commodity symbol is read as EUR/. Explain that, rather than just
          -- reporting the unexpected 4. (A number can't follow an amount, so this is safe.)
          -- The symbol is checked first, so that the usual case needs no lookahead.
          when (ascommodityside (astyle a) == R && "/" `T.isSuffixOf` acommodity a) $ do
            off <- getOffset
            (spaced, mnext) <- lift peekAfterSpaces
            let looksdivided = case Maybe Char
mnext of
                  Just Char
c | Char -> Bool
isDigit Char
c -> Bool
True
                         | Bool -> Bool
not Bool
spaced -> Char
c Char -> String -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Char
'(',Char
'.',Char
'-',Char
'+']
                  Maybe Char
_ -> Bool
False
            when looksdivided $
              customFailure $ parseErrorAtRegion (off-1) off $
                "this / is read as part of the commodity symbol " ++ T.unpack (acommodity a)
                ++ "; to divide, write a space before it (eg 10 EUR / 4)"
          a <$ spaces

    parensp :: Int
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
parensp Int
depth = Token CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'(' StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
spaces StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> Int
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
sump (Int
depthInt -> Int -> Int
forall a. Num a => a -> a -> a
+Int
1) StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* (Token CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
')' StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
-> String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"closing parenthesis") StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
spaces

    exprError :: (Int, Int) -> String -> m a
exprError (Int
off, Int
off') String
msg = HledgerParseErrorData -> m a
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData -> m a) -> HledgerParseErrorData -> m a
forall a b. (a -> b) -> a -> b
$ Int -> Int -> String -> HledgerParseErrorData
parseErrorAtRegion Int
off Int
off' String
msg

    hascommodity :: Amount -> Bool
hascommodity = Bool -> Bool
not (Bool -> Bool) -> (Amount -> Bool) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. CommoditySymbol -> Bool
T.null (CommoditySymbol -> Bool)
-> (Amount -> CommoditySymbol) -> Amount -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> CommoditySymbol
acommodity

    addAmounts :: (Int, Int)
-> Char
-> Amount
-> Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
addAmounts (Int, Int)
reg Char
op Amount
a Amount
b
      | Amount -> Bool
hascommodity Amount
a Bool -> Bool -> Bool
&& Amount -> Bool
hascommodity Amount
b Bool -> Bool -> Bool
&& Amount -> CommoditySymbol
acommodity Amount
a CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= Amount -> CommoditySymbol
acommodity Amount
b = (Int, Int)
-> String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall {s} {m :: * -> *} {a}.
MonadParsec HledgerParseErrorData s m =>
(Int, Int) -> String -> m a
exprError (Int, Int)
reg (String
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount)
-> String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a b. (a -> b) -> a -> b
$
          String
"can't " String -> String -> String
forall a. [a] -> [a] -> [a]
++ (if Char
op Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'+' then String
"add" else String
"subtract") String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" amounts with different commodities ("
          String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack (Amount -> CommoditySymbol
acommodity Amount
a) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
" and " String -> String -> String
forall a. [a] -> [a] -> [a]
++ CommoditySymbol -> String
T.unpack (Amount -> CommoditySymbol
acommodity Amount
b) String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
")"
      | Bool
otherwise = do
          -- a number with no commodity takes the other side's commodity and style
          let a' :: Amount
a' = if Amount -> Bool
hascommodity Amount
a Bool -> Bool -> Bool
|| Bool -> Bool
not (Amount -> Bool
hascommodity Amount
b) then Amount
a else Amount
b
              q :: Quantity
q = (if Char
op Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'+' then Quantity -> Quantity -> Quantity
forall a. Num a => a -> a -> a
(+) else (-)) (Amount -> Quantity
aquantity Amount
a) (Amount -> Quantity
aquantity Amount
b)
          s <- AmountStyle -> JournalParser m AmountStyle
forall (m :: * -> *). AmountStyle -> JournalParser m AmountStyle
shareAmountStyle (Amount -> AmountStyle
astyle Amount
a'){asprecision = max (asprecision $ astyle a) (asprecision $ astyle b)}
          pure a'{aquantity = q, astyle = s}

    multiplyAmounts :: (Int, Int) -> Char -> Amount -> Amount -> m Amount
multiplyAmounts (Int, Int)
reg Char
op Amount
a Amount
b
      | Char
op Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'*' Bool -> Bool -> Bool
&& Amount -> Bool
hascommodity Amount
a Bool -> Bool -> Bool
&& Amount -> Bool
hascommodity Amount
b = (Int, Int) -> String -> m Amount
forall {s} {m :: * -> *} {a}.
MonadParsec HledgerParseErrorData s m =>
(Int, Int) -> String -> m a
exprError (Int, Int)
reg
          String
"can't multiply two amounts with commodity symbols; one side of * should be a plain number"
      | Char
op Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'/' Bool -> Bool -> Bool
&& Amount -> Bool
hascommodity Amount
a Bool -> Bool -> Bool
&& Amount -> Bool
hascommodity Amount
b = (Int, Int) -> String -> m Amount
forall {s} {m :: * -> *} {a}.
MonadParsec HledgerParseErrorData s m =>
(Int, Int) -> String -> m a
exprError (Int, Int)
reg
          String
"can't divide two amounts with commodity symbols; one side of / should be a plain number"
      | Char
op Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'/' Bool -> Bool -> Bool
&& Amount -> Quantity
aquantity Amount
b Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Quantity
0 = (Int, Int) -> String -> m Amount
forall {s} {m :: * -> *} {a}.
MonadParsec HledgerParseErrorData s m =>
(Int, Int) -> String -> m a
exprError (Int, Int)
reg String
"can't divide by zero"
      | Char
op Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'*' Bool -> Bool -> Bool
&& Amount -> Bool
hascommodity Amount
b = Amount -> m Amount
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Amount -> m Amount) -> Amount -> m Amount
forall a b. (a -> b) -> a -> b
$ Quantity -> Amount -> Amount
multiplyAmount (Amount -> Quantity
aquantity Amount
a) Amount
b
      | Char
op Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'*' = Amount -> m Amount
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Amount -> m Amount) -> Amount -> m Amount
forall a b. (a -> b) -> a -> b
$ Quantity -> Amount -> Amount
multiplyAmount (Amount -> Quantity
aquantity Amount
b) Amount
a
      -- a number divided by an amount, eg 1 / 1.14 EUR (inverting a rate), is in the amount's commodity, as in Ledger
      | Amount -> Bool
hascommodity Amount
b = Amount -> m Amount
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Amount
b{aquantity = aquantity a / aquantity b}
      | Bool
otherwise = Amount -> m Amount
forall a. a -> m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Amount -> m Amount) -> Amount -> m Amount
forall a b. (a -> b) -> a -> b
$ Quantity -> Amount -> Amount
divideAmount (Amount -> Quantity
aquantity Amount
b) Amount
a

-- | Try to parse a single-commodity amount from a string
parseamount :: String -> Either HledgerParseErrors Amount
parseamount :: String -> Either HledgerParseErrors Amount
parseamount String
s = Parsec HledgerParseErrorData CommoditySymbol Amount
-> String -> CommoditySymbol -> Either HledgerParseErrors Amount
forall e s a.
Parsec e s a -> String -> s -> Either (ParseErrorBundle s e) a
runParser (StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol Identity)
  Amount
-> Journal -> Parsec HledgerParseErrorData CommoditySymbol Amount
forall (m :: * -> *) s a. Monad m => StateT s m a -> s -> m a
evalStateT (StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol Identity)
  Amount
forall (m :: * -> *). JournalParser m Amount
amountp StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol Identity)
  Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol Identity) ()
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol Identity)
     Amount
forall a b.
StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol Identity) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol Identity) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol Identity) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol Identity) ()
forall e s (m :: * -> *). MonadParsec e s m => m ()
eof) Journal
nulljournal) String
"" (String -> CommoditySymbol
T.pack String
s)

-- | Try to parse a single-commodity amount from a string, using these commodities' styles to read an ambiguous number
-- (eg 10.000 EUR is ten thousand if EUR's decimal mark is a comma, or if it has no decimal places).
parseamountWithStyles :: M.Map CommoditySymbol AmountStyle -> String -> Either HledgerParseErrors Amount
parseamountWithStyles :: Map CommoditySymbol AmountStyle
-> String -> Either HledgerParseErrors Amount
parseamountWithStyles Map CommoditySymbol AmountStyle
styles String
s = Parsec HledgerParseErrorData CommoditySymbol Amount
-> String -> CommoditySymbol -> Either HledgerParseErrors Amount
forall e s a.
Parsec e s a -> String -> s -> Either (ParseErrorBundle s e) a
runParser (StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol Identity)
  Amount
-> Journal -> Parsec HledgerParseErrorData CommoditySymbol Amount
forall (m :: * -> *) s a. Monad m => StateT s m a -> s -> m a
evalStateT (StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol Identity)
  Amount
forall (m :: * -> *). JournalParser m Amount
amountp StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol Identity)
  Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol Identity) ()
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol Identity)
     Amount
forall a b.
StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol Identity) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol Identity) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol Identity) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol Identity) ()
forall e s (m :: * -> *). MonadParsec e s m => m ()
eof) Journal
j) String
"" (String -> CommoditySymbol
T.pack String
s)
  where
    j :: Journal
j = Journal
nulljournal{jdeclaredcommodities = M.mapWithKey commodity styles}
    commodity :: CommoditySymbol -> AmountStyle -> Commodity
commodity CommoditySymbol
c AmountStyle
st = Commodity{csymbol :: CommoditySymbol
csymbol=CommoditySymbol
c, cformat :: Maybe AmountStyle
cformat=AmountStyle -> Maybe AmountStyle
forall a. a -> Maybe a
Just AmountStyle
st, ccomment :: CommoditySymbol
ccomment=CommoditySymbol
"", ctags :: [(CommoditySymbol, CommoditySymbol)]
ctags=[], caliases :: [(Amount, SourcePos)]
caliases=[], csourcepos :: SourcePos
csourcepos=String -> SourcePos
initialPos String
""}

-- | Parse a single-commodity amount from a string, or get an error.
parseamount' :: String -> Amount
parseamount' :: String -> Amount
parseamount' String
s =
  case String -> Either HledgerParseErrors Amount
parseamount String
s of
    Right Amount
amt -> Amount
amt
    Left HledgerParseErrors
err  -> String -> Amount
forall {b}. String -> b
error' (String -> Amount) -> String -> Amount
forall a b. (a -> b) -> a -> b
$ HledgerParseErrors -> String
forall a. Show a => a -> String
show HledgerParseErrors
err  -- PARTIAL: XXX should throwError

-- | Like parseamount', but returns a MixedAmount.
parsemixedamount :: String -> Either HledgerParseErrors MixedAmount
parsemixedamount :: String -> Either HledgerParseErrors MixedAmount
parsemixedamount = (Amount -> MixedAmount)
-> Either HledgerParseErrors Amount
-> Either HledgerParseErrors MixedAmount
forall a b.
(a -> b)
-> Either HledgerParseErrors a -> Either HledgerParseErrors b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Amount -> MixedAmount
mixedAmount (Either HledgerParseErrors Amount
 -> Either HledgerParseErrors MixedAmount)
-> (String -> Either HledgerParseErrors Amount)
-> String
-> Either HledgerParseErrors MixedAmount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Either HledgerParseErrors Amount
parseamount

-- | Like parseamount', but returns a MixedAmount.
parsemixedamount' :: String -> MixedAmount
parsemixedamount' :: String -> MixedAmount
parsemixedamount' = Amount -> MixedAmount
mixedAmount (Amount -> MixedAmount)
-> (String -> Amount) -> String -> MixedAmount
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Amount
parseamount'

-- | Parse a minus or plus sign followed by zero or more spaces,
-- or nothing, returning a function that negates or does nothing.
signp :: Num a => TextParser m (a -> a)
signp :: forall a (m :: * -> *). Num a => TextParser m (a -> a)
signp = do
  -- check the next character first: most amounts have no sign
  mc <- TextParser m (Maybe Char)
forall (m :: * -> *). TextParser m (Maybe Char)
peekChar
  case mc of
    Just Char
'-' -> a -> a
forall a. Num a => a -> a
negate (a -> a)
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m (a -> a)
forall a b.
a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ (Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'-' ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces)
    Just Char
'+' -> a -> a
forall a. a -> a
id     (a -> a)
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m (a -> a)
forall a b.
a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ (Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'+' ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces)
    Maybe Char
_        -> (a -> a)
-> ParsecT HledgerParseErrorData CommoditySymbol m (a -> a)
forall a. a -> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure a -> a
forall a. a -> a
id

commoditysymbolp :: TextParser m CommoditySymbol
commoditysymbolp :: forall (m :: * -> *). TextParser m CommoditySymbol
commoditysymbolp = (do
  mc <- TextParser m (Maybe Char)
forall (m :: * -> *). TextParser m (Maybe Char)
peekChar
  if mc == Just '"' then quotedcommoditysymbolp else simplecommoditysymbolp
  ) TextParser m CommoditySymbol
-> String -> TextParser m CommoditySymbol
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"commodity symbol"

quotedcommoditysymbolp :: TextParser m CommoditySymbol
quotedcommoditysymbolp :: forall (m :: * -> *). TextParser m CommoditySymbol
quotedcommoditysymbolp =
  ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
forall (m :: * -> *) open close a.
Applicative m =>
m open -> m close -> m a -> m a
between (Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'"') (Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'"') (ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
 -> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol)
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
forall a b. (a -> b) -> a -> b
$ Maybe String
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhileP Maybe String
forall a. Maybe a
Nothing Char -> Bool
Token CommoditySymbol -> Bool
f
  where f :: Char -> Bool
f Char
c = Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
';' Bool -> Bool -> Bool
&& Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\n' Bool -> Bool -> Bool
&& Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\"'

simplecommoditysymbolp :: TextParser m CommoditySymbol
simplecommoditysymbolp :: forall (m :: * -> *). TextParser m CommoditySymbol
simplecommoditysymbolp = Maybe String
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhile1P Maybe String
forall a. Maybe a
Nothing (Bool -> Bool
not (Bool -> Bool) -> (Char -> Bool) -> Char -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> Bool
isNonsimpleCommodityChar)

-- | Ledger-style cost notation:
-- @ UNITAMT, @@ TOTALAMT, (@) UNITAMT, or (@@) TOTALAMT. The () are ignored.
-- The amount can be an amount expression (see amountexprp) (#2857).
costp :: Amount -> JournalParser m AmountCost
costp :: forall (m :: * -> *). Amount -> JournalParser m AmountCost
costp Amount
baseAmt =
  -- dbg "costp" $
  String
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     AmountCost
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     AmountCost
forall a.
String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall e s (m :: * -> *) a.
MonadParsec e s m =>
String -> m a -> m a
label String
"transaction price" (StateT
   Journal
   (ParsecT HledgerParseErrorData CommoditySymbol m)
   AmountCost
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData CommoditySymbol m)
      AmountCost)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     AmountCost
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     AmountCost
forall a b. (a -> b) -> a -> b
$ do
  -- https://www.ledger-cli.org/3.0/doc/ledger3.html#Virtual-posting-costs
  -- (optional parts are checked for cheaply before parsing, as usual)
  -- ( might begin something else, like a valuation expression or lot note, so backtrack if no @ follows
  parenthesised <- (Maybe Char -> Maybe Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'(') (Maybe Char -> Bool)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe Char)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ParsecT HledgerParseErrorData CommoditySymbol m (Maybe Char)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe Char)
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData CommoditySymbol m (Maybe Char)
forall (m :: * -> *). TextParser m (Maybe Char)
peekChar
  if parenthesised then void $ try $ string "(@" else void $ char '@'
  totalCost <- (== Just '@') <$> lift peekChar
  when totalCost $ void $ char '@'
  when parenthesised $ void $ char ')'

  lift skipNonNewlineSpaces
  priceAmount <- showCalculatedFully <$> amountexprp OrdinaryAmount -- <?> "unpriced amount (specifying a price)"

  let amtsign' = Quantity -> Quantity
forall a. Num a => a -> a
signum (Quantity -> Quantity) -> Quantity -> Quantity
forall a b. (a -> b) -> a -> b
$ Amount -> Quantity
aquantity Amount
baseAmt
      amtsign  = if Quantity
amtsign' Quantity -> Quantity -> Bool
forall a. Eq a => a -> a -> Bool
== Quantity
0 then Quantity
1 else Quantity
amtsign'

  pure $ if totalCost
            then TotalCost priceAmount{aquantity=amtsign * aquantity priceAmount}
            else UnitCost  priceAmount
  where
    -- A cost calculated with * or / in an amount expression has more decimal places than were written.
    -- Unlike a posting amount, it is kept exact (not rounded), so that eg (1 / 1.14 EUR) works as a rate.
    -- Show it exactly, or if it's a repeating decimal, with 8 decimal places (or more if written).
    showCalculatedFully :: Amount -> Amount
showCalculatedFully Amount
a
      | Amount -> Word8
amountInternalPrecision Amount
a Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
> Amount -> Word8
amountDisplayPrecision Amount
a =
          Word8 -> Amount -> Amount
amountSetPrecisionMin (Amount -> Word8
amountDisplayPrecision Amount
a) (Amount -> Amount) -> Amount -> Amount
forall a b. (a -> b) -> a -> b
$ Maybe Word8 -> Amount -> Amount
amountSetFullPrecisionUpTo Maybe Word8
forall a. Maybe a
Nothing Amount
a
      | Bool
otherwise = Amount
a

-- | A valuation function or value can be written in double parentheses after an amount.
valuationexprp :: JournalParser m ()
valuationexprp :: forall {m :: * -> *}.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
valuationexprp =
  -- dbg "valuationexprp" $
  String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall a.
String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall e s (m :: * -> *) a.
MonadParsec e s m =>
String -> m a -> m a
label String
"valuation expression" (StateT
   Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ())
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall a b. (a -> b) -> a -> b
$ do
  Tokens CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens CommoditySymbol
"(("
  _ <- CommoditySymbol -> CommoditySymbol
T.strip (CommoditySymbol -> CommoditySymbol)
-> (String -> CommoditySymbol) -> String -> CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> CommoditySymbol
T.pack (String -> CommoditySymbol)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) String
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) String
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
many (StateT
   Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) String)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) String
forall a b. (a -> b) -> a -> b
$ [Token CommoditySymbol]
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Token CommoditySymbol)
forall (f :: * -> *) e s (m :: * -> *).
(Foldable f, MonadParsec e s m) =>
f (Token s) -> m (Token s)
noneOf [Char
')',Char
'\n'])  -- XXX other line endings ?
  string "))"
  return ()

balanceassertionp :: JournalParser m BalanceAssertion
balanceassertionp :: forall (m :: * -> *). JournalParser m BalanceAssertion
balanceassertionp = do
  sourcepos <- JournalParser m SourcePos
forall (m :: * -> *). JournalParser m SourcePos
getSourcePos'
  char '='
  istotal <- (== Just '=') <$> lift peekChar
  when istotal $ void $ char '='
  isinclusive <- (== Just '*') <$> lift peekChar
  when isinclusive $ void $ char '*'
  lift skipNonNewlineSpaces
  -- this amount can have a cost, but not a cost basis.
  -- balance assertions ignore it, but balance assignments will use it
  a <- amountnobasisp <?> "amount (for a balance assertion or assignment)"
  return BalanceAssertion
    { baamount    = a
    , batotal     = istotal
    , bainclusive = isinclusive
    , baposition  = sourcepos
    }

-- Parse lot cost in curly braces.
-- Accepts either:
--   Ledger-style:  {UNITCOST} or {{TOTALCOST}} or {=FIXEDUNITCOST} or {{=FIXEDTOTALCOST}} or {}
--   Consolidated:  {DATE, "LABEL", COST} or {{DATE, "LABEL", TOTALCOST}}
--                  with all fields optional and in DLC order
-- If total cost syntax {{}} is used, the parsed cost is converted to unit cost
-- by dividing by the posting quantity (with full Decimal precision, so that
-- `{{T}}` and `@@T` yield equal per-unit Decimals — important for the strict
-- comparison in `journalCheckAcquireBasis`).
lotcostp :: Quantity -> JournalParser m CostBasis
lotcostp :: forall (m :: * -> *). Quantity -> JournalParser m CostBasis
lotcostp Quantity
postingqty =
  -- dbg "lotcostp" $
  String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) CostBasis
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) CostBasis
forall a.
String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall e s (m :: * -> *) a.
MonadParsec e s m =>
String -> m a -> m a
label String
"lot cost" (StateT
   Journal (ParsecT HledgerParseErrorData CommoditySymbol m) CostBasis
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData CommoditySymbol m)
      CostBasis)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) CostBasis
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) CostBasis
forall a b. (a -> b) -> a -> b
$ do
  Token CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'{'
  doublebrace <- Bool
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
forall (m :: * -> *) a. Alternative m => a -> m a -> m a
option Bool
False (StateT
   Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
forall a b. (a -> b) -> a -> b
$ Token CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'{' StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Bool
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
forall a.
a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
True
  lift skipNonNewlineSpaces
  -- Peek to decide: consolidated vs ledger
  -- consolidated starts with date (digit), label ("), or empty }
  -- ledger starts with =, amount, or empty }
  c <- lookAhead anySingle
  cb <- case c of
    Char
'}' -> CostBasis
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) CostBasis
forall a.
a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Maybe Day -> Maybe CommoditySymbol -> Maybe Amount -> CostBasis
CostBasis Maybe Day
forall a. Maybe a
Nothing Maybe CommoditySymbol
forall a. Maybe a
Nothing Maybe Amount
forall a. Maybe a
Nothing)
    Char
'=' -> StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) CostBasis
forall {m :: * -> *}.
StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) CostBasis
ledgerCost
    Char
'"' -> StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) CostBasis
consolidatedNoDate
    Char
_   -> StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) CostBasis
tryDateOrLedger
  -- A comma, quote or digit here means another part follows the cost,
  -- ie the parts are out of order; say so, rather than "expecting '}'".
  mnext <- optional $ lookAhead anySingle
  when (maybe False startsAnotherPart mnext) wrongOrderError
  char '}'
  when doublebrace $ void $ char '}'
  pure $ if doublebrace then mapCbCost convertToUnitCost cb else cb
  where
    -- Apply a function to the cost amount, if any, of a CostBasis.
    mapCbCost :: (Amount -> Amount) -> CostBasis -> CostBasis
mapCbCost Amount -> Amount
f (CostBasis Maybe Day
md Maybe CommoditySymbol
ml Maybe Amount
mc) = Maybe Day -> Maybe CommoditySymbol -> Maybe Amount -> CostBasis
CostBasis Maybe Day
md Maybe CommoditySymbol
ml ((Amount -> Amount) -> Maybe Amount -> Maybe Amount
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Amount -> Amount
f Maybe Amount
mc)

    startsAnotherPart :: Char -> Bool
startsAnotherPart Char
c = Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
',' Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'"' Bool -> Bool -> Bool
|| Char -> Bool
isDigit Char
c

    wrongOrderError :: StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
wrongOrderError = do
      off <- StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
      customFailure $ parseErrorAt off
        "cost basis parts must be in this order (if present): {DATE, \"LABEL\", COST}"

    -- Does a date (YYYY-D...) come next ?
    looksLikeDatep :: StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
looksLikeDatep = Bool
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
forall (m :: * -> *) a. Alternative m => a -> m a -> m a
option Bool
False (StateT
   Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
forall a.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
lookAhead (StateT
   Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
forall a.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (StateT
   Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
forall a b. (a -> b) -> a -> b
$
      Int
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) String
forall (m :: * -> *) a. Monad m => Int -> m a -> m [a]
count Int
4 StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol m)
  (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m (Token s)
digitChar StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Token CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'-' StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol m)
  (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m (Token s)
digitChar StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Bool
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
forall a.
a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
True

    -- The inner parsers below leave the closing }(}) for the outer parser.

    tryDateOrLedger :: StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) CostBasis
tryDateOrLedger = do
      -- Does input look like a date (YYYY-D...) ? If so, commit to consolidated
      -- date parsing (no try), so invalid dates give clear errors instead of
      -- falling through to the amount parser with a confusing message.
      looksLikeDate <- StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
looksLikeDatep
      if looksLikeDate
        then do
          d <- datep
          lift skipNonNewlineSpaces
          void $ lookAhead (oneOf [',','}'])
          consolidatedAfterDate d
        else ledgerCost  -- not a date, parse as ledger amount

    consolidatedAfterDate :: Day
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) CostBasis
consolidatedAfterDate Day
d = do
      -- after date: optional ", LABEL", optional ", COST"
      mlabel <- StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol m)
  CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe CommoditySymbol)
forall (f :: * -> *) a. Alternative f => f a -> f (Maybe a)
optional (StateT
   Journal
   (ParsecT HledgerParseErrorData CommoditySymbol m)
   CommoditySymbol
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData CommoditySymbol m)
      (Maybe CommoditySymbol))
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe CommoditySymbol)
forall a b. (a -> b) -> a -> b
$ StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol m)
  CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
forall a.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (StateT
   Journal
   (ParsecT HledgerParseErrorData CommoditySymbol m)
   CommoditySymbol
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData CommoditySymbol m)
      CommoditySymbol)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
forall a b. (a -> b) -> a -> b
$ Token CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
',' StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol m)
  CommoditySymbol
quotedLabelp StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol m)
  CommoditySymbol
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* ParsecT HledgerParseErrorData CommoditySymbol m ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
      mcost  <- optional $ char ',' >> lift skipNonNewlineSpaces >> simpleamountp OrdinaryAmount <* lift skipNonNewlineSpaces
      pure $ CostBasis (Just d) mlabel mcost

    consolidatedNoDate :: StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) CostBasis
consolidatedNoDate = do
      -- parse "LABEL", then optional ", COST" (a date here is out of order)
      mlabel <- CommoditySymbol -> Maybe CommoditySymbol
forall a. a -> Maybe a
Just (CommoditySymbol -> Maybe CommoditySymbol)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe CommoditySymbol)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol m)
  CommoditySymbol
quotedLabelp
      lift skipNonNewlineSpaces
      mcost <- optional $ do
        char ',' >> lift skipNonNewlineSpaces
        looksLikeDate <- looksLikeDatep
        when looksLikeDate wrongOrderError
        simpleamountp OrdinaryAmount <* lift skipNonNewlineSpaces
      pure $ CostBasis Nothing mlabel mcost

    quotedLabelp :: StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol m)
  CommoditySymbol
quotedLabelp = do
      Token CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'"'
      lbl <- String -> CommoditySymbol
T.pack (String -> CommoditySymbol)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) String
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) String
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
many ([Token CommoditySymbol]
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Token CommoditySymbol)
forall (f :: * -> *) e s (m :: * -> *).
(Foldable f, MonadParsec e s m) =>
f (Token s) -> m (Token s)
noneOf [Char
'"', Char
'\n'])
      char '"'
      pure lbl

    ledgerCost :: StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) CostBasis
ledgerCost = do
      _fixed <- (Maybe Char -> Bool)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe Char)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
forall a b.
(a -> b)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Maybe Char -> Bool
forall a. Maybe a -> Bool
isJust (StateT
   Journal
   (ParsecT HledgerParseErrorData CommoditySymbol m)
   (Maybe Char)
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe Char)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Bool
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe Char)
forall (f :: * -> *) a. Alternative f => f a -> f (Maybe a)
optional (StateT
   Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData CommoditySymbol m)
      (Maybe Char))
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Maybe Char)
forall a b. (a -> b) -> a -> b
$ Token CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'='
      lift skipNonNewlineSpaces
      ma <- optional $ simpleamountp OrdinaryAmount
      lift skipNonNewlineSpaces
      pure $ CostBasis Nothing Nothing ma

    -- Divide with full Decimal precision (so `{{T}}` and `@@T` give equal
    -- per-unit Decimals for the strict basis check), and widen display
    -- precision to show the quotient's digits. A total basis is unsigned,
    -- like a total cost: divide by the quantity's magnitude so a negative
    -- posting (a disposal, or a short open) gets a positive unit basis.
    convertToUnitCost :: Amount -> Amount
convertToUnitCost = Quantity -> Amount -> Amount
divideAmountAndUpdatePrecision (Quantity -> Quantity
forall a. Num a => a -> a
abs Quantity
postingqty)

-- Parse a Ledger-style [LOTDATE].
lotdatep :: JournalParser m Day
lotdatep :: forall (m :: * -> *). JournalParser m Day
lotdatep =
  -- dbg "lotdatep" $
  String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Day
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Day
forall a.
String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall e s (m :: * -> *) a.
MonadParsec e s m =>
String -> m a -> m a
label String
"ledger-style lot date" (StateT
   Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Day
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Day)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Day
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Day
forall a b. (a -> b) -> a -> b
$ do
  Token CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'['
  ParsecT HledgerParseErrorData CommoditySymbol m ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  d <- StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Day
forall (m :: * -> *). JournalParser m Day
datep
  lift skipNonNewlineSpaces
  char ']'
  return d

-- Parse a Ledger-style (LOT NOTE).
-- Any double-quote characters inside the parentheses are stripped,
-- because they would disrupt round-tripping of hledger's label syntax.
lotnotep :: JournalParser m Text
lotnotep :: forall (m :: * -> *). JournalParser m CommoditySymbol
lotnotep =
  -- dbg "lotnotep" $
  String
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
forall a.
String
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
forall e s (m :: * -> *) a.
MonadParsec e s m =>
String -> m a -> m a
label String
"ledger-style lot note" (StateT
   Journal
   (ParsecT HledgerParseErrorData CommoditySymbol m)
   CommoditySymbol
 -> StateT
      Journal
      (ParsecT HledgerParseErrorData CommoditySymbol m)
      CommoditySymbol)
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
forall a b. (a -> b) -> a -> b
$ do
  Token CommoditySymbol
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'('
  ParsecT HledgerParseErrorData CommoditySymbol m ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  note <- CommoditySymbol -> CommoditySymbol
stripEnd (CommoditySymbol -> CommoditySymbol)
-> (String -> CommoditySymbol) -> String -> CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> CommoditySymbol
T.pack (String -> CommoditySymbol)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) String
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     CommoditySymbol
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) String
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
many (StateT
   Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
 -> StateT
      Journal (ParsecT HledgerParseErrorData CommoditySymbol m) String)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Char
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) String
forall a b. (a -> b) -> a -> b
$ [Token CommoditySymbol]
-> StateT
     Journal
     (ParsecT HledgerParseErrorData CommoditySymbol m)
     (Token CommoditySymbol)
forall (f :: * -> *) e s (m :: * -> *).
(Foldable f, MonadParsec e s m) =>
f (Token s) -> m (Token s)
noneOf [Char
')',Char
'\n'])  -- XXX other line endings ?
  char ')'
  return $ T.filter (/= '"') note

-- | Parse a string representation of a number for its value and display
-- attributes.
--
-- Some international number formats are accepted, eg either period or comma
-- may be used for the decimal mark, and the other of these may be used for
-- separating digit groups in the integer part. See
-- http://en.wikipedia.org/wiki/Decimal_separator for more examples.
--
-- This returns: the parsed numeric value, the precision (number of digits
-- seen following the decimal mark), the decimal mark character used if any,
-- and the digit group style if any.
--
numberp :: Maybe AmountStyle -> TextParser m (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
numberp :: forall (m :: * -> *).
Maybe AmountStyle
-> TextParser
     m (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
numberp Maybe AmountStyle
suggestedStyle = String
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
forall a.
String
-> ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall e s (m :: * -> *) a.
MonadParsec e s m =>
String -> m a -> m a
label String
"number" (ParsecT
   HledgerParseErrorData
   CommoditySymbol
   m
   (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
 -> ParsecT
      HledgerParseErrorData
      CommoditySymbol
      m
      (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle))
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
forall a b. (a -> b) -> a -> b
$ do
    -- a number is an optional sign followed by a sequence of digits possibly
    -- interspersed with periods, commas, or both
    -- dbgparse 0 "numberp"
    sign <- TextParser m (Quantity -> Quantity)
forall a (m :: * -> *). Num a => TextParser m (a -> a)
signp
    ambiguousNum <- rawnumberp
    mExp <- optionalexponentp
    dbg7 "numberp suggestedStyle" suggestedStyle `seq` return ()
    case dbg7 "numberp quantity,precision,mdecimalpoint,mgrps"
           $ interpretRawNumber Nothing suggestedStyle ambiguousNum mExp of
      Left String
errMsg -> String
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
forall a.
HasCallStack =>
String -> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (m :: * -> *) a.
(MonadFail m, HasCallStack) =>
String -> m a
Fail.fail String
errMsg
      Right (Quantity
q, Word8
p, Maybe Char
d, Maybe DigitGroupStyle
g) -> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
forall a. a -> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Quantity -> Quantity
sign Quantity
q, Word8
p, Maybe Char
d, Maybe DigitGroupStyle
g)

exponentp :: TextParser m Integer
exponentp :: forall (m :: * -> *). TextParser m Integer
exponentp = Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char' Char
Token CommoditySymbol
'e' ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Integer -> Integer)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Integer -> Integer)
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> ParsecT
  HledgerParseErrorData CommoditySymbol m (Integer -> Integer)
forall a (m :: * -> *). Num a => TextParser m (a -> a)
signp ParsecT
  HledgerParseErrorData CommoditySymbol m (Integer -> Integer)
-> ParsecT HledgerParseErrorData CommoditySymbol m Integer
-> ParsecT HledgerParseErrorData CommoditySymbol m Integer
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m (a -> b)
-> ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> ParsecT HledgerParseErrorData CommoditySymbol m Integer
forall e s (m :: * -> *) a.
(MonadParsec e s m, Token s ~ Char, Num a) =>
m a
decimal ParsecT HledgerParseErrorData CommoditySymbol m Integer
-> String
-> ParsecT HledgerParseErrorData CommoditySymbol m Integer
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> String -> m a
<?> String
"exponent"

-- | Parse an exponent if one follows, checking the next character first,
-- since most numbers have none.
optionalexponentp :: TextParser m (Maybe Integer)
optionalexponentp :: forall (m :: * -> *). TextParser m (Maybe Integer)
optionalexponentp = do
  mc <- TextParser m (Maybe Char)
forall (m :: * -> *). TextParser m (Maybe Char)
peekChar
  if mc == Just 'e' || mc == Just 'E' then optional (try exponentp) else pure Nothing

-- | Interpret a possibly-ambiguous raw number as a decimal number.
-- The suggested style (from a decimal-mark or commodity directive, eg), if any,
-- is used to disambiguate it.
-- If a required decimal mark is given (from a decimal-mark directive, eg),
-- the number must use only that decimal mark.
interpretRawNumber
  :: Maybe Char
  -> Maybe AmountStyle
  -> Either AmbiguousNumber RawNumber
  -> Maybe Integer
  -> Either String (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
interpretRawNumber :: Maybe Char
-> Maybe AmountStyle
-> Either AmbiguousNumber RawNumber
-> Maybe Integer
-> Either
     String (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
interpretRawNumber Maybe Char
mrequiredmark Maybe AmountStyle
msuggestedStyle Either AmbiguousNumber RawNumber
ambiguousNum Maybe Integer
mExp = do
  raw <- RawNumber -> Either String RawNumber
checkDecimalMark (RawNumber -> Either String RawNumber)
-> RawNumber -> Either String RawNumber
forall a b. (a -> b) -> a -> b
$ (AmbiguousNumber -> RawNumber)
-> (RawNumber -> RawNumber)
-> Either AmbiguousNumber RawNumber
-> RawNumber
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (Maybe AmountStyle -> AmbiguousNumber -> RawNumber
disambiguateNumber Maybe AmountStyle
msuggestedStyle) RawNumber -> RawNumber
forall a. a -> a
id Either AmbiguousNumber RawNumber
ambiguousNum
  fromRawNumber raw mExp
  where
    checkDecimalMark :: RawNumber -> Either String RawNumber
checkDecimalMark RawNumber
raw = case Maybe Char
mrequiredmark of
      Just Char
d
        | Just Char
m <- RawNumber -> Maybe Char
rawDecimalMark RawNumber
raw, Char
m Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
d ->
          Char -> String -> Either String RawNumber
forall {a} {b}. Show a => a -> String -> Either String b
declared Char
d (String -> Either String RawNumber)
-> String -> Either String RawNumber
forall a b. (a -> b) -> a -> b
$ String
"but this number's decimal mark is " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Char -> String
forall a. Show a => a -> String
show Char
m
        -- rawnumberp decides that a mark appearing more than once is a digit group mark.
        -- If that's the declared decimal mark, the number is probably mistyped (eg 1.2.34);
        -- don't silently read it as a larger number.
        | Char -> Maybe Char
forall a. a -> Maybe a
Just Char
d Maybe Char -> Maybe Char -> Bool
forall a. Eq a => a -> a -> Bool
== RawNumber -> Maybe Char
rawDigitGroupMark RawNumber
raw ->
          Char -> String -> Either String RawNumber
forall {a} {b}. Show a => a -> String -> Either String b
declared Char
d String
"so it can appear only once"
      Maybe Char
_ -> RawNumber -> Either String RawNumber
forall a b. b -> Either a b
Right RawNumber
raw
    declared :: a -> String -> Either String b
declared a
d String
msg = String -> Either String b
forall a b. a -> Either a b
Left (String -> Either String b) -> String -> Either String b
forall a b. (a -> b) -> a -> b
$ String
"invalid number: the decimal mark is declared to be " String -> String -> String
forall a. [a] -> [a] -> [a]
++ a -> String
forall a. Show a => a -> String
show a
d String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
", " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
msg
    rawDecimalMark :: RawNumber -> Maybe Char
rawDecimalMark (NoSeparators DigitGrp
_ Maybe (Char, DigitGrp)
mdec)     = (Char, DigitGrp) -> Char
forall a b. (a, b) -> a
fst ((Char, DigitGrp) -> Char) -> Maybe (Char, DigitGrp) -> Maybe Char
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe (Char, DigitGrp)
mdec
    rawDecimalMark (WithSeparators Char
_ [DigitGrp]
_ Maybe (Char, DigitGrp)
mdec) = (Char, DigitGrp) -> Char
forall a b. (a, b) -> a
fst ((Char, DigitGrp) -> Char) -> Maybe (Char, DigitGrp) -> Maybe Char
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe (Char, DigitGrp)
mdec
    rawDigitGroupMark :: RawNumber -> Maybe Char
rawDigitGroupMark (WithSeparators Char
sep [DigitGrp]
_ Maybe (Char, DigitGrp)
_) = Char -> Maybe Char
forall a. a -> Maybe a
Just Char
sep
    rawDigitGroupMark NoSeparators{}           = Maybe Char
forall a. Maybe a
Nothing

-- | Interpret a raw number as a decimal number.
--
-- Returns:
-- - the decimal number
-- - the precision (number of digits after the decimal point)
-- - the decimal point character, if any
-- - the digit group style, if any (digit group character and sizes of digit groups)
fromRawNumber
  :: RawNumber
  -> Maybe Integer
  -> Either String
            (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
fromRawNumber :: RawNumber
-> Maybe Integer
-> Either
     String (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
fromRawNumber (WithSeparators{}) (Just Integer
_) =
    String
-> Either
     String (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
forall a b. a -> Either a b
Left String
"invalid number: digit separators and exponents may not be used together"
fromRawNumber RawNumber
raw Maybe Integer
mExp = do
    (quantity, precision) <- Integer -> DigitGrp -> DigitGrp -> Either String (Quantity, Word8)
toQuantity (Integer -> Maybe Integer -> Integer
forall a. a -> Maybe a -> a
fromMaybe Integer
0 Maybe Integer
mExp) (RawNumber -> DigitGrp
digitGroup RawNumber
raw) (RawNumber -> DigitGrp
decimalGroup RawNumber
raw)
    -- force the Maybes' contents, so that parsed amount styles don't retain the raw number
    let !mdec = Maybe Char -> Maybe Char
forall {a}. Maybe a -> Maybe a
forceMaybe (Maybe Char -> Maybe Char) -> Maybe Char -> Maybe Char
forall a b. (a -> b) -> a -> b
$ RawNumber -> Maybe Char
mDecPt RawNumber
raw
        !mgrps = Maybe DigitGroupStyle -> Maybe DigitGroupStyle
forall {a}. Maybe a -> Maybe a
forceMaybe (Maybe DigitGroupStyle -> Maybe DigitGroupStyle)
-> Maybe DigitGroupStyle -> Maybe DigitGroupStyle
forall a b. (a -> b) -> a -> b
$ RawNumber -> Maybe DigitGroupStyle
digitGroupStyle RawNumber
raw
    return (quantity, precision, mdec, mgrps)
  where
    forceMaybe :: Maybe a -> Maybe a
forceMaybe Maybe a
m = case Maybe a
m of
      Just a
x  -> a
x a -> Maybe a -> Maybe a
forall a b. a -> b -> b
`seq` Maybe a
m
      Maybe a
Nothing -> Maybe a
m
    toQuantity :: Integer -> DigitGrp -> DigitGrp -> Either String (Quantity, Word8)
    toQuantity :: Integer -> DigitGrp -> DigitGrp -> Either String (Quantity, Word8)
toQuantity Integer
e DigitGrp
preDecimalGrp DigitGrp
postDecimalGrp
      | Integer
precision Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Integer
0   = (Quantity, Word8) -> Either String (Quantity, Word8)
forall a b. b -> Either a b
Right (Word8 -> Integer -> Quantity
forall i. Word8 -> i -> DecimalRaw i
Decimal Word8
0 (Integer
digitGrpNum Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
10Integer -> Integer -> Integer
forall a b. (Num a, Integral b) => a -> b -> a
^(-Integer
precision)), Word8
0)
      | Integer
precision Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Integer
256 = (Quantity, Word8) -> Either String (Quantity, Word8)
forall a b. b -> Either a b
Right (Word8 -> Integer -> Quantity
forall i. Word8 -> i -> DecimalRaw i
Decimal Word8
precision8 Integer
digitGrpNum, Word8
precision8)
      | Bool
otherwise = String -> Either String (Quantity, Word8)
forall a b. a -> Either a b
Left String
"invalid number: numbers with more than 255 decimal places are currently not supported"
      where
        digitGrpNum :: Integer
digitGrpNum = DigitGrp -> Integer
digitGroupNumber (DigitGrp -> Integer) -> DigitGrp -> Integer
forall a b. (a -> b) -> a -> b
$ DigitGrp
preDecimalGrp DigitGrp -> DigitGrp -> DigitGrp
forall a. Semigroup a => a -> a -> a
<> DigitGrp
postDecimalGrp
        precision :: Integer
precision   = Word -> Integer
forall a. Integral a => a -> Integer
toInteger (DigitGrp -> Word
digitGroupLength DigitGrp
postDecimalGrp) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
- Integer
e
        precision8 :: Word8
precision8  = Integer -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral Integer
precision :: Word8

    mDecPt :: RawNumber -> Maybe Char
mDecPt (NoSeparators DigitGrp
_ Maybe (Char, DigitGrp)
mDecimals)           = (Char, DigitGrp) -> Char
forall a b. (a, b) -> a
fst ((Char, DigitGrp) -> Char) -> Maybe (Char, DigitGrp) -> Maybe Char
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe (Char, DigitGrp)
mDecimals
    mDecPt (WithSeparators Char
_ [DigitGrp]
_ Maybe (Char, DigitGrp)
mDecimals)       = (Char, DigitGrp) -> Char
forall a b. (a, b) -> a
fst ((Char, DigitGrp) -> Char) -> Maybe (Char, DigitGrp) -> Maybe Char
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe (Char, DigitGrp)
mDecimals
    decimalGroup :: RawNumber -> DigitGrp
decimalGroup (NoSeparators DigitGrp
_ Maybe (Char, DigitGrp)
mDecimals)     = DigitGrp
-> ((Char, DigitGrp) -> DigitGrp)
-> Maybe (Char, DigitGrp)
-> DigitGrp
forall b a. b -> (a -> b) -> Maybe a -> b
maybe DigitGrp
forall a. Monoid a => a
mempty (Char, DigitGrp) -> DigitGrp
forall a b. (a, b) -> b
snd Maybe (Char, DigitGrp)
mDecimals
    decimalGroup (WithSeparators Char
_ [DigitGrp]
_ Maybe (Char, DigitGrp)
mDecimals) = DigitGrp
-> ((Char, DigitGrp) -> DigitGrp)
-> Maybe (Char, DigitGrp)
-> DigitGrp
forall b a. b -> (a -> b) -> Maybe a -> b
maybe DigitGrp
forall a. Monoid a => a
mempty (Char, DigitGrp) -> DigitGrp
forall a b. (a, b) -> b
snd Maybe (Char, DigitGrp)
mDecimals
    digitGroup :: RawNumber -> DigitGrp
digitGroup (NoSeparators DigitGrp
digitGrp Maybe (Char, DigitGrp)
_)        = DigitGrp
digitGrp
    digitGroup (WithSeparators Char
_ [DigitGrp]
digitGrps Maybe (Char, DigitGrp)
_)   = [DigitGrp] -> DigitGrp
forall a. Monoid a => [a] -> a
mconcat [DigitGrp]
digitGrps
    digitGroupStyle :: RawNumber -> Maybe DigitGroupStyle
digitGroupStyle (NoSeparators DigitGrp
_ Maybe (Char, DigitGrp)
_)          = Maybe DigitGroupStyle
forall a. Maybe a
Nothing
    digitGroupStyle (WithSeparators Char
sep [DigitGrp]
grps Maybe (Char, DigitGrp)
_) = DigitGroupStyle -> Maybe DigitGroupStyle
forall a. a -> Maybe a
Just (DigitGroupStyle -> Maybe DigitGroupStyle)
-> ([Word8] -> DigitGroupStyle) -> [Word8] -> Maybe DigitGroupStyle
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> [Word8] -> DigitGroupStyle
DigitGroups Char
sep ([Word8] -> Maybe DigitGroupStyle)
-> [Word8] -> Maybe DigitGroupStyle
forall a b. (a -> b) -> a -> b
$ [DigitGrp] -> [Word8]
groupSizes [DigitGrp]
grps

    -- Outputs digit group sizes from least significant to most significant
    groupSizes :: [DigitGrp] -> [Word8]
    groupSizes :: [DigitGrp] -> [Word8]
groupSizes [DigitGrp]
digitGrps = [Word8] -> [Word8]
forall a. [a] -> [a]
reverse ([Word8] -> [Word8]) -> [Word8] -> [Word8]
forall a b. (a -> b) -> a -> b
$ case (DigitGrp -> Word8) -> [DigitGrp] -> [Word8]
forall a b. (a -> b) -> [a] -> [b]
map (Word -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Word -> Word8) -> (DigitGrp -> Word) -> DigitGrp -> Word8
forall b c a. (b -> c) -> (a -> b) -> a -> c
. DigitGrp -> Word
digitGroupLength) [DigitGrp]
digitGrps of
      (Word8
a:Word8
b:[Word8]
cs) | Word8
a Word8 -> Word8 -> Bool
forall a. Ord a => a -> a -> Bool
< Word8
b -> Word8
bWord8 -> [Word8] -> [Word8]
forall a. a -> [a] -> [a]
:[Word8]
cs
      [Word8]
gs               -> [Word8]
gs

disambiguateNumber :: Maybe AmountStyle -> AmbiguousNumber -> RawNumber
disambiguateNumber :: Maybe AmountStyle -> AmbiguousNumber -> RawNumber
disambiguateNumber Maybe AmountStyle
msuggestedStyle (AmbiguousNumber DigitGrp
grp1 Char
sep DigitGrp
grp2) =
  -- If present, use the suggested style to disambiguate;
  -- otherwise, assume that the separator is a decimal point where possible.
  if Char -> Bool
isDecimalMark Char
sep Bool -> Bool -> Bool
&&
     Bool -> (AmountStyle -> Bool) -> Maybe AmountStyle -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
True (Char
sep Char -> AmountStyle -> Bool
`isValidDecimalBy`) Maybe AmountStyle
msuggestedStyle
  then DigitGrp -> Maybe (Char, DigitGrp) -> RawNumber
NoSeparators DigitGrp
grp1 ((Char, DigitGrp) -> Maybe (Char, DigitGrp)
forall a. a -> Maybe a
Just (Char
sep, DigitGrp
grp2))
  else Char -> [DigitGrp] -> Maybe (Char, DigitGrp) -> RawNumber
WithSeparators Char
sep [DigitGrp
grp1, DigitGrp
grp2] Maybe (Char, DigitGrp)
forall a. Maybe a
Nothing
  where
    -- A style with neither a decimal mark nor digit groups (eg from a CSV currency rule
    -- like "currency $", unlike a D or commodity directive) says nothing about the number.
    isValidDecimalBy :: Char -> AmountStyle -> Bool
    isValidDecimalBy :: Char -> AmountStyle -> Bool
isValidDecimalBy Char
c = \case
      AmountStyle{asdecimalmark :: AmountStyle -> Maybe Char
asdecimalmark = Just Char
d} -> Char
d Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
c
      AmountStyle{asdigitgroups :: AmountStyle -> Maybe DigitGroupStyle
asdigitgroups = Just (DigitGroups Char
g [Word8]
_)} -> Char
g Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
c
      AmountStyle
_ -> Bool
True

-- | Parse and interpret the structure of a number without external hints.
-- Numbers are digit strings, possibly separated into digit groups by one
-- of two types of separators. (1) Numbers may optionally have a decimal
-- mark, which may be either a period or comma. (2) Numbers may
-- optionally contain digit group marks, which must all be either a
-- period, a comma, or a space.
--
-- It is our task to deduce the characters used as decimal mark and
-- digit group mark, based on the allowed syntax. For instance, we
-- make use of the fact that a decimal mark can occur at most once and
-- must be to the right of all digit group marks.
--
-- >>> parseTest rawnumberp "1,234,567.89"
-- Right (WithSeparators ',' ["1","234","567"] (Just ('.',"89")))
-- >>> parseTest rawnumberp "1,000"
-- Left (AmbiguousNumber "1" ',' "000")
-- >>> parseTest rawnumberp "1 000"
-- Right (WithSeparators ' ' ["1","000"] Nothing)
-- >>> parseTest rawnumberp "1'000"
-- Right (WithSeparators '\'' ["1","000"] Nothing)
-- >>> parseTest rawnumberp "1_000"
-- Right (WithSeparators '_' ["1","000"] Nothing)
--
rawnumberp :: TextParser m (Either AmbiguousNumber RawNumber)
rawnumberp :: forall (m :: * -> *).
TextParser m (Either AmbiguousNumber RawNumber)
rawnumberp = String
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     (Either AmbiguousNumber RawNumber)
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     (Either AmbiguousNumber RawNumber)
forall a.
String
-> ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall e s (m :: * -> *) a.
MonadParsec e s m =>
String -> m a -> m a
label String
"number" (ParsecT
   HledgerParseErrorData
   CommoditySymbol
   m
   (Either AmbiguousNumber RawNumber)
 -> ParsecT
      HledgerParseErrorData
      CommoditySymbol
      m
      (Either AmbiguousNumber RawNumber))
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     (Either AmbiguousNumber RawNumber)
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     (Either AmbiguousNumber RawNumber)
forall a b. (a -> b) -> a -> b
$ do
  -- (The next characters are inspected directly in a few places below,
  -- avoiding failed parse attempts on this hot path.)
  mc <- TextParser m (Maybe Char)
forall (m :: * -> *). TextParser m (Maybe Char)
peekChar
  rawNumber <- if maybe False isDecimalMark mc then Right <$> leadingDecimalPt else leadingDigits

  -- Guard against mistyped numbers
  mExtraDecimalSep <- peekChar
  when (maybe False isDecimalMark mExtraDecimalSep) $
    Fail.fail "invalid number (invalid use of separator)"

  next2 <- peekChars2
  case next2 of
    (Just Char
' ', Just Char
d) | Char -> Bool
isDigit Char
d -> do
      off <- ParsecT HledgerParseErrorData CommoditySymbol m Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
      customFailure $ parseErrorAt (off + 1) "invalid number (excessive trailing digits)"
    (Maybe Char, Maybe Char)
_ -> () -> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a. a -> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

  return $ dbg7 "rawnumberp" rawNumber
  where

  leadingDecimalPt :: TextParser m RawNumber
  leadingDecimalPt :: forall (m :: * -> *). TextParser m RawNumber
leadingDecimalPt = do
    decPt <- (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
(Token s -> Bool) -> m (Token s)
satisfy Char -> Bool
Token CommoditySymbol -> Bool
isDecimalMark
    decGrp <- digitgroupp
    pure $ NoSeparators mempty (Just (decPt, decGrp))

  leadingDigits :: TextParser m (Either AmbiguousNumber RawNumber)
  leadingDigits :: forall (m :: * -> *).
TextParser m (Either AmbiguousNumber RawNumber)
leadingDigits = do
    grp1 <- TextParser m DigitGrp
forall (m :: * -> *). TextParser m DigitGrp
digitgroupp
    -- More digit groups (after a separator) or a decimal mark may follow; most often neither does.
    next2 <- peekChars2
    let more = case (Maybe Char, Maybe Char)
next2 of
          (Just Char
c1, Maybe Char
_)       | Char -> Bool
isDecimalMark Char
c1 -> Bool
True
          (Just Char
c1, Just Char
c2) | Char -> Bool
isDigitSeparatorChar Char
c1 Bool -> Bool -> Bool
&& Char -> Bool
isDigit Char
c2 -> Bool
True
          (Maybe Char, Maybe Char)
_ -> Bool
False
    if more
    then withSeparators grp1 <|> fmap Right (trailingDecimalPt grp1)
                             <|> pure (Right $ NoSeparators grp1 Nothing)
    else pure (Right $ NoSeparators grp1 Nothing)

  withSeparators :: DigitGrp -> TextParser m (Either AmbiguousNumber RawNumber)
  withSeparators :: forall (m :: * -> *).
DigitGrp -> TextParser m (Either AmbiguousNumber RawNumber)
withSeparators DigitGrp
grp1 = do
    (sep, grp2) <- ParsecT HledgerParseErrorData CommoditySymbol m (Char, DigitGrp)
-> ParsecT HledgerParseErrorData CommoditySymbol m (Char, DigitGrp)
forall a.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (ParsecT HledgerParseErrorData CommoditySymbol m (Char, DigitGrp)
 -> ParsecT
      HledgerParseErrorData CommoditySymbol m (Char, DigitGrp))
-> ParsecT HledgerParseErrorData CommoditySymbol m (Char, DigitGrp)
-> ParsecT HledgerParseErrorData CommoditySymbol m (Char, DigitGrp)
forall a b. (a -> b) -> a -> b
$ (,) (Char -> DigitGrp -> (Char, DigitGrp))
-> ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     (DigitGrp -> (Char, DigitGrp))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
(Token s -> Bool) -> m (Token s)
satisfy Char -> Bool
Token CommoditySymbol -> Bool
isDigitSeparatorChar ParsecT
  HledgerParseErrorData
  CommoditySymbol
  m
  (DigitGrp -> (Char, DigitGrp))
-> ParsecT HledgerParseErrorData CommoditySymbol m DigitGrp
-> ParsecT HledgerParseErrorData CommoditySymbol m (Char, DigitGrp)
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m (a -> b)
-> ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> ParsecT HledgerParseErrorData CommoditySymbol m DigitGrp
forall (m :: * -> *). TextParser m DigitGrp
digitgroupp
    grps <- many $ try $ char sep *> digitgroupp

    let digitGroups = DigitGrp
grp1 DigitGrp -> [DigitGrp] -> [DigitGrp]
forall a. a -> [a] -> [a]
: DigitGrp
grp2 DigitGrp -> [DigitGrp] -> [DigitGrp]
forall a. a -> [a] -> [a]
: [DigitGrp]
grps
    fmap Right (withDecimalPt sep digitGroups)
      <|> pure (withoutDecimalPt grp1 sep grp2 grps)

  withDecimalPt :: Char -> [DigitGrp] -> TextParser m RawNumber
  withDecimalPt :: forall (m :: * -> *). Char -> [DigitGrp] -> TextParser m RawNumber
withDecimalPt Char
digitSep [DigitGrp]
digitGroups = do
    decPt <- (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
(Token s -> Bool) -> m (Token s)
satisfy ((Token CommoditySymbol -> Bool)
 -> ParsecT
      HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol))
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall a b. (a -> b) -> a -> b
$ \Token CommoditySymbol
c -> Char -> Bool
isDecimalMark Char
Token CommoditySymbol
c Bool -> Bool -> Bool
&& Char
Token CommoditySymbol
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
digitSep
    decDigitGrp <- option mempty digitgroupp

    pure $ WithSeparators digitSep digitGroups (Just (decPt, decDigitGrp))

  withoutDecimalPt
    :: DigitGrp
    -> Char
    -> DigitGrp
    -> [DigitGrp]
    -> Either AmbiguousNumber RawNumber
  withoutDecimalPt :: DigitGrp
-> Char
-> DigitGrp
-> [DigitGrp]
-> Either AmbiguousNumber RawNumber
withoutDecimalPt DigitGrp
grp1 Char
sep DigitGrp
grp2 [DigitGrp]
grps
    | [DigitGrp] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [DigitGrp]
grps Bool -> Bool -> Bool
&& Char -> Bool
isDecimalMark Char
sep =
        AmbiguousNumber -> Either AmbiguousNumber RawNumber
forall a b. a -> Either a b
Left (AmbiguousNumber -> Either AmbiguousNumber RawNumber)
-> AmbiguousNumber -> Either AmbiguousNumber RawNumber
forall a b. (a -> b) -> a -> b
$ DigitGrp -> Char -> DigitGrp -> AmbiguousNumber
AmbiguousNumber DigitGrp
grp1 Char
sep DigitGrp
grp2
    | Bool
otherwise = RawNumber -> Either AmbiguousNumber RawNumber
forall a b. b -> Either a b
Right (RawNumber -> Either AmbiguousNumber RawNumber)
-> RawNumber -> Either AmbiguousNumber RawNumber
forall a b. (a -> b) -> a -> b
$ Char -> [DigitGrp] -> Maybe (Char, DigitGrp) -> RawNumber
WithSeparators Char
sep (DigitGrp
grp1DigitGrp -> [DigitGrp] -> [DigitGrp]
forall a. a -> [a] -> [a]
:DigitGrp
grp2DigitGrp -> [DigitGrp] -> [DigitGrp]
forall a. a -> [a] -> [a]
:[DigitGrp]
grps) Maybe (Char, DigitGrp)
forall a. Maybe a
Nothing

  trailingDecimalPt :: DigitGrp -> TextParser m RawNumber
  trailingDecimalPt :: forall (m :: * -> *). DigitGrp -> TextParser m RawNumber
trailingDecimalPt DigitGrp
grp1 = do
    decPt <- (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
(Token s -> Bool) -> m (Token s)
satisfy Char -> Bool
Token CommoditySymbol -> Bool
isDecimalMark
    pure $ NoSeparators grp1 (Just (decPt, mempty))

isDigitSeparatorChar :: Char -> Bool
isDigitSeparatorChar :: Char -> Bool
isDigitSeparatorChar Char
c = Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'.' Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
',' Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'\'' Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'_' Bool -> Bool -> Bool
|| Char -> Bool
isDigitSeparatorSpaceChar Char
c

-- | Kinds of unicode space character we accept as digit group marks.
-- See also https://en.wikipedia.org/wiki/Decimal_separator#Digit_grouping .
isDigitSeparatorSpaceChar :: Char -> Bool
isDigitSeparatorSpaceChar :: Char -> Bool
isDigitSeparatorSpaceChar Char
c =
     Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
' '  -- space
  Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
' '  -- no-break space
  Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
' '  -- en space
  Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
' '  -- em space
  Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
' '  -- punctuation space
  Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
' '  -- thin space
  Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
' '  -- narrow no-break space
  Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
' '  -- medium mathematical space

-- | Some kinds of number literal we might parse.
data RawNumber
  = NoSeparators   DigitGrp (Maybe (Char, DigitGrp))
    -- ^ A number with no digit group marks (eg 100),
    --   or with a leading or trailing comma or period
    --   which (apparently) we interpret as a decimal mark (like 100. or .100)
  | WithSeparators Char [DigitGrp] (Maybe (Char, DigitGrp))
    -- ^ A number with identifiable digit group marks
    --   (eg 1,000,000 or 1,000.50 or 1 000)
  deriving (Int -> RawNumber -> String -> String
[RawNumber] -> String -> String
RawNumber -> String
(Int -> RawNumber -> String -> String)
-> (RawNumber -> String)
-> ([RawNumber] -> String -> String)
-> Show RawNumber
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> RawNumber -> String -> String
showsPrec :: Int -> RawNumber -> String -> String
$cshow :: RawNumber -> String
show :: RawNumber -> String
$cshowList :: [RawNumber] -> String -> String
showList :: [RawNumber] -> String -> String
Show, RawNumber -> RawNumber -> Bool
(RawNumber -> RawNumber -> Bool)
-> (RawNumber -> RawNumber -> Bool) -> Eq RawNumber
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: RawNumber -> RawNumber -> Bool
== :: RawNumber -> RawNumber -> Bool
$c/= :: RawNumber -> RawNumber -> Bool
/= :: RawNumber -> RawNumber -> Bool
Eq)

-- | Another kind of number literal: this one contains either a digit
-- group separator or a decimal mark, we're not sure which (eg 1,000 or 100.50).
data AmbiguousNumber = AmbiguousNumber DigitGrp Char DigitGrp
  deriving (Int -> AmbiguousNumber -> String -> String
[AmbiguousNumber] -> String -> String
AmbiguousNumber -> String
(Int -> AmbiguousNumber -> String -> String)
-> (AmbiguousNumber -> String)
-> ([AmbiguousNumber] -> String -> String)
-> Show AmbiguousNumber
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> AmbiguousNumber -> String -> String
showsPrec :: Int -> AmbiguousNumber -> String -> String
$cshow :: AmbiguousNumber -> String
show :: AmbiguousNumber -> String
$cshowList :: [AmbiguousNumber] -> String -> String
showList :: [AmbiguousNumber] -> String -> String
Show, AmbiguousNumber -> AmbiguousNumber -> Bool
(AmbiguousNumber -> AmbiguousNumber -> Bool)
-> (AmbiguousNumber -> AmbiguousNumber -> Bool)
-> Eq AmbiguousNumber
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: AmbiguousNumber -> AmbiguousNumber -> Bool
== :: AmbiguousNumber -> AmbiguousNumber -> Bool
$c/= :: AmbiguousNumber -> AmbiguousNumber -> Bool
/= :: AmbiguousNumber -> AmbiguousNumber -> Bool
Eq)

-- | Description of a single digit group in a number literal.
-- "Thousands" is one well known digit grouping, but there are others.
data DigitGrp = DigitGrp {
  DigitGrp -> Word
digitGroupLength :: !Word,    -- ^ The number of digits in this group.
                                -- This is Word to avoid the need to do overflow
                                -- checking for the Semigroup instance of DigitGrp.
  DigitGrp -> Integer
digitGroupNumber :: !Integer  -- ^ The natural number formed by this group's digits. This should always be positive.
} deriving (DigitGrp -> DigitGrp -> Bool
(DigitGrp -> DigitGrp -> Bool)
-> (DigitGrp -> DigitGrp -> Bool) -> Eq DigitGrp
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: DigitGrp -> DigitGrp -> Bool
== :: DigitGrp -> DigitGrp -> Bool
$c/= :: DigitGrp -> DigitGrp -> Bool
/= :: DigitGrp -> DigitGrp -> Bool
Eq)

-- | A custom show instance, showing digit groups as the parser saw them.
instance Show DigitGrp where
  show :: DigitGrp -> String
show (DigitGrp Word
len Integer
n) = String
"\"" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
padding String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
numStr String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\""
    where numStr :: String
numStr = Integer -> String
forall a. Show a => a -> String
show Integer
n
          padding :: String
padding = Integer -> Char -> String
forall i a. Integral i => i -> a -> [a]
genericReplicate (Word -> Integer
forall a. Integral a => a -> Integer
toInteger Word
len Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
- Int -> Integer
forall a. Integral a => a -> Integer
toInteger (String -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length String
numStr)) Char
'0'

instance Sem.Semigroup DigitGrp where
  DigitGrp Word
l1 Integer
n1 <> :: DigitGrp -> DigitGrp -> DigitGrp
<> DigitGrp Word
l2 Integer
n2 = Word -> Integer -> DigitGrp
DigitGrp (Word
l1 Word -> Word -> Word
forall a. Num a => a -> a -> a
+ Word
l2) (Integer
n1 Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
10Integer -> Word -> Integer
forall a b. (Num a, Integral b) => a -> b -> a
^Word
l2 Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
n2)

instance Monoid DigitGrp where
  mempty :: DigitGrp
mempty = Word -> Integer -> DigitGrp
DigitGrp Word
0 Integer
0
  mappend :: DigitGrp -> DigitGrp -> DigitGrp
mappend = DigitGrp -> DigitGrp -> DigitGrp
forall a. Semigroup a => a -> a -> a
(Sem.<>)

digitgroupp :: TextParser m DigitGrp
digitgroupp :: forall (m :: * -> *). TextParser m DigitGrp
digitgroupp = String
-> ParsecT HledgerParseErrorData CommoditySymbol m DigitGrp
-> ParsecT HledgerParseErrorData CommoditySymbol m DigitGrp
forall a.
String
-> ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall e s (m :: * -> *) a.
MonadParsec e s m =>
String -> m a -> m a
label String
"digits"
            (ParsecT HledgerParseErrorData CommoditySymbol m DigitGrp
 -> ParsecT HledgerParseErrorData CommoditySymbol m DigitGrp)
-> ParsecT HledgerParseErrorData CommoditySymbol m DigitGrp
-> ParsecT HledgerParseErrorData CommoditySymbol m DigitGrp
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> DigitGrp
makeGroup (CommoditySymbol -> DigitGrp)
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
-> ParsecT HledgerParseErrorData CommoditySymbol m DigitGrp
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe String
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhile1P (String -> Maybe String
forall a. a -> Maybe a
Just String
"digit") Char -> Bool
Token CommoditySymbol -> Bool
isDigit
  where
    makeGroup :: CommoditySymbol -> DigitGrp
makeGroup = (Word -> Integer -> DigitGrp) -> (Word, Integer) -> DigitGrp
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry Word -> Integer -> DigitGrp
DigitGrp ((Word, Integer) -> DigitGrp)
-> (CommoditySymbol -> (Word, Integer))
-> CommoditySymbol
-> DigitGrp
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((Word, Integer) -> Char -> (Word, Integer))
-> (Word, Integer) -> CommoditySymbol -> (Word, Integer)
forall a. (a -> Char -> a) -> a -> CommoditySymbol -> a
T.foldl' (Word, Integer) -> Char -> (Word, Integer)
forall {a} {b}. (Num a, Num b) => (a, b) -> Char -> (a, b)
step (Word
0, Integer
0)
    step :: (a, b) -> Char -> (a, b)
step (!a
l, !b
a) Char
c = (a
la -> a -> a
forall a. Num a => a -> a -> a
+a
1, b
ab -> b -> b
forall a. Num a => a -> a -> a
*b
10 b -> b -> b
forall a. Num a => a -> a -> a
+ Int -> b
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Char -> Int
digitToInt Char
c))

--- *** comments

multilinecommentp :: TextParser m ()
multilinecommentp :: forall (m :: * -> *). TextParser m ()
multilinecommentp = ParsecT HledgerParseErrorData CommoditySymbol m ()
startComment ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> ParsecT HledgerParseErrorData CommoditySymbol m ()
anyLine ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall (m :: * -> *) a end. MonadPlus m => m a -> m end -> m end
`skipManyTill` ParsecT HledgerParseErrorData CommoditySymbol m ()
endComment
  where
    startComment :: ParsecT HledgerParseErrorData CommoditySymbol m ()
startComment = Tokens CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens CommoditySymbol
"comment" ParsecT
  HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall (m :: * -> *). TextParser m ()
trailingSpaces
    endComment :: ParsecT HledgerParseErrorData CommoditySymbol m ()
endComment = ParsecT HledgerParseErrorData CommoditySymbol m ()
forall e s (m :: * -> *). MonadParsec e s m => m ()
eof ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Tokens CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Tokens s -> m (Tokens s)
string Tokens CommoditySymbol
"end comment" ParsecT
  HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall (m :: * -> *). TextParser m ()
trailingSpaces

    trailingSpaces :: ParsecT HledgerParseErrorData CommoditySymbol m ()
trailingSpaces = ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* ParsecT HledgerParseErrorData CommoditySymbol m Char
ParsecT
  HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m (Token s)
newline
    anyLine :: ParsecT HledgerParseErrorData CommoditySymbol m ()
anyLine = ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (ParsecT HledgerParseErrorData CommoditySymbol m Char
 -> ParsecT HledgerParseErrorData CommoditySymbol m ())
-> ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a b. (a -> b) -> a -> b
$ Maybe String
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhileP Maybe String
forall a. Maybe a
Nothing (Token CommoditySymbol -> Token CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/=Char
Token CommoditySymbol
'\n') ParsecT
  HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
-> ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m Char
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> ParsecT HledgerParseErrorData CommoditySymbol m Char
ParsecT
  HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m (Token s)
newline

{-# INLINABLE multilinecommentp #-}

-- | A blank or comment line in journal format: a line that's empty or
-- containing only whitespace or whose first non-whitespace character
-- is semicolon, hash, or star. See also emptyorcommentlinep2.
emptyorcommentlinep :: TextParser m ()
emptyorcommentlinep :: forall (m :: * -> *). TextParser m ()
emptyorcommentlinep = do
  String -> TextParser m ()
forall (m :: * -> *). String -> TextParser m ()
dp String
"emptyorcommentlinep"
  TextParser m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  mc <- TextParser m (Maybe Char)
forall (m :: * -> *). TextParser m (Maybe Char)
peekChar
  if maybe False isLineCommentStart mc then skiplinecommentp else void newline
  where
    skiplinecommentp :: TextParser m ()
    skiplinecommentp :: forall (m :: * -> *). TextParser m ()
skiplinecommentp = do
      (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
(Token s -> Bool) -> m (Token s)
satisfy Char -> Bool
Token CommoditySymbol -> Bool
isLineCommentStart
      ParsecT
  HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (ParsecT
   HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
 -> ParsecT HledgerParseErrorData CommoditySymbol m ())
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a b. (a -> b) -> a -> b
$ Maybe String
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhileP Maybe String
forall a. Maybe a
Nothing (Token CommoditySymbol -> Token CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
Token CommoditySymbol
'\n')
      ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m (Maybe Char)
forall (f :: * -> *) a. Alternative f => f a -> f (Maybe a)
optional ParsecT HledgerParseErrorData CommoditySymbol m Char
ParsecT
  HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m (Token s)
newline
      () -> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a. a -> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

{-# INLINABLE emptyorcommentlinep #-}

-- | A newer comment line parser.
-- Parses a line which is empty, all blanks, or whose first non-blank character is one of those provided.
-- A final newline is optional.
emptyorcommentlinep2 :: [Char] -> TextParser m ()
emptyorcommentlinep2 :: forall (m :: * -> *). String -> TextParser m ()
emptyorcommentlinep2 String
cs =
  String
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a.
String
-> ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall e s (m :: * -> *) a.
MonadParsec e s m =>
String -> m a -> m a
label (String
"empty line or comment line beginning with "String -> String -> String
forall a. [a] -> [a] -> [a]
++String
cs) (ParsecT HledgerParseErrorData CommoditySymbol m ()
 -> ParsecT HledgerParseErrorData CommoditySymbol m ())
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a b. (a -> b) -> a -> b
$ do
    String -> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall (m :: * -> *). String -> TextParser m ()
dp String
"emptyorcommentlinep2"
    ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
    ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void ParsecT HledgerParseErrorData CommoditySymbol m Char
ParsecT
  HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m (Token s)
newline ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> ParsecT
  HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void ParsecT
  HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
commentp
    where
      commentp :: ParsecT
  HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
commentp = do
        [ParsecT HledgerParseErrorData CommoditySymbol m String]
-> ParsecT HledgerParseErrorData CommoditySymbol m String
forall (f :: * -> *) (m :: * -> *) a.
(Foldable f, Alternative m) =>
f (m a) -> m a
choice ((Char -> ParsecT HledgerParseErrorData CommoditySymbol m String)
-> String
-> [ParsecT HledgerParseErrorData CommoditySymbol m String]
forall a b. (a -> b) -> [a] -> [b]
map (ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m String
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
some(ParsecT HledgerParseErrorData CommoditySymbol m Char
 -> ParsecT HledgerParseErrorData CommoditySymbol m String)
-> (Char -> ParsecT HledgerParseErrorData CommoditySymbol m Char)
-> Char
-> ParsecT HledgerParseErrorData CommoditySymbol m String
forall b c a. (b -> c) -> (a -> b) -> a -> c
.Char -> ParsecT HledgerParseErrorData CommoditySymbol m Char
Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char) String
cs)
        Maybe String
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhileP Maybe String
forall a. Maybe a
Nothing (Token CommoditySymbol -> Token CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/=Char
Token CommoditySymbol
'\n') ParsecT
  HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
-> ParsecT HledgerParseErrorData CommoditySymbol m (Maybe Char)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m (Maybe Char)
forall (f :: * -> *) a. Alternative f => f a -> f (Maybe a)
optional ParsecT HledgerParseErrorData CommoditySymbol m Char
ParsecT
  HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
m (Token s)
newline

-- | Is this a character that, as the first non-whitespace on a line,
-- starts a comment line ?
isLineCommentStart :: Char -> Bool
isLineCommentStart :: Char -> Bool
isLineCommentStart Char
'#' = Bool
True
isLineCommentStart Char
'*' = Bool
True
isLineCommentStart Char
';' = Bool
True
isLineCommentStart Char
_   = Bool
False

-- | Is this a character that, appearing anywhere within a line,
-- starts a comment ?
isSameLineCommentStart :: Char -> Bool
isSameLineCommentStart :: Char -> Bool
isSameLineCommentStart Char
';' = Bool
True
isSameLineCommentStart Char
_   = Bool
False

-- | Parse a comment following a journal item, possibly continued on multiple lines,
-- and return the comment text.
--
-- >>> rtp followingcommentp ""   -- no comment
-- Right ""
-- >>> rtp followingcommentp ";"    -- just a (empty) same-line comment. newline is added
-- Right "\n"
-- >>> rtp followingcommentp ";  \n"
-- Right "\n"
-- >>> rtp followingcommentp ";\n ;\n"  -- a same-line and a next-line comment
-- Right "\n\n"
-- >>> rtp followingcommentp "\n ;\n"  -- just a next-line comment. Insert an empty same-line comment so the next-line comment doesn't become a same-line comment.
-- Right "\n\n"
--
followingcommentp :: TextParser m Text
followingcommentp :: forall (m :: * -> *). TextParser m CommoditySymbol
followingcommentp = (CommoditySymbol, ()) -> CommoditySymbol
forall a b. (a, b) -> a
fst ((CommoditySymbol, ()) -> CommoditySymbol)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (CommoditySymbol, ())
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TextParser m ()
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (CommoditySymbol, ())
forall a (m :: * -> *).
(Monoid a, Show a) =>
TextParser m a -> TextParser m (CommoditySymbol, a)
followingcommentpWith (ParsecT
  HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
-> TextParser m ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (ParsecT
   HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
 -> TextParser m ())
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
-> TextParser m ()
forall a b. (a -> b) -> a -> b
$ Maybe String
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhileP Maybe String
forall a. Maybe a
Nothing (Token CommoditySymbol -> Token CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
Token CommoditySymbol
'\n'))

{-# INLINABLE followingcommentp #-}

-- | Parse a following comment, possibly continued on multiple lines,
-- using the provided line parser to parse each line.
-- This returns the comment text, and the combined results from the line parser.
--
-- Following comments are a 1-or-more-lines comment,
-- beginning with a semicolon possibly preceded by whitespace on the current line,
-- or with an indented semicolon on the next line.
-- Additional lines also must begin with an indented semicolon.
--
-- Like Ledger, we sometimes allow data to be embedded in comments.
-- account directive comments and transaction comments can contain tags,
-- and posting comments can contain tags or bracketed posting dates.
-- This helper lets us handle these variations. 
-- The line parser should consume all input up until the next newline.
-- See followingcommentp for some tests.
--
followingcommentpWith :: (Monoid a, Show a) => TextParser m a -> TextParser m (Text, a)
followingcommentpWith :: forall a (m :: * -> *).
(Monoid a, Show a) =>
TextParser m a -> TextParser m (CommoditySymbol, a)
followingcommentpWith TextParser m a
contentp = do
  ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
  -- there can be 0 or 1 sameLine (checking for its semicolon cheaply, as usually there is none)
  mc <- TextParser m (Maybe Char)
forall (m :: * -> *). TextParser m (Maybe Char)
peekChar
  sameLine <- if mc == Just ';' then (:[]) <$> (headerp *> match' contentp) else pure []
  _ <- eolof
  -- there can be 0 or more nextLines
  nextLines <- manyWhile nextlineiscomment $
    skipNonNewlineSpaces1 *> headerp *> match' contentp <* eolof
  let
    -- if there's just a next-line comment, insert an empty same-line comment
    -- so the next-line comment doesn't get rendered as a same-line comment.
    sameLine' | [(CommoditySymbol, a)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(CommoditySymbol, a)]
sameLine Bool -> Bool -> Bool
&& Bool -> Bool
not ([(CommoditySymbol, a)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(CommoditySymbol, a)]
nextLines) = [(CommoditySymbol
"",a
forall a. Monoid a => a
mempty)]
              | Bool
otherwise = [(CommoditySymbol, a)]
sameLine
    (texts, contents) = unzip $ sameLine' ++ nextLines
    strippedCommentText = [CommoditySymbol] -> CommoditySymbol
T.unlines ([CommoditySymbol] -> CommoditySymbol)
-> [CommoditySymbol] -> CommoditySymbol
forall a b. (a -> b) -> a -> b
$ (CommoditySymbol -> CommoditySymbol)
-> [CommoditySymbol] -> [CommoditySymbol]
forall a b. (a -> b) -> [a] -> [b]
map CommoditySymbol -> CommoditySymbol
T.strip [CommoditySymbol]
texts
    commentContent = [a] -> a
forall a. Monoid a => [a] -> a
mconcat [a]
contents
  pure (strippedCommentText, commentContent)

  where
    headerp :: ParsecT HledgerParseErrorData CommoditySymbol m ()
headerp = Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
';' ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
    -- does the next line begin with an indented semicolon ?
    nextlineiscomment :: ParsecT HledgerParseErrorData CommoditySymbol m Bool
nextlineiscomment = do
      (spaced, mnext) <- TextParser m (Bool, Maybe Char)
forall (m :: * -> *). TextParser m (Bool, Maybe Char)
peekAfterSpaces
      pure $ spaced && mnext == Just ';'

{-# INLINABLE followingcommentpWith #-}


-- Parse the tags from a single comment line, eg for use with followingcommentpWith.
-- XXX what part of a comment line ? leading whitespace / semicolon or not ?
commentlinetagsp :: TextParser m [Tag]
commentlinetagsp :: forall (m :: * -> *).
TextParser m [(CommoditySymbol, CommoditySymbol)]
commentlinetagsp = do
  -- XXX sketchy
  tagName <- ([CommoditySymbol] -> CommoditySymbol
forall a. HasCallStack => [a] -> a
last ([CommoditySymbol] -> CommoditySymbol)
-> (CommoditySymbol -> [CommoditySymbol])
-> CommoditySymbol
-> CommoditySymbol
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Char -> Bool) -> CommoditySymbol -> [CommoditySymbol]
T.split Char -> Bool
isSpace) (CommoditySymbol -> CommoditySymbol)
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe String
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhileP Maybe String
forall a. Maybe a
Nothing (\Token CommoditySymbol
c -> Char
Token CommoditySymbol
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
':' Bool -> Bool -> Bool
&& Char
Token CommoditySymbol
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\n')
  atColon tagName <|> pure [] -- if not ':', then either '\n' or EOF

  where
    atColon :: Text -> TextParser m [Tag]
    atColon :: forall (m :: * -> *).
CommoditySymbol
-> TextParser m [(CommoditySymbol, CommoditySymbol)]
atColon CommoditySymbol
name = Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
':' ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     [(CommoditySymbol, CommoditySymbol)]
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     [(CommoditySymbol, CommoditySymbol)]
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> do
      if CommoditySymbol -> Bool
T.null CommoditySymbol
name
        then ParsecT
  HledgerParseErrorData
  CommoditySymbol
  m
  [(CommoditySymbol, CommoditySymbol)]
forall (m :: * -> *).
TextParser m [(CommoditySymbol, CommoditySymbol)]
commentlinetagsp
        else do
          ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
          val <- TextParser m CommoditySymbol
forall (m :: * -> *). TextParser m CommoditySymbol
tagValue
          let tag = (CommoditySymbol
name, CommoditySymbol
val)
          (tag:) <$> commentlinetagsp

    tagValue :: TextParser m Text
    tagValue :: forall (m :: * -> *). TextParser m CommoditySymbol
tagValue = do
      val <- CommoditySymbol -> CommoditySymbol
T.strip (CommoditySymbol -> CommoditySymbol)
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe String
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhileP Maybe String
forall a. Maybe a
Nothing (\Token CommoditySymbol
c -> Char
Token CommoditySymbol
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
',' Bool -> Bool -> Bool
&& Char
Token CommoditySymbol
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\n')
      _ <- optional $ char ','
      pure val

{-# INLINABLE commentlinetagsp #-}


-- | Parse a transaction comment and extract its tags.
--
-- The first line of a transaction may be followed a 1-or-more-lines comment,
-- beginning with a semicolon possibly preceded by whitespace on the current line,
-- or with an indented semicolon on the next line. Additional lines also must
-- begin with an indented semicolon.
-- See also followingcommentpWith.
--
-- 2000/1/1 ; a transaction comment starting on the same line ...
--   ; extending to the next line
--   account1  $1
--   account2
--
-- Tags are name-value pairs.
--
-- >>> let getTags (_,tags) = tags
-- >>> let parseTags = fmap getTags . rtp transactioncommentp
--
-- >>> parseTags "; name1: val1, name2:all this is value2"
-- Right [("name1","val1"),("name2","all this is value2")]
--
-- A tag's name must be immediately followed by a colon, without
-- separating whitespace. The corresponding value consists of all the text
-- following the colon up until the next colon or newline, stripped of
-- leading and trailing whitespace.
--
transactioncommentp :: TextParser m (Text, [Tag])
transactioncommentp :: forall (m :: * -> *).
TextParser
  m (CommoditySymbol, [(CommoditySymbol, CommoditySymbol)])
transactioncommentp = TextParser m [(CommoditySymbol, CommoditySymbol)]
-> TextParser
     m (CommoditySymbol, [(CommoditySymbol, CommoditySymbol)])
forall a (m :: * -> *).
(Monoid a, Show a) =>
TextParser m a -> TextParser m (CommoditySymbol, a)
followingcommentpWith TextParser m [(CommoditySymbol, CommoditySymbol)]
forall (m :: * -> *).
TextParser m [(CommoditySymbol, CommoditySymbol)]
commentlinetagsp
{-# INLINABLE transactioncommentp #-}


-- | Parse a posting comment and extract its tags and dates.
--
-- Postings may be followed by comments, which begin with semicolons and
-- extend to the end of the line. Posting comments may span multiple
-- lines, but comment lines below the posting must be preceded by
-- leading whitespace.
--
-- 2000/1/1
--   account1  $1 ; a posting comment starting on the same line ...
--   ; extending to the next line
--
--   account2
--   ; a posting comment beginning on the next line
--
-- Tags are name-value pairs.
--
-- >>> let getTags (_,tags,_,_) = tags
-- >>> let parseTags = fmap getTags . rtp (postingcommentp Nothing)
--
-- >>> parseTags "; name1: val1, name2:all this is value2"
-- Right [("name1","val1"),("name2","all this is value2")]
--
-- A tag's name must be immediately followed by a colon, without
-- separating whitespace. The corresponding value consists of all the text
-- following the colon up until the next colon or newline, stripped of
-- leading and trailing whitespace.
--
-- Posting dates may be expressed with "date"/"date2" tags or with
-- bracketed date syntax. Posting dates will inherit their year from the
-- transaction date if the year is not specified. We throw parse errors on
-- invalid dates.
--
-- >>> let getDates (_,_,d1,d2) = (d1, d2)
-- >>> let parseDates = fmap getDates . rtp (postingcommentp (Just 2000))
--
-- >>> parseDates "; date: 1/2, date2: 1999/12/31"
-- Right (Just 2000-01-02,Just 1999-12-31)
-- >>> parseDates "; [1/2=1999/12/31]"
-- Right (Just 2000-01-02,Just 1999-12-31)
--
-- Example: tags, date tags, and bracketed dates
-- >>> rtp (postingcommentp (Just 2000)) "; a:b, date:3/4, [=5/6]"
-- Right ("a:b, date:3/4, [=5/6]\n",[("a","b"),("date","3/4")],Just 2000-03-04,Just 2000-05-06)
--
-- Example: extraction of dates from date tags ignores trailing text
-- >>> rtp (postingcommentp (Just 2000)) "; date:3/4=5/6"
-- Right ("date:3/4=5/6\n",[("date","3/4=5/6")],Just 2000-03-04,Nothing)
--
-- Example: date tags with empty values set no date
-- >>> rtp (postingcommentp (Just 2000)) "; date:, date2: , a:b"
-- Right ("date:, date2: , a:b\n",[("date",""),("date2",""),("a","b")],Nothing,Nothing)
--
postingcommentp
  :: Maybe Year -> TextParser m (Text, [Tag], Maybe Day, Maybe Day)
postingcommentp :: forall (m :: * -> *).
Maybe Integer
-> TextParser
     m
     (CommoditySymbol, [(CommoditySymbol, CommoditySymbol)], Maybe Day,
      Maybe Day)
postingcommentp Maybe Integer
mYear = do
  (commentText, (tags, dateTags)) <-
    TextParser m ([(CommoditySymbol, CommoditySymbol)], [DateTag])
-> TextParser
     m
     (CommoditySymbol,
      ([(CommoditySymbol, CommoditySymbol)], [DateTag]))
forall a (m :: * -> *).
(Monoid a, Show a) =>
TextParser m a -> TextParser m (CommoditySymbol, a)
followingcommentpWith (Maybe Integer
-> TextParser m ([(CommoditySymbol, CommoditySymbol)], [DateTag])
forall (m :: * -> *).
Maybe Integer
-> TextParser m ([(CommoditySymbol, CommoditySymbol)], [DateTag])
commenttagsanddatesp Maybe Integer
mYear)
  let mdate  = DateTag -> Day
forall a b. (a, b) -> b
snd (DateTag -> Day) -> Maybe DateTag -> Maybe Day
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (DateTag -> Bool) -> [DateTag] -> Maybe DateTag
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
==CommoditySymbol
"date") (CommoditySymbol -> Bool)
-> (DateTag -> CommoditySymbol) -> DateTag -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
.DateTag -> CommoditySymbol
forall a b. (a, b) -> a
fst) [DateTag]
dateTags
      mdate2 = DateTag -> Day
forall a b. (a, b) -> b
snd (DateTag -> Day) -> Maybe DateTag -> Maybe Day
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (DateTag -> Bool) -> [DateTag] -> Maybe DateTag
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((CommoditySymbol -> CommoditySymbol -> Bool
forall a. Eq a => a -> a -> Bool
==CommoditySymbol
"date2")(CommoditySymbol -> Bool)
-> (DateTag -> CommoditySymbol) -> DateTag -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
.DateTag -> CommoditySymbol
forall a b. (a, b) -> a
fst) [DateTag]
dateTags
  pure (commentText, tags, mdate, mdate2)
{-# INLINABLE postingcommentp #-}


commenttagsanddatesp
  :: Maybe Year -> TextParser m ([Tag], [DateTag])
commenttagsanddatesp :: forall (m :: * -> *).
Maybe Integer
-> TextParser m ([(CommoditySymbol, CommoditySymbol)], [DateTag])
commenttagsanddatesp Maybe Integer
mYear = do
  (txt, dateTags) <- ParsecT HledgerParseErrorData CommoditySymbol m [DateTag]
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     (Tokens CommoditySymbol, [DateTag])
forall e s (m :: * -> *) a.
MonadParsec e s m =>
m a -> m (Tokens s, a)
match (ParsecT HledgerParseErrorData CommoditySymbol m [DateTag]
 -> ParsecT
      HledgerParseErrorData
      CommoditySymbol
      m
      (Tokens CommoditySymbol, [DateTag]))
-> ParsecT HledgerParseErrorData CommoditySymbol m [DateTag]
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     (Tokens CommoditySymbol, [DateTag])
forall a b. (a -> b) -> a -> b
$ Char -> ParsecT HledgerParseErrorData CommoditySymbol m [DateTag]
forall (m :: * -> *). Char -> TextParser m [DateTag]
readUpTo Char
':'
  -- next char is either ':' or '\n' (or EOF)
  let tagName = [CommoditySymbol] -> CommoditySymbol
forall a. HasCallStack => [a] -> a
last ((Char -> Bool) -> CommoditySymbol -> [CommoditySymbol]
T.split Char -> Bool
isSpace CommoditySymbol
txt)
  (fmap.second) (dateTags++) (atColon tagName) <|> pure ([], dateTags) -- if not ':', then either '\n' or EOF

  where
    readUpTo :: Char -> TextParser m [DateTag]
    readUpTo :: forall (m :: * -> *). Char -> TextParser m [DateTag]
readUpTo Char
end = do
      ParsecT
  HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (ParsecT
   HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
 -> ParsecT HledgerParseErrorData CommoditySymbol m ())
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a b. (a -> b) -> a -> b
$ Maybe String
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhileP Maybe String
forall a. Maybe a
Nothing (\Token CommoditySymbol
c -> Char
Token CommoditySymbol
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
end Bool -> Bool -> Bool
&& Char
Token CommoditySymbol
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'\n' Bool -> Bool -> Bool
&& Char
Token CommoditySymbol
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'[')
      -- if not '[' then ':' or '\n' or EOF
      TextParser m [DateTag] -> TextParser m [DateTag]
forall (m :: * -> *).
TextParser m [DateTag] -> TextParser m [DateTag]
atBracket (Char -> TextParser m [DateTag]
forall (m :: * -> *). Char -> TextParser m [DateTag]
readUpTo Char
end) TextParser m [DateTag]
-> TextParser m [DateTag] -> TextParser m [DateTag]
forall a.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> [DateTag] -> TextParser m [DateTag]
forall a. a -> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure []

    atBracket :: TextParser m [DateTag] -> TextParser m [DateTag]
    atBracket :: forall (m :: * -> *).
TextParser m [DateTag] -> TextParser m [DateTag]
atBracket TextParser m [DateTag]
cont = do
      -- Uses the fact that bracketed date-tags cannot contain newlines
      dateTags <- [DateTag] -> TextParser m [DateTag] -> TextParser m [DateTag]
forall (m :: * -> *) a. Alternative m => a -> m a -> m a
option [] (TextParser m [DateTag] -> TextParser m [DateTag])
-> TextParser m [DateTag] -> TextParser m [DateTag]
forall a b. (a -> b) -> a -> b
$ TextParser m [DateTag] -> TextParser m [DateTag]
forall a.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
lookAhead (Maybe Integer -> TextParser m [DateTag]
forall (m :: * -> *). Maybe Integer -> TextParser m [DateTag]
bracketeddatetagsp Maybe Integer
mYear)
      _ <- char '['
      dateTags' <- cont
      pure $ dateTags ++ dateTags'

    atColon :: Text -> TextParser m ([Tag], [DateTag])
    atColon :: forall (m :: * -> *).
CommoditySymbol
-> TextParser m ([(CommoditySymbol, CommoditySymbol)], [DateTag])
atColon CommoditySymbol
name = Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
':' ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     ([(CommoditySymbol, CommoditySymbol)], [DateTag])
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     ([(CommoditySymbol, CommoditySymbol)], [DateTag])
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> do
      ParsecT HledgerParseErrorData CommoditySymbol m ()
forall s (m :: * -> *).
(Stream s, Token s ~ Char) =>
ParsecT HledgerParseErrorData s m ()
skipNonNewlineSpaces
      (tags, dateTags) <- case CommoditySymbol
name of
        CommoditySymbol
""      -> ([(CommoditySymbol, CommoditySymbol)], [DateTag])
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     ([(CommoditySymbol, CommoditySymbol)], [DateTag])
forall a. a -> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([], [])
        CommoditySymbol
"date"  -> CommoditySymbol
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     ([(CommoditySymbol, CommoditySymbol)], [DateTag])
forall (m :: * -> *).
CommoditySymbol
-> TextParser m ([(CommoditySymbol, CommoditySymbol)], [DateTag])
dateValue CommoditySymbol
name
        CommoditySymbol
"date2" -> CommoditySymbol
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     ([(CommoditySymbol, CommoditySymbol)], [DateTag])
forall (m :: * -> *).
CommoditySymbol
-> TextParser m ([(CommoditySymbol, CommoditySymbol)], [DateTag])
dateValue CommoditySymbol
name
        CommoditySymbol
_       -> CommoditySymbol
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     ([(CommoditySymbol, CommoditySymbol)], [DateTag])
forall (m :: * -> *).
CommoditySymbol
-> TextParser m ([(CommoditySymbol, CommoditySymbol)], [DateTag])
tagValue CommoditySymbol
name
      _ <- optional $ char ','
      bimap (tags++) (dateTags++) <$> commenttagsanddatesp mYear

    -- An empty value (allowed for compatibility with Ledger, where date: is ordinary metadata)
    -- makes an ordinary tag, setting no date.
    dateValue :: Text -> TextParser m ([Tag], [DateTag])
    dateValue :: forall (m :: * -> *).
CommoditySymbol
-> TextParser m ([(CommoditySymbol, CommoditySymbol)], [DateTag])
dateValue CommoditySymbol
name = (ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
lookAhead (ParsecT
  HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void ((Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
(Token s -> Bool) -> m (Token s)
satisfy (\Token CommoditySymbol
c -> Char
Token CommoditySymbol
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
',' Bool -> Bool -> Bool
|| Char
Token CommoditySymbol
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'\n')) ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall e s (m :: * -> *). MonadParsec e s m => m ()
eof) ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     ([(CommoditySymbol, CommoditySymbol)], [DateTag])
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     ([(CommoditySymbol, CommoditySymbol)], [DateTag])
forall a b.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m b
-> ParsecT HledgerParseErrorData CommoditySymbol m b
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> CommoditySymbol
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     ([(CommoditySymbol, CommoditySymbol)], [DateTag])
forall (m :: * -> *).
CommoditySymbol
-> TextParser m ([(CommoditySymbol, CommoditySymbol)], [DateTag])
tagValue CommoditySymbol
name) ParsecT
  HledgerParseErrorData
  CommoditySymbol
  m
  ([(CommoditySymbol, CommoditySymbol)], [DateTag])
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     ([(CommoditySymbol, CommoditySymbol)], [DateTag])
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     m
     ([(CommoditySymbol, CommoditySymbol)], [DateTag])
forall a.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> do
      (txt, (date, dateTags)) <- TextParser m (Day, [DateTag])
-> TextParser m (CommoditySymbol, (Day, [DateTag]))
forall (m :: * -> *) a.
TextParser m a -> TextParser m (CommoditySymbol, a)
match' (TextParser m (Day, [DateTag])
 -> TextParser m (CommoditySymbol, (Day, [DateTag])))
-> TextParser m (Day, [DateTag])
-> TextParser m (CommoditySymbol, (Day, [DateTag]))
forall a b. (a -> b) -> a -> b
$ do
        date <- Maybe Integer -> TextParser m Day
forall (m :: * -> *). Maybe Integer -> TextParser m Day
datep' Maybe Integer
mYear
        dateTags <- readUpTo ','
        pure (date, dateTags)
      let val = CommoditySymbol -> CommoditySymbol
T.strip CommoditySymbol
txt
      pure $ ( [(name, val)]
             , (name, date) : dateTags )

    tagValue :: Text -> TextParser m ([Tag], [DateTag])
    tagValue :: forall (m :: * -> *).
CommoditySymbol
-> TextParser m ([(CommoditySymbol, CommoditySymbol)], [DateTag])
tagValue CommoditySymbol
name = do
      (txt, dateTags) <- TextParser m [DateTag] -> TextParser m (CommoditySymbol, [DateTag])
forall (m :: * -> *) a.
TextParser m a -> TextParser m (CommoditySymbol, a)
match' (TextParser m [DateTag]
 -> TextParser m (CommoditySymbol, [DateTag]))
-> TextParser m [DateTag]
-> TextParser m (CommoditySymbol, [DateTag])
forall a b. (a -> b) -> a -> b
$ Char -> TextParser m [DateTag]
forall (m :: * -> *). Char -> TextParser m [DateTag]
readUpTo Char
','
      let val = CommoditySymbol -> CommoditySymbol
T.strip CommoditySymbol
txt
      pure $ ( [(name, val)]
             , dateTags )

{-# INLINABLE commenttagsanddatesp #-}

-- | Parse Ledger-style bracketed posting dates ([DATE=DATE2]), as
-- "date" and/or "date2" tags. Anything that looks like an attempt at
-- this (a square-bracketed sequence of 0123456789/-.= containing at
-- least one digit and one date separator) is also parsed, and will
-- throw an appropriate error.
--
-- The dates are parsed in full here so that errors are reported in
-- the right position. A missing year in DATE can be inferred if a
-- default date is provided. A missing year in DATE2 will be inferred
-- from DATE.
--
-- >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[2016/1/2=3/4]"
-- Right [("date",2016-01-02),("date2",2016-03-04)]
--
-- >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[1]"
-- Left ...not a bracketed date...
--
-- >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[2016/1/32]"
-- Left ...1:2:...This is not a valid date...
--
-- >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[1/31]"
-- Left ...1:2:...This partial date can not be parsed because the current year is unknown...
--
-- >>> either (Left . customErrorBundlePretty) Right $ rtp (bracketeddatetagsp Nothing) "[0123456789/-.=/-.=]"
-- Left ...1:13:...expecting month or day...
--
bracketeddatetagsp
  :: Maybe Year -> TextParser m [(TagName, Day)]
bracketeddatetagsp :: forall (m :: * -> *). Maybe Integer -> TextParser m [DateTag]
bracketeddatetagsp Maybe Integer
mYear1 = do
  -- dbgparse 0 "bracketeddatetagsp"
  ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
try (ParsecT HledgerParseErrorData CommoditySymbol m ()
 -> ParsecT HledgerParseErrorData CommoditySymbol m ())
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
-> ParsecT HledgerParseErrorData CommoditySymbol m ()
forall a b. (a -> b) -> a -> b
$ do
    s <- ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
forall a.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall e s (m :: * -> *) a. MonadParsec e s m => m a -> m a
lookAhead
       (ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
 -> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol)
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
forall a b. (a -> b) -> a -> b
$ ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
forall (m :: * -> *) open close a.
Applicative m =>
m open -> m close -> m a -> m a
between (Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'[') (Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
']')
       (ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
 -> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol)
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
-> ParsecT HledgerParseErrorData CommoditySymbol m CommoditySymbol
forall a b. (a -> b) -> a -> b
$ Maybe String
-> (Token CommoditySymbol -> Bool)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Tokens CommoditySymbol)
forall e s (m :: * -> *).
MonadParsec e s m =>
Maybe String -> (Token s -> Bool) -> m (Tokens s)
takeWhile1P Maybe String
forall a. Maybe a
Nothing Char -> Bool
Token CommoditySymbol -> Bool
isBracketedDateChar
    unless (T.any isDigit s && T.any isDateSepChar s) $
      Fail.fail "not a bracketed date"
  -- Looks sufficiently like a bracketed date to commit to parsing a date

  ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m [DateTag]
-> ParsecT HledgerParseErrorData CommoditySymbol m [DateTag]
forall (m :: * -> *) open close a.
Applicative m =>
m open -> m close -> m a -> m a
between (Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'[') (Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
']') (ParsecT HledgerParseErrorData CommoditySymbol m [DateTag]
 -> ParsecT HledgerParseErrorData CommoditySymbol m [DateTag])
-> ParsecT HledgerParseErrorData CommoditySymbol m [DateTag]
-> ParsecT HledgerParseErrorData CommoditySymbol m [DateTag]
forall a b. (a -> b) -> a -> b
$ do
    md1 <- ParsecT HledgerParseErrorData CommoditySymbol m Day
-> ParsecT HledgerParseErrorData CommoditySymbol m (Maybe Day)
forall (f :: * -> *) a. Alternative f => f a -> f (Maybe a)
optional (ParsecT HledgerParseErrorData CommoditySymbol m Day
 -> ParsecT HledgerParseErrorData CommoditySymbol m (Maybe Day))
-> ParsecT HledgerParseErrorData CommoditySymbol m Day
-> ParsecT HledgerParseErrorData CommoditySymbol m (Maybe Day)
forall a b. (a -> b) -> a -> b
$ Maybe Integer
-> ParsecT HledgerParseErrorData CommoditySymbol m Day
forall (m :: * -> *). Maybe Integer -> TextParser m Day
datep' Maybe Integer
mYear1

    let mYear2 = (Day -> Integer) -> Maybe Day -> Maybe Integer
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Day -> Integer
readYear Maybe Day
md1 Maybe Integer -> Maybe Integer -> Maybe Integer
forall a. Maybe a -> Maybe a -> Maybe a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> Maybe Integer
mYear1
    md2 <- optional $ char '=' *> datep' mYear2

    pure $ catMaybes [("date",) <$> md1, ("date2",) <$> md2]

  where
    readYear :: Day -> Integer
readYear = (Integer, Int, Int) -> Integer
forall {a} {b} {c}. (a, b, c) -> a
first3 ((Integer, Int, Int) -> Integer)
-> (Day -> (Integer, Int, Int)) -> Day -> Integer
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Day -> (Integer, Int, Int)
toGregorian
    isBracketedDateChar :: Char -> Bool
isBracketedDateChar Char
c = Char -> Bool
isDigit Char
c Bool -> Bool -> Bool
|| Char -> Bool
isDateSepChar Char
c Bool -> Bool -> Bool
|| Char
c Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'='

{-# INLINABLE bracketeddatetagsp #-}

-- | Get the account name aliases from options, if any.
-- A bad alias argument causes a program exit with a parse error message.
aliasesFromOpts :: InputOpts -> [AccountAlias]
aliasesFromOpts :: InputOpts -> [AccountAlias]
aliasesFromOpts = (String -> AccountAlias) -> [String] -> [AccountAlias]
forall a b. (a -> b) -> [a] -> [b]
map String -> AccountAlias
parseAliasOpt ([String] -> [AccountAlias])
-> (InputOpts -> [String]) -> InputOpts -> [AccountAlias]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. InputOpts -> [String]
aliases_
  where
    parseAliasOpt :: String -> AccountAlias
parseAliasOpt String
a =
      case Parsec HledgerParseErrorData CommoditySymbol AccountAlias
-> String
-> CommoditySymbol
-> Either HledgerParseErrors AccountAlias
forall e s a.
Parsec e s a -> String -> s -> Either (ParseErrorBundle s e) a
runParser Parsec HledgerParseErrorData CommoditySymbol AccountAlias
forall (m :: * -> *). TextParser m AccountAlias
accountaliasp String
"--alias" (String -> CommoditySymbol
T.pack String
a) of
        Right AccountAlias
alias -> AccountAlias
alias
        Left HledgerParseErrors
e      -> String -> AccountAlias
forall {b}. String -> b
error' (String -> AccountAlias) -> String -> AccountAlias
forall a b. (a -> b) -> a -> b
$ HledgerParseErrors -> String
customErrorBundlePretty HledgerParseErrors
e  -- PARTIAL:

accountaliasp :: TextParser m AccountAlias
accountaliasp :: forall (m :: * -> *). TextParser m AccountAlias
accountaliasp = TextParser m AccountAlias
forall (m :: * -> *). TextParser m AccountAlias
regexaliasp TextParser m AccountAlias
-> TextParser m AccountAlias -> TextParser m AccountAlias
forall a.
ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
-> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|> TextParser m AccountAlias
forall (m :: * -> *). TextParser m AccountAlias
basicaliasp

basicaliasp :: TextParser m AccountAlias
basicaliasp :: forall (m :: * -> *). TextParser m AccountAlias
basicaliasp = do
  -- dbgparse 0 "basicaliasp"
  old <- String -> String
rstrip (String -> String)
-> ParsecT HledgerParseErrorData CommoditySymbol m String
-> ParsecT HledgerParseErrorData CommoditySymbol m String
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m String
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
some (ParsecT HledgerParseErrorData CommoditySymbol m Char
 -> ParsecT HledgerParseErrorData CommoditySymbol m String)
-> ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m String
forall a b. (a -> b) -> a -> b
$ [Token CommoditySymbol]
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall (f :: * -> *) e s (m :: * -> *).
(Foldable f, MonadParsec e s m) =>
f (Token s) -> m (Token s)
noneOf (String
"=" :: [Char]))
  char '='
  skipNonNewlineSpaces
  new <- rstrip <$> anySingle `manyTill` eolof  -- eol in journal, eof in command lines, normally
  return $ BasicAlias (T.pack old) (T.pack new)

regexaliasp :: TextParser m AccountAlias
regexaliasp :: forall (m :: * -> *). TextParser m AccountAlias
regexaliasp = do
  -- dbgparse 0 "regexaliasp"
  (off1, off2, re) <- ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT HledgerParseErrorData CommoditySymbol m Char
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Int, Int, CommoditySymbol)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Int, Int, CommoditySymbol)
forall (m :: * -> *) open close a.
Applicative m =>
m open -> m close -> m a -> m a
between (Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'/') (Token CommoditySymbol
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Token CommoditySymbol)
forall e s (m :: * -> *).
(MonadParsec e s m, Token s ~ Char) =>
Token s -> m (Token s)
char Char
Token CommoditySymbol
'/') (ParsecT
   HledgerParseErrorData CommoditySymbol m (Int, Int, CommoditySymbol)
 -> ParsecT
      HledgerParseErrorData
      CommoditySymbol
      m
      (Int, Int, CommoditySymbol))
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Int, Int, CommoditySymbol)
-> ParsecT
     HledgerParseErrorData CommoditySymbol m (Int, Int, CommoditySymbol)
forall a b. (a -> b) -> a -> b
$ do
    off1 <- ParsecT HledgerParseErrorData CommoditySymbol m Int
forall e s (m :: * -> *). MonadParsec e s m => m Int
getOffset
    re <- fmap T.concat . some $
             (T.singleton <$> noneOf ("/\\\n\r" :: [Char]))               -- paranoid: don't try to read past line end
             <|> string "\\/"                                             -- allow escaping forward slashes
             <|> (liftM2 T.cons (char '\\') (T.singleton <$> anySingle))  -- Otherwise leave backslashes in
    off2 <- getOffset
    return (off1, off2, re)
  skipNonNewlineSpaces
  char '='
  skipNonNewlineSpaces
  repl <- anySingle `manyTill` eolof
  case toRegexCI re of
    Right Regexp
r -> AccountAlias
-> ParsecT HledgerParseErrorData CommoditySymbol m AccountAlias
forall a. a -> ParsecT HledgerParseErrorData CommoditySymbol m a
forall (m :: * -> *) a. Monad m => a -> m a
return (AccountAlias
 -> ParsecT HledgerParseErrorData CommoditySymbol m AccountAlias)
-> AccountAlias
-> ParsecT HledgerParseErrorData CommoditySymbol m AccountAlias
forall a b. (a -> b) -> a -> b
$! Regexp -> String -> AccountAlias
RegexAlias Regexp
r String
repl
    Left String
e  -> HledgerParseErrorData
-> ParsecT HledgerParseErrorData CommoditySymbol m AccountAlias
forall e s (m :: * -> *) a. MonadParsec e s m => e -> m a
customFailure (HledgerParseErrorData
 -> ParsecT HledgerParseErrorData CommoditySymbol m AccountAlias)
-> HledgerParseErrorData
-> ParsecT HledgerParseErrorData CommoditySymbol m AccountAlias
forall a b. (a -> b) -> a -> b
$! Int -> Int -> String -> HledgerParseErrorData
parseErrorAtRegion Int
off1 Int
off2 String
e

--- ** tests

tests_Common :: TestTree
tests_Common = String -> [TestTree] -> TestTree
testGroup String
"Common" [

   String -> [TestTree] -> TestTree
testGroup String
"amountp" [
    String -> IO () -> TestTree
testCase String
"basic"                  (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> Amount -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
amountp CommoditySymbol
"$47.18"     (Quantity -> Amount
usd Quantity
47.18)
   ,String -> IO () -> TestTree
testCase String
"ends with decimal mark" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> Amount -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
amountp CommoditySymbol
"$1."        (Quantity -> Amount
usd Quantity
1  Amount -> AmountPrecision -> Amount
`withPrecision` Word8 -> AmountPrecision
Precision Word8
0)
   ,String -> IO () -> TestTree
testCase String
"unit price"             (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> Amount -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
amountp CommoditySymbol
"$10 @ €0.5"
      -- not precise enough:
      -- (usd 10 `withPrecision` 0 `at` (eur 0.5 `withPrecision` 1)) -- `withStyle` asdecimalmark=Just '.'
      Amount
nullamt{
         acommodity="$"
        ,aquantity=10 -- need to test internal precision with roundTo ? I think not
        ,astyle=amountstyle{asprecision=Precision 0, asdecimalmark=Nothing}
        ,acost=Just $ UnitCost $
          nullamt{
             acommodity="€"
            ,aquantity=0.5
            ,astyle=amountstyle{asprecision=Precision 1, asdecimalmark=Just '.'}
            }
        }
   ,String -> IO () -> TestTree
testCase String
"total price"            (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> Amount -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
amountp CommoditySymbol
"$10 @@ €5"
      Amount
nullamt{
         acommodity="$"
        ,aquantity=10
        ,astyle=amountstyle{asprecision=Precision 0, asdecimalmark=Nothing}
        ,acost=Just $ TotalCost $
          nullamt{
             acommodity="€"
            ,aquantity=5
            ,astyle=amountstyle{asprecision=Precision 0, asdecimalmark=Nothing}
            }
        }
   ,String -> IO () -> TestTree
testCase String
"unit price, parenthesised" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> IO ()
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> IO ()
assertParse StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
amountp CommoditySymbol
"$10 (@) €0.5"
   ,String -> IO () -> TestTree
testCase String
"total price, parenthesised" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> IO ()
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> IO ()
assertParse StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
amountp CommoditySymbol
"$10 (@@) €0.5"
   ]

  ,let p :: JournalParser m Amount
p = AmountParseKind -> JournalParser m Amount
forall (m :: * -> *). AmountParseKind -> JournalParser m Amount
postingamountp AmountParseKind
OrdinaryAmount
       -- the parts of the result which the expression rules decide
       costParts :: AmountCost -> (String, CommoditySymbol, Quantity)
costParts (UnitCost Amount
a)  = (String
"@" :: String, Amount -> CommoditySymbol
acommodity Amount
a, Amount -> Quantity
aquantity Amount
a)
       costParts (TotalCost Amount
a) = (String
"@@", Amount -> CommoditySymbol
acommodity Amount
a, Amount -> Quantity
aquantity Amount
a)
       eq :: CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
input CommoditySymbol
c Quantity
q Word8
prec = StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol
-> (Amount -> (CommoditySymbol, Quantity, AmountPrecision))
-> (CommoditySymbol, Quantity, AmountPrecision)
-> IO ()
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> (a -> b) -> b -> IO ()
assertParseEqOn StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
p CommoditySymbol
input (\Amount
a -> (Amount -> CommoditySymbol
acommodity Amount
a, Amount -> Quantity
aquantity Amount
a, AmountStyle -> AmountPrecision
asprecision (AmountStyle -> AmountPrecision) -> AmountStyle -> AmountPrecision
forall a b. (a -> b) -> a -> b
$ Amount -> AmountStyle
astyle Amount
a)) (CommoditySymbol
c, Quantity
q, Word8 -> AmountPrecision
Precision Word8
prec)
   in String -> [TestTree] -> TestTree
testGroup String
"postingamountp" [
     String -> IO () -> TestTree
testCase String
"a simple amount is unchanged"  (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> Amount -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
p CommoditySymbol
"$47.18" (Quantity -> Amount
usd Quantity
47.18)
    ,String -> IO () -> TestTree
testCase String
"the example in #2648"          (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"$-50.20 + $-209.00 + $-16.54 + $-438" CommoditySymbol
"$" (-Quantity
713.74) Word8
2
    ,String -> IO () -> TestTree
testCase String
"subtraction, spaces optional"  (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"10 EUR-2.50 EUR" CommoditySymbol
"EUR" Quantity
7.5 Word8
2
    ,String -> IO () -> TestTree
testCase String
"a sign after an operator"      (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"$10 - -$5" CommoditySymbol
"$" Quantity
15 Word8
0
    ,String -> IO () -> TestTree
testCase String
"* and / before + and -"        (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"$1 + $2 * 3" CommoditySymbol
"$" Quantity
7 Word8
0
    ,String -> IO () -> TestTree
testCase String
"parentheses"                   (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"($1 + $2) * 3" CommoditySymbol
"$" Quantity
9 Word8
0
    ,String -> IO () -> TestTree
testCase String
"nested parentheses"            (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"((1.0 + 2) * (3 - 1)) / 4" CommoditySymbol
"" Quantity
1.5 Word8
1
    ,String -> IO () -> TestTree
testCase String
"a sign before parentheses"     (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"-($1 + $2) - +($3)" CommoditySymbol
"$" (-Quantity
6) Word8
0
    ,String -> IO () -> TestTree
testCase String
"/ with a right-side symbol"    (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"10.00 EUR / 4" CommoditySymbol
"EUR" Quantity
2.5 Word8
2
    ,String -> IO () -> TestTree
testCase String
"a right-side symbol in parentheses" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"(10.00 EUR + 5 EUR) / 4" CommoditySymbol
"EUR" Quantity
3.75 Word8
2
    ,String -> IO () -> TestTree
testCase String
"* is exact, with the amount's precision" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"$47.97 * 0.05" CommoditySymbol
"$" Quantity
2.3985 Word8
2
    ,String -> IO () -> TestTree
testCase String
"/ is exact, with the amount's precision" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$
       StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol
-> (Amount -> (Bool, AmountPrecision))
-> (Bool, AmountPrecision)
-> IO ()
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> (a -> b) -> b -> IO ()
assertParseEqOn StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
p CommoditySymbol
"$100.00 / 3" (\Amount
a -> (Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
> Quantity
33.3333333 Bool -> Bool -> Bool
&& Amount -> Quantity
aquantity Amount
a Quantity -> Quantity -> Bool
forall a. Ord a => a -> a -> Bool
< Quantity
33.3333334, AmountStyle -> AmountPrecision
asprecision (AmountStyle -> AmountPrecision) -> AmountStyle -> AmountPrecision
forall a b. (a -> b) -> a -> b
$ Amount -> AmountStyle
astyle Amount
a)) (Bool
True, Word8 -> AmountPrecision
Precision Word8
2)
    ,String -> IO () -> TestTree
testCase String
"an amount on the right of *"   (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"3 * $10.005" CommoditySymbol
"$" Quantity
30.015 Word8
3
    ,String -> IO () -> TestTree
testCase String
"the plain number's decimal places don't count" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"0.5 * $10" CommoditySymbol
"$" Quantity
5 Word8
0
    ,String -> IO () -> TestTree
testCase String
"two plain numbers use the left one's precision" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"5 / 2" CommoditySymbol
"" Quantity
2.5 Word8
0
    ,String -> IO () -> TestTree
testCase String
"precision of + is the larger"  (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"$1 + $0.5" CommoditySymbol
"$" Quantity
1.5 Word8
1
    ,String -> IO () -> TestTree
testCase String
"a number takes the other side's commodity" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
       CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"$10 + 5.5" CommoditySymbol
"$" Quantity
15.5 Word8
1
       CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"5 - $10" CommoditySymbol
"$" (-Quantity
5) Word8
0
       CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"(2 + 3) * 10 EUR" CommoditySymbol
"EUR" Quantity
50 Word8
0
       StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> (Amount -> Side) -> Side -> IO ()
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> (a -> b) -> b -> IO ()
assertParseEqOn StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
p CommoditySymbol
"5 + 10 EUR" (AmountStyle -> Side
ascommodityside (AmountStyle -> Side) -> (Amount -> AmountStyle) -> Amount -> Side
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> AmountStyle
astyle) Side
R
    ,String -> IO () -> TestTree
testCase String
"a cost applies to the result"  (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol
-> (Amount
    -> (Quantity, Maybe (String, CommoditySymbol, Quantity)))
-> (Quantity, Maybe (String, CommoditySymbol, Quantity))
-> IO ()
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> (a -> b) -> b -> IO ()
assertParseEqOn StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
p CommoditySymbol
"1 X + 2 X @ $3" (\Amount
a -> (Amount -> Quantity
aquantity Amount
a, AmountCost -> (String, CommoditySymbol, Quantity)
costParts (AmountCost -> (String, CommoditySymbol, Quantity))
-> Maybe AmountCost -> Maybe (String, CommoditySymbol, Quantity)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Amount -> Maybe AmountCost
acost Amount
a)) (Quantity
3, (String, CommoditySymbol, Quantity)
-> Maybe (String, CommoditySymbol, Quantity)
forall a. a -> Maybe a
Just (String
"@", CommoditySymbol
"$", Quantity
3))
    ,String -> IO () -> TestTree
testCase String
"different commodities"         (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
p CommoditySymbol
"$1 + 1 EUR" String
"can't add amounts with different commodities ($ and EUR)"
    ,String -> IO () -> TestTree
testCase String
"two amounts with commodities in *" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
p CommoditySymbol
"$2 * $1" String
"can't multiply two amounts with commodity symbols"
    ,String -> IO () -> TestTree
testCase String
"a number divided by an amount has its commodity and precision" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
       CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"9 / $3" CommoditySymbol
"$" Quantity
3 Word8
0
       CommoditySymbol -> CommoditySymbol -> Quantity -> Word8 -> IO ()
eq CommoditySymbol
"3 / 1.50 EUR" CommoditySymbol
"EUR" Quantity
2 Word8
2
       StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> (Amount -> Side) -> Side -> IO ()
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> (a -> b) -> b -> IO ()
assertParseEqOn StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
p CommoditySymbol
"1 / 1.25 EUR" (AmountStyle -> Side
ascommodityside (AmountStyle -> Side) -> (Amount -> AmountStyle) -> Amount -> Side
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Amount -> AmountStyle
astyle) Side
R
    ,String -> IO () -> TestTree
testCase String
"two amounts with commodities in /" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
p CommoditySymbol
"$9 / $3" String
"can't divide two amounts with commodity symbols"
    ,String -> IO () -> TestTree
testCase String
"division by zero"              (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
       StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
p CommoditySymbol
"$1 / 0" String
"can't divide by zero"
       StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
p CommoditySymbol
"1 / $0" String
"can't divide by zero"
    ,String -> IO () -> TestTree
testCase String
"no space before / after a commodity symbol" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
       StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
p CommoditySymbol
"10 EUR/4" String
"this / is read as part of the commodity symbol EUR/; to divide, write a space before it"
       StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
p CommoditySymbol
"10 EUR/ 4" String
"this / is read as part of the commodity symbol EUR/"
       StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
p CommoditySymbol
"10 EUR/-2" String
"this / is read as part of the commodity symbol EUR/"
       StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol
-> (Amount -> CommoditySymbol)
-> CommoditySymbol
-> IO ()
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> (a -> b) -> b -> IO ()
assertParseEqOn StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
p CommoditySymbol
"10 EUR/ + 2 EUR/" Amount -> CommoditySymbol
acommodity CommoditySymbol
"EUR/"
    ,String -> IO () -> TestTree
testCase String
"an unclosed parenthesis"       (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
p CommoditySymbol
"($1 + $2" String
"closing parenthesis"
    ,String -> IO () -> TestTree
testCase String
"the default commodity applies only to a result with no commodity" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
       let p' :: StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
p' = (Journal -> Journal)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' (\Journal
j -> Journal
j{jparsedefaultcommodity=Just ("$", amountstyle)}) StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall (m :: * -> *). JournalParser m Amount
p
           on :: CommoditySymbol
-> (Amount -> (CommoditySymbol, Quantity))
-> (CommoditySymbol, Quantity)
-> IO ()
on = StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol
-> (Amount -> (CommoditySymbol, Quantity))
-> (CommoditySymbol, Quantity)
-> IO ()
forall b st a.
(HasCallStack, Eq b, Show b, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> (a -> b) -> b -> IO ()
assertParseEqOn StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). JournalParser m Amount
p'
       CommoditySymbol
-> (Amount -> (CommoditySymbol, Quantity))
-> (CommoditySymbol, Quantity)
-> IO ()
on CommoditySymbol
"10 EUR * 2" (\Amount
a -> (Amount -> CommoditySymbol
acommodity Amount
a, Amount -> Quantity
aquantity Amount
a)) (CommoditySymbol
"EUR", Quantity
20)
       CommoditySymbol
-> (Amount -> (CommoditySymbol, Quantity))
-> (CommoditySymbol, Quantity)
-> IO ()
on CommoditySymbol
"10 EUR + 2" (\Amount
a -> (Amount -> CommoditySymbol
acommodity Amount
a, Amount -> Quantity
aquantity Amount
a)) (CommoditySymbol
"EUR", Quantity
12)
       CommoditySymbol
-> (Amount -> (CommoditySymbol, Quantity))
-> (CommoditySymbol, Quantity)
-> IO ()
on CommoditySymbol
"10 + 2"     (\Amount
a -> (Amount -> CommoditySymbol
acommodity Amount
a, Amount -> Quantity
aquantity Amount
a)) (CommoditySymbol
"$", Quantity
12)
    ]

  ,let p :: JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p = ParsecT
  HledgerParseErrorData
  CommoditySymbol
  IO
  (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> JournalParser
     IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (Maybe AmountStyle
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     IO
     (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
forall (m :: * -> *).
Maybe AmountStyle
-> TextParser
     m (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
numberp Maybe AmountStyle
forall a. Maybe a
Nothing) :: JournalParser IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle) in
   String -> IO () -> TestTree
testCase String
"numberp" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
"0"          (Quantity
0, Word8
0, Maybe Char
forall a. Maybe a
Nothing, Maybe DigitGroupStyle
forall a. Maybe a
Nothing)
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
"1"          (Quantity
1, Word8
0, Maybe Char
forall a. Maybe a
Nothing, Maybe DigitGroupStyle
forall a. Maybe a
Nothing)
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
"1.1"        (Quantity
1.1, Word8
1, Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'.', Maybe DigitGroupStyle
forall a. Maybe a
Nothing)
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
"1,000.1"    (Quantity
1000.1, Word8
1, Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'.', DigitGroupStyle -> Maybe DigitGroupStyle
forall a. a -> Maybe a
Just (DigitGroupStyle -> Maybe DigitGroupStyle)
-> DigitGroupStyle -> Maybe DigitGroupStyle
forall a b. (a -> b) -> a -> b
$ Char -> [Word8] -> DigitGroupStyle
DigitGroups Char
',' [Word8
3])
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
"1_000.1"    (Quantity
1000.1, Word8
1, Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'.', DigitGroupStyle -> Maybe DigitGroupStyle
forall a. a -> Maybe a
Just (DigitGroupStyle -> Maybe DigitGroupStyle)
-> DigitGroupStyle -> Maybe DigitGroupStyle
forall a b. (a -> b) -> a -> b
$ Char -> [Word8] -> DigitGroupStyle
DigitGroups Char
'_' [Word8
3])
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
"1'000.1"    (Quantity
1000.1, Word8
1, Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'.', DigitGroupStyle -> Maybe DigitGroupStyle
forall a. a -> Maybe a
Just (DigitGroupStyle -> Maybe DigitGroupStyle)
-> DigitGroupStyle -> Maybe DigitGroupStyle
forall a b. (a -> b) -> a -> b
$ Char -> [Word8] -> DigitGroupStyle
DigitGroups Char
'\'' [Word8
3])
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
"1.00.000,1" (Quantity
100000.1, Word8
1, Char -> Maybe Char
forall a. a -> Maybe a
Just Char
',', DigitGroupStyle -> Maybe DigitGroupStyle
forall a. a -> Maybe a
Just (DigitGroupStyle -> Maybe DigitGroupStyle)
-> DigitGroupStyle -> Maybe DigitGroupStyle
forall a b. (a -> b) -> a -> b
$ Char -> [Word8] -> DigitGroupStyle
DigitGroups Char
'.' [Word8
3,Word8
2])
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
"1,000,000"  (Quantity
1000000, Word8
0, Maybe Char
forall a. Maybe a
Nothing, DigitGroupStyle -> Maybe DigitGroupStyle
forall a. a -> Maybe a
Just (DigitGroupStyle -> Maybe DigitGroupStyle)
-> DigitGroupStyle -> Maybe DigitGroupStyle
forall a b. (a -> b) -> a -> b
$ Char -> [Word8] -> DigitGroupStyle
DigitGroups Char
',' [Word8
3,Word8
3])  -- could be simplified to [3]
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
"1."         (Quantity
1, Word8
0, Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'.', Maybe DigitGroupStyle
forall a. Maybe a
Nothing)
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
"1,"         (Quantity
1, Word8
0, Char -> Maybe Char
forall a. a -> Maybe a
Just Char
',', Maybe DigitGroupStyle
forall a. Maybe a
Nothing)
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
".1"         (Quantity
0.1, Word8
1, Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'.', Maybe DigitGroupStyle
forall a. Maybe a
Nothing)
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
",1"         (Quantity
0.1, Word8
1, Char -> Maybe Char
forall a. a -> Maybe a
Just Char
',', Maybe DigitGroupStyle
forall a. Maybe a
Nothing)
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
"" String
""
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
"1,000.000,1" String
""
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
"1.000,000.1" String
""
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
"1,000.000.1" String
""
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
"1,,1" String
""
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
"1..1" String
""
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
".1," String
""
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
",1." String
""
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq    JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
"1.555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555" (Quantity
1.555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555, Word8
255, Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'.', Maybe DigitGroupStyle
forall a. Maybe a
Nothing)
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p CommoditySymbol
"1.5555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555" String
""

  ,String -> IO () -> TestTree
testCase String
"numberp with a suggested decimal mark" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     let p :: Char
-> JournalParser
     IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p Char
c = ParsecT
  HledgerParseErrorData
  CommoditySymbol
  IO
  (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> JournalParser
     IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
forall (m :: * -> *) a. Monad m => m a -> StateT Journal m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (Maybe AmountStyle
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     IO
     (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
forall (m :: * -> *).
Maybe AmountStyle
-> TextParser
     m (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
numberp (Maybe AmountStyle
 -> ParsecT
      HledgerParseErrorData
      CommoditySymbol
      IO
      (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle))
-> Maybe AmountStyle
-> ParsecT
     HledgerParseErrorData
     CommoditySymbol
     IO
     (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
forall a b. (a -> b) -> a -> b
$ AmountStyle -> Maybe AmountStyle
forall a. a -> Maybe a
Just AmountStyle
amountstyle{asdecimalmark=Just c}) :: JournalParser IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq    (Char
-> JournalParser
     IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p Char
'.') CommoditySymbol
"1.000"        (Quantity
1, Word8
3, Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'.', Maybe DigitGroupStyle
forall a. Maybe a
Nothing)
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq    (Char
-> JournalParser
     IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p Char
',') CommoditySymbol
"1.000"        (Quantity
1000, Word8
0, Maybe Char
forall a. Maybe a
Nothing, DigitGroupStyle -> Maybe DigitGroupStyle
forall a. a -> Maybe a
Just (DigitGroupStyle -> Maybe DigitGroupStyle)
-> DigitGroupStyle -> Maybe DigitGroupStyle
forall a b. (a -> b) -> a -> b
$ Char -> [Word8] -> DigitGroupStyle
DigitGroups Char
'.' [Word8
3])
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq    (Char
-> JournalParser
     IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p Char
',') CommoditySymbol
"1.000.000"    (Quantity
1000000, Word8
0, Maybe Char
forall a. Maybe a
Nothing, DigitGroupStyle -> Maybe DigitGroupStyle
forall a. a -> Maybe a
Just (DigitGroupStyle -> Maybe DigitGroupStyle)
-> DigitGroupStyle -> Maybe DigitGroupStyle
forall a b. (a -> b) -> a -> b
$ Char -> [Word8] -> DigitGroupStyle
DigitGroups Char
'.' [Word8
3,Word8
3])
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq    (Char
-> JournalParser
     IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p Char
'.') CommoditySymbol
"1,000,000"    (Quantity
1000000, Word8
0, Maybe Char
forall a. Maybe a
Nothing, DigitGroupStyle -> Maybe DigitGroupStyle
forall a. a -> Maybe a
Just (DigitGroupStyle -> Maybe DigitGroupStyle)
-> DigitGroupStyle -> Maybe DigitGroupStyle
forall a b. (a -> b) -> a -> b
$ Char -> [Word8] -> DigitGroupStyle
DigitGroups Char
',' [Word8
3,Word8
3])
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq    (Char
-> JournalParser
     IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p Char
'.') CommoditySymbol
"1 000 000"    (Quantity
1000000, Word8
0, Maybe Char
forall a. Maybe a
Nothing, DigitGroupStyle -> Maybe DigitGroupStyle
forall a. a -> Maybe a
Just (DigitGroupStyle -> Maybe DigitGroupStyle)
-> DigitGroupStyle -> Maybe DigitGroupStyle
forall a b. (a -> b) -> a -> b
$ Char -> [Word8] -> DigitGroupStyle
DigitGroups Char
' ' [Word8
3,Word8
3])
     -- the suggested decimal mark is used only for disambiguation, not enforced
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq    (Char
-> JournalParser
     IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p Char
'.') CommoditySymbol
"1.2.34"       (Quantity
1234, Word8
0, Maybe Char
forall a. Maybe a
Nothing, DigitGroupStyle -> Maybe DigitGroupStyle
forall a. a -> Maybe a
Just (DigitGroupStyle -> Maybe DigitGroupStyle)
-> DigitGroupStyle -> Maybe DigitGroupStyle
forall a b. (a -> b) -> a -> b
$ Char -> [Word8] -> DigitGroupStyle
DigitGroups Char
'.' [Word8
2,Word8
1,Word8
1])
     JournalParser
  IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> CommoditySymbol
-> (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
-> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq    (Char
-> JournalParser
     IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
p Char
',') CommoditySymbol
"1,000,000.00" (Quantity
1000000, Word8
2, Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'.', DigitGroupStyle -> Maybe DigitGroupStyle
forall a. a -> Maybe a
Just (DigitGroupStyle -> Maybe DigitGroupStyle)
-> DigitGroupStyle -> Maybe DigitGroupStyle
forall a b. (a -> b) -> a -> b
$ Char -> [Word8] -> DigitGroupStyle
DigitGroups Char
',' [Word8
3,Word8
3])

  ,String -> IO () -> TestTree
testCase String
"amountp with a decimal-mark directive" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ do
     let p :: AmountParseKind
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
p AmountParseKind
kind = (Journal -> Journal)
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify' (\Journal
j -> Journal
j{jparsedecimalmark=Just ','}) StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) ()
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall a b.
StateT Journal (ParsecT HledgerParseErrorData CommoditySymbol m) a
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> AmountParseKind
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol m) Amount
forall (m :: * -> *). AmountParseKind -> JournalParser m Amount
amountp' AmountParseKind
kind
     StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> IO ()
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> IO ()
assertParse      (AmountParseKind
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). AmountParseKind -> JournalParser m Amount
p AmountParseKind
OrdinaryAmount) CommoditySymbol
"1.000,5 EUR"
     StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError (AmountParseKind
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). AmountParseKind -> JournalParser m Amount
p AmountParseKind
OrdinaryAmount) CommoditySymbol
"1,000.5 EUR"       String
"number's decimal mark is '.'"
     StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError (AmountParseKind
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). AmountParseKind -> JournalParser m Amount
p AmountParseKind
OrdinaryAmount) CommoditySymbol
".5 EUR"            String
"number's decimal mark is '.'"
     StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError (AmountParseKind
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). AmountParseKind -> JournalParser m Amount
p AmountParseKind
OrdinaryAmount) CommoditySymbol
"1 X @ 1,000.5 EUR" String
"number's decimal mark is '.'"
     StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> String -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> String -> IO ()
assertParseError (AmountParseKind
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). AmountParseKind -> JournalParser m Amount
p AmountParseKind
OrdinaryAmount) CommoditySymbol
"1,000,000 EUR"     String
"so it can appear only once"
     -- directives declaring a display style may use a different decimal mark
     StateT
  Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
-> CommoditySymbol -> IO ()
forall st a.
(HasCallStack, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> IO ()
assertParse      (AmountParseKind
-> StateT
     Journal (ParsecT HledgerParseErrorData CommoditySymbol IO) Amount
forall (m :: * -> *). AmountParseKind -> JournalParser m Amount
p AmountParseKind
StyleAmount)    CommoditySymbol
"1,000.5 EUR"

  ,String -> [TestTree] -> TestTree
testGroup String
"spaceandamountormissingp" [
     String -> IO () -> TestTree
testCase String
"space and amount" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol IO)
  MixedAmount
-> CommoditySymbol -> MixedAmount -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol IO)
  MixedAmount
forall (m :: * -> *). JournalParser m MixedAmount
spaceandamountormissingp CommoditySymbol
" $47.18" (Amount -> MixedAmount
mixedAmount (Amount -> MixedAmount) -> Amount -> MixedAmount
forall a b. (a -> b) -> a -> b
$ Quantity -> Amount
usd Quantity
47.18)
    ,String -> IO () -> TestTree
testCase String
"empty string" (IO () -> TestTree) -> IO () -> TestTree
forall a b. (a -> b) -> a -> b
$ StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol IO)
  MixedAmount
-> CommoditySymbol -> MixedAmount -> IO ()
forall a st.
(HasCallStack, Eq a, Show a, Default st) =>
StateT st (ParsecT HledgerParseErrorData CommoditySymbol IO) a
-> CommoditySymbol -> a -> IO ()
assertParseEq StateT
  Journal
  (ParsecT HledgerParseErrorData CommoditySymbol IO)
  MixedAmount
forall (m :: * -> *). JournalParser m MixedAmount
spaceandamountormissingp CommoditySymbol
"" MixedAmount
missingmixedamt
    -- ,testCase "just space" $ assertParseEq spaceandamountormissingp " " missingmixedamt  -- XXX should it ?
    -- ,testCase "just amount" $ assertParseError spaceandamountormissingp "$47.18" ""  -- succeeds, consuming nothing
    ]

  ]