packages feed

hledger-lib-2.0: Hledger/Read/Common.hs

--- * -*- 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.
   rFormat :: StorageFormat
    -- The file extensions recognised as containing this format.
  ,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.
  ,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).
  ,rParser :: MonadIO m => InputOpts -> ErroringJournalParser m ParsedJournal
  }

instance Show (Reader m) where show r = show (rFormat r) ++ " 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 r = case rFormat r of
  Sep _ -> True
  Rules -> True
  _     -> 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 readfn = do
  j <- 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 f = case splitAtElement ':' f of
  [_,"-"] -> True
  ["-"] -> True
  _ -> 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 usecoloronstdout 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 =  -- keep synced with Check.*
             boolopt "strict" rawopts 
          || (stringopt "args" rawopts == "balanced" && stringopt "command" rawopts == "check")

        -- Do we really need to do all this work just to get the requested end date? This is duplicating
        -- much of reportOptsToSpec.
        ropts = rawOptsToReportOpts day usecoloronstdout rawopts
        argsquery = map fst . rights . map (parseQueryTerm day) $ querystring_ ropts
        datequery = simplifyQuery . filterQuery queryIsDate . And $ queryFromFlags ropts : argsquery

        txnbalancingprecision = either err id $ transactionBalancingPrecisionFromOpts rawopts
          where err e = error' $ "could not parse --txn-tolerance: " ++ e  -- PARTIAL:

        styles = either err id $ commodityStyleFromRawOpts rawopts
          where err e = error' $ "could not parse --commodity-style: '" ++ e ++ "'"  -- PARTIAL:

    in 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 p iopts fp =
  p iopts fp <=< dbgTimeIO 1 ("read " <> takeFileName fp) <=< lift . hGetContentsPortably 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 d rawopts = do
    arg <- maybestringopt "forecast" rawopts
    let period = parsePeriodExpr d . textStripQuotes $ T.pack arg
    return $ if null arg then nulldatespan else either badParse (getSpan arg) period
  where
    badParse e = usageError $ "could not parse forecast period: "++customErrorBundlePretty e
    getSpan arg (interval, requestedspan) = case interval of
        NoInterval -> requestedspan
        _          -> usageError $ "--forecast's argument should not contain a report interval ("
                                 ++ show interval ++ " in \"" ++ arg ++ "\")"

-- | 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 =
  foldM (\r -> fmap (\(c,a) -> M.insert c a r) . parseCommodity) mempty optList
  where
    optList = listofstringopt "commodity-style" rawOpts
    parseCommodity optStr = case parseamount optStr of
      Left _ -> Left optStr
      Right (Amount acommodity _ astyle _ _) -> Right (acommodity, 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 =
  case maybestringopt "txn-tolerance" rawopts of
    Nothing        -> Right TBPEntry
    Just "entry"   -> Right TBPEntry
    Just "display" -> Right TBPDisplay
    Just s         -> Left $ "'"<>s<>"', 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 parser iopts f txt =
    initialiseAndParseJournal parser iopts f txt >>= journalFinalise iopts f 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 parser iopts f txt = do
    cf <- liftIO $ canonicalizePath f
    prettyParseErrors (runParserT (evalStateT parser (initJournal cf)) f txt)
      >>= dbgTimeIO 1 ("parse " <> takeFileName f)
      >>= \j -> j <$ dbgFastPathStats (jparsefastpathstats j)
  where
    y = first3 . toGregorian $ _ioDay iopts
    initJournal cf = 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 = withExceptT customErrorBundlePretty . liftEither
                    <=< withExceptT (finalErrorBundlePretty . attachSource f 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 FastPathStats{..}
  | debugLevel < 1 || null shares = return ()
  | otherwise = dbgMsgIO 1 $ "fast path was used for " ++ intercalate ", " shares ++ declined
  where
    shares = [share fpsTxnsFast   fpsTxnsGeneral   "transactions" | fpsTxnsFast   + fpsTxnsGeneral   > 0]
          ++ [share fpsPricesFast fpsPricesGeneral "prices"       | fpsPricesFast + fpsPricesGeneral > 0]
    -- eg "51% of 900 transactions" (the percentage rounded)
    share fast general what = show ((200 * fast + total) `div` (2 * total)) ++ "% of " ++ show total ++ " " ++ what
      where total = fast + general
    declined
      | M.null fpsDeclines = ""
      | otherwise = "; declined: " ++ intercalate ", "
          [show n ++ " " ++ T.unpack reason | (reason, n) <- sortOn (negate . snd) $ M.toList 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 = 100000

journalFinalise :: InputOpts -> FilePath -> Text -> ParsedJournal -> ExceptT String IO Journal
journalFinalise InputOpts{_scanfiles=True} f txt pj =
  -- just finding the files read: record the main file's info, put lists in parse order, and stop
  return $ pj & journalAddFile (JournalFile f txt 0) & journalReverse
journalFinalise iopts@InputOpts{auto_,balancingopts_,ignore_lots_,infer_costs_,infer_equity_,strict_,verbose_tags_,_ioDay} f txt pj = do
  let
    BalancingOpts{commodity_styles_, ignore_assertions_} = balancingopts_
    -- Hack: peek at the command line to know if certain checks were requested.
    checking checkname = "check" `elem` args && checkname `elem` args where args = progArgs
    checkordereddates = checking "ordereddates"
    checkassertions = not ignore_assertions_ || strict_ || checking "assertions"
    lotschecking    = not ignore_lots_       || strict_ || checking "lots"  -- are lot checks wanted ?
    lenientlots     = not lotschecking
    haslots         = journalHasLotFeatures pj  -- does the journal use lots at all ? if not, the lot stages are skipped, they would do nothing
    checklots       = haslots && 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  name stage = dbgTime 1 name . stage          -- a stage returning a Journal
    timedE name stage = fmap (dbgTime 1 name) . stage   -- a stage returning an Either error Journal

  t <- liftIO 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) $ \forecastspan -> do
    let n = sum [ length $ periodicTransactionDates pt forecastspan | pt <- jperiodictxns pj ]
    when (n > maxExpectedForecastTxns) $ warnIO $ printf
      ("--forecast would generate %d transactions (forecast period %s),\n"
      <> "using a lot of memory. If not intended, press control-C now, and check for a mistyped date.")
      n (showDateSpan 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
      >>= (\j -> if checkordereddates then journalCheckOrdereddates j $> j else Right j)     -- maybe check that journal entries are in date order
      >>= (\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) <- timedE "journalBalanceTransactionsAndDeferAssertions"
              (journalBalanceTransactionsAndDeferAssertions
                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}) 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" (\j4 -> journalCheckAssertsWith iopts j4 $> 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{_forecastOnlyForDisplay, _ioDay} j =
  journalCheckAsserts _ioDay $
    if _forecastOnlyForDisplay then j{jtxns = filter (not . isForecast) $ jtxns j} else j
  where isForecast = isJust . lookup generatedTransactionTagName . 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 verbosetags d bopts =
    -- Balance all transactions without checking balance assertions,
    journalBalanceTransactions 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.)
    >=> journalModifyTransactions verbosetags 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 _ Nothing j = j
journalAddForecast verbosetags (Just forecastspan) j = j{jtxns = jtxns j ++ forecasttxns}
  where
    {-# HLINT ignore "Move concatMap out" #-}
    forecasttxns =
        map (txnTieKnot . transactionTransformPostings (styleAmounts $ journalCommodityStyles j))
      . filter (spanContainsDate forecastspan . tdate)
      . concatMap (\pt -> runPeriodicTransaction verbosetags pt forecastspan)
      $ jperiodictxns 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 lenient j = do
  txns' <- mapM processTransaction (jtxns j)
  Right j{jtxns = txns'}
  where
    parseAmt s = case parseamount s of
      Right a  -> Just a
      Left _   -> Nothing

    processTransaction t = do
      ps' <- mapM processPosting (tpostings t)
      Right t{tpostings = ps'}

    processPosting p
      | lenient   = Right $ either (const p) id $ inferPosting p
      | otherwise = inferPosting p

    inferPosting p = case lotSubaccountName (paccount p) of
      Nothing   -> Right p
      Just name -> do
        cb <- first (lotErr p) $ parseLotName parseAmt 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 a = case acostbasis a of
              Nothing -> Right a{acostbasis = Just cb}
              Just existing -> do
                merged <- first (lotConflictErr p) $ mergeCostBasis cb 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 p msg = lotPosErr p $ msg
      ++ "\n\nA final account name part enclosed in { } must be a valid lot subaccount name."
      ++ "\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 p msg = lotPosErr p $ msg
      ++ "\n\nThe lot subaccount name and the amount's lot annotation must agree."
      ++ "\nPlease make them match, or remove one of them."

    lotPosErr :: Posting -> String -> String
    lotPosErr p msg = printf "%s:%d:\n%s\n%s" f line ex msg
      where (f, line, _, ex) = makePostingAccountErrorExcerpt p

setYear :: Year -> JournalParser m ()
setYear y = modify' (\j -> j{jparsedefaultyear=Just y})

getYear :: JournalParser m (Maybe Year)
getYear = fmap jparsedefaultyear get

dp :: String -> TextParser m ()
dp = const $ 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 = journalDecimalMarkStyle <$> get

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

setDefaultCommodityAndStyle :: (CommoditySymbol,AmountStyle) -> JournalParser m ()
setDefaultCommodityAndStyle cs = modify' (\j -> j{jparsedefaultcommodity=Just cs})

getDefaultCommodityAndStyle :: JournalParser m (Maybe (CommoditySymbol,AmountStyle))
getDefaultCommodityAndStyle = jparsedefaultcommodity `fmap` 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 = fmap snd <$> 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 commodity = flip journalAmountStyleFor commodity <$> 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{jdeclaredcommodities, jparsedefaultcommodity} commodity =
  listToMaybe $ catMaybes [M.lookup commodity jdeclaredcommodities >>= cformat, snd <$> 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 s = do
  styles <- jparseamountstyles <$> get
  case S.lookupLE s styles of
    Just s' | s' == s -> return s'
    _ -> do
      modify' $ \j -> j{jparseamountstyles = S.insert s styles}
      return 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 t = do
  texts <- jparsetexts <$> get
  case S.lookupLE t texts of
    Just t' | t' == t -> return t'
    _ -> do
      let t' = T.copy t  -- don't retain the whole input text this is a slice of
      modify' $ \j -> j{jparsetexts = S.insert t' texts}
      return t'

addDeclaredAccountTags :: AccountName -> [Tag] -> JournalParser m ()
addDeclaredAccountTags acct atags =
  modify' (\j -> j{jdeclaredaccounttags = M.insertWith (flip union) acct atags (jdeclaredaccounttags j)})

addDeclaredAccountType :: AccountName -> AccountType -> JournalParser m ()
addDeclaredAccountType acct atype =
  modify' (\j -> j{jdeclaredaccounttypes = M.insertWith (++) atype [acct] (jdeclaredaccounttypes j)})

pushParentAccount :: AccountName -> JournalParser m ()
pushParentAccount acct = modify' (\j -> j{jparseparentaccounts = acct : jparseparentaccounts j})

getParentAccount :: JournalParser m AccountName
getParentAccount = fmap (concatAccountNames . reverse . jparseparentaccounts) 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' = do
  o <- getOffset
  manchor <- jparsepos <$> get
  pos <- case manchor of
    Just (ParsePos anchor@(SourcePos f l _) o0 s0) | o >= o0 -> do
      let
        consumed = T.take (o - o0) s0  -- the text between the anchor and here
        newlines = T.count "\n" consumed
        -- walk the current line only: from the anchor if that is on this line, else from the line's start
        (startpos, lineprefix)
          | newlines == 0 = (anchor, consumed)
          | otherwise     = (SourcePos f (mkPos $ unPos l + newlines) pos1, T.takeWhileEnd (/= '\n') consumed)
      return $ pstateSourcePos $ reachOffsetNoLine (T.length lineprefix) PosState
        { pstateInput = lineprefix, pstateOffset = 0, pstateSourcePos = startpos
        , pstateTabWidth = defaultTabWidth, pstateLinePrefix = "" }
    _ -> getSourcePos
  s <- getInput
  modify' $ \j -> j{jparsepos = Just $ ParsePos pos o s}
  return pos

addAccountAlias :: MonadState Journal m => AccountAlias -> m ()
addAccountAlias a = modify' (\(j@Journal{..}) -> j{jparsealiases=a:jparsealiases})

getAccountAliases :: MonadState Journal m => m [AccountAlias]
getAccountAliases = fmap jparsealiases 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 f j@Journal{jfiles=fs} = 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' p = do
  (!txt, p') <- match p
  pure (txt, p')

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

statusp :: TextParser m Status
statusp = do
  -- a status mark may follow, after optional spaces; check cheaply, since usually there is none
  (_, mc) <- peekAfterSpaces
  case mc of
    Just '*' -> Cleared <$ (skipNonNewlineSpaces *> char '*')
    Just '!' -> Pending <$ (skipNonNewlineSpaces *> char '!')
    _        -> pure Unmarked

codep :: TextParser m Text
codep = do
  -- a code in parentheses may follow, after spaces; check cheaply, since usually there is none
  (spaced, mc) <- peekAfterSpaces
  if spaced && mc == Just '('
  then do
    skipNonNewlineSpaces1
    char '('
    code <- takeWhileP Nothing $ \c -> c /= ')' && c /= '\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 = noncommenttextp <?> "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 = do
  mYear <- getYear
  lift $ datep' mYear

datep' :: Maybe Year -> TextParser m Day
datep' mYear = do
    startOffset <- getOffset
    d1 <- yearorintp <?> "year or month"
    sep <- datesepchar <?> "date separator"
    d2 <- decimal <?> "month or day"
    case d1 of
      Left y  -> fullDate startOffset y sep d2
      Right m -> partialDate startOffset mYear m d2
    <?> "full or partial date"
  where
    fullDate :: Int -> Year -> Char -> Month -> TextParser m Day
    fullDate startOffset year sep month = do
      sep2 <- satisfy isDateSepChar <?> "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
        Nothing -> 
          customFailure $ parseErrorAtRegion startOffset endOffset $
            "This is not a valid date, please fix it."
        Just date -> pure $! date

    partialDate :: Int -> Maybe Year -> Month -> MonthDay -> TextParser m Day
    partialDate startOffset myr month day = do
      endOffset <- getOffset
      case myr of
        Just year ->
          case fromGregorianValid year month day of
            Nothing -> 
              customFailure $ parseErrorAtRegion startOffset endOffset $
                "This is not a valid date, please fix it."
            Just date -> pure $! date

        Nothing ->
          customFailure $ parseErrorAtRegion startOffset endOffset $
            "This partial date can not be parsed because the current year is unknown.\n"
            ++"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 = do
  mYear <- getYear
  lift $ datetimep' mYear

datetimep' :: Maybe Year -> TextParser m LocalTime
datetimep' mYear = do
  day <- datep' 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 = do
  time <- timeOfDay
  optional timeZone -- ignoring time zones
  pure time

  where
    timeOfDay :: TextParser m TimeOfDay
    timeOfDay = do
      off1 <- 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 = do
      d1 <- digitToInt <$> digitChar
      d2 <- digitToInt <$> (digitChar <?> "a second digit")
      pure $ d1*10 + d2

    timeZone :: TextParser m String
    timeZone = do
      plusminus <- satisfy $ \c -> c == '-' || c == '+'
      fourDigits <- count 4 (digitChar <?> "a digit (for a time zone)")
      pure $ plusminus:fourDigits

secondarydatep :: Day -> TextParser m Day
secondarydatep primaryDate = char '=' *> datep' (Just primaryYear)
  where primaryYear = first3 $ toGregorian primaryDate

-- | Parse a year number or an Int. Years must contain at least four
-- digits.
yearorintp :: TextParser m (Either Year Int)
yearorintp = do
    yearOrMonth <- takeWhile1P (Just "digit") isDigit
    let n = readDecimal 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 allowsemicolon = aliasedaccountnamep allowsemicolon >>= 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 allowsemicolon = do
  als <- 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 a = do
  parent <- 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 _ (Right a') = return $! a'
orAliasError a (Left e)   = error' $ "problem in account alias applied to "++T.unpack a++": "++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 als parent optals a =
  accountNameApplyAliases optals . joinAccountNames parent =<< accountNameApplyAliases als 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 = nonemptypartsp id singlespacedtext1p

-- Like accountnamep, but stops parsing if it reaches a semicolon.
accountnamenosemicolonp :: TextParser m AccountName
accountnamenosemicolonp = nonemptypartsp id 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 = nonemptypartsp (\a -> fromMaybe a $ T.stripSuffix acctsep a) 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 f p = do
  off1 <- getOffset
  a <- p
  off2 <- getOffset
  let a' = f 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 = [acctsepchar]

-- | Parse a single line of possibly empty text enclosed in double quotes.
doublequotedtextp :: TextParser m Text
doublequotedtextp = between (char '"') (char '"') $
  takeWhileP Nothing $ \c -> not $ isNewline c || c == '"'

-- | Parse possibly empty text, including whitespace, 
-- until a comment start (semicolon) or newline.
noncommenttextp :: TextParser m T.Text
noncommenttextp = takeWhileP Nothing (\c -> not $ isSameLineCommentStart c || isNewline c)

-- | Parse non-empty text, including whitespace, 
-- until a comment start (semicolon) or newline.
noncommenttext1p :: TextParser m T.Text
noncommenttext1p = takeWhile1P Nothing (\c -> not $ isSameLineCommentStart c || isNewline 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 = singlespacedtextsatisfying1p (const 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 = singlespacedtextsatisfying1p (not . 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 f = do
  firstPart <- partp
  otherParts <- manyWhile nextissinglespaceandpart $ try $ singlespacep *> partp
  pure $! T.unwords $ firstPart : otherParts
  where
    partp = takeWhile1P Nothing (\c -> f c && not (isSpace c))
    -- is the next part separated from here by exactly one space ? (checked cheaply before parsing)
    nextissinglespaceandpart = do
      next2 <- peekChars2
      pure $ case next2 of
        (Just c1, Just c2) -> isNonNewlineSpace c1 && f c2 && not (isSpace c2)
        _                  -> 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 = spacenonewline *> notFollowedBy spacenonewline

--- *** amounts

-- | Parse whitespace then an amount, or return the special "missing" marker amount.
spaceandamountormissingp :: JournalParser m MixedAmount
spaceandamountormissingp =
  option missingmixedamt $ try $ do
    lift $ skipNonNewlineSpaces1
    mixedAmount <$> 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 = amountp' 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 (Eq, Show)

-- An amount with optional cost, valuation, and/or cost basis, as described above.
amountp' :: AmountParseKind -> JournalParser m Amount
amountp' kind =
  -- dbg "amountp'" $
  label "amount" $ do
  amt <- simpleamountp kind <* lift 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 kind =
  label "amount" $ do
  amt <- amountexprp kind <* lift 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 amt = do
  let spaces = lift $ 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 mcost mval mcb mdate mnote = do
        (mc1, mc2) <- lift peekChars2
        case (mc1, mc2) of
          (Just '@', _)        | isNothing mcost -> costp amt <* spaces          >>= \x -> annotations (Just x) mval mcb mdate mnote
          (Just '(', Just '@') | isNothing mcost -> costp amt <* spaces          >>= \x -> annotations (Just x) mval mcb mdate mnote
          (Just '(', Just '(') | isNothing mval  -> valuationexprp <* spaces     >>= \x -> annotations mcost (Just x) mcb mdate mnote
          (Just '{', _)        | isNothing mcb   -> lotcostp (aquantity amt) <* spaces >>= \x -> annotations mcost mval (Just x) mdate mnote
          (Just '[', _)        | isNothing mdate -> lotdatep <* spaces           >>= \x -> annotations mcost mval mcb (Just x) mnote
          (Just '(', _)        | isNothing mnote -> lotnotep <* spaces           >>= \x -> annotations mcost mval mcb mdate (Just x)
          _ -> pure (mcost, mval, mcb, mdate, mnote)
  (mcost, _valuationexpr, mlotcb, mlotdate, mlotnote) <- annotations Nothing Nothing Nothing Nothing Nothing
  -- Reject mixing consolidated {DATE,...} or {"LABEL",...} with ledger-style [DATE] or (NOTE)
  let isConsolidated = case mlotcb of
        Just cb | isJust (cbDate cb) || isJust (cbLabel cb) -> True
        _ -> False
  when (isConsolidated && (isJust mlotdate || isJust mlotnote)) $
    Fail.fail "hledger lot syntax {...} cannot be combined with ledger-style [DATE] or (NOTE)"
  let mcostbasis =
        case (mlotcb, mlotdate, mlotnote) of
          (Nothing, Nothing, Nothing) -> Nothing
          _ -> Just $ CostBasis
                 { cbCost  = mlotcb >>= cbCost
                 , cbDate  = (mlotcb >>= cbDate) <|> mlotdate
                 , cbLabel = (mlotcb >>= cbLabel) <|> mlotnote
                 }
  pure $ amt { acost = mcost, acostbasis = mcostbasis }

-- An amount with optional cost, but no cost basis.
amountnobasisp :: JournalParser m Amount
amountnobasisp =
  -- dbg "amountnobasisp" $ 
  label "amount" $ do
  let spaces = lift $ skipNonNewlineSpaces
  amt <- simpleamountp 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 = simpleamountp' 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' mdepth kind =
  -- dbg "simpleamountp" $
  do
  sign <- lift 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 c = c == '"' || not (isNonsimpleCommodityChar c)

  isoperand = isJust mdepth
  inparens  = maybe False (> 0) mdepth
  rightsymbolp :: TextParser n CommoditySymbol
  rightsymbolp
    | inparens  = quotedcommoditysymbolp <|> takeWhile1P Nothing (\c -> not (isNonsimpleCommodityChar c) && c /= ')')
    | otherwise = commoditysymbolp

  -- An amount with commodity symbol on the left.
  leftsymbolamountp :: (Decimal -> Decimal) -> JournalParser m Amount
  leftsymbolamountp sign = label "amount" $ do
    c <- shareText =<< lift commoditysymbolp
    mdecmarkStyle <- getDecimalMarkStyle
    mcommodityStyle <- getAmountStyle c
    -- XXX amounts of this commodity in periodic transaction rules and auto posting rules ? #1461
    let suggestedStyle = mdecmarkStyle <|> mcommodityStyle
    commodityspaced <- lift skipNonNewlineSpaces'
    sign2 <- lift $ signp
    offBeforeNum <- getOffset
    ambiguousRawNum <- lift rawnumberp
    mExponent <- lift optionalexponentp
    offAfterNum <- getOffset
    let numRegion = (offBeforeNum, 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 sign = label "amount" $ do
    offBeforeNum <- getOffset
    ambiguousRawNum <- lift rawnumberp
    mExponent <- lift optionalexponentp
    offAfterNum <- getOffset
    let numRegion = (offBeforeNum, offAfterNum)
    -- A commodity symbol may follow the number, possibly after spaces; check cheaply first.
    (_, mnext) <- lift peekAfterSpaces
    mSpaceAndCommodity <- lift $
      if maybe False (\c -> startsCommoditySymbol c && not (isoperand && c == '/') && not (inparens && c == ')')) mnext
      then optional $ try $ (,) <$> skipNonNewlineSpaces' <*> rightsymbolp
      else pure Nothing
    case mSpaceAndCommodity of
      -- right symbol amount
      Just (commodityspaced, c0) -> do
        c <- shareText c0
        mdecmarkStyle <- getDecimalMarkStyle
        mcommodityStyle <- getAmountStyle c
        -- XXX amounts of this commodity in periodic transaction rules and auto posting rules ? #1461
        let msuggestedStyle = mdecmarkStyle <|> 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
      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   <- 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 = mdecmarkStyle <|> mcommodityStyle <|> 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 (defc,defs) | kind /= MultiplierAmount ->
                (defc, defs{asprecision=max (asprecision defs) prec
                           ,asdecimalmark=asdecimalmark defs <|> mdec
                           ,asdigitgroups=asdigitgroups defs <|> mgrps})
              _ -> ("", 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 posRegion msuggestedStyle ambiguousNum 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 kind == StyleAmount then pure Nothing else jparsedecimalmark <$> get
    case interpretRawNumber mrequiredmark msuggestedStyle ambiguousNum mExp of
      Left errMsg -> customFailure $
                       uncurry parseErrorAtRegion posRegion errMsg
      Right (q,p,d,g) -> pure (q, Precision p, d, 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 kind = do
  a <- sump (0 :: Int)
  if kind /= MultiplierAmount && T.null (acommodity a) then withDefaultCommodity a else pure a
  where
    spaces = lift skipNonNewlineSpaces

    -- if a default commodity has been set, apply it and its style (like simpleamountp)
    withDefaultCommodity a = do
      defcs <- getDefaultCommodityAndStyle
      case defcs of
        Just (defc, defs) -> do
          s <- shareAmountStyle 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}
        Nothing -> pure a

    -- a sum or difference of products (depth is the number of enclosing parentheses)
    sump depth = productp depth >>= sumrestp depth
    sumrestp depth a = do
      mop <- lift peekChar
      case mop of
        Just op | op `elem` ['+','-'] -> do
          off <- getOffset
          b <- char op *> spaces *> productp depth
          off' <- getOffset
          c <- addAmounts (off, off') op a b
          sumrestp depth c
        _ -> pure a

    -- a product or quotient of factors
    productp depth = factorp depth >>= productrestp depth
    productrestp depth a = do
      mop <- lift peekChar
      case mop of
        Just op | op `elem` ['*','/'] -> do
          off <- getOffset
          b <- char op *> spaces *> factorp depth
          off' <- getOffset
          c <- multiplyAmounts (off, off') op a b
          productrestp depth c
        _ -> pure 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 depth = do
      s <- getInput
      case T.uncons s of
        Just ('(', _) -> parensp depth
        Just (c, rest) | c `elem` ['-','+'], "(" `T.isPrefixOf` T.dropWhile isNonNewlineSpace rest -> do
          a <- anySingle *> spaces *> parensp depth
          pure $ if c == '-' then a{aquantity = negate $ aquantity a} else a
        _ -> do
          a <- simpleamountp' (Just depth) 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 mnext of
                  Just c | isDigit c -> True
                         | not spaced -> c `elem` ['(','.','-','+']
                  _ -> 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 depth = char '(' *> spaces *> sump (depth+1) <* (char ')' <?> "closing parenthesis") <* spaces

    exprError (off, off') msg = customFailure $ parseErrorAtRegion off off' msg

    hascommodity = not . T.null . acommodity

    addAmounts reg op a b
      | hascommodity a && hascommodity b && acommodity a /= acommodity b = exprError reg $
          "can't " ++ (if op == '+' then "add" else "subtract") ++ " amounts with different commodities ("
          ++ T.unpack (acommodity a) ++ " and " ++ T.unpack (acommodity b) ++ ")"
      | otherwise = do
          -- a number with no commodity takes the other side's commodity and style
          let a' = if hascommodity a || not (hascommodity b) then a else b
              q = (if op == '+' then (+) else (-)) (aquantity a) (aquantity b)
          s <- shareAmountStyle (astyle a'){asprecision = max (asprecision $ astyle a) (asprecision $ astyle b)}
          pure a'{aquantity = q, astyle = s}

    multiplyAmounts reg op a b
      | op == '*' && hascommodity a && hascommodity b = exprError reg
          "can't multiply two amounts with commodity symbols; one side of * should be a plain number"
      | op == '/' && hascommodity a && hascommodity b = exprError reg
          "can't divide two amounts with commodity symbols; one side of / should be a plain number"
      | op == '/' && aquantity b == 0 = exprError reg "can't divide by zero"
      | op == '*' && hascommodity b = pure $ multiplyAmount (aquantity a) b
      | op == '*' = pure $ multiplyAmount (aquantity b) a
      -- a number divided by an amount, eg 1 / 1.14 EUR (inverting a rate), is in the amount's commodity, as in Ledger
      | hascommodity b = pure b{aquantity = aquantity a / aquantity b}
      | otherwise = pure $ divideAmount (aquantity b) a

-- | Try to parse a single-commodity amount from a string
parseamount :: String -> Either HledgerParseErrors Amount
parseamount s = runParser (evalStateT (amountp <* eof) nulljournal) "" (T.pack 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 styles s = runParser (evalStateT (amountp <* eof) j) "" (T.pack s)
  where
    j = nulljournal{jdeclaredcommodities = M.mapWithKey commodity styles}
    commodity c st = Commodity{csymbol=c, cformat=Just st, ccomment="", ctags=[], caliases=[], csourcepos=initialPos ""}

-- | Parse a single-commodity amount from a string, or get an error.
parseamount' :: String -> Amount
parseamount' s =
  case parseamount s of
    Right amt -> amt
    Left err  -> error' $ show err  -- PARTIAL: XXX should throwError

-- | Like parseamount', but returns a MixedAmount.
parsemixedamount :: String -> Either HledgerParseErrors MixedAmount
parsemixedamount = fmap mixedAmount . parseamount

-- | Like parseamount', but returns a MixedAmount.
parsemixedamount' :: String -> MixedAmount
parsemixedamount' = mixedAmount . 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 = do
  -- check the next character first: most amounts have no sign
  mc <- peekChar
  case mc of
    Just '-' -> negate <$ (char '-' *> skipNonNewlineSpaces)
    Just '+' -> id     <$ (char '+' *> skipNonNewlineSpaces)
    _        -> pure id

commoditysymbolp :: TextParser m CommoditySymbol
commoditysymbolp = (do
  mc <- peekChar
  if mc == Just '"' then quotedcommoditysymbolp else simplecommoditysymbolp
  ) <?> "commodity symbol"

quotedcommoditysymbolp :: TextParser m CommoditySymbol
quotedcommoditysymbolp =
  between (char '"') (char '"') $ takeWhileP Nothing f
  where f c = c /= ';' && c /= '\n' && c /= '\"'

simplecommoditysymbolp :: TextParser m CommoditySymbol
simplecommoditysymbolp = takeWhile1P Nothing (not . 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 baseAmt =
  -- dbg "costp" $
  label "transaction price" $ 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 <- (== Just '(') <$> lift 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' = signum $ aquantity baseAmt
      amtsign  = if amtsign' == 0 then 1 else 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 a
      | amountInternalPrecision a > amountDisplayPrecision a =
          amountSetPrecisionMin (amountDisplayPrecision a) $ amountSetFullPrecisionUpTo Nothing a
      | otherwise = a

-- | A valuation function or value can be written in double parentheses after an amount.
valuationexprp :: JournalParser m ()
valuationexprp =
  -- dbg "valuationexprp" $
  label "valuation expression" $ do
  string "(("
  _ <- T.strip . T.pack <$> (many $ noneOf [')','\n'])  -- XXX other line endings ?
  string "))"
  return ()

balanceassertionp :: JournalParser m BalanceAssertion
balanceassertionp = do
  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 postingqty =
  -- dbg "lotcostp" $
  label "lot cost" $ do
  char '{'
  doublebrace <- option False $ char '{' >> pure 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
    '}' -> pure (CostBasis Nothing Nothing Nothing)
    '=' -> ledgerCost
    '"' -> consolidatedNoDate
    _   -> 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 f (CostBasis md ml mc) = CostBasis md ml (fmap f mc)

    startsAnotherPart c = c == ',' || c == '"' || isDigit c

    wrongOrderError = do
      off <- 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 = option False $ lookAhead $ try $
      count 4 digitChar >> char '-' >> digitChar >> pure True

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

    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 <- looksLikeDatep
      if looksLikeDate
        then do
          d <- datep
          lift skipNonNewlineSpaces
          void $ lookAhead (oneOf [',','}'])
          consolidatedAfterDate d
        else ledgerCost  -- not a date, parse as ledger amount

    consolidatedAfterDate d = do
      -- after date: optional ", LABEL", optional ", COST"
      mlabel <- optional $ try $ char ',' >> lift skipNonNewlineSpaces >> quotedLabelp <* lift skipNonNewlineSpaces
      mcost  <- optional $ char ',' >> lift skipNonNewlineSpaces >> simpleamountp OrdinaryAmount <* lift skipNonNewlineSpaces
      pure $ CostBasis (Just d) mlabel mcost

    consolidatedNoDate = do
      -- parse "LABEL", then optional ", COST" (a date here is out of order)
      mlabel <- Just <$> quotedLabelp
      lift skipNonNewlineSpaces
      mcost <- optional $ do
        char ',' >> lift skipNonNewlineSpaces
        looksLikeDate <- looksLikeDatep
        when looksLikeDate wrongOrderError
        simpleamountp OrdinaryAmount <* lift skipNonNewlineSpaces
      pure $ CostBasis Nothing mlabel mcost

    quotedLabelp = do
      char '"'
      lbl <- T.pack <$> many (noneOf ['"', '\n'])
      char '"'
      pure lbl

    ledgerCost = do
      _fixed <- fmap isJust $ optional $ char '='
      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 = divideAmountAndUpdatePrecision (abs postingqty)

-- Parse a Ledger-style [LOTDATE].
lotdatep :: JournalParser m Day
lotdatep =
  -- dbg "lotdatep" $
  label "ledger-style lot date" $ do
  char '['
  lift skipNonNewlineSpaces
  d <- 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 =
  -- dbg "lotnotep" $
  label "ledger-style lot note" $ do
  char '('
  lift skipNonNewlineSpaces
  note <- stripEnd . T.pack <$> (many $ noneOf [')','\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 suggestedStyle = label "number" $ do
    -- a number is an optional sign followed by a sequence of digits possibly
    -- interspersed with periods, commas, or both
    -- dbgparse 0 "numberp"
    sign <- 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 errMsg -> Fail.fail errMsg
      Right (q, p, d, g) -> pure (sign q, p, d, g)

exponentp :: TextParser m Integer
exponentp = char' 'e' *> signp <*> decimal <?> "exponent"

-- | Parse an exponent if one follows, checking the next character first,
-- since most numbers have none.
optionalexponentp :: TextParser m (Maybe Integer)
optionalexponentp = do
  mc <- 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 mrequiredmark msuggestedStyle ambiguousNum mExp = do
  raw <- checkDecimalMark $ either (disambiguateNumber msuggestedStyle) id ambiguousNum
  fromRawNumber raw mExp
  where
    checkDecimalMark raw = case mrequiredmark of
      Just d
        | Just m <- rawDecimalMark raw, m /= d ->
          declared d $ "but this number's decimal mark is " ++ show 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.
        | Just d == rawDigitGroupMark raw ->
          declared d "so it can appear only once"
      _ -> Right raw
    declared d msg = Left $ "invalid number: the decimal mark is declared to be " ++ show d ++ ", " ++ msg
    rawDecimalMark (NoSeparators _ mdec)     = fst <$> mdec
    rawDecimalMark (WithSeparators _ _ mdec) = fst <$> mdec
    rawDigitGroupMark (WithSeparators sep _ _) = Just sep
    rawDigitGroupMark NoSeparators{}           = 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 (WithSeparators{}) (Just _) =
    Left "invalid number: digit separators and exponents may not be used together"
fromRawNumber raw mExp = do
    (quantity, precision) <- toQuantity (fromMaybe 0 mExp) (digitGroup raw) (decimalGroup raw)
    -- force the Maybes' contents, so that parsed amount styles don't retain the raw number
    let !mdec = forceMaybe $ mDecPt raw
        !mgrps = forceMaybe $ digitGroupStyle raw
    return (quantity, precision, mdec, mgrps)
  where
    forceMaybe m = case m of
      Just x  -> x `seq` m
      Nothing -> m
    toQuantity :: Integer -> DigitGrp -> DigitGrp -> Either String (Quantity, Word8)
    toQuantity e preDecimalGrp postDecimalGrp
      | precision < 0   = Right (Decimal 0 (digitGrpNum * 10^(-precision)), 0)
      | precision < 256 = Right (Decimal precision8 digitGrpNum, precision8)
      | otherwise = Left "invalid number: numbers with more than 255 decimal places are currently not supported"
      where
        digitGrpNum = digitGroupNumber $ preDecimalGrp <> postDecimalGrp
        precision   = toInteger (digitGroupLength postDecimalGrp) - e
        precision8  = fromIntegral precision :: Word8

    mDecPt (NoSeparators _ mDecimals)           = fst <$> mDecimals
    mDecPt (WithSeparators _ _ mDecimals)       = fst <$> mDecimals
    decimalGroup (NoSeparators _ mDecimals)     = maybe mempty snd mDecimals
    decimalGroup (WithSeparators _ _ mDecimals) = maybe mempty snd mDecimals
    digitGroup (NoSeparators digitGrp _)        = digitGrp
    digitGroup (WithSeparators _ digitGrps _)   = mconcat digitGrps
    digitGroupStyle (NoSeparators _ _)          = Nothing
    digitGroupStyle (WithSeparators sep grps _) = Just . DigitGroups sep $ groupSizes grps

    -- Outputs digit group sizes from least significant to most significant
    groupSizes :: [DigitGrp] -> [Word8]
    groupSizes digitGrps = reverse $ case map (fromIntegral . digitGroupLength) digitGrps of
      (a:b:cs) | a < b -> b:cs
      gs               -> gs

disambiguateNumber :: Maybe AmountStyle -> AmbiguousNumber -> RawNumber
disambiguateNumber msuggestedStyle (AmbiguousNumber grp1 sep grp2) =
  -- If present, use the suggested style to disambiguate;
  -- otherwise, assume that the separator is a decimal point where possible.
  if isDecimalMark sep &&
     maybe True (sep `isValidDecimalBy`) msuggestedStyle
  then NoSeparators grp1 (Just (sep, grp2))
  else WithSeparators sep [grp1, grp2] 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 c = \case
      AmountStyle{asdecimalmark = Just d} -> d == c
      AmountStyle{asdigitgroups = Just (DigitGroups g _)} -> g /= c
      _ -> 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 = label "number" $ do
  -- (The next characters are inspected directly in a few places below,
  -- avoiding failed parse attempts on this hot path.)
  mc <- 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 ' ', Just d) | isDigit d -> do
      off <- getOffset
      customFailure $ parseErrorAt (off + 1) "invalid number (excessive trailing digits)"
    _ -> pure ()

  return $ dbg7 "rawnumberp" rawNumber
  where

  leadingDecimalPt :: TextParser m RawNumber
  leadingDecimalPt = do
    decPt <- satisfy isDecimalMark
    decGrp <- digitgroupp
    pure $ NoSeparators mempty (Just (decPt, decGrp))

  leadingDigits :: TextParser m (Either AmbiguousNumber RawNumber)
  leadingDigits = do
    grp1 <- digitgroupp
    -- More digit groups (after a separator) or a decimal mark may follow; most often neither does.
    next2 <- peekChars2
    let more = case next2 of
          (Just c1, _)       | isDecimalMark c1 -> True
          (Just c1, Just c2) | isDigitSeparatorChar c1 && isDigit c2 -> True
          _ -> 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 grp1 = do
    (sep, grp2) <- try $ (,) <$> satisfy isDigitSeparatorChar <*> digitgroupp
    grps <- many $ try $ char sep *> digitgroupp

    let digitGroups = grp1 : grp2 : grps
    fmap Right (withDecimalPt sep digitGroups)
      <|> pure (withoutDecimalPt grp1 sep grp2 grps)

  withDecimalPt :: Char -> [DigitGrp] -> TextParser m RawNumber
  withDecimalPt digitSep digitGroups = do
    decPt <- satisfy $ \c -> isDecimalMark c && c /= digitSep
    decDigitGrp <- option mempty digitgroupp

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

  withoutDecimalPt
    :: DigitGrp
    -> Char
    -> DigitGrp
    -> [DigitGrp]
    -> Either AmbiguousNumber RawNumber
  withoutDecimalPt grp1 sep grp2 grps
    | null grps && isDecimalMark sep =
        Left $ AmbiguousNumber grp1 sep grp2
    | otherwise = Right $ WithSeparators sep (grp1:grp2:grps) Nothing

  trailingDecimalPt :: DigitGrp -> TextParser m RawNumber
  trailingDecimalPt grp1 = do
    decPt <- satisfy isDecimalMark
    pure $ NoSeparators grp1 (Just (decPt, mempty))

isDigitSeparatorChar :: Char -> Bool
isDigitSeparatorChar c = c == '.' || c == ',' || c == '\'' || c == '_' || isDigitSeparatorSpaceChar 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 c =
     c == ' '  -- space
  || c == ' '  -- no-break space
  || c == ' '  -- en space
  || c == ' '  -- em space
  || c == ' '  -- punctuation space
  || c == ' '  -- thin space
  || c == ' '  -- narrow no-break space
  || c == ' '  -- 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 (Show, 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 (Show, 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 {
  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.
  digitGroupNumber :: !Integer  -- ^ The natural number formed by this group's digits. This should always be positive.
} deriving (Eq)

-- | A custom show instance, showing digit groups as the parser saw them.
instance Show DigitGrp where
  show (DigitGrp len n) = "\"" ++ padding ++ numStr ++ "\""
    where numStr = show n
          padding = genericReplicate (toInteger len - toInteger (length numStr)) '0'

instance Sem.Semigroup DigitGrp where
  DigitGrp l1 n1 <> DigitGrp l2 n2 = DigitGrp (l1 + l2) (n1 * 10^l2 + n2)

instance Monoid DigitGrp where
  mempty = DigitGrp 0 0
  mappend = (Sem.<>)

digitgroupp :: TextParser m DigitGrp
digitgroupp = label "digits"
            $ makeGroup <$> takeWhile1P (Just "digit") isDigit
  where
    makeGroup = uncurry DigitGrp . T.foldl' step (0, 0)
    step (!l, !a) c = (l+1, a*10 + fromIntegral (digitToInt c))

--- *** comments

multilinecommentp :: TextParser m ()
multilinecommentp = startComment *> anyLine `skipManyTill` endComment
  where
    startComment = string "comment" *> trailingSpaces
    endComment = eof <|> string "end comment" *> trailingSpaces

    trailingSpaces = skipNonNewlineSpaces <* newline
    anyLine = void $ takeWhileP Nothing (/='\n') *> 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 = do
  dp "emptyorcommentlinep"
  skipNonNewlineSpaces
  mc <- peekChar
  if maybe False isLineCommentStart mc then skiplinecommentp else void newline
  where
    skiplinecommentp :: TextParser m ()
    skiplinecommentp = do
      satisfy isLineCommentStart
      void $ takeWhileP Nothing (/= '\n')
      optional newline
      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 cs =
  label ("empty line or comment line beginning with "++cs) $ do
    dp "emptyorcommentlinep2"
    skipNonNewlineSpaces
    void newline <|> void commentp
    where
      commentp = do
        choice (map (some.char) cs)
        takeWhileP Nothing (/='\n') <* optional newline

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

-- | Is this a character that, appearing anywhere within a line,
-- starts a comment ?
isSameLineCommentStart :: Char -> Bool
isSameLineCommentStart ';' = True
isSameLineCommentStart _   = 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 = fst <$> followingcommentpWith (void $ takeWhileP Nothing (/= '\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 contentp = do
  skipNonNewlineSpaces
  -- there can be 0 or 1 sameLine (checking for its semicolon cheaply, as usually there is none)
  mc <- 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' | null sameLine && not (null nextLines) = [("",mempty)]
              | otherwise = sameLine
    (texts, contents) = unzip $ sameLine' ++ nextLines
    strippedCommentText = T.unlines $ map T.strip texts
    commentContent = mconcat contents
  pure (strippedCommentText, commentContent)

  where
    headerp = char ';' *> skipNonNewlineSpaces
    -- does the next line begin with an indented semicolon ?
    nextlineiscomment = do
      (spaced, mnext) <- 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 = do
  -- XXX sketchy
  tagName <- (last . T.split isSpace) <$> takeWhileP Nothing (\c -> c /= ':' && c /= '\n')
  atColon tagName <|> pure [] -- if not ':', then either '\n' or EOF

  where
    atColon :: Text -> TextParser m [Tag]
    atColon name = char ':' *> do
      if T.null name
        then commentlinetagsp
        else do
          skipNonNewlineSpaces
          val <- tagValue
          let tag = (name, val)
          (tag:) <$> commentlinetagsp

    tagValue :: TextParser m Text
    tagValue = do
      val <- T.strip <$> takeWhileP Nothing (\c -> c /= ',' && c /= '\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 = followingcommentpWith 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 mYear = do
  (commentText, (tags, dateTags)) <-
    followingcommentpWith (commenttagsanddatesp mYear)
  let mdate  = snd <$> find ((=="date") .fst) dateTags
      mdate2 = snd <$> find ((=="date2").fst) dateTags
  pure (commentText, tags, mdate, mdate2)
{-# INLINABLE postingcommentp #-}


commenttagsanddatesp
  :: Maybe Year -> TextParser m ([Tag], [DateTag])
commenttagsanddatesp mYear = do
  (txt, dateTags) <- match $ readUpTo ':'
  -- next char is either ':' or '\n' (or EOF)
  let tagName = last (T.split isSpace txt)
  (fmap.second) (dateTags++) (atColon tagName) <|> pure ([], dateTags) -- if not ':', then either '\n' or EOF

  where
    readUpTo :: Char -> TextParser m [DateTag]
    readUpTo end = do
      void $ takeWhileP Nothing (\c -> c /= end && c /= '\n' && c /= '[')
      -- if not '[' then ':' or '\n' or EOF
      atBracket (readUpTo end) <|> pure []

    atBracket :: TextParser m [DateTag] -> TextParser m [DateTag]
    atBracket cont = do
      -- Uses the fact that bracketed date-tags cannot contain newlines
      dateTags <- option [] $ lookAhead (bracketeddatetagsp mYear)
      _ <- char '['
      dateTags' <- cont
      pure $ dateTags ++ dateTags'

    atColon :: Text -> TextParser m ([Tag], [DateTag])
    atColon name = char ':' *> do
      skipNonNewlineSpaces
      (tags, dateTags) <- case name of
        ""      -> pure ([], [])
        "date"  -> dateValue name
        "date2" -> dateValue name
        _       -> tagValue 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 name = (lookAhead (void (satisfy (\c -> c == ',' || c == '\n')) <|> eof) *> tagValue name) <|> do
      (txt, (date, dateTags)) <- match' $ do
        date <- datep' mYear
        dateTags <- readUpTo ','
        pure (date, dateTags)
      let val = T.strip txt
      pure $ ( [(name, val)]
             , (name, date) : dateTags )

    tagValue :: Text -> TextParser m ([Tag], [DateTag])
    tagValue name = do
      (txt, dateTags) <- match' $ readUpTo ','
      let val = T.strip 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 mYear1 = do
  -- dbgparse 0 "bracketeddatetagsp"
  try $ do
    s <- lookAhead
       $ between (char '[') (char ']')
       $ takeWhile1P Nothing 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

  between (char '[') (char ']') $ do
    md1 <- optional $ datep' mYear1

    let mYear2 = fmap readYear md1 <|> mYear1
    md2 <- optional $ char '=' *> datep' mYear2

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

  where
    readYear = first3 . toGregorian
    isBracketedDateChar c = isDigit c || isDateSepChar c || c == '='

{-# 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 = map parseAliasOpt . aliases_
  where
    parseAliasOpt a =
      case runParser accountaliasp "--alias" (T.pack a) of
        Right alias -> alias
        Left e      -> error' $ customErrorBundlePretty e  -- PARTIAL:

accountaliasp :: TextParser m AccountAlias
accountaliasp = regexaliasp <|> basicaliasp

basicaliasp :: TextParser m AccountAlias
basicaliasp = do
  -- dbgparse 0 "basicaliasp"
  old <- rstrip <$> (some $ noneOf ("=" :: [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 = do
  -- dbgparse 0 "regexaliasp"
  (off1, off2, re) <- between (char '/') (char '/') $ do
    off1 <- 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 r -> return $! RegexAlias r repl
    Left e  -> customFailure $! parseErrorAtRegion off1 off2 e

--- ** tests

tests_Common = testGroup "Common" [

   testGroup "amountp" [
    testCase "basic"                  $ assertParseEq amountp "$47.18"     (usd 47.18)
   ,testCase "ends with decimal mark" $ assertParseEq amountp "$1."        (usd 1  `withPrecision` Precision 0)
   ,testCase "unit price"             $ assertParseEq amountp "$10 @ €0.5"
      -- not precise enough:
      -- (usd 10 `withPrecision` 0 `at` (eur 0.5 `withPrecision` 1)) -- `withStyle` asdecimalmark=Just '.'
      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 '.'}
            }
        }
   ,testCase "total price"            $ assertParseEq amountp "$10 @@ €5"
      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}
            }
        }
   ,testCase "unit price, parenthesised" $ assertParse amountp "$10 (@) €0.5"
   ,testCase "total price, parenthesised" $ assertParse amountp "$10 (@@) €0.5"
   ]

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

  ,let p = lift (numberp Nothing) :: JournalParser IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle) in
   testCase "numberp" $ do
     assertParseEq p "0"          (0, 0, Nothing, Nothing)
     assertParseEq p "1"          (1, 0, Nothing, Nothing)
     assertParseEq p "1.1"        (1.1, 1, Just '.', Nothing)
     assertParseEq p "1,000.1"    (1000.1, 1, Just '.', Just $ DigitGroups ',' [3])
     assertParseEq p "1_000.1"    (1000.1, 1, Just '.', Just $ DigitGroups '_' [3])
     assertParseEq p "1'000.1"    (1000.1, 1, Just '.', Just $ DigitGroups '\'' [3])
     assertParseEq p "1.00.000,1" (100000.1, 1, Just ',', Just $ DigitGroups '.' [3,2])
     assertParseEq p "1,000,000"  (1000000, 0, Nothing, Just $ DigitGroups ',' [3,3])  -- could be simplified to [3]
     assertParseEq p "1."         (1, 0, Just '.', Nothing)
     assertParseEq p "1,"         (1, 0, Just ',', Nothing)
     assertParseEq p ".1"         (0.1, 1, Just '.', Nothing)
     assertParseEq p ",1"         (0.1, 1, Just ',', Nothing)
     assertParseError p "" ""
     assertParseError p "1,000.000,1" ""
     assertParseError p "1.000,000.1" ""
     assertParseError p "1,000.000.1" ""
     assertParseError p "1,,1" ""
     assertParseError p "1..1" ""
     assertParseError p ".1," ""
     assertParseError p ",1." ""
     assertParseEq    p "1.555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555" (1.555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555, 255, Just '.', Nothing)
     assertParseError p "1.5555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555" ""

  ,testCase "numberp with a suggested decimal mark" $ do
     let p c = lift (numberp $ Just amountstyle{asdecimalmark=Just c}) :: JournalParser IO (Quantity, Word8, Maybe Char, Maybe DigitGroupStyle)
     assertParseEq    (p '.') "1.000"        (1, 3, Just '.', Nothing)
     assertParseEq    (p ',') "1.000"        (1000, 0, Nothing, Just $ DigitGroups '.' [3])
     assertParseEq    (p ',') "1.000.000"    (1000000, 0, Nothing, Just $ DigitGroups '.' [3,3])
     assertParseEq    (p '.') "1,000,000"    (1000000, 0, Nothing, Just $ DigitGroups ',' [3,3])
     assertParseEq    (p '.') "1 000 000"    (1000000, 0, Nothing, Just $ DigitGroups ' ' [3,3])
     -- the suggested decimal mark is used only for disambiguation, not enforced
     assertParseEq    (p '.') "1.2.34"       (1234, 0, Nothing, Just $ DigitGroups '.' [2,1,1])
     assertParseEq    (p ',') "1,000,000.00" (1000000, 2, Just '.', Just $ DigitGroups ',' [3,3])

  ,testCase "amountp with a decimal-mark directive" $ do
     let p kind = modify' (\j -> j{jparsedecimalmark=Just ','}) >> amountp' kind
     assertParse      (p OrdinaryAmount) "1.000,5 EUR"
     assertParseError (p OrdinaryAmount) "1,000.5 EUR"       "number's decimal mark is '.'"
     assertParseError (p OrdinaryAmount) ".5 EUR"            "number's decimal mark is '.'"
     assertParseError (p OrdinaryAmount) "1 X @ 1,000.5 EUR" "number's decimal mark is '.'"
     assertParseError (p OrdinaryAmount) "1,000,000 EUR"     "so it can appear only once"
     -- directives declaring a display style may use a different decimal mark
     assertParse      (p StyleAmount)    "1,000.5 EUR"

  ,testGroup "spaceandamountormissingp" [
     testCase "space and amount" $ assertParseEq spaceandamountormissingp " $47.18" (mixedAmount $ usd 47.18)
    ,testCase "empty string" $ assertParseEq spaceandamountormissingp "" missingmixedamt
    -- ,testCase "just space" $ assertParseEq spaceandamountormissingp " " missingmixedamt  -- XXX should it ?
    -- ,testCase "just amount" $ assertParseError spaceandamountormissingp "$47.18" ""  -- succeeds, consuming nothing
    ]

  ]