rustledger-parser 0.18.0

Beancount parser with error recovery and full syntax support
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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
//! Green-tree conversion path (PR 1 of the lossless-CST-tax removal — see the
//! profiling sizing spike: the CST→AST conversion is ~74% of the load, and
//! ~33% of that is red-node (`SyntaxNode` cursor) traversal that allocates +
//! refcounts a `NodeData` per node touch).
//!
//! This module walks the **immutable green tree** top-down, threading the
//! absolute byte offset, instead of materializing red nodes. It is built in
//! parallel with [`super::convert`] and gated by a differential oracle that
//! pins its output byte-identical to the red path.
//!
//! Status: full transaction conversion (header + postings + cost/price), wired
//! into `parse_via_cst_opts` with a **red fallback** — green returns `Some` only
//! when it exactly replicates red, bailing on transaction metadata, direct-child
//! comments, deprecated `|`, unparseable amounts, and posting flag/metadata/
//! arithmetic (those layer on next). Measured −16% load on a 10k-txn workload.
//! Pinned by field-level oracles + the `parse_green_eq_red_corpus` differential
//! test + the `fuzz_green_eq_red` fuzz target.

use super::ast::AstNode as _; // brings `Directive::can_cast` into scope
use super::convert::{
    DescendantsWalkResult, TopLevelWalkResult, classify_recovery_error, decode_string_token,
    is_comment_kind, is_trivia_kind, number_meta_value, parse_date_token, parse_decimal_token,
};
use rowan::{Language, NodeOrToken};
use rustledger_core::cost::{CostNumber, CostSpec};
use rustledger_core::directive::{PriceAnnotation, PriceKind};
use rustledger_core::{
    Account, Amount, Currency, IncompleteAmount, InternedStr, Link, MetaValue, Metadata, NaiveDate,
    Posting, Span, Spanned, Tag,
};

/// Every top-level (child-of-root) **node** paired with its source [`Span`],
/// computed by threading the absolute byte offset through the green tree — no
/// red-node allocation. Equivalent to `root.children().map(node_span)` on the
/// red tree; the differential test pins that equivalence. Offset drift (esp.
/// across a leading BOM and multi-byte text) is the #1 correctness hazard, so
/// this validates it before any body conversion rides on it.
// Span-validation helper exercised only by the differential tests (the wired
// path threads offsets inline); targeted allow so the rest of the module is
// still checked for dead code.
#[allow(dead_code)]
pub(super) fn top_level_node_spans(
    root: &crate::SyntaxNode,
    bom_offset: u32,
) -> Vec<(crate::SyntaxKind, Span)> {
    let green = root.green();
    let mut out = Vec::new();
    let mut offset = bom_offset as usize;
    for child in green.children() {
        let len = match &child {
            NodeOrToken::Node(n) => u32::from(n.text_len()) as usize,
            NodeOrToken::Token(t) => u32::from(t.text_len()) as usize,
        };
        if let NodeOrToken::Node(n) = child {
            let kind = crate::BeancountLanguage::kind_from_raw(n.kind());
            out.push((kind, Span::new(offset, offset + len)));
        }
        offset += len;
    }
    out
}

/// Flag char for a header flag-token kind. Mirrors `TransactionFlag::cast` +
/// `flag_char_from_transaction` in [`super::convert`]: STAR/TXN→`*`,
/// PENDING→`!`, HASH→`#`, FLAG/single-char-CURRENCY → first char.
fn flag_char(kind: crate::SyntaxKind, text: &str) -> Option<char> {
    use crate::SyntaxKind as K;
    match kind {
        K::STAR | K::TXN_KW => Some('*'),
        K::PENDING_KW => Some('!'),
        K::HASH => Some('#'),
        K::FLAG => text.chars().next(),
        K::CURRENCY if text.len() == 1 => text.chars().next(),
        _ => None,
    }
}

/// Convert a `TRANSACTION` green node's **header** (date / flag / payee+
/// narration / tags / links) and span, in a single fused pass over its direct
/// children — no red-node allocation. Metadata, postings, and trailing comments
/// are left empty here (next increment); the oracle compares only the header
/// fields for now. `base` is the node's absolute start offset (BOM-inclusive).
///
/// Returns `None` if the date is absent/invalid (matching red, which drops the
/// directive). Error emission for an invalid date lands with the next increment.
pub(super) fn convert_transaction_header(
    node: &rowan::GreenNodeData,
    base: usize,
) -> Option<(rustledger_core::directive::Transaction, Span)> {
    use crate::SyntaxKind as K;
    let span = Span::new(base, base + u32::from(node.text_len()) as usize);

    let mut date: Option<NaiveDate> = None;
    let mut date_seen = false;
    let mut flag = '*';
    let mut seen_flag = false;
    let mut seen_str_tag_link = false;
    let mut strings: Vec<String> = Vec::new();
    let mut tags: Vec<Tag> = Vec::new();
    let mut links: Vec<Link> = Vec::new();
    let mut past_header = false;

    for child in node.children() {
        let NodeOrToken::Token(t) = child else {
            // POSTING / META_ENTRY child nodes — handled in the next increment.
            continue;
        };
        let kind = crate::BeancountLanguage::kind_from_raw(t.kind());
        let text = t.text();
        if past_header {
            // Body-level flat TAG/LINK tokens (between postings) join the set,
            // deduped against what the header already contributed.
            match kind {
                K::TAG => {
                    let tg = Tag::new(text.trim_start_matches('#'));
                    if !tags.contains(&tg) {
                        tags.push(tg);
                    }
                }
                K::LINK => {
                    let lk = Link::new(text.trim_start_matches('^'));
                    if !links.contains(&lk) {
                        links.push(lk);
                    }
                }
                _ => {}
            }
        } else {
            match kind {
                K::NEWLINE => past_header = true,
                // Latch on the FIRST date token (like red's `node.date()`): if it
                // fails to parse, `date` stays None and the directive bails to red
                // — don't scan ahead to a later valid-looking date in junk input.
                K::DATE if !date_seen => {
                    date_seen = true;
                    date = parse_date_token(text);
                }
                K::STRING => {
                    seen_str_tag_link = true;
                    if let Some(s) = decode_string_token(text) {
                        strings.push(s);
                    }
                }
                K::TAG => {
                    seen_str_tag_link = true;
                    tags.push(Tag::new(text.trim_start_matches('#')));
                }
                K::LINK => {
                    seen_str_tag_link = true;
                    links.push(Link::new(text.trim_start_matches('^')));
                }
                // Flag region: the first flag-kind token before any STRING/TAG/LINK.
                k if !seen_flag && !seen_str_tag_link => {
                    if let Some(c) = flag_char(k, text) {
                        flag = c;
                        seen_flag = true;
                    }
                }
                _ => {}
            }
        }
    }
    let date = date?;

    // 0 -> empty narration; 1 -> narration only; 2 -> payee + narration;
    // 3+ -> last is narration, payee dropped (matches red).
    let mut it = strings.into_iter();
    let (payee_str, narration_str) = match (it.next(), it.next(), it.next()) {
        (None, _, _) => (None, String::new()),
        (Some(n), None, _) => (None, n),
        (Some(p), Some(n), None) => (Some(p), n),
        (Some(_), Some(_), Some(c)) => (None, it.last().unwrap_or(c)),
    };

    let txn = rustledger_core::directive::Transaction {
        date,
        flag,
        payee: payee_str.map(InternedStr::from),
        narration: InternedStr::from(narration_str),
        tags,
        links,
        meta: Metadata::default(),
        postings: Vec::new(),
        trailing_comments: Vec::new(),
    };
    Some((txn, span))
}

/// Convert a non-arithmetic `AMOUNT` green node into an `IncompleteAmount`.
/// Returns `None` for arithmetic-expression amounts (`5 + 3 USD`) — those are a
/// later increment; the simple oracle corpus excludes them.
fn simple_amount(node: &rowan::GreenNodeData) -> Option<IncompleteAmount> {
    use crate::SyntaxKind as K;
    let mut sign_minus = false;
    let mut number: Option<rust_decimal::Decimal> = None;
    let mut number_seen = false;
    let mut currency: Option<Currency> = None;
    let mut complex = false;
    for child in node.children() {
        let NodeOrToken::Token(t) = child else {
            complex = true;
            continue;
        };
        match crate::BeancountLanguage::kind_from_raw(t.kind()) {
            K::MINUS if !number_seen => sign_minus = true,
            K::PLUS if !number_seen => {}
            K::NUMBER if !number_seen => {
                number_seen = true;
                number = parse_decimal_token(t.text());
                // An unparseable NUMBER (e.g. >28 digits) makes red emit a
                // diagnostic; bail to red so the error isn't dropped.
                if number.is_none() {
                    complex = true;
                }
            }
            K::CURRENCY if currency.is_none() => currency = Some(Currency::new(t.text())),
            K::WHITESPACE => {}
            // Operator, second number, or extra currency => arithmetic/complex.
            K::NUMBER
            | K::PLUS
            | K::MINUS
            | K::STAR
            | K::SLASH
            | K::L_PAREN
            | K::R_PAREN
            | K::CURRENCY => complex = true,
            _ => {}
        }
    }
    if complex {
        return None;
    }
    let number = number.map(|n| if sign_minus { -n } else { n });
    match (number, currency) {
        (Some(n), Some(c)) => Some(IncompleteAmount::Complete(Amount::new(n, c))),
        (Some(n), None) => Some(IncompleteAmount::NumberOnly(n)),
        (None, Some(c)) => Some(IncompleteAmount::CurrencyOnly(c)),
        (None, None) => None,
    }
}

/// Convert a `COST_SPEC` green node into a `CostSpec` (forms `{N CCY}`,
/// `{{T CCY}}`, `{N # T CCY}`, `{*}` merge, plus optional date + label). Mirrors
/// `convert_cost_spec` / `cost_total_after_hash` in [`super::convert`]. Cost
/// numbers are plain `NUMBER` tokens (no arithmetic evaluation); an unparseable
/// one yields `number: None` like red, which emits no diagnostic for cost
/// numbers — so this needs no bail and always returns a `CostSpec`.
fn convert_cost_spec(node: &rowan::GreenNodeData) -> CostSpec {
    use crate::SyntaxKind as K;
    let mut is_total = false;
    let mut first_number: Option<rust_decimal::Decimal> = None;
    let mut seen_number = false;
    let mut past_hash = false;
    let mut post_hash_seen = false;
    let mut post_hash_total: Option<rust_decimal::Decimal> = None;
    let mut currency: Option<Currency> = None;
    let mut date: Option<NaiveDate> = None;
    let mut date_seen = false;
    let mut label: Option<String> = None;
    let mut label_seen = false;
    for child in node.children() {
        let NodeOrToken::Token(t) = child else {
            continue;
        };
        match crate::BeancountLanguage::kind_from_raw(t.kind()) {
            // `is_total` = any `{{` present anywhere — mirrors red `is_total()`
            // (`first_token(.., L_DOUBLE_BRACE).is_some()`). The merge flag is
            // computed separately in `cost_is_merge` (see its note).
            K::L_DOUBLE_BRACE => is_total = true,
            K::NUMBER => {
                if past_hash {
                    // Latch the FIRST post-`#` NUMBER token (parsed or not),
                    // exactly like red's `cost_total_after_hash`, which `return`s
                    // at the first NUMBER after the hash regardless of whether it
                    // parses. The old `post_hash_total.is_none()` guard kept
                    // scanning past an unparseable total and latched a *later*
                    // number, so green produced `Total{later}` where red yielded
                    // `None` (→ `PerUnit{first}`) — the `fuzz_green_eq_red`
                    // divergence on `{N # <unparseable> T}`.
                    if !post_hash_seen {
                        post_hash_seen = true;
                        post_hash_total = parse_decimal_token(t.text());
                    }
                } else if !seen_number {
                    seen_number = true;
                    first_number = parse_decimal_token(t.text());
                }
            }
            K::HASH => {
                if seen_number {
                    past_hash = true;
                }
            }
            K::CURRENCY if currency.is_none() => {
                currency = Some(Currency::new(t.text()));
            }
            K::DATE if !date_seen => {
                date_seen = true;
                date = parse_date_token(t.text());
            }
            K::STRING if !label_seen => {
                label_seen = true;
                label = decode_string_token(t.text());
            }
            _ => {}
        }
    }
    let number = if let Some(total) = post_hash_total {
        Some(CostNumber::Total { value: total })
    } else {
        match (first_number, is_total) {
            (Some(v), true) => Some(CostNumber::Total { value: v }),
            (Some(v), false) => Some(CostNumber::PerUnit { value: v }),
            (None, _) => None,
        }
    };
    CostSpec {
        number,
        currency,
        date,
        label,
        merge: cost_is_merge(node),
    }
}

/// Whether a cost spec is a merge cost (`{*}`). Exact mirror of red
/// [`super::ast`]'s `CostSpec::is_merge`: only the first non-whitespace token
/// after the opener decides (`*` → merge, anything else → not), and it stops
/// there. The previous scan-everything pass kept re-arming on later openers, so
/// a malformed cost containing a stray `{*}`-shaped run flipped the flag where
/// red did not — the divergence `fuzz_green_eq_red` caught. Keep byte-for-byte
/// with red.
fn cost_is_merge(node: &rowan::GreenNodeData) -> bool {
    use crate::SyntaxKind as K;
    let mut past_opener = false;
    for child in node.children() {
        let NodeOrToken::Token(t) = child else {
            continue;
        };
        match crate::BeancountLanguage::kind_from_raw(t.kind()) {
            K::L_BRACE | K::L_DOUBLE_BRACE | K::L_BRACE_HASH => past_opener = true,
            K::WHITESPACE if past_opener => {}
            K::STAR if past_opener => return true,
            _ if past_opener => return false,
            _ => {}
        }
    }
    false
}

/// Convert a `PRICE_ANNOTATION` green node into a `PriceAnnotation`: `@@`→Total,
/// `@`→Unit, with the (non-arithmetic) amount. Returns `None` when the amount is
/// present but arithmetic/malformed, signalling the caller to bail (later
/// increment evaluates those).
fn convert_price_annotation(node: &rowan::GreenNodeData) -> Option<PriceAnnotation> {
    use crate::SyntaxKind as K;
    let mut is_total = false;
    let mut amount_present = false;
    let mut amount: Option<IncompleteAmount> = None;
    for child in node.children() {
        match &child {
            NodeOrToken::Token(t) => {
                if crate::BeancountLanguage::kind_from_raw(t.kind()) == K::AT_AT {
                    is_total = true;
                }
            }
            NodeOrToken::Node(n) => {
                if crate::BeancountLanguage::kind_from_raw(n.kind()) == K::AMOUNT && !amount_present
                {
                    amount_present = true;
                    amount = simple_amount(n);
                }
            }
        }
    }
    if amount_present && amount.is_none() {
        return None; // arithmetic / malformed price amount — bail
    }
    Some(PriceAnnotation {
        kind: if is_total {
            PriceKind::Total
        } else {
            PriceKind::Unit
        },
        amount,
    })
}

/// Derive the typed [`MetaValue`] of a `META_ENTRY` green node. Mirrors
/// `meta_value_from_entry` in [`super::convert`] exactly: priority is string >
/// number/amount > date > account > currency > bool > tag/link > none, and a
/// type that's present-but-unparseable (e.g. a malformed string, an
/// over-precision number, a bad date) falls through to the next, matching red.
fn meta_value(entry: &rowan::GreenNodeData) -> MetaValue {
    use crate::SyntaxKind as K;
    let mut string_t: Option<String> = None;
    let mut number_t: Option<String> = None;
    let mut currency_t: Option<String> = None;
    let mut date_t: Option<String> = None;
    let mut account_t: Option<String> = None;
    let mut bool_v: Option<bool> = None;
    let mut tag_link: Option<MetaValue> = None;
    // Minus sign negating the number: a MINUS token AFTER the key and BEFORE the
    // first NUMBER (mirrors `meta_entry_has_minus_sign`).
    let mut past_key = false;
    let mut minus = false;
    let mut minus_decided = false;

    for child in entry.children() {
        let NodeOrToken::Token(t) = child else {
            continue;
        };
        let kind = crate::BeancountLanguage::kind_from_raw(t.kind());
        // First-of-kind value tokens (matches red's `first_token` accessors).
        match kind {
            K::STRING if string_t.is_none() => string_t = Some(t.text().to_string()),
            K::NUMBER if number_t.is_none() => number_t = Some(t.text().to_string()),
            K::CURRENCY if currency_t.is_none() => currency_t = Some(t.text().to_string()),
            K::DATE if date_t.is_none() => date_t = Some(t.text().to_string()),
            K::ACCOUNT if account_t.is_none() => account_t = Some(t.text().to_string()),
            K::BOOL_TRUE if bool_v.is_none() => bool_v = Some(true),
            K::BOOL_FALSE if bool_v.is_none() => bool_v = Some(false),
            K::TAG if tag_link.is_none() => {
                tag_link = Some(MetaValue::Tag(Tag::new(t.text().trim_start_matches('#'))));
            }
            K::LINK if tag_link.is_none() => {
                tag_link = Some(MetaValue::Link(Link::new(t.text().trim_start_matches('^'))));
            }
            _ => {}
        }
        if past_key && !minus_decided {
            match kind {
                K::MINUS => {
                    minus = true;
                    minus_decided = true;
                }
                K::NUMBER => minus_decided = true,
                _ => {}
            }
        }
        if kind == K::META_KEY {
            past_key = true;
        }
    }

    if let Some(s) = string_t
        && let Some(decoded) = decode_string_token(&s)
    {
        return MetaValue::String(decoded);
    }
    if let Some(nt) = number_t
        && let Some(mut dec) = parse_decimal_token(&nt)
    {
        if minus {
            dec = -dec;
        }
        if let Some(c) = currency_t {
            return MetaValue::Amount(Amount::new(dec, Currency::new(&c)));
        }
        return number_meta_value(&nt, dec);
    }
    if let Some(dt) = date_t
        && let Some(date) = parse_date_token(&dt)
    {
        return MetaValue::Date(date);
    }
    if let Some(a) = account_t {
        return MetaValue::Account(Account::new(&a));
    }
    if let Some(c) = currency_t {
        return MetaValue::Currency(Currency::new(&c));
    }
    if let Some(b) = bool_v {
        return MetaValue::Bool(b);
    }
    if let Some(tl) = tag_link {
        return tl;
    }
    MetaValue::None
}

/// Key + typed value for a single `META_ENTRY` green node (key = first
/// `META_KEY` token with the trailing `:` stripped), or `None` if it has no key.
/// Folded directly into the posting/transaction conversion loops so the parent's
/// children are walked only once — no separate metadata pass over them.
fn meta_entry_kv(entry: &rowan::GreenNodeData) -> Option<(String, MetaValue)> {
    use crate::SyntaxKind as K;
    let key = entry.children().find_map(|c| match c {
        NodeOrToken::Token(t)
            if crate::BeancountLanguage::kind_from_raw(t.kind()) == K::META_KEY =>
        {
            Some(t.text().strip_suffix(':').unwrap_or(t.text()).to_string())
        }
        _ => None,
    })?;
    Some((key, meta_value(entry)))
}

/// Posting flag char. Mirrors `PostingFlag::cast` + `flag_char_from_posting`:
/// STAR→`*`, PENDING→`!`, HASH→`#`, FLAG/single-char-CURRENCY → first char.
/// Note: unlike a transaction flag this does NOT accept `txn`.
fn posting_flag_char(kind: crate::SyntaxKind, text: &str) -> Option<char> {
    use crate::SyntaxKind as K;
    match kind {
        K::STAR => Some('*'),
        K::PENDING_KW => Some('!'),
        K::HASH => Some('#'),
        K::FLAG => text.chars().next(),
        K::CURRENCY if text.len() == 1 => text.chars().next(),
        _ => None,
    }
}

/// Convert a `POSTING` green node (flag + account + non-arithmetic units + cost
/// spec + price annotation + per-posting metadata + span + same-line trailing
/// comments). Returns `None` for postings with a trailing-sibling amount or an
/// arithmetic amount — those fall back to red. `base` is the node's absolute
/// start offset. Span policy matches red `posting_span`: ends at the first
/// NEWLINE's start.
pub(super) fn convert_simple_posting(
    node: &rowan::GreenNodeData,
    base: usize,
) -> Option<Spanned<Posting>> {
    use crate::SyntaxKind as K;
    let mut flag: Option<char> = None;
    let mut flag_decided = false;
    let mut account: Option<Account> = None;
    let mut units: Option<IncompleteAmount> = None;
    let mut cost: Option<CostSpec> = None;
    let mut price: Option<PriceAnnotation> = None;
    let mut meta = Metadata::default();
    let mut trailing_comments: Vec<String> = Vec::new();
    let mut newline_off: Option<usize> = None;
    let mut amount_seen = false;
    let mut offset = base;
    for child in node.children() {
        let len = match &child {
            NodeOrToken::Node(n) => u32::from(n.text_len()) as usize,
            NodeOrToken::Token(t) => u32::from(t.text_len()) as usize,
        };
        match &child {
            NodeOrToken::Token(t) => {
                let kind = crate::BeancountLanguage::kind_from_raw(t.kind());
                if kind == K::ACCOUNT && account.is_none() {
                    flag_decided = true; // account reached; flag decision is settled
                    account = Some(Account::new(t.text()));
                } else if kind == K::NEWLINE && newline_off.is_none() {
                    newline_off = Some(offset);
                } else if newline_off.is_none() && is_comment_kind(kind) {
                    trailing_comments.push(t.text().to_string());
                } else if !flag_decided && account.is_none() && kind != K::WHITESPACE {
                    // First non-whitespace token before the account is the flag iff
                    // it's a flag kind (else `None`), matching red's `Posting::flag`.
                    flag_decided = true;
                    flag = posting_flag_char(kind, t.text());
                }
            }
            NodeOrToken::Node(n) => match crate::BeancountLanguage::kind_from_raw(n.kind()) {
                K::AMOUNT if !amount_seen => {
                    amount_seen = true;
                    // `?` bails on an arithmetic/malformed amount (later increment).
                    units = Some(simple_amount(n)?);
                }
                K::COST_SPEC if cost.is_none() => cost = Some(convert_cost_spec(n)),
                // `?` bails if the price amount is arithmetic/malformed.
                K::PRICE_ANNOTATION if price.is_none() => {
                    price = Some(convert_price_annotation(n)?);
                }
                K::META_ENTRY => {
                    if let Some((k, v)) = meta_entry_kv(n) {
                        meta.insert(k, v);
                    }
                }
                // second amount — arithmetic/multi-amount falls back to red.
                K::AMOUNT => return None,
                _ => {}
            },
        }
        offset += len;
    }
    let account = account?;
    let end = newline_off.unwrap_or(base + u32::from(node.text_len()) as usize);
    Some(Spanned::new(
        Posting {
            account,
            units,
            cost,
            price,
            flag,
            meta,
            comments: Vec::new(),
            trailing_comments,
        },
        Span::new(base, end),
    ))
}

/// Assemble a full `TRANSACTION` directive from its green node, or return `None`
/// to fall back to red. Returns `Some` **only** when the transaction is fully
/// and identically convertible on green: a valid date, all simple postings, and
/// no direct-child comments or deprecated `|` — those need red's attach +
/// diagnostic logic the green path doesn't yet replicate. Header fields,
/// postings, and transaction-level metadata are all converted here. Bailing to
/// red keeps the hybrid's output exactly equal to red. `base` is the node start.
pub(super) fn convert_transaction(
    node: &rowan::GreenNodeData,
    base: usize,
) -> Option<Spanned<rustledger_core::Directive>> {
    use crate::SyntaxKind as K;
    let (mut txn, span) = convert_transaction_header(node, base)?;
    let mut postings = Vec::new();
    let mut meta = Metadata::default();
    let mut offset = base;
    for child in node.children() {
        let len = match &child {
            NodeOrToken::Node(n) => u32::from(n.text_len()) as usize,
            NodeOrToken::Token(t) => u32::from(t.text_len()) as usize,
        };
        match &child {
            NodeOrToken::Token(t) => {
                let kind = crate::BeancountLanguage::kind_from_raw(t.kind());
                // Direct-child comments (header-trailing / inter-posting /
                // txn-trailing) and the deprecated `|` need red's attach +
                // diagnostic logic — bail.
                if is_comment_kind(kind) || kind == K::PIPE {
                    return None;
                }
            }
            // One pass: postings and transaction-level metadata (posting
            // metadata lives inside the POSTING nodes, handled per-posting).
            NodeOrToken::Node(n) => match crate::BeancountLanguage::kind_from_raw(n.kind()) {
                K::POSTING => postings.push(convert_simple_posting(n, offset)?),
                K::META_ENTRY => {
                    if let Some((k, v)) = meta_entry_kv(n) {
                        meta.insert(k, v);
                    }
                }
                _ => {}
            },
        }
        offset += len;
    }
    txn.postings = postings;
    txn.meta = meta;
    Some(Spanned::new(
        rustledger_core::Directive::Transaction(txn),
        span,
    ))
}

/// Green-tree re-implementation of `walk_descendants_once` — the #1 allocation
/// site in the conversion (red `descendants_with_tokens()` heap-allocates +
/// refcounts a `NodeData` per node touched, over EVERY token in the file).
///
/// Recursively walks the green tree threading three pieces of state that red got
/// for free from the red cursor: the absolute byte `offset`, an `in_error_node`
/// flag (replacing red's per-token `parent_ancestors()` `ERROR_NODE` probe — the
/// green tree has no parent pointers), and the linear `preceded_by_ws` column-0
/// comment state. Produces a byte-identical [`DescendantsWalkResult`]. Tree
/// depth is grammar-bounded (~6 levels; arithmetic and error recovery don't nest
/// structurally), so the recursion can't blow the stack on adversarial input.
pub(super) fn walk_descendants(
    root: &crate::SyntaxNode,
    bom_offset: u32,
    collect_occurrences: bool,
) -> DescendantsWalkResult {
    let mut w = DescendantsWalker {
        offset: bom_offset as usize,
        preceded_by_ws: false,
        collect_occurrences,
        result: DescendantsWalkResult {
            inline_errors: Vec::new(),
            top_level_comments: Vec::new(),
            currency_occurrences: Vec::new(),
            account_occurrences: Vec::new(),
        },
    };
    w.walk(&root.green(), false);
    w.result
}

struct DescendantsWalker {
    offset: usize,
    preceded_by_ws: bool,
    collect_occurrences: bool,
    result: DescendantsWalkResult,
}

impl DescendantsWalker {
    fn walk(&mut self, node: &rowan::GreenNodeData, in_error_node: bool) {
        use crate::SyntaxKind as K;
        for child in node.children() {
            match child {
                NodeOrToken::Node(n) => {
                    let kind = crate::BeancountLanguage::kind_from_raw(n.kind());
                    // Directive nodes reset the column-0 comment state (mirrors the
                    // red walk's `Node` arm).
                    if super::ast::Directive::can_cast(kind) {
                        self.preceded_by_ws = false;
                    }
                    self.walk(n, in_error_node || kind == K::ERROR_NODE);
                }
                NodeOrToken::Token(t) => {
                    let start = self.offset;
                    let len = u32::from(t.text_len()) as usize;
                    self.offset += len;
                    let kind = crate::BeancountLanguage::kind_from_raw(t.kind());
                    self.token(kind, t.text(), start, len, in_error_node);
                }
            }
        }
    }

    fn token(
        &mut self,
        kind: crate::SyntaxKind,
        text: &str,
        start: usize,
        len: usize,
        in_error_node: bool,
    ) {
        use crate::SyntaxKind as K;
        // ---- column-0 comment state machine ----
        match kind {
            K::NEWLINE => self.preceded_by_ws = false,
            K::WHITESPACE => self.preceded_by_ws = true,
            k if is_comment_kind(k) => {
                if !self.preceded_by_ws {
                    self.result.top_level_comments.push(Spanned::new(
                        text.to_string(),
                        Span::new(start, start + len),
                    ));
                }
            }
            _ => self.preceded_by_ws = false,
        }

        // ---- inline errors + occurrence collection ----
        if kind == K::BOM {
            return;
        }
        let has_bom = text.contains(crate::bom::BOM_CHAR);
        let is_error_token = kind == K::ERROR_TOKEN;
        // The ERROR_NODE check is only consulted for tokens whose emission depends
        // on it; gate the rest out fast (most tokens are plain whitespace/idents).
        let needs = (self.collect_occurrences && matches!(kind, K::CURRENCY | K::ACCOUNT))
            || has_bom
            || is_error_token;
        if !needs {
            return;
        }
        let span = Span::new(start, start + len);
        if self.collect_occurrences && kind == K::CURRENCY && !in_error_node {
            self.result
                .currency_occurrences
                .push(Spanned::new(Currency::new(text), span));
        }
        if self.collect_occurrences && kind == K::ACCOUNT && !in_error_node {
            self.result
                .account_occurrences
                .push(Spanned::new(Account::new(text), span));
        }
        // Inline errors: a BOM byte (-> BomInDirectiveBody) or ERROR_TOKEN
        // (-> SyntaxError) in a recognized directive; skip inside ERROR_NODE.
        if (!has_bom && !is_error_token) || in_error_node {
            return;
        }
        if has_bom {
            self.result.inline_errors.push(
                crate::ParseError::new(crate::ParseErrorKind::BomInDirectiveBody, span)
                    .with_hint(crate::diagnostics::BOM_REMOVAL_HINT),
            );
        } else {
            self.result.inline_errors.push(crate::ParseError::new(
                crate::ParseErrorKind::SyntaxError("unexpected input".to_string()),
                span,
            ));
        }
    }
}

/// Length of a green child (node or token) in bytes.
fn child_len(child: NodeOrToken<&rowan::GreenNodeData, &rowan::GreenTokenData>) -> usize {
    match child {
        NodeOrToken::Node(n) => u32::from(n.text_len()) as usize,
        NodeOrToken::Token(t) => u32::from(t.text_len()) as usize,
    }
}

/// Green-tree re-implementation of `walk_top_level_once`: per-top-level-directive
/// validation (indentation, custom-value, transaction-body, error-node, and
/// org-section-marker comments). Iterates the green root's direct children
/// threading the stripped-frame byte offset — no per-child red-node allocation —
/// and dispatches the same five checks, producing a byte-identical
/// [`TopLevelWalkResult`]. `offset` is stripped-frame; spans add `bom_offset`.
pub(super) fn walk_top_level(
    root: &crate::SyntaxNode,
    stripped: &str,
    bom_offset: u32,
) -> TopLevelWalkResult {
    use crate::SyntaxKind as K;
    let mut errors = Vec::new();
    let mut section_marker_comments = Vec::new();
    let green = root.green();
    let mut offset = 0usize;
    for child in green.children() {
        let len = child_len(child);
        if let NodeOrToken::Node(n) = &child {
            let kind = crate::BeancountLanguage::kind_from_raw(n.kind());
            if super::ast::Directive::can_cast(kind) {
                tl_indented_check(n, offset, bom_offset, stripped, &mut errors);
            }
            match kind {
                K::CUSTOM_DIRECTIVE => tl_custom_check(n, offset, bom_offset, &mut errors),
                K::TRANSACTION => tl_transaction_body_check(n, offset, bom_offset, &mut errors),
                K::ERROR_NODE => {
                    tl_error_node_check(n, offset, bom_offset, stripped, &mut errors);
                    tl_section_marker_check(n, offset, bom_offset, &mut section_marker_comments);
                }
                _ => {}
            }
        }
        offset += len;
    }
    TopLevelWalkResult {
        errors,
        section_marker_comments,
    }
}

/// `indented_directive_check` on green: a directive's first non-trivia token
/// starting past its line's column 0 is a "must start at column 0" error.
fn tl_indented_check(
    node: &rowan::GreenNodeData,
    base: usize,
    bom_offset: u32,
    stripped: &str,
    out: &mut Vec<crate::ParseError>,
) {
    let mut offset = base;
    let mut content: Option<(usize, usize)> = None;
    for child in node.children() {
        let len = child_len(child);
        if let NodeOrToken::Token(t) = &child
            && !is_trivia_kind(crate::BeancountLanguage::kind_from_raw(t.kind()))
        {
            content = Some((offset, offset + len));
            break;
        }
        offset += len;
    }
    let Some((content_start, content_end)) = content else {
        return;
    };
    // Line start: last '\n' before content_start (byte scan — boundary-agnostic).
    let line_start = stripped
        .as_bytes()
        .get(..content_start)
        .and_then(|bytes| bytes.iter().rposition(|&b| b == b'\n'))
        .map_or(0, |nl| nl + 1);
    if content_start > line_start {
        let span = Span::new(
            line_start + bom_offset as usize,
            content_end + bom_offset as usize,
        );
        out.push(crate::ParseError::new(
            crate::ParseErrorKind::SyntaxError(
                "top-level directive must start at column 0".to_string(),
            ),
            span,
        ));
    }
}

/// `custom_value_check` on green: after the header (date / `custom` / type
/// string), a bare CURRENCY (not paired as `NUMBER CURRENCY`) is invalid.
fn tl_custom_check(
    node: &rowan::GreenNodeData,
    base: usize,
    bom_offset: u32,
    out: &mut Vec<crate::ParseError>,
) {
    use crate::SyntaxKind as K;
    // Non-trivia direct tokens with their stripped offsets.
    let mut toks: Vec<(crate::SyntaxKind, usize, usize)> = Vec::new();
    let mut offset = base;
    for child in node.children() {
        let len = child_len(child);
        if let NodeOrToken::Token(t) = &child {
            let kind = crate::BeancountLanguage::kind_from_raw(t.kind());
            if !is_trivia_kind(kind) {
                toks.push((kind, offset, len));
            }
        }
        offset += len;
    }
    let mut seen_type_string = false;
    for i in 0..toks.len() {
        let (kind, start, len) = toks[i];
        if !seen_type_string {
            if kind == K::STRING {
                seen_type_string = true;
            }
            continue;
        }
        if kind == K::CURRENCY && !(i > 0 && toks[i - 1].0 == K::NUMBER) {
            let span = Span::new(
                start + bom_offset as usize,
                start + len + bom_offset as usize,
            );
            out.push(crate::ParseError::new(
                crate::ParseErrorKind::SyntaxError(
                    "bare currency literal is not a valid custom directive value".to_string(),
                ),
                span,
            ));
        }
    }
}

/// `transaction_body_check` on green: a body line with catch-all tokens (outside
/// `POSTING` / `META_ENTRY` nodes) is "unexpected input".
fn tl_transaction_body_check(
    node: &rowan::GreenNodeData,
    base: usize,
    bom_offset: u32,
    out: &mut Vec<crate::ParseError>,
) {
    use crate::SyntaxKind as K;
    let mut past_header = false;
    let mut saw_header_content = false;
    let mut line_start: Option<usize> = None;
    let mut line_has_content = false;
    let mut offset = base;
    for child in node.children() {
        let len = child_len(child);
        match &child {
            NodeOrToken::Token(t) => {
                let kind = crate::BeancountLanguage::kind_from_raw(t.kind());
                let (start, end) = (offset, offset + len);
                if past_header {
                    if line_start.is_none() {
                        line_start = Some(start);
                    }
                    if kind == K::NEWLINE {
                        if line_has_content && let Some(ls) = line_start {
                            let span =
                                Span::new(ls + bom_offset as usize, end + bom_offset as usize);
                            out.push(crate::ParseError::new(
                                crate::ParseErrorKind::SyntaxError("unexpected input".to_string()),
                                span,
                            ));
                        }
                        line_start = None;
                        line_has_content = false;
                    } else if !is_trivia_kind(kind)
                        && !is_comment_kind(kind)
                        && !matches!(kind, K::TAG | K::LINK)
                    {
                        line_has_content = true;
                    }
                } else if kind == K::NEWLINE {
                    if saw_header_content {
                        past_header = true;
                    }
                } else if !is_trivia_kind(kind) {
                    saw_header_content = true;
                }
            }
            NodeOrToken::Node(_) => {
                // POSTING / META_ENTRY: not catch-all. Reset line state.
                line_start = None;
                line_has_content = false;
                past_header = true;
            }
        }
        offset += len;
    }
}

/// `error_node_check` on green: each `ERROR_NODE` line that is neither a section
/// marker nor a column-0 comment emits a classified recovery error (+ a
/// secondary BOM diagnostic when the line also contains a BOM byte).
fn tl_error_node_check(
    node: &rowan::GreenNodeData,
    base: usize,
    bom_offset: u32,
    stripped: &str,
    out: &mut Vec<crate::ParseError>,
) {
    use crate::SyntaxKind as K;
    let mut line_start: Option<usize> = None;
    let mut first_non_trivia: Option<crate::SyntaxKind> = None;
    let mut offset = base;
    for child in node.children() {
        let len = child_len(child);
        if let NodeOrToken::Token(t) = &child {
            let kind = crate::BeancountLanguage::kind_from_raw(t.kind());
            let (start, end) = (offset, offset + len);
            if line_start.is_none() {
                line_start = Some(start);
            }
            if kind == K::NEWLINE {
                let is_section = first_non_trivia == Some(K::STAR);
                let is_comment = matches!(first_non_trivia, Some(k) if is_comment_kind(k));
                if !is_section
                    && !is_comment
                    && first_non_trivia.is_some()
                    && let Some(ls) = line_start
                {
                    let span = Span::new(ls + bom_offset as usize, end + bom_offset as usize);
                    let line_text = stripped.get(ls..end).unwrap_or("");
                    let primary = classify_recovery_error(line_text, span);
                    let primary_is_bom =
                        matches!(primary.kind, crate::ParseErrorKind::BomInDirectiveBody);
                    out.push(primary);
                    if !primary_is_bom && line_text.contains(crate::bom::BOM_CHAR) {
                        out.push(
                            crate::ParseError::new(crate::ParseErrorKind::BomInDirectiveBody, span)
                                .with_hint(crate::diagnostics::BOM_REMOVAL_HINT),
                        );
                    }
                }
                line_start = None;
                first_non_trivia = None;
            } else if first_non_trivia.is_none() && !is_trivia_kind(kind) {
                first_non_trivia = Some(kind);
            }
        }
        offset += len;
    }
}

/// `section_marker_check` on green: emit an empty-string comment for each
/// `*`-starting (org-mode section) line inside an `ERROR_NODE`.
fn tl_section_marker_check(
    node: &rowan::GreenNodeData,
    base: usize,
    bom_offset: u32,
    out: &mut Vec<Spanned<String>>,
) {
    use crate::SyntaxKind as K;
    let mut line_start: Option<usize> = None;
    let mut first_non_trivia: Option<crate::SyntaxKind> = None;
    let mut offset = base;
    for child in node.children() {
        let len = child_len(child);
        if let NodeOrToken::Token(t) = &child {
            let kind = crate::BeancountLanguage::kind_from_raw(t.kind());
            let (start, end) = (offset, offset + len);
            if line_start.is_none() {
                line_start = Some(start);
            }
            if kind == K::NEWLINE {
                if first_non_trivia == Some(K::STAR)
                    && let Some(ls) = line_start
                {
                    out.push(Spanned::new(
                        String::new(),
                        Span::new(ls + bom_offset as usize, end + bom_offset as usize),
                    ));
                }
                line_start = None;
                first_non_trivia = None;
            } else if first_non_trivia.is_none() && !is_trivia_kind(kind) {
                first_non_trivia = Some(kind);
            }
        }
        offset += len;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{SyntaxKind, parse_structured};
    use rustledger_core::Directive;

    fn red_spans(root: &crate::SyntaxNode, bom: u32) -> Vec<(SyntaxKind, Span)> {
        root.children()
            .map(|n| {
                let r = n.text_range();
                let s = (u32::from(r.start()) + bom) as usize;
                let e = (u32::from(r.end()) + bom) as usize;
                (n.kind(), Span::new(s, e))
            })
            .collect()
    }

    #[test]
    fn green_node_spans_match_red() {
        let cases = [
            "",
            "2020-01-01 open Assets:Cash USD\n",
            "2020-01-01 * \"p\" \"m\"\n  Assets:Cash 5.00 USD\n  Income:X\n",
            "; leading comment\n\n2020-01-01 open A\n2020-01-02 close A\n",
            "option \"title\" \"x\"\n2020-01-01 commodity USD\n",
            "2020-01-01 price AAPL 5 USD\n2020-01-01 balance A 0 USD\n",
            "\u{feff}2020-01-01 open A\n",
            "2020-01-01 * \"é\" \"münts\"\n  A 1 EUR\n  B\n",
            "garbage !! line\n2020-01-01 open A\n",
            "2020-01-01 txn \"x\"\n  A 10 AAPL {2.00 USD}\n  B -20.00 USD\n",
        ];
        for src in cases {
            let (stripped, has_bom) = crate::bom::strip_leading(src);
            let bom = if has_bom { 3 } else { 0 };
            let root = parse_structured(stripped);
            assert_eq!(
                top_level_node_spans(&root, bom),
                red_spans(&root, bom),
                "green vs red node spans diverged for: {src:?}"
            );
        }
    }

    /// Field-level oracle: green transaction-header fields must equal the red
    /// path's. (No BOM in these cases, so absolute offset == stripped offset.)
    #[test]
    fn green_txn_header_matches_red() {
        let cases = [
            "2020-01-01 * \"payee\" \"narr\"\n  A 1 USD\n  B\n",
            "2020-01-01 ! \"only narration\"\n  A 1 USD\n  B\n",
            "2020-01-01 txn \"n\"\n  A 1 USD\n  B\n",
            "2020-01-01 # \"flagged\"\n  A 1 USD\n  B\n",
            "2020-01-01 *\n  A 1 USD\n  B\n",
            "2020-01-01 * \"p\" \"n\" #tag1 #tag2 ^link-a\n  A 1 USD\n  B\n",
            "2020-01-01 * \"esc \\\"q\\\" tab\\there\"\n  A 1 USD\n  B\n",
            "2020-01-01 * \"é payee\" \"münts\"\n  A 1 EUR\n  B\n",
        ];
        for src in cases {
            // green: find the first TRANSACTION node + its offset, convert header.
            let root = parse_structured(src);
            let green = root.green();
            let mut offset = 0usize;
            let mut txn_node = None;
            for child in green.children() {
                let len = match &child {
                    NodeOrToken::Node(n) => u32::from(n.text_len()) as usize,
                    NodeOrToken::Token(t) => u32::from(t.text_len()) as usize,
                };
                if let NodeOrToken::Node(n) = child
                    && crate::BeancountLanguage::kind_from_raw(n.kind()) == SyntaxKind::TRANSACTION
                {
                    txn_node = Some((n, offset));
                    break;
                }
                offset += len;
            }
            let (txn_green, base) = txn_node.expect("transaction node");
            let (g, g_span) = convert_transaction_header(txn_green, base).expect("green header");

            // red: full parse, pull the first transaction directive.
            let red = crate::parse(src);
            let red_sp = &red.directives[0];
            let Directive::Transaction(r) = &red_sp.value else {
                panic!("expected transaction for {src:?}");
            };
            assert_eq!(g.date, r.date, "date {src:?}");
            assert_eq!(g.flag, r.flag, "flag {src:?}");
            assert_eq!(g.payee, r.payee, "payee {src:?}");
            assert_eq!(g.narration, r.narration, "narration {src:?}");
            assert_eq!(g.tags, r.tags, "tags {src:?}");
            assert_eq!(g.links, r.links, "links {src:?}");
            assert_eq!(g_span, red_sp.span, "span {src:?}");
        }
    }

    /// Field oracle: green simple-posting conversion must equal the red path's,
    /// for simple postings (account + non-arithmetic units + trailing comment +
    /// elided units). No BOM in these cases.
    #[test]
    fn green_simple_posting_matches_red() {
        let cases = [
            "2020-01-01 * \"p\"\n  Assets:Cash 5.00 USD\n  Income:X\n",
            "2020-01-01 * \"p\"\n  Assets:A -10 EUR\n  Assets:B 10 EUR\n",
            "2020-01-01 * \"p\"\n  A 5 USD  ; note here\n  B\n",
            "2020-01-01 * \"p\"\n  A 1234.5678 USD\n  B 0 USD\n",
            // cost specs
            "2020-01-01 * \"p\"\n  Assets:Stock 10 AAPL {2.00 USD}\n  Assets:Cash -20.00 USD\n",
            "2020-01-01 * \"p\"\n  Assets:Stock 10 AAPL {{20.00 USD}}\n  Assets:Cash -20.00 USD\n",
            "2020-01-01 * \"p\"\n  A 10 AAPL {2.00 USD, 2021-06-01}\n  B -20.00 USD\n",
            "2020-01-01 * \"p\"\n  A 10 AAPL {2.00 USD, \"lot-1\"}\n  B -20.00 USD\n",
            "2020-01-01 * \"p\"\n  A -5 AAPL {1.50 # 8.00 USD}\n  B 8.00 USD\n  Income:G\n",
            // prices (@ unit, @@ total) + cost+price together
            "2020-01-01 * \"p\"\n  A 10 AAPL @ 3.00 USD\n  B -30.00 USD\n",
            "2020-01-01 * \"p\"\n  A 10 AAPL @@ 25.00 USD\n  B -25.00 USD\n",
            "2020-01-01 * \"p\"\n  A -5 AAPL {2.00 USD} @ 3.00 USD\n  B 15.00 USD\n  Income:G\n",
        ];
        for src in cases {
            let red = crate::parse(src);
            let Directive::Transaction(rtxn) = &red.directives[0].value else {
                panic!("txn {src:?}");
            };
            let root = parse_structured(src);
            let green = root.green();
            // locate the TRANSACTION node + base
            let mut off = 0usize;
            let mut txn = None;
            for child in green.children() {
                let len = match &child {
                    NodeOrToken::Node(n) => u32::from(n.text_len()) as usize,
                    NodeOrToken::Token(t) => u32::from(t.text_len()) as usize,
                };
                if let NodeOrToken::Node(n) = child
                    && crate::BeancountLanguage::kind_from_raw(n.kind()) == SyntaxKind::TRANSACTION
                {
                    txn = Some((n, off));
                    break;
                }
                off += len;
            }
            let (txn_node, txn_base) = txn.expect("txn node");
            // walk its POSTING children, comparing each to red.
            let mut poff = txn_base;
            let mut gi = 0usize;
            for child in txn_node.children() {
                let len = match &child {
                    NodeOrToken::Node(n) => u32::from(n.text_len()) as usize,
                    NodeOrToken::Token(t) => u32::from(t.text_len()) as usize,
                };
                if let NodeOrToken::Node(n) = child
                    && crate::BeancountLanguage::kind_from_raw(n.kind()) == SyntaxKind::POSTING
                {
                    let gp = convert_simple_posting(n, poff).expect("simple posting");
                    let rp = &rtxn.postings[gi];
                    assert_eq!(gp.value, rp.value, "posting {gi} value {src:?}");
                    assert_eq!(gp.span, rp.span, "posting {gi} span {src:?}");
                    gi += 1;
                }
                poff += len;
            }
            assert_eq!(gi, rtxn.postings.len(), "posting count {src:?}");
        }
    }

    /// End-to-end differential: the green-wired `parse` must equal the pure-red
    /// `parse_red_only` on every input — exercising the green path (simple txns)
    /// AND every red-fallback trigger (flag / metadata / comment / arithmetic /
    /// multi-amount / pipe / invalid date), plus non-transaction directives,
    /// BOM, multi-byte, and error recovery. (The fuzz target generalizes this.)
    #[test]
    fn parse_green_eq_red_corpus() {
        let corpus = [
            "",
            "2020-01-01 * \"p\" \"n\"\n  A 1 USD\n  B\n",
            "2020-01-01 ! \"x\" #t ^l\n  A 10 AAPL {2 USD} @ 3 USD\n  B -20 USD\n  Income:G\n",
            "2020-01-01 * \"p\"\n  ! A 1 USD\n  B\n", // posting flag -> red fallback
            "2020-01-01 * \"p\"\n  A 1 USD\n    note: \"m\"\n  B\n", // posting meta -> fallback
            "2020-01-01 * \"p\"\n  meta: \"x\"\n  A 1 USD\n  B\n", // txn meta -> fallback
            "2020-01-01 * \"p\"\n  ; a comment\n  A 1 USD\n  B\n", // body comment -> fallback
            "2020-01-01 * \"p\"\n  A 5 USD + 3 USD\n  B\n", // arithmetic -> fallback
            "2020-01-01 * \"p\"\n  A 5 USD 3 USD\n  B\n", // multi-amount -> fallback
            "2020-01-01 * \"p\" | \"n\"\n  A 1 USD\n  B\n", // deprecated pipe -> fallback
            "2020-13-99 * \"bad date\"\n  A 1 USD\n  B\n", // invalid date -> fallback
            // Regression (fuzz_green_eq_red crash-a45e3089): an invalid FIRST date
            // followed by a valid-looking later date token. Green must latch the
            // first date (-> None -> bail to red, which drops the directive), NOT
            // scan ahead to the second date and keep a directive red discards.
            "2020-99-99 * \"x\" 2021-01-01\n  A 1 USD\n  B\n",
            "3333/33/3 X\n", // the minimized fuzz shape (slash date, month 33)
            // Regression (fuzz_green_eq_red cost-merge): a malformed cost `{,{*`
            // — opener, a non-`*` token (red's is_merge decides not-merge and
            // stops), then a SECOND opener + `*`. Green must mirror red and not
            // re-arm on the later `{`, which used to flip `merge` to true.
            "2020-01-01 *\n Aa:B 1 USD{,{*",
            // Regression (fuzz_green_eq_red cost-number): `{N # <X> T}` where the
            // first post-`#` token is a NUMBER that does NOT parse (here
            // `\u{06f6}`, an Arabic-Indic digit the lexer tokenizes as NUMBER but
            // rust_decimal rejects). Green must latch that FIRST post-hash NUMBER
            // (-> None -> PerUnit{N}, mirroring red's `cost_total_after_hash`),
            // NOT scan on to the later parseable `0` and emit `Total{0}`.
            "7046/7/1D\n\tA:F{7#\u{06f6}>0",
            "\u{feff}2020-01-01 * \"p\"\n  A 1 USD\n  B\n", // BOM
            "2020-01-01 * \"é\" \"münts\"\n  Aaa 1 EUR\n  B\n", // multi-byte
            "garbage\n2020-01-01 open A\n2020-01-01 * \"p\"\n  A 1 USD\n  B\n", // error recovery
            "2020-01-01 open A\n2020-01-02 close A\noption \"x\" \"y\"\n", // non-txn
            // posting flags (now green, were red fallback)
            "2020-01-01 * \"p\"\n  ! Assets:A 1 USD\n  * Assets:B -1 USD\n",
            "2020-01-01 * \"p\"\n  A Assets:Letter 1 USD\n  Assets:B -1 USD\n",
            "2020-01-01 * \"p\"\n  # Assets:A 1 USD\n  Assets:B -1 USD\n",
            // per-posting metadata — every MetaValue type
            "2020-01-01 * \"p\"\n  Assets:A 1 USD\n    str: \"hello\"\n    int: 42\n    neg: -7\n    dec: 3.14\n    amt: 5.00 USD\n    dt: 2021-06-01\n    acct: Assets:Other\n    cur: EUR\n    yes: TRUE\n    no: FALSE\n    tg: #atag\n    lk: ^alink\n    empty:\n  Assets:B -1 USD\n",
            // transaction-level metadata (now green, was red fallback)
            "2020-01-01 * \"p\"\n  meta1: \"x\"\n  count: 3\n  Assets:A 1 USD\n  Assets:B -1 USD\n",
            // flag + cost + price + posting-meta together
            "2020-01-01 * \"p\"\n  ! Assets:S 10 AAPL {2 USD} @ 3 USD\n    lot: \"q1\"\n  Assets:C 15 USD\n  Income:G\n",
            // walk_descendants distinctive paths:
            "; column-0 comment\n  ; indented comment\n2020-01-01 open Assets:A USD\n",
            "2020-01-01 * \"p\"\n  Assets:Cash 5 USD\n  Income:Salary -5 EUR\n", // occurrences
            "!!garbage Assets:InError 5 BAD!!\n2020-01-01 open Assets:Real USD\n", // error-node suppresses occ
            "* Org Section Heading\n** Sub\n2020-01-01 open A\n", // org-mode section markers
            "2020-01-01 open A\n2020-01-01 open B\n2020-01-01 open C\n", // many account occurrences
            // walk_top_level distinctive checks:
            "  2020-01-01 open Assets:A USD\n", // indented directive -> col-0 error
            "\t2020-01-01 close Assets:A\n",    // tab-indented directive
            "2020-01-01 custom \"budget\" USD\n", // bare currency in custom -> error
            "2020-01-01 custom \"b\" 10 USD \"ok\" NZD\n", // amount ok, trailing bare cur -> error
            "2020-01-01 * \"p\"\n  unexpected junk here\n  A 1 USD\n  B\n", // txn body catch-all
            "2020-01-01 * \"p\" #tag1\n  A 1 USD\n  #bodytag\n  B\n", // body tag/link is valid (no error)
            "@@@ totally invalid line @@@\n2020-01-01 open A\n", // error-node classified recovery error
            "* Section\n**  Indented Sub\n; c0 comment\n2020-01-01 open A\n", // section markers + comment
        ];
        for src in corpus {
            let g = crate::parse(src);
            let r = crate::cst::parse_red_only(src);
            let dbg = |p: &crate::ParseResult| {
                (
                    format!("{:?}", p.directives),
                    format!("{:?}", p.errors),
                    format!("{:?}", p.comments),
                    format!("{:?}", p.options),
                    // The green walk_descendants produces these too.
                    format!("{:?}", p.account_occurrences),
                    format!("{:?}", p.currency_occurrences),
                )
            };
            assert_eq!(
                dbg(&g),
                dbg(&r),
                "green-wired parse diverged from red for: {src:?}"
            );
        }
    }
}