doppio 2.4.1

A typed compiler pipeline for plain-text Ledger accounting -- parse, resolve, and elaborate .ledger files with a library API built for programmatic use.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
//! Abstract Syntax Tree (AST) for the Ledger file format.
//!
//! This module defines the data types produced by the parser. The AST is a
//! faithful, low-level representation of the source text: dates may lack a
//! year, amounts are unevaluated [`ValueExpr`] trees, and directives are kept
//! in their raw form. Subsequent pipeline stages ([`crate::resolution`] and
//! [`crate::elaboration`]) refine these into higher-level structures.
//!
//! Many of the structural types here are now `pub(crate)` after the 1.0
//! API audit. They are populated by the parser and consumed by the
//! resolver, but never inspected by external callers -- the resolver
//! consumes the journal and produces a [`crate::resolution::HIR`].
//! Enum variants and fields that the resolver doesn't observe show up
//! as dead code under `cargo clippy`; the suppression below is
//! deliberate and tracks future cleanup as a 1.x quality-of-life
//! task rather than gating the 1.0 cut.

#![allow(dead_code)]

use std::{collections::BTreeMap, fmt::Display};

use chrono::{Datelike, NaiveDate};
use pest::Parser as PestParser;
use rust_decimal::Decimal;

use crate::grammars::ledger::{self, LedgerParser};

/// The root of a parsed ledger file.
///
/// Contains all top-level entries in source order. The `entries` field
/// itself is crate-private because the [`Entry`] enum is an internal
/// representation; consumers receive a `Journal` from
/// [`crate::grammars::ledger::Parser::parse`] and pass it on to
/// [`crate::resolution::HIR::try_from`] without inspecting it directly.
#[derive(Debug)]
pub struct Journal {
    pub(crate) entries: Vec<Entry>,
}

/// A single top-level entry in the journal.
#[derive(Debug)]
pub(crate) enum Entry {
    /// A double-entry accounting transaction (date, description, postings).
    Transaction(Transaction),
    /// A configuration directive (`commodity`, `account`, `alias`, ...).
    Directive(Directive),
    /// A `P` price directive recording the market price of a commodity.
    HistoricalPrice(HistoricalPrice),
    /// A standalone balance assertion directive.
    ///
    /// Example: `2024-01-15 = Assets:Checking  $1000.00`
    Assertion(AssertionDirective),
    /// A Beancount `pad` directive: backfill the difference between two
    /// accounts up to the next balance assertion. Emitted by the
    /// Beancount frontend as a marker; the elaboration semantics are
    /// the subject of #147.
    Pad(PadDirective),
    /// A comment line starting with `;`, `#`, `*`, `%`, or `|`.
    Comment(String),
    /// An automated posting rule (`= QUERY\n  POSTINGS…`).
    ///
    /// During elaboration, for each real transaction whose postings match
    /// the `query`, the rule's `postings` are instantiated as
    /// virtual-unbalanced (`(Account)`) postings appended to the
    /// matched transaction. Commodity-less amounts in the rule body are
    /// interpreted as multipliers of the matched posting's amount; amounts
    /// with an explicit commodity are taken literally.
    AutoRule(AutoRule),
    /// A `C N1 X = N2 Y` commodity-conversion directive (ledger-cli).
    ///
    /// Declares a fixed exchange rate between commodity `X` (LHS / canonical)
    /// and commodity `Y` (RHS / alias). The divisor that converts a Y-amount
    /// to its X-equivalent is `N1 * N2`.
    ///
    /// See issue #248 for the full semantic specification.
    CommodityConversion {
        /// Amount on the LHS: `N1` units of commodity `X` (the canonical side).
        lhs: CommodityAmount,
        /// Amount on the RHS: `N2` units of commodity `Y` (the alias side).
        rhs: CommodityAmount,
    },
}

/// A bare `<number> <commodity>` pair used in `C` conversion directives.
///
/// Unlike [`ValueExpr`], these are fully concrete at parse time — no
/// arithmetic or aliases are permitted inside a `C` directive amount.
#[derive(Debug, Clone)]
pub(crate) struct CommodityAmount {
    /// The numeric value (e.g. `100.00` in `C 100.00c = 1.00s`).
    pub value: Decimal,
    /// The commodity symbol (e.g. `"c"` in `C 100.00c = 1.00s`).
    pub commodity: String,
}

/// An automated posting rule (`= QUERY\n  POSTINGS…`).
///
/// When a real posting's account name satisfies the rule's `query`,
/// the rule's body postings are synthesised as virtual-unbalanced
/// entries appended to that transaction. Commodity-less body amounts
/// are multipliers; commodity-bearing body amounts are literal.
#[derive(Clone, Default, Debug)]
pub(crate) struct AutoRule {
    /// The raw query string (regex pattern or account expression).
    pub query: String,
    /// The body postings to synthesise on a match.
    pub postings: Vec<Posting>,
}

/// A Beancount `pad` directive marker.
///
/// `<date> pad <target_account> <source_account>` instructs Beancount to
/// post a balancing transaction from `source_account` to `target_account`
/// that brings `target_account`'s balance to whatever the next `balance`
/// assertion against it expects. The resolver does not act on this today
/// (see #147 for the evaluator design); it is preserved here so that
/// downstream consumers can see pads exist.
#[derive(Debug, Clone)]
pub(crate) struct PadDirective {
    /// The date the pad applies on.
    pub date: Date,
    /// The account whose balance will be brought to the next assertion.
    pub target_account: String,
    /// The counter-account that absorbs the padding amount.
    pub source_account: String,
}

/// A standalone balance assertion directive outside of any transaction.
///
/// These directives assert that an account's balance equals a given amount
/// at a specific date. The assertion is not enforced by the resolution stage;
/// enforcement is handled by the elaboration stage (see issue #37).
///
/// Example: `2024-01-15 == Assets:Checking  $1000.00`
#[derive(Debug, Clone)]
pub(crate) struct AssertionDirective {
    /// The date at which the balance assertion applies.
    pub date: Date,
    /// The account whose balance is being asserted.
    pub account: String,
    /// The expected balance expressed as a value expression.
    pub amount: ValueExpr,
    /// `true` if `==` (strict equality), `false` if `=` (weak/approximate).
    pub strict: bool,
}

/// A `P` price directive: the market price of one unit of `commodity` in
/// terms of the `price` expression at the given `date`.
///
/// Example: `P 2024-01-15 14:30:00 AAPL $182.50`
#[derive(Debug, Clone)]
pub(crate) struct HistoricalPrice {
    /// The date on which this price was recorded.
    pub date: Date,
    /// Optional wall-clock time of the price quote (`HH:MM` or `HH:MM:SS`).
    pub time: Option<String>,
    /// The commodity whose price is being recorded (e.g. `"AAPL"`, `"BTC"`).
    pub commodity: String,
    /// The price of one unit of `commodity` as a value expression.
    pub price: ValueExpr,
}

/// A configuration directive parsed from the ledger source.
#[derive(Debug)]
pub(crate) enum Directive {
    /// A `commodity` block declaring properties of a commodity symbol.
    Commodity {
        /// The canonical commodity name (e.g. `"USD"`, `"BTC"`, `"$"`).
        name: String,
        /// Free-form notes attached to the commodity block header.
        notes: Vec<String>,
        /// Structured sub-items (`alias`, `format`, `nomarket`, `default`, ...).
        items: Vec<CommodityItem>,
    },
    /// An `account` block declaring properties of an account.
    Account {
        /// The canonical account name (e.g. `"Assets:Bank:Checking"`).
        name: String,
        /// Free-form notes attached to the account block header.
        notes: Vec<String>,
        /// Structured sub-items (`alias`, `note`, ...).
        items: Vec<AccountItem>,
    },
    /// A directive whose keyword was not recognised.
    Unknown(String),
    /// A top-level `alias <from> = <to>` account shorthand.
    Alias {
        /// The short name to be used in postings.
        alias: String,
        /// The full account name it expands to.
        account: String,
    },
    /// A `define name[(params)] = body` named alias.
    ///
    /// When `params` is empty this is a simple value alias: any occurrence of
    /// `name` in a value expression is substituted with the stored body during
    /// elaboration.
    ///
    /// When `params` is non-empty this is a parameterized macro: a call-site
    /// `name(arg1, arg2)` is evaluated by binding each `params[i]` to `args[i]`
    /// in the evaluation context and then evaluating the body.
    Define {
        /// The alias name (a plain identifier).
        name: String,
        /// Ordered parameter names. Empty for non-parameterized defines.
        params: Vec<String>,
        /// The body expression -- either a value expression or a boolean expression.
        body: DefineBody,
    },
    /// A `tag` block declaring validation rules for a metadata tag.
    ///
    /// Transactions and postings may carry `; TagName: value` metadata.
    /// The `tag` directive attaches assertions and checks that are evaluated
    /// whenever such a `TagName: value` pair is encountered during elaboration.
    Tag {
        /// The tag name (e.g. `"Statement"`, `"IncomeType"`).
        name: String,
        /// Fatal assertions: elaboration halts if any fails.
        asserts: Vec<BoolExpr>,
        /// Non-fatal checks: a warning is printed to stderr but elaboration continues.
        checks: Vec<BoolExpr>,
    },
}

/// A single key/value item inside a `commodity` directive block.
#[derive(Clone, Debug)]
pub(crate) enum CommodityItem {
    /// An alternative name for this commodity (`alias <name>`).
    Alias(String),
    /// A display format string, e.g. `"1,000.00 USD"`.
    Format(String),
    /// Marks the commodity as having no market price data (`nomarket`).
    NoMarket,
    /// Marks this commodity as the default when no commodity is specified.
    Default,
    /// A free-form note describing the commodity.
    Note(String),
    /// An unrecognised sub-directive with an optional value.
    Unknown(String, Option<String>),
}

/// A single key/value item inside an `account` directive block.
#[derive(Clone, Debug)]
pub(crate) enum AccountItem {
    /// An alternative name for this account (`alias <name>`).
    Alias(String),
    /// A free-form note describing the account.
    Note(String),
    /// A fatal assertion that every posting to this account must satisfy.
    ///
    /// Elaboration halts with [`crate::ElaborationError::AccountAssertionFailed`]
    /// if the expression evaluates to `false` for any posting.
    Assert(BoolExpr),
    /// A non-fatal check that every posting to this account should satisfy.
    ///
    /// If the expression evaluates to `false`, a warning is printed to stderr
    /// but elaboration continues.
    Check(BoolExpr),
    /// The booking method declared on a Beancount `open` directive (e.g.
    /// `open Assets:Brokerage AAPL "FIFO"`). Governs how an ambiguous
    /// `{}` reduction is resolved against the account's running
    /// inventory. See [`crate::resolution::BookingMethod`].
    Booking(crate::resolution::BookingMethod),
    /// An unrecognised sub-directive with an optional value.
    Unknown(String, Option<String>),
}

/// A boolean expression used in `assert` / `check` account sub-directives.
///
/// The grammar supports a simple left-to-right structure:
/// `lhs [cmp_op rhs] [bool_op continuation]`.
/// Full precedence parsing of boolean operators is a TODO(#74-followup).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BoolExpr {
    /// Left-hand side value expression (e.g. `commodity`, `amount`).
    pub lhs: ValueExpr,
    /// Optional comparison: operator and right-hand side.
    pub cmp: Option<(CmpOp, ValueExpr)>,
    /// Optional logical continuation chained to the right.
    pub chain: Option<(BoolOp, Box<BoolExpr>)>,
}

/// Comparison operator used in [`BoolExpr`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CmpOp {
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
    /// `=~` -- LHS string matches the regex RHS.
    RegexMatch,
    /// `!~` -- LHS string does not match the regex RHS.
    RegexNotMatch,
}

impl std::fmt::Display for CmpOp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CmpOp::Eq => write!(f, "=="),
            CmpOp::Ne => write!(f, "!="),
            CmpOp::Lt => write!(f, "<"),
            CmpOp::Le => write!(f, "<="),
            CmpOp::Gt => write!(f, ">"),
            CmpOp::Ge => write!(f, ">="),
            CmpOp::RegexMatch => write!(f, "=~"),
            CmpOp::RegexNotMatch => write!(f, "!~"),
        }
    }
}

/// Boolean chaining operator used in [`BoolExpr`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BoolOp {
    And,
    Or,
}

impl std::fmt::Display for BoolOp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BoolOp::And => write!(f, "and"),
            BoolOp::Or => write!(f, "or"),
        }
    }
}

impl std::fmt::Display for BoolExpr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.lhs)?;
        if let Some((op, rhs)) = &self.cmp {
            write!(f, " {op} {rhs}")?;
        }
        if let Some((op, cont)) = &self.chain {
            write!(f, " {op} {cont}")?;
        }
        Ok(())
    }
}

/// The body of a `define` directive.
///
/// A define body is either a value expression (for plain amount aliases and
/// arithmetic macros) or a boolean expression (for predicate macros used in
/// `assert`/`check` directives).
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum DefineBody {
    /// A value expression, e.g. `define monthly = $1500`.
    Value(ValueExpr),
    /// A boolean expression, e.g. `define positive(x) = x > 0`.
    Bool(BoolExpr),
}

impl std::fmt::Display for DefineBody {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DefineBody::Value(e) => write!(f, "{e}"),
            DefineBody::Bool(e) => write!(f, "{e}"),
        }
    }
}

/// A parsed date, with an optional year.
///
/// Ledger's grammar always requires a four-digit year, but this struct
/// keeps it `Option<i32>` so the parser can represent partially-specified
/// dates uniformly. The [`crate::resolution`] stage rejects dates where
/// no year can be determined.
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Default, Debug)]
pub(crate) struct Date {
    /// The calendar year, e.g. `2024`. `None` if not present in the source.
    pub year: Option<i32>,
    /// Month of the year (1-12).
    pub month: u32,
    /// Day of the month (1-31).
    pub date: u32,
}

impl From<NaiveDate> for Date {
    fn from(value: NaiveDate) -> Self {
        Self {
            year: Some(value.year()),
            month: value.month0() + 1,
            date: value.day0() + 1,
        }
    }
}

/// A double-entry accounting transaction as it appears in the source.
///
/// Amounts in the postings are unevaluated [`ValueExpr`] trees; the
/// [`crate::elaboration`] stage evaluates them and ensures the transaction
/// balances.
///
/// This is the raw parse-tree representation. For programmatic transaction
/// construction, use [`crate::resolution::Transaction`] and its builder methods instead.
#[derive(Clone, Default, Debug)]
pub(crate) struct Transaction {
    /// The primary (effective) date.
    pub date: Date,
    /// An optional secondary date (`date=secondary_date`), used for the
    /// "date the transaction was actually processed" semantics.
    pub secondary_date: Option<Date>,
    /// Cleared (`*`), pending (`!`), or uncleared (no marker).
    pub state: TransactionState,
    /// An optional reference code in parentheses, e.g. `(INV-42)`.
    pub code: Option<String>,
    /// The payee / description text following the header date and state.
    pub description: String,
    /// Lines starting with `;` in the transaction header (before postings).
    pub notes: Vec<String>,
    /// The individual account postings that make up this transaction.
    pub postings: Vec<Posting>,
}

impl Display for Transaction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(year) = self.date.year {
            write!(f, "{year:04}-")?;
        }
        write!(f, "{:02}-{:02}", self.date.month, self.date.date)?;

        if let Some(ref date) = self.secondary_date {
            write!(f, "=")?;
            if let Some(year) = date.year {
                write!(f, "{year:04}-")?;
            }
            write!(f, "{:02}-{:02}", date.month, date.date)?;
        }

        match self.state {
            TransactionState::Uncleared => {}
            TransactionState::Pending => write!(f, " !")?,
            TransactionState::Cleared => write!(f, " *")?,
        }

        if let Some(ref code) = self.code {
            write!(f, " ({code})")?;
        }

        writeln!(f, " {}", self.description)?;

        for note in self.notes.iter() {
            writeln!(f, "    ; {note}")?;
        }

        for posting in self.postings.iter() {
            posting.fmt(f)?;
        }

        Ok(())
    }
}

/// Virtual-posting semantics for an [`ast::Posting`].
///
/// Ledger-cli permits two virtual-posting markers that change balance-rule
/// semantics:
///
/// - `Real` -- ordinary posting; participates in the transaction balance check.
/// - `VirtualUnbalanced` -- written as `(Account)`; the posting is excluded from
///   the transaction's balance check. The two "real" postings must balance among
///   themselves; the virtual posting is stored but contributes no balancing
///   obligation.
/// - `VirtualBalanced` -- written as `[Account]`; the posting is included in the
///   balance check (like a real posting) but is flagged so reports can show or
///   hide it via `--real`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum PostingKind {
    /// Ordinary posting -- participates in the transaction balance check.
    #[default]
    Real,
    /// `(Account)` -- excluded from the balance check.
    VirtualUnbalanced,
    /// `[Account]` -- included in the balance check, but flagged as virtual.
    VirtualBalanced,
}

/// A single posting (debit or credit line) within a transaction.
///
/// This is the raw parse-tree representation. For programmatic posting
/// construction, use [`crate::resolution::Posting`] and its builder methods instead.
#[derive(Clone, Default, Debug)]
pub(crate) struct Posting {
    /// The account name, e.g. `"Expenses:Food"`.
    ///
    /// For virtual postings the surrounding markers (`(` `)` or `[` `]`) are
    /// stripped by the parser -- only the bare account name is stored here.
    /// The marker semantics live in [`Self::kind`].
    pub account: String,
    /// The amount, or `None` if this is a "null posting" whose value should
    /// be inferred by the elaboration stage as the negation of all others.
    pub amount: Option<AmountDetails>,
    /// Per-posting cleared/pending state (overrides the transaction state).
    pub state: TransactionState,
    /// Lines starting with `;` indented beneath the posting line.
    pub notes: Vec<String>,
    /// Whether this is a real, virtual-unbalanced, or virtual-balanced posting.
    pub kind: PostingKind,
}

impl Posting {
    /// Creates a new real posting for `account` with no amount and no notes.
    pub fn new<S: Into<String>>(account: S) -> Self {
        Self {
            account: account.into(),
            amount: None,
            state: TransactionState::Uncleared,
            notes: vec![],
            kind: PostingKind::Real,
        }
    }

    /// Appends a note to this posting (builder pattern).
    pub fn with_note<S: Into<String>>(mut self, note: S) -> Self {
        self.notes.push(note.into());
        self
    }

    /// Sets the amount for this posting (builder pattern).
    pub fn with_amount<A: Into<AmountDetails>>(mut self, amount: A) -> Self {
        self.amount = Some(amount.into());
        self
    }
}

impl Display for Posting {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "    ")?;
        match self.state {
            TransactionState::Uncleared => {}
            TransactionState::Pending => write!(f, "! ")?,
            TransactionState::Cleared => write!(f, "* ")?,
        }

        write!(f, "{}", self.account)?;

        if let Some(ref amount) = self.amount {
            write!(f, "  {amount}")?;
        }
        writeln!(f)?;

        for note in self.notes.iter() {
            writeln!(f, "    ; {note}")?;
        }
        Ok(())
    }
}

/// The amount field of a posting, in one of two forms.
///
/// Marked `#[non_exhaustive]` so that doppio can grow new posting-amount
/// shapes (e.g. for future budget directives) in 1.x without bumping
/// the major version. Match arms must use a wildcard `_ => ...` arm.
#[derive(PartialEq, Eq, Clone, Debug)]
#[non_exhaustive]
pub enum AmountDetails {
    /// A standard amount expression, with optional lot pricing and/or a
    /// balance assertion.
    ///
    /// Example: `10 AAPL {$150} @ $155 = $1550`
    Amount {
        /// The value expression (may be arithmetic, e.g. `(100 + 50) USD`).
        value: ValueExpr,
        /// Lot persistence annotations: `{cost}`, `[date]`, `((note))`.
        lot_annotation: Option<LotAnnotation>,
        /// Cost basis: `@ price_per_unit` or `@@ total_cost`.
        lot_pricing: Option<LotPricing>,
        /// If present, the account balance after this posting must equal this
        /// value (`= expected_balance`).
        balance_assertion: Option<ValueExpr>,
    },
    /// A balance assignment: `= target_balance`, with no explicit debit/credit
    /// value. The posting amount is computed as `target - current_balance`.
    BalanceAssignment(ValueExpr),
    /// hledger's "balance everything" form: `=* target` or `==* target`,
    /// typically `==* 0` in retained-earnings transactions. Synthesizes a
    /// multi-commodity posting that brings the account's balance in
    /// every commodity it currently holds to `target` (which is
    /// expected to be a bare number with no commodity).
    BalanceAssignmentAllCommodities(ValueExpr),
}

impl<I: Into<ValueExpr>> From<I> for AmountDetails {
    fn from(value: I) -> Self {
        AmountDetails::Amount {
            value: value.into(),
            lot_annotation: None,
            lot_pricing: None,
            balance_assertion: None,
        }
    }
}

impl Display for AmountDetails {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AmountDetails::Amount {
                value,
                lot_annotation,
                lot_pricing,
                balance_assertion,
            } => {
                write!(f, "{value}")?;
                if let Some(ann) = lot_annotation {
                    if let Some(cost) = &ann.cost {
                        write!(f, " {{{cost}}}")?;
                    }
                    if let Some(date) = ann.date {
                        write!(f, " [{date}]")?;
                    }
                    if let Some(note) = &ann.note {
                        write!(f, " (({note}))")?;
                    }
                }
                if let Some(lot_pricing) = lot_pricing {
                    match lot_pricing {
                        LotPricing::Unit(value_expr) => write!(f, " @ {value_expr}")?,
                        LotPricing::Total(value_expr) => write!(f, " @@ {value_expr}")?,
                    }
                }
                if let Some(balance_assertion) = balance_assertion {
                    write!(f, " = {balance_assertion}")?;
                }
                Ok(())
            }
            AmountDetails::BalanceAssignment(value) => {
                write!(f, "={value}")
            }
            // hledger-specific syntax with no ledger-cli equivalent:
            // ledger's `= X` is single-commodity assignment, which is
            // semantically different from "zero every commodity in
            // the inventory." Render as `==* X` (the original
            // hledger source form); output containing this variant
            // therefore does NOT round-trip through the ledger
            // parser. Proper per-frontend writers are #206.
            AmountDetails::BalanceAssignmentAllCommodities(value) => {
                write!(f, "==* {value}")
            }
        }
    }
}

impl Display for ValueExpr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ValueExpr::Amount { value, commodity } => {
                write!(f, "{value}")?;
                if let Some(commodity) = commodity {
                    write!(f, " {commodity}")?;
                }
                Ok(())
            }
            ValueExpr::Str(s) => write!(f, "\"{s}\""),
            // TODO: forward-slashes inside `pattern` are not re-escaped, so a
            // pattern like `a/b` renders as `/a/b/` which does not round-trip
            // through the parser. Fix when round-trip fidelity is required.
            ValueExpr::Regex(pattern) => write!(f, "/{pattern}/"),
            ValueExpr::Unary { op, expr } => {
                let op = match op {
                    Op::Add => "+",
                    Op::Sub => "-",
                    Op::Mul => "*",
                    Op::Div => "/",
                };
                write!(f, "{op}{expr}")
            }
            ValueExpr::Binary { lhs, rhs, op } => {
                let op = match op {
                    Op::Add => "+",
                    Op::Sub => "-",
                    Op::Mul => "*",
                    Op::Div => "/",
                };
                write!(f, "{lhs} {op} {rhs}")
            }
            ValueExpr::Function { name, args } => {
                write!(f, "{name}(")?;
                let mut args = args.iter();
                if let Some(a) = args.next() {
                    write!(f, "{a}")?;
                }
                for a in args {
                    write!(f, ", {a}")?;
                }
                write!(f, ")")
            }
            ValueExpr::Commodity(c) => write!(f, "{c}"),
            ValueExpr::Typed { expr, commodity } => write!(f, "{expr} {commodity}"),
            ValueExpr::Access { expr, field } => write!(f, "{expr}.{field}"),
            ValueExpr::Object(_) => todo!(),
            ValueExpr::Group(b) => write!(f, "({b})"),
        }
    }
}

/// An unevaluated value expression, produced by the parser and consumed by
/// the elaboration stage.
///
/// The variants cover all syntactic forms that can appear in a posting amount:
/// numeric literals, string literals, arithmetic, function calls, and
/// commodity type annotations.
///
/// Marked `#[non_exhaustive]` so that the grammar can grow new
/// expression forms in 1.x without bumping the major version. Match
/// arms must use a wildcard `_ => ...` arm.
#[derive(PartialEq, Eq, Debug, Clone)]
#[non_exhaustive]
pub enum ValueExpr {
    /// A key-value object, used as the return type of the `account()` function.
    /// Fields are accessed with the [`ValueExpr::Access`] form.
    Object(BTreeMap<String, Self>),

    /// A numeric amount with an optional commodity.
    ///
    /// `commodity: None` means the commodity is not yet known; the elaboration
    /// stage fills it in from the context's default commodity.
    Amount {
        value: Decimal,
        commodity: Option<String>,
    },

    /// A prefix unary operator applied to a sub-expression.
    ///
    /// Only `+` and `-` are meaningful on amounts; `*` and `/` produce an
    /// [`EvaluationError`](crate::EvaluationError).
    Unary { op: Op, expr: Box<ValueExpr> },

    /// An infix binary operator applied to two sub-expressions.
    Binary {
        lhs: Box<ValueExpr>,
        rhs: Box<ValueExpr>,
        op: Op,
    },

    /// A function call, e.g. `account("Assets:Bank")` or `scrub(100 USD)`.
    Function { name: String, args: Vec<ValueExpr> },

    /// A bare commodity symbol that appears without an adjacent number,
    /// e.g. in `$-123` the `$` is parsed as a `Commodity` and `123` as
    /// `Amount { value: 123, commodity: None }`, with `-` as a `Binary { op: Sub }`
    /// between them. This special form is resolved in the evaluator.
    Commodity(String),

    /// A type annotation wrapping a parenthesised expression: `(expr) USD`.
    /// The elaboration stage verifies that the inner expression's commodity
    /// is compatible with the annotation.
    Typed {
        expr: Box<ValueExpr>,
        commodity: String,
    },

    /// A string literal (double-quoted).
    Str(String),

    /// A regex literal: `/pattern/`. Carries the raw pattern string between
    /// the delimiters (backslash-escapes are preserved as written). The regex
    /// is compiled on first use by the evaluator; it is never compiled here
    /// at parse time, keeping the AST independent of the `regex` crate.
    Regex(String),

    /// Field access on an object expression: `account("Foo").total`.
    Access { expr: Box<ValueExpr>, field: String },

    /// A parenthesised boolean expression appearing in a value-expression
    /// position, e.g. `(amt > 0 or amt < -10)`.
    ///
    /// This variant is introduced when the grammar matches
    /// `"(" ~ bool_expr ~ ")"` inside `base_primary`. The evaluator converts
    /// it to a `ValueExpr::Amount` of `1` (true) or `0` (false) so that it
    /// can participate in arithmetic or be used as the LHS of a comparison.
    Group(Box<BoolExpr>),
}

impl ValueExpr {
    /// Convenience constructor for an amount with a known commodity.
    pub fn amount(value: Decimal, commodity: String) -> ValueExpr {
        ValueExpr::Amount {
            value,
            commodity: Some(commodity),
        }
    }

    /// Parse a Ledger value expression from a string.
    ///
    /// Useful for testing or standalone expression evaluation without
    /// going through the full journal parser.
    ///
    /// # Example
    /// ```
    /// # use doppio::ast::ValueExpr;
    /// let expr = ValueExpr::parse("100 USD").unwrap();
    /// ```
    pub fn parse(input: &str) -> Result<ValueExpr, pest::error::Error<ledger::Rule>> {
        let mut pairs = LedgerParser::parse(ledger::Rule::value_expr, input)?;
        let pair = pairs.next().unwrap();
        Ok(ledger::parse_expr(pair))
    }
}

impl<S: Into<String>> From<(Decimal, S)> for ValueExpr {
    fn from(value: (Decimal, S)) -> Self {
        Self::amount(value.0, value.1.into())
    }
}

/// Arithmetic operator used in [`ValueExpr::Binary`] and [`ValueExpr::Unary`].
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Op {
    Add,
    Sub,
    Mul,
    Div,
}

/// The cost-basis annotation on a posting amount.
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum LotPricing {
    /// Per-unit price: `@ price`. The total cost is `amount * price`.
    Unit(ValueExpr),
    /// Total price: `@@ total`. The total cost is taken as-is.
    Total(ValueExpr),
}

/// Lot persistence annotations that pin per-lot metadata for capital-gains
/// tracking and FIFO/LIFO lot selection.
///
/// Corresponds to the `{cost}`, `[date]`, and `((note))` annotation forms
/// in ledger-cli syntax.  All fields are optional; the struct is present on
/// an [`AmountDetails::Amount`] only when at least one annotation was found.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct LotAnnotation {
    /// Per-unit cost basis (or, when [`Self::cost_is_total`] is `true`,
    /// the *total* lot cost). `None` if no `{cost}` / `{{total}}`
    /// annotation was present.
    pub cost: Option<ValueExpr>,
    /// `true` when the cost was expressed as a total via the
    /// `{{total}}` double-brace form. The elaborator divides
    /// [`Self::cost`] by the posting's unit count before using it as
    /// per-unit basis. Defaults to `false` (per-unit).
    pub cost_is_total: bool,
    /// Acquisition date.  `None` if no `[date]` annotation was present.
    pub date: Option<chrono::NaiveDate>,
    /// Free-form note.  `None` if no `((note))` annotation was present.
    pub note: Option<String>,
}

/// Cleared/pending state of a transaction or individual posting.
#[derive(Clone, Debug, Default)]
pub enum TransactionState {
    /// No state marker -- the transaction has not been reviewed.
    #[default]
    Uncleared,
    /// `!` -- the transaction is pending confirmation.
    Pending,
    /// `*` -- the transaction has been confirmed/reconciled.
    Cleared,
}

#[cfg(test)]
mod tests {
    use super::*;
    use rust_decimal::Decimal;

    #[test]
    fn test_date_ordering() {
        let d1 = Date {
            year: Some(2024),
            month: 1,
            date: 1,
        };
        let d2 = Date {
            year: Some(2024),
            month: 6,
            date: 15,
        };
        let d3 = Date {
            year: Some(2025),
            month: 1,
            date: 1,
        };
        let d4 = Date {
            year: Some(2024),
            month: 1,
            date: 1,
        };

        assert!(d1 < d2);
        assert!(d2 < d3);
        assert!(d1 < d3);
        assert_eq!(d1, d4);
        assert!(d3 > d1);

        let mut dates = vec![d3.clone(), d1.clone(), d2.clone()];
        dates.sort();
        assert_eq!(dates, vec![d1, d2, d3]);
    }

    #[test]
    fn test_transaction_display_indentation() {
        let mut tx = Transaction::default();
        tx.date = Date {
            year: Some(2024),
            month: 1,
            date: 15,
        };
        tx.description = "Test payee".to_string();
        tx.notes = vec!["a note".to_string()];
        let mut posting = Posting::new("Assets:Bank");
        posting.amount = Some(AmountDetails::Amount {
            value: ValueExpr::Amount {
                value: Decimal::from(100),
                commodity: Some("USD".into()),
            },
            lot_annotation: None,
            lot_pricing: None,
            balance_assertion: None,
        });
        tx.postings = vec![posting];

        let out = format!("{tx}");
        // Notes use 4-space indent
        assert!(
            out.contains("    ; a note"),
            "note should have 4-space indent, got:\n{out}"
        );
        // Posting line uses 4-space indent
        assert!(
            out.contains("    Assets:Bank"),
            "posting should have 4-space indent, got:\n{out}"
        );
    }

    #[test]
    fn test_value_expr_parse_amount() {
        let expr = ValueExpr::parse("100 USD").unwrap();
        assert_eq!(
            expr,
            ValueExpr::Amount {
                value: "100".parse().unwrap(),
                commodity: Some("USD".into()),
            }
        );
    }

    #[test]
    fn test_value_expr_parse_prefixed_commodity() {
        let expr = ValueExpr::parse("$50").unwrap();
        assert_eq!(
            expr,
            ValueExpr::Amount {
                value: "50".parse().unwrap(),
                commodity: Some("$".into()),
            }
        );
    }

    #[test]
    fn test_value_expr_parse_arithmetic() {
        // Should parse without error and produce a Binary node
        let expr = ValueExpr::parse("10 + 5 USD").unwrap();
        assert!(
            matches!(expr, ValueExpr::Binary { .. } | ValueExpr::Typed { .. }),
            "expected Binary or Typed, got {expr:?}"
        );
    }

    #[test]
    fn test_value_expr_parse_error() {
        assert!(ValueExpr::parse("@@@invalid").is_err());
    }
}