rustledger-parser 0.16.2

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
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
//! Source-driven tests for `parse_structured` (phase 2.1-2.4).
//!
//! Each test feeds real Beancount source through the structured
//! parser and asserts the resulting tree shape against the
//! Directive-Terminator Rule (see `cst::trivia`).
//!
//! These complement (do NOT replace) the hand-constructed-tree
//! tests in `cst::trivia::tests` — those pin the policy as
//! invariants on tree shape, these pin that
//! `parse_structured(source)` actually PRODUCES trees matching
//! those invariants on real source.

// Each test references many `SyntaxKind` variants for its expected
// children sequence; a per-test glob import is the cleanest local
// shape. Clippy's enum_glob_use lint is the wrong call here.
#![allow(clippy::enum_glob_use)]

use rustledger_parser::{SyntaxKind, SyntaxNode, parse_structured};

/// Per-child kind sequence for a node. Distinguishes tokens from
/// nested nodes so a test can assert both leaf trivia and structural
/// wrapping at the same node level.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Element {
    Tok(SyntaxKind),
    Node(SyntaxKind),
}

fn elements_of(node: &SyntaxNode) -> Vec<Element> {
    node.children_with_tokens()
        .map(|el| match el {
            rowan::NodeOrToken::Token(t) => Element::Tok(t.kind()),
            rowan::NodeOrToken::Node(n) => Element::Node(n.kind()),
        })
        .collect()
}

fn tok_seq(kinds: &[SyntaxKind]) -> Vec<Element> {
    kinds.iter().copied().map(Element::Tok).collect()
}

/// Find direct-children directive nodes of any specific
/// `*_DIRECTIVE` kind under `root`.
fn directives(root: &SyntaxNode) -> Vec<SyntaxNode> {
    root.children()
        .filter(|c| {
            matches!(
                c.kind(),
                SyntaxKind::OPEN_DIRECTIVE
                    | SyntaxKind::CLOSE_DIRECTIVE
                    | SyntaxKind::BALANCE_DIRECTIVE
                    | SyntaxKind::PAD_DIRECTIVE
                    | SyntaxKind::EVENT_DIRECTIVE
                    | SyntaxKind::QUERY_DIRECTIVE
                    | SyntaxKind::NOTE_DIRECTIVE
                    | SyntaxKind::DOCUMENT_DIRECTIVE
                    | SyntaxKind::PRICE_DIRECTIVE
                    | SyntaxKind::COMMODITY_DIRECTIVE
                    | SyntaxKind::PUSHTAG_DIRECTIVE
                    | SyntaxKind::POPTAG_DIRECTIVE
                    | SyntaxKind::PUSHMETA_DIRECTIVE
                    | SyntaxKind::POPMETA_DIRECTIVE
                    | SyntaxKind::OPTION_DIRECTIVE
                    | SyntaxKind::INCLUDE_DIRECTIVE
                    | SyntaxKind::PLUGIN_DIRECTIVE
                    | SyntaxKind::CUSTOM_DIRECTIVE
                    | SyntaxKind::TRANSACTION
            )
        })
        .collect()
}

/// Round-trip property: the tree's text must equal the source for
/// every input. Asserted at the top of every test.
fn assert_round_trip(source: &str, tree: &SyntaxNode) {
    assert_eq!(
        tree.text().to_string(),
        source,
        "structured parser must round-trip byte-identically",
    );
}

// ---------- 10 dated directives ----------

#[test]
fn open_directive_with_currency() {
    use SyntaxKind::*;
    let source = "2024-01-01 open Assets:Cash USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), OPEN_DIRECTIVE);
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[
            DATE, WHITESPACE, OPEN_KW, WHITESPACE, ACCOUNT, WHITESPACE, CURRENCY, NEWLINE
        ]),
    );
}

#[test]
fn close_directive() {
    use SyntaxKind::*;
    let source = "2024-12-31 close Assets:Cash\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), CLOSE_DIRECTIVE);
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[DATE, WHITESPACE, CLOSE_KW, WHITESPACE, ACCOUNT, NEWLINE]),
    );
}

#[test]
fn balance_directive() {
    use SyntaxKind::*;
    let source = "2024-06-30 balance Assets:Cash 100.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), BALANCE_DIRECTIVE);
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[
            DATE, WHITESPACE, BALANCE_KW, WHITESPACE, ACCOUNT, WHITESPACE, NUMBER, WHITESPACE,
            CURRENCY, NEWLINE,
        ]),
    );
}

#[test]
fn pad_directive() {
    use SyntaxKind::*;
    let source = "2024-01-01 pad Assets:Cash Equity:Opening-Balances\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), PAD_DIRECTIVE);
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[
            DATE, WHITESPACE, PAD_KW, WHITESPACE, ACCOUNT, WHITESPACE, ACCOUNT, NEWLINE,
        ]),
    );
}

#[test]
fn event_directive() {
    use SyntaxKind::*;
    let source = "2024-01-15 event \"location\" \"Berlin\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), EVENT_DIRECTIVE);
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[
            DATE, WHITESPACE, EVENT_KW, WHITESPACE, STRING, WHITESPACE, STRING, NEWLINE,
        ]),
    );
}

#[test]
fn query_directive() {
    use SyntaxKind::*;
    let source = "2024-01-01 query \"income\" \"SELECT *\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), QUERY_DIRECTIVE);
}

#[test]
fn note_directive() {
    use SyntaxKind::*;
    let source = "2024-01-15 note Assets:Cash \"deposit\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), NOTE_DIRECTIVE);
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[
            DATE, WHITESPACE, NOTE_KW, WHITESPACE, ACCOUNT, WHITESPACE, STRING, NEWLINE,
        ]),
    );
}

#[test]
fn document_directive() {
    use SyntaxKind::*;
    let source = "2024-01-15 document Assets:Cash \"/path/to/file.pdf\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), DOCUMENT_DIRECTIVE);
}

#[test]
fn price_directive() {
    use SyntaxKind::*;
    let source = "2024-01-15 price USD 1.10 EUR\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), PRICE_DIRECTIVE);
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[
            DATE, WHITESPACE, PRICE_KW, WHITESPACE, CURRENCY, WHITESPACE, NUMBER, WHITESPACE,
            CURRENCY, NEWLINE,
        ]),
    );
}

#[test]
fn commodity_directive() {
    use SyntaxKind::*;
    let source = "2024-01-01 commodity USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), COMMODITY_DIRECTIVE);
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[
            DATE,
            WHITESPACE,
            COMMODITY_KW,
            WHITESPACE,
            CURRENCY,
            NEWLINE
        ]),
    );
}

// ---------- 4 standalone-keyword directives ----------

#[test]
fn pushtag_directive() {
    use SyntaxKind::*;
    let source = "pushtag #project-x\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), PUSHTAG_DIRECTIVE);
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[PUSHTAG_KW, WHITESPACE, TAG, NEWLINE]),
    );
}

#[test]
fn poptag_directive() {
    use SyntaxKind::*;
    let source = "poptag #project-x\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), POPTAG_DIRECTIVE);
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[POPTAG_KW, WHITESPACE, TAG, NEWLINE]),
    );
}

#[test]
fn pushmeta_directive() {
    use SyntaxKind::*;
    let source = "pushmeta key: \"value\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), PUSHMETA_DIRECTIVE);
}

#[test]
fn popmeta_directive() {
    use SyntaxKind::*;
    let source = "popmeta key:\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), POPMETA_DIRECTIVE);
}

// ---------- Trivia attachment tests (Directive-Terminator Rule) ----------

#[test]
fn rule_1_same_line_trailing_comment_inside_directive() {
    use SyntaxKind::*;
    let source = "2024-01-01 open Assets:Cash  ; main checking\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), OPEN_DIRECTIVE);
    // Rule 1: WS + COMMENT + terminator NEWLINE all INSIDE the directive.
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[
            DATE, WHITESPACE, OPEN_KW, WHITESPACE, ACCOUNT, WHITESPACE, COMMENT, NEWLINE,
        ]),
    );
}

#[test]
fn rule_2_blank_line_leads_following_directive() {
    use SyntaxKind::*;
    let source = "2024-01-01 open Assets:Cash\n\
                  \n\
                  2024-01-02 open Assets:Bank\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 2);
    // Rule 1: d1 owns its own terminator NEWLINE.
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[DATE, WHITESPACE, OPEN_KW, WHITESPACE, ACCOUNT, NEWLINE]),
    );
    // Rule 2: the blank-line NEWLINE leads d2.
    assert_eq!(
        elements_of(&ds[1]),
        tok_seq(&[
            NEWLINE, DATE, WHITESPACE, OPEN_KW, WHITESPACE, ACCOUNT, NEWLINE
        ]),
    );
}

#[test]
fn rule_3_copyright_header_under_source_file() {
    use SyntaxKind::*;
    let source = ";; Copyright 2024\n\
                  2024-01-01 open Assets:Cash\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    // Rule 3: header trivia is direct under SOURCE_FILE, NOT inside d1.
    assert_eq!(
        elements_of(&tree),
        vec![
            Element::Tok(COMMENT),
            Element::Tok(NEWLINE),
            Element::Node(OPEN_DIRECTIVE),
        ],
    );
}

#[test]
fn rule_4_trailing_comment_block_under_source_file() {
    use SyntaxKind::*;
    let source = "2024-01-01 open Assets:Cash\n\
                  ;; closing remarks\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    // Rule 4: trailing comment block is direct under SOURCE_FILE,
    // NOT inside the file-final directive.
    assert_eq!(
        elements_of(&tree),
        vec![
            Element::Node(OPEN_DIRECTIVE),
            Element::Tok(COMMENT),
            Element::Tok(NEWLINE),
        ],
    );
}

#[test]
fn rule_5_unterminated_final_directive() {
    use SyntaxKind::*;
    let source = "2024-01-01 open Assets:Cash";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    // Rule 5: no terminator. Directive ends at last content token.
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[DATE, WHITESPACE, OPEN_KW, WHITESPACE, ACCOUNT]),
    );
}

#[test]
fn rule_5_unterminated_with_same_line_trailing_trivia() {
    use SyntaxKind::*;
    let source = "2024-01-01 open Assets:Cash  ; eol-no-nl";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    // Rules 1+5: same-line trailing trivia stays INSIDE the
    // directive even without a terminator NEWLINE.
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[
            DATE, WHITESPACE, OPEN_KW, WHITESPACE, ACCOUNT, WHITESPACE, COMMENT,
        ]),
    );
}

#[test]
fn mixed_directive_kinds_each_get_their_own_node() {
    use SyntaxKind::*;
    let source = "2024-01-01 open Assets:Cash USD\n\
                  pushtag #x\n\
                  2024-01-02 close Assets:Cash\n\
                  poptag #x\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 4);
    assert_eq!(ds[0].kind(), OPEN_DIRECTIVE);
    assert_eq!(ds[1].kind(), PUSHTAG_DIRECTIVE);
    assert_eq!(ds[2].kind(), CLOSE_DIRECTIVE);
    assert_eq!(ds[3].kind(), POPTAG_DIRECTIVE);
}

// ---------- Phase 2.1b: TRANSACTION header recognition ----------

#[test]
fn transaction_with_star_flag_header_only() {
    use SyntaxKind::*;
    // `*` indicates a completed transaction. Header-only (no
    // postings yet — that's the simplest TRANSACTION shape).
    let source = "2024-01-15 * \"Coffee\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), TRANSACTION);
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[DATE, WHITESPACE, STAR, WHITESPACE, STRING, NEWLINE]),
    );
}

#[test]
fn transaction_with_pending_kw_flag() {
    use SyntaxKind::*;
    // `!` lexes as PENDING_KW (`Token::Pending` →
    // `SyntaxKind::PENDING_KW`), NOT as `FLAG`. It signals an
    // incomplete/warning transaction in Beancount syntax.
    let source = "2024-01-15 ! \"WIP\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), TRANSACTION);
    // Pin the exact token sequence so a regression that
    // mistokenizes `!` or fails to wrap the full header fires.
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[DATE, WHITESPACE, PENDING_KW, WHITESPACE, STRING, NEWLINE]),
    );
}

#[test]
fn transaction_with_txn_keyword() {
    use SyntaxKind::*;
    // Explicit `txn` keyword form.
    let source = "2024-01-15 txn \"explicit\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), TRANSACTION);
}

#[test]
fn transaction_with_postings_wraps_full_multi_line_body() {
    use SyntaxKind::*;
    // Per cst::trivia's multi-line clause, TRANSACTION owns its
    // header AND every indented sub-line until non-indented
    // content (or EOF). Postings here are flat tokens inside
    // TRANSACTION; PR 2.2 will introduce POSTING / AMOUNT / etc.
    // sub-nodes.
    let source = "2024-01-15 * \"Coffee\"\n\
                  \x20\x20Assets:Cash  -5.00 USD\n\
                  \x20\x20Expenses:Food  5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), TRANSACTION);
    // SOURCE_FILE owns ONLY the TRANSACTION node — no orphaned
    // posting tokens.
    assert_eq!(elements_of(&tree), vec![Element::Node(TRANSACTION)]);
}

#[test]
fn transaction_with_metadata_and_postings() {
    use SyntaxKind::*;
    // Transactions can carry intra-transaction metadata AND
    // postings. All sub-lines inside TRANSACTION.
    let source = "2024-01-15 * \"Coffee\"\n\
                  \x20\x20note: \"morning\"\n\
                  \x20\x20Assets:Cash  -5.00 USD\n\
                  \x20\x20Expenses:Food  5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(elements_of(&tree), vec![Element::Node(TRANSACTION)]);
}

#[test]
fn transaction_with_payee_and_narration() {
    use SyntaxKind::*;
    // Full transaction header with payee + narration + tag + link.
    let source = "2024-01-15 * \"Coffee Shop\" \"Morning coffee\" #daily ^trip1\n\
                  \x20\x20Assets:Cash  -5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), TRANSACTION);
}

#[test]
fn transaction_terminates_at_next_top_level_directive() {
    use SyntaxKind::*;
    // After a transaction's postings, a non-indented DATE starts
    // a NEW directive. TRANSACTION must close cleanly; the next
    // OPEN_DIRECTIVE must not be absorbed.
    let source = "2024-01-15 * \"Coffee\"\n\
                  \x20\x20Assets:Cash  -5.00 USD\n\
                  2024-01-16 open Assets:Bank\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 2);
    assert_eq!(ds[0].kind(), TRANSACTION);
    assert_eq!(ds[1].kind(), OPEN_DIRECTIVE);
}

#[test]
fn transaction_terminates_at_blank_line_before_next_directive() {
    use SyntaxKind::*;
    // A blank line after a transaction's last posting ends it.
    // The blank-line NEWLINE becomes inter-directive trivia
    // leading the next directive (rule 2).
    let source = "2024-01-15 * \"Coffee\"\n\
                  \x20\x20Assets:Cash  -5.00 USD\n\
                  \n\
                  2024-01-16 open Assets:Bank\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 2);
    assert_eq!(ds[0].kind(), TRANSACTION);
    assert_eq!(ds[1].kind(), OPEN_DIRECTIVE);
    // The blank-line NEWLINE leads OPEN per rule 2.
    let d2_first = elements_of(&ds[1]).first().copied();
    assert_eq!(d2_first, Some(Element::Tok(NEWLINE)));
}

#[test]
fn transaction_with_indented_comment_between_postings() {
    use SyntaxKind::*;
    // Comments interleaved with postings stay inside TRANSACTION.
    let source = "2024-01-15 * \"Coffee\"\n\
                  \x20\x20Assets:Cash  -5.00 USD\n\
                  \x20\x20; documentation comment\n\
                  \x20\x20Expenses:Food  5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(elements_of(&tree), vec![Element::Node(TRANSACTION)]);
}

#[test]
fn transaction_with_implied_flag_via_bare_string() {
    use SyntaxKind::*;
    // Beancount accepts the implied-transaction shorthand:
    // `DATE WS STRING ...` with no explicit flag. The legacy
    // AST parser at parser.rs:1713 dispatches `Token::String(_)`
    // to parse_transaction_directive with an implied `*`. Common
    // in real ledgers as a convenient shorthand.
    let source = "2024-01-15 \"Coffee\"\n\
                  \x20\x20Assets:Cash 100 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), TRANSACTION);
    // SOURCE_FILE owns only the TRANSACTION — no orphaned posting.
    assert_eq!(elements_of(&tree), vec![Element::Node(TRANSACTION)]);
}

#[test]
fn transaction_with_hash_flag() {
    use SyntaxKind::*;
    // `#` is promoted to a transaction flag when it appears in
    // the post-DATE flag slot. The lexer's `Token::is_txn_flag`
    // includes Hash and the AST parser's `parse_flag` accepts it;
    // the CST mirrors that contract.
    let source = "2024-01-15 # \"pending hash\"\n\
                  \x20\x20Assets:Cash 100 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), TRANSACTION);
    // SOURCE_FILE owns only the TRANSACTION — no orphaned posting.
    assert_eq!(elements_of(&tree), vec![Element::Node(TRANSACTION)]);
}

#[test]
fn transaction_with_single_char_currency_as_flag() {
    use SyntaxKind::*;
    // NYSE/NASDAQ-style single-letter tickers (T, V, F, X, ...)
    // tokenize as CURRENCY (priority 3 over FLAG in the lexer)
    // but are accepted as transaction flags. The AST parser's
    // `parse_flag` arm `Token::Currency(s) if s.len() == 1` does
    // this; the CST mirrors it.
    let source = "2024-01-15 T \"AT&T dividend\"\n\
                  \x20\x20Assets:Brokerage 10 T\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), TRANSACTION);
    assert_eq!(elements_of(&tree), vec![Element::Node(TRANSACTION)]);
}

#[test]
fn transaction_multi_char_currency_after_date_is_not_a_flag() {
    // Guard against the reverse: `USD` (a real currency, length 3)
    // must NOT be treated as a transaction flag. The CURRENCY arm
    // gates on length == 1.
    let source = "2024-01-15 USD \"garbled\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    // No directive recognized — falls into the passthrough branch.
    let ds = directives(&tree);
    assert!(
        ds.is_empty(),
        "multi-char CURRENCY after DATE must not be a transaction flag",
    );
}

#[test]
fn transaction_blank_line_inside_body_terminates_and_orphans_subsequent_postings() {
    use SyntaxKind::*;
    // Pins the documented blank-line termination behavior (matches
    // Python beancount). The second posting after the blank line
    // ends up flat under SOURCE_FILE, not inside the TRANSACTION.
    // PR 2.2b's POSTING-wrapping work must NOT accidentally widen
    // the body scope across blank lines; this test guards that.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash 100 USD\n\
                  \n\
                  \x20\x20Liab:Card -100 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    // Exactly ONE recognized directive (the transaction). The
    // post-blank posting is flat passthrough, not a second
    // structural node.
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), TRANSACTION);

    // The TRANSACTION header tokens (DATE, STAR) are direct flat
    // children. The first posting line is wrapped in a POSTING
    // node; the second posting (post-blank) is NOT.
    let header_kinds: Vec<SyntaxKind> = elements_of(&ds[0])
        .iter()
        .filter_map(|e| match e {
            Element::Tok(k) => Some(*k),
            Element::Node(_) => None,
        })
        .collect();
    assert!(
        header_kinds.contains(&DATE) && header_kinds.contains(&STAR),
        "tx contains header",
    );
    // Exactly one POSTING is wrapped inside the TRANSACTION; the
    // post-blank posting is orphaned under SOURCE_FILE.
    let postings_inside_tx = ds[0].children().filter(|n| n.kind() == POSTING).count();
    assert_eq!(
        postings_inside_tx, 1,
        "only the FIRST posting is wrapped inside the tx; the second is orphaned",
    );
    // ACCOUNT count across the whole tree: 2 (one in the wrapped
    // POSTING, one orphaned flat under SOURCE_FILE).
    let total_accounts = tree
        .descendants_with_tokens()
        .filter(|e| e.kind() == ACCOUNT)
        .count();
    assert_eq!(total_accounts, 2);
}

#[test]
fn transaction_trailing_indented_comment_at_eof_stays_inside() {
    use SyntaxKind::*;
    // TRANSACTION deliberately diverges from rule 4 (which puts
    // indented trailing comments under SOURCE_FILE for the 14
    // single-line directive kinds). The transaction body
    // predicate accepts any indented non-blank line, so a
    // trailing indented comment after the last posting stays
    // inside the TRANSACTION. Compare with
    // `indented_comment_at_eof_after_no_metadata_directive_is_file_trailing`
    // earlier in this file for the OPEN_DIRECTIVE policy.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash 100 USD\n\
                  \x20\x20Liab:Card -100 USD\n\
                  \x20\x20; closing note for this transaction\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), TRANSACTION);
    // SOURCE_FILE owns ONLY the TRANSACTION — comment is inside.
    assert_eq!(elements_of(&tree), vec![Element::Node(TRANSACTION)]);
}

#[test]
fn transaction_unterminated_at_eof_with_postings() {
    use SyntaxKind::*;
    // No final NEWLINE on the last posting line. Per rule 5,
    // TRANSACTION wraps content up to EOF without fabricating
    // a terminator.
    let source = "2024-01-15 * \"Coffee\"\n\
                  \x20\x20Assets:Cash  -5.00 USD";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), TRANSACTION);
}

// ---------- Pass-through for still-unrecognized content ----------

// ---------- Phase 2.2a: META_ENTRY structural wrapping ----------

/// Walk all `META_ENTRY` descendants of a node, in source order.
fn meta_entries(node: &SyntaxNode) -> Vec<SyntaxNode> {
    node.descendants()
        .filter(|n| n.kind() == SyntaxKind::META_ENTRY)
        .collect()
}

#[test]
fn meta_entry_wraps_metadata_sub_line_inside_open_directive() {
    use SyntaxKind::*;
    let source = "2024-01-01 open Assets:Cash\n  description: \"main checking\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let mes = meta_entries(&tree);
    assert_eq!(mes.len(), 1);
    assert_eq!(
        elements_of(&mes[0]),
        tok_seq(&[WHITESPACE, META_KEY, WHITESPACE, STRING, NEWLINE]),
    );
}

#[test]
fn meta_entry_wraps_each_of_multiple_metadata_sub_lines() {
    use SyntaxKind::*;
    let source = "2024-01-01 open Assets:Cash\n\
                  \x20\x20key1: \"value1\"\n\
                  \x20\x20key2: \"value2\"\n\
                  \x20\x20key3: \"value3\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let mes = meta_entries(&tree);
    assert_eq!(mes.len(), 3);
    for me in &mes {
        assert_eq!(
            elements_of(me),
            tok_seq(&[WHITESPACE, META_KEY, WHITESPACE, STRING, NEWLINE]),
        );
    }
}

#[test]
fn meta_entry_does_not_wrap_indented_comments() {
    use SyntaxKind::*;
    // An indented `;`-comment between metadata entries stays as
    // flat children of the parent directive — NOT inside a
    // META_ENTRY. META_ENTRY is reserved for metadata sub-lines
    // proper (the `WS META_KEY ... NEWLINE` shape).
    let source = "2024-01-01 open Assets:Cash\n\
                  \x20\x20k1: \"v1\"\n\
                  \x20\x20; doc comment\n\
                  \x20\x20k2: \"v2\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let mes = meta_entries(&tree);
    assert_eq!(mes.len(), 2, "only k1 and k2 are META_ENTRYs");

    // The indented comment line lives as flat tokens (WS, COMMENT,
    // NEWLINE) inside the OPEN_DIRECTIVE between the two
    // META_ENTRY nodes.
    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    let kids: Vec<Element> = elements_of(&ds[0]);
    let comment_pos = kids
        .iter()
        .position(|e| matches!(e, Element::Tok(COMMENT)))
        .expect("indented COMMENT lives flat in the directive");
    let n_me_before_comment = kids[..comment_pos]
        .iter()
        .filter(|e| matches!(e, Element::Node(META_ENTRY)))
        .count();
    let n_me_after_comment = kids[comment_pos..]
        .iter()
        .filter(|e| matches!(e, Element::Node(META_ENTRY)))
        .count();
    assert_eq!(n_me_before_comment, 1, "k1 META_ENTRY precedes the comment");
    assert_eq!(n_me_after_comment, 1, "k2 META_ENTRY follows the comment");
}

#[test]
fn meta_entry_inside_transaction_body() {
    use SyntaxKind::*;
    // Transactions can carry intra-transaction metadata. The
    // META_ENTRY wrapping applies there too.
    let source = "2024-01-15 * \"Coffee\"\n\
                  \x20\x20note: \"morning\"\n\
                  \x20\x20Assets:Cash -5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let mes = meta_entries(&tree);
    assert_eq!(mes.len(), 1);
    assert_eq!(
        elements_of(&mes[0]),
        tok_seq(&[WHITESPACE, META_KEY, WHITESPACE, STRING, NEWLINE]),
    );

    // The `note:` line is at the same indent as the posting (2
    // spaces) and appears BEFORE the posting, so it's
    // TRANSACTION-level metadata: META_ENTRY is a direct child of
    // TRANSACTION. The posting line is now wrapped in POSTING
    // (PR 2.2b).
    let txs: Vec<SyntaxNode> = tree
        .children()
        .filter(|c| c.kind() == TRANSACTION)
        .collect();
    assert_eq!(txs.len(), 1);
    let n_meta_entries_in_tx = txs[0].children().filter(|n| n.kind() == META_ENTRY).count();
    assert_eq!(n_meta_entries_in_tx, 1);
    let n_postings_in_tx = txs[0].children().filter(|n| n.kind() == POSTING).count();
    assert_eq!(n_postings_in_tx, 1);
}

#[test]
fn meta_entry_at_eof_without_trailing_newline() {
    use SyntaxKind::*;
    // Per rule 5 of `cst::trivia` (unterminated final directive),
    // a metadata sub-line that ends mid-content without a final
    // NEWLINE still gets wrapped in META_ENTRY — the META_ENTRY
    // simply has no NEWLINE child. Pins the rustdoc claim.
    let source = "2024-01-01 open Assets:Cash\n  key: \"v\"";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let mes = meta_entries(&tree);
    assert_eq!(mes.len(), 1);
    // The META_ENTRY contains WS + META_KEY + WS + STRING and NO
    // NEWLINE (last token reached EOF).
    assert_eq!(
        elements_of(&mes[0]),
        tok_seq(&[WHITESPACE, META_KEY, WHITESPACE, STRING]),
    );
}

#[test]
fn meta_entry_with_value_kinds_other_than_string() {
    use SyntaxKind::*;
    // Metadata values can be a NUMBER, ACCOUNT, CURRENCY, DATE,
    // boolean, etc. META_ENTRY wraps the whole sub-line regardless
    // of the value kind — phase 3's typed AST will surface
    // `value()` accessors that decode by inspecting children.
    let source = "2024-01-01 open Assets:Cash\n\
                  \x20\x20count: 42\n\
                  \x20\x20since: 2024-01-01\n\
                  \x20\x20mirror: Assets:Mirror\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let mes = meta_entries(&tree);
    assert_eq!(mes.len(), 3);
    // Spot-check the second (DATE-valued) entry's value-token kind.
    let date_me_kinds = elements_of(&mes[1]);
    assert!(date_me_kinds.contains(&Element::Tok(DATE)));
}

// ---------- Phase 2.2b: POSTING structural wrapping ----------

/// Walk all `POSTING` descendants of a node, in source order.
fn postings(node: &SyntaxNode) -> Vec<SyntaxNode> {
    node.descendants()
        .filter(|n| n.kind() == SyntaxKind::POSTING)
        .collect()
}

#[test]
fn posting_wraps_account_only_line() {
    use SyntaxKind::*;
    // The simplest posting: indent + ACCOUNT (no amount). Beancount
    // calls this an "auto" posting — booking infers the amount from
    // the others. Round-trip + a single POSTING wrapper around the
    // sub-line.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    assert_eq!(
        elements_of(&ps[0]),
        tok_seq(&[WHITESPACE, ACCOUNT, NEWLINE]),
    );
}

#[test]
fn posting_wraps_account_with_amount_and_currency() {
    use SyntaxKind::*;
    // A normal posting with amount + currency. POSTING contains
    // the indent WHITESPACE, ACCOUNT, inter-token WHITESPACE, an
    // AMOUNT sub-node (PR 2.2c), then NEWLINE.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  -5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    assert_eq!(
        elements_of(&ps[0]),
        vec![
            Element::Tok(WHITESPACE),
            Element::Tok(ACCOUNT),
            Element::Tok(WHITESPACE),
            Element::Node(AMOUNT),
            Element::Tok(NEWLINE),
        ],
    );

    // AMOUNT internal shape: MINUS NUMBER WS CURRENCY.
    let amounts: Vec<SyntaxNode> = ps[0].children().filter(|n| n.kind() == AMOUNT).collect();
    assert_eq!(amounts.len(), 1);
    assert_eq!(
        elements_of(&amounts[0]),
        tok_seq(&[MINUS, NUMBER, WHITESPACE, CURRENCY]),
    );
}

#[test]
fn posting_wraps_each_of_multiple_postings_in_a_transaction() {
    use SyntaxKind::*;
    // Two postings → two POSTING nodes; each wraps an AMOUNT
    // sub-node around the NUMBER + CURRENCY portion (PR 2.2c).
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  -5.00 USD\n\
                  \x20\x20Expenses:Food  5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 2);
    for p in &ps {
        assert!(
            elements_of(p)
                .iter()
                .any(|e| matches!(e, Element::Tok(ACCOUNT)))
        );
        let n_amounts = p.children().filter(|n| n.kind() == AMOUNT).count();
        assert_eq!(n_amounts, 1, "each POSTING contains exactly one AMOUNT");
    }
}

#[test]
fn posting_with_pending_flag_wraps_flag_inside_node() {
    use SyntaxKind::*;
    // `! Assets:Cash ...` — the PENDING_KW flag sits between the
    // indent and the ACCOUNT. After PR 2.2c, the amount portion is
    // wrapped in an AMOUNT sub-node; the flag and account remain
    // flat tokens inside POSTING.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20! Assets:Cash  -5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    assert_eq!(
        elements_of(&ps[0]),
        vec![
            Element::Tok(WHITESPACE),
            Element::Tok(PENDING_KW),
            Element::Tok(WHITESPACE),
            Element::Tok(ACCOUNT),
            Element::Tok(WHITESPACE),
            Element::Node(AMOUNT),
            Element::Tok(NEWLINE),
        ],
    );
}

#[test]
fn posting_attached_meta_entry_lives_inside_posting() {
    use SyntaxKind::*;
    // The key PR 2.2b semantic: a META_ENTRY sub-line at STRICTLY
    // GREATER indent than the preceding POSTING attaches to that
    // POSTING (not to the TRANSACTION). Mirrors the legacy AST
    // parser's `parse_posting_metadata` (DeepIndent loop), which
    // accumulates metadata into `posting.meta`.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  -5.00 USD\n\
                  \x20\x20\x20\x20note: \"posting-attached\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let txs: Vec<SyntaxNode> = tree
        .children()
        .filter(|c| c.kind() == TRANSACTION)
        .collect();
    assert_eq!(txs.len(), 1);
    // TRANSACTION direct children: ONE POSTING, ZERO META_ENTRY
    // (the deeper-indented META_ENTRY belongs to the POSTING, not
    // to TRANSACTION).
    let tx_posting_count = txs[0].children().filter(|n| n.kind() == POSTING).count();
    let tx_meta_count = txs[0].children().filter(|n| n.kind() == META_ENTRY).count();
    assert_eq!(tx_posting_count, 1);
    assert_eq!(tx_meta_count, 0);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    // POSTING's children include the META_ENTRY as a structural
    // child (alongside the posting's flat tokens).
    let posting_meta_count = ps[0].children().filter(|n| n.kind() == META_ENTRY).count();
    assert_eq!(posting_meta_count, 1);
}

#[test]
fn same_indent_metadata_attaches_to_preceding_posting() {
    use SyntaxKind::*;
    // A META_ENTRY at the SAME indent as the preceding POSTING is
    // posting-attached, matching Beancount. Beancount attributes
    // metadata by POSITION (any `key: value` line following a posting,
    // before the next posting, attaches to that posting) rather than
    // by relative indent, so same-column `key: value` is POSTING
    // metadata, not transaction metadata. (Verified against the
    // Python beancount loader: a same-indent `key:` line lands in the
    // preceding posting's `meta`.) This is the case that drove the
    // last `effective_date`-example compat divergence.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  -5.00 USD\n\
                  \x20\x20note: \"on cash\"\n\
                  \x20\x20Expenses:Food  5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let txs: Vec<SyntaxNode> = tree
        .children()
        .filter(|c| c.kind() == TRANSACTION)
        .collect();
    assert_eq!(txs.len(), 1);
    // TRANSACTION direct children: TWO POSTINGs and NO direct
    // META_ENTRY (the metadata lives inside the first POSTING).
    let tx_posting_count = txs[0].children().filter(|n| n.kind() == POSTING).count();
    let tx_meta_count = txs[0].children().filter(|n| n.kind() == META_ENTRY).count();
    assert_eq!(tx_posting_count, 2);
    assert_eq!(tx_meta_count, 0);
    // The META_ENTRY is a child of the FIRST posting; the second has none.
    let ps = postings(&tree);
    assert_eq!(ps.len(), 2);
    assert_eq!(
        ps[0].children().filter(|n| n.kind() == META_ENTRY).count(),
        1
    );
    assert_eq!(
        ps[1].children().filter(|n| n.kind() == META_ENTRY).count(),
        0
    );
}

#[test]
fn posting_attached_multiple_meta_entries_all_inside_posting() {
    use SyntaxKind::*;
    // Multiple deeper-indented metadata lines following the same
    // POSTING all attach to it.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  -5.00 USD\n\
                  \x20\x20\x20\x20key1: \"v1\"\n\
                  \x20\x20\x20\x20key2: \"v2\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let posting_meta_count = ps[0].children().filter(|n| n.kind() == META_ENTRY).count();
    assert_eq!(posting_meta_count, 2);
}

#[test]
fn posting_attached_meta_entry_terminates_at_next_posting() {
    use SyntaxKind::*;
    // After posting-attached metadata, a NEW POSTING line at the
    // standard indent closes the current POSTING and opens a new
    // one. The new POSTING starts empty (no inherited metadata).
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  -5.00 USD\n\
                  \x20\x20\x20\x20note: \"on cash\"\n\
                  \x20\x20Expenses:Food  5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 2);
    // First POSTING owns the META_ENTRY; second is clean.
    let first_meta = ps[0].children().filter(|n| n.kind() == META_ENTRY).count();
    let second_meta = ps[1].children().filter(|n| n.kind() == META_ENTRY).count();
    assert_eq!(first_meta, 1);
    assert_eq!(second_meta, 0);
}

#[test]
fn postings_at_increasing_indents_produce_siblings_and_meta_attributes_to_latest() {
    use SyntaxKind::*;
    // Defensive shape: Beancount normally uses uniform posting
    // indentation. But the state machine doesn't enforce
    // monotonic indent — two posting lines at different indents
    // produce sibling POSTING nodes, and a subsequent META_ENTRY
    // attributes against the MOST-RECENTLY-OPENED POSTING's
    // indent. Pins this behavior so any future "monotonic indent"
    // refactor is a visible, intentional break.
    //
    // Source:
    //   posting at 2 spaces
    //   posting at 4 spaces  (DEEPER than the first)
    //   meta at 2 spaces     (NOT strictly deeper than 4)
    //
    // Expected: two POSTING siblings; the meta closes the second
    // (its indent is shallower) and lands at TRANSACTION level.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:A\n\
                  \x20\x20\x20\x20Assets:B  10 USD\n\
                  \x20\x20note: \"transaction-level\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 2, "two POSTING siblings at different indents");

    let txs: Vec<SyntaxNode> = tree
        .children()
        .filter(|c| c.kind() == TRANSACTION)
        .collect();
    assert_eq!(txs.len(), 1);
    let tx_meta = txs[0].children().filter(|n| n.kind() == META_ENTRY).count();
    assert_eq!(
        tx_meta, 1,
        "meta at shallower indent than the open POSTING lands at TRANSACTION level",
    );
    // Neither POSTING owns the META_ENTRY.
    for p in &ps {
        let inner_meta = p.children().filter(|n| n.kind() == META_ENTRY).count();
        assert_eq!(inner_meta, 0);
    }
}

#[test]
fn meta_entry_before_first_posting_stays_at_transaction_level() {
    use SyntaxKind::*;
    // A META_ENTRY that appears BEFORE any POSTING (regardless of
    // indent depth, since there's no preceding POSTING to attach
    // to) is always TRANSACTION-level.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20\x20\x20note: \"before posting\"\n\
                  \x20\x20Assets:Cash  -5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let txs: Vec<SyntaxNode> = tree
        .children()
        .filter(|c| c.kind() == TRANSACTION)
        .collect();
    assert_eq!(txs.len(), 1);
    let tx_meta = txs[0].children().filter(|n| n.kind() == META_ENTRY).count();
    let tx_posting = txs[0].children().filter(|n| n.kind() == POSTING).count();
    assert_eq!(tx_meta, 1);
    assert_eq!(tx_posting, 1);
    // The POSTING itself has no META_ENTRY child.
    let ps = postings(&tree);
    assert_eq!(
        ps[0].children().filter(|n| n.kind() == META_ENTRY).count(),
        0
    );
}

#[test]
fn deeper_indented_comment_stays_inside_posting_with_following_meta() {
    use SyntaxKind::*;
    // Doc-comment-for-following-posting-metadata idiom: an indented
    // `;` comment at indent STRICTLY GREATER than the open POSTING
    // (and at the same depth as the subsequent posting-attached
    // META_ENTRY) belongs to the POSTING. Both the comment AND the
    // META_ENTRY land inside the POSTING node.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  -5.00 USD\n\
                  \x20\x20\x20\x20; comment about note\n\
                  \x20\x20\x20\x20note: \"deeper\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);

    // The deeper-indented META_ENTRY is attached to the POSTING.
    let posting_meta_count = ps[0].children().filter(|n| n.kind() == META_ENTRY).count();
    assert_eq!(posting_meta_count, 1);

    // The deeper-indented COMMENT token is also inside POSTING.
    let posting_comment_count = ps[0]
        .children_with_tokens()
        .filter(|e| e.kind() == COMMENT)
        .count();
    assert_eq!(
        posting_comment_count, 1,
        "deeper-indented `;` comment stays inside POSTING with following meta",
    );

    // TRANSACTION's direct children have ZERO orphaned META_ENTRY
    // or COMMENT.
    let txs: Vec<SyntaxNode> = tree
        .children()
        .filter(|c| c.kind() == TRANSACTION)
        .collect();
    let tx_meta = txs[0].children().filter(|n| n.kind() == META_ENTRY).count();
    let tx_comment = txs[0]
        .children_with_tokens()
        .filter(|e| e.kind() == COMMENT)
        .count();
    assert_eq!(tx_meta, 0);
    assert_eq!(tx_comment, 0);
}

#[test]
fn deeper_indented_comment_stays_inside_posting_even_without_following_meta() {
    use SyntaxKind::*;
    // Rule is purely indent-based: a deeper-indented comment
    // belongs to the open POSTING regardless of whether a
    // META_ENTRY follows. Pins the rule's edge so the predicate
    // can't drift to "only attach when followed by meta".
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  -5.00 USD\n\
                  \x20\x20\x20\x20; trailing posting doc\n\
                  \x20\x20Expenses:Food  5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 2);
    let first_comment_count = ps[0]
        .children_with_tokens()
        .filter(|e| e.kind() == COMMENT)
        .count();
    let second_comment_count = ps[1]
        .children_with_tokens()
        .filter(|e| e.kind() == COMMENT)
        .count();
    assert_eq!(first_comment_count, 1);
    assert_eq!(second_comment_count, 0);
}

#[test]
fn posting_with_indented_comment_between_postings_terminates_posting() {
    use SyntaxKind::*;
    // An indented `;`-comment between two posting lines is
    // TRANSACTION-level inter-posting trivia: it closes the
    // current POSTING. The comment ends up as flat tokens between
    // the two POSTING nodes (matches the existing
    // `transaction_with_indented_comment_between_postings`
    // structural intent).
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  -5.00 USD\n\
                  \x20\x20; doc comment\n\
                  \x20\x20Expenses:Food  5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 2);
    // The COMMENT token lives between the two POSTING nodes as a
    // flat child of TRANSACTION, NOT inside either POSTING.
    let txs: Vec<SyntaxNode> = tree
        .children()
        .filter(|c| c.kind() == TRANSACTION)
        .collect();
    let tx_kids = elements_of(&txs[0]);
    let first_posting_idx = tx_kids
        .iter()
        .position(|e| matches!(e, Element::Node(POSTING)))
        .unwrap();
    let comment_idx = tx_kids
        .iter()
        .position(|e| matches!(e, Element::Tok(COMMENT)))
        .expect("indented comment is a flat TRANSACTION child");
    assert!(
        comment_idx > first_posting_idx,
        "comment follows first POSTING"
    );
}

#[test]
fn posting_at_eof_without_trailing_newline_still_wrapped() {
    use SyntaxKind::*;
    // Per rule 5 of `cst::trivia` (unterminated final directive),
    // a POSTING that reaches EOF mid-content without a final
    // NEWLINE still gets wrapped — the POSTING simply has no
    // NEWLINE child.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  -5.00 USD";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    // POSTING children: WS, ACCOUNT, WS, AMOUNT (no trailing
    // NEWLINE because of rule 5).
    assert_eq!(
        elements_of(&ps[0]),
        vec![
            Element::Tok(WHITESPACE),
            Element::Tok(ACCOUNT),
            Element::Tok(WHITESPACE),
            Element::Node(AMOUNT),
        ],
    );
    // AMOUNT internal shape, also unterminated.
    let amounts: Vec<SyntaxNode> = ps[0].children().filter(|n| n.kind() == AMOUNT).collect();
    assert_eq!(
        elements_of(&amounts[0]),
        tok_seq(&[MINUS, NUMBER, WHITESPACE, CURRENCY]),
    );
}

#[test]
fn star_flagged_posting_wraps_flag_inside_node() {
    use SyntaxKind::*;
    // `* Account ...` (STAR-flagged posting) is also a valid
    // beancount posting shape. The STAR sits between the indent
    // and the ACCOUNT inside POSTING.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20* Assets:Cash  -5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let kinds: Vec<SyntaxKind> = elements_of(&ps[0])
        .iter()
        .filter_map(|e| match e {
            Element::Tok(k) => Some(*k),
            Element::Node(_) => None,
        })
        .collect();
    assert!(kinds.starts_with(&[WHITESPACE, STAR, WHITESPACE, ACCOUNT]));
}

#[test]
fn flagged_posting_with_question_mark_wraps_flag_inside_node() {
    use SyntaxKind::*;
    // `? Account ...` — the `?` flag emits a FLAG token (the
    // single-letter alphabetic flags P/S/T/C/U/R/M are tokenized
    // as CURRENCY by lexer priority 3 — covered by
    // `single_char_currency_flagged_posting_wraps_currency_as_flag`).
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20? Assets:Cash  -5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let kinds: Vec<SyntaxKind> = elements_of(&ps[0])
        .iter()
        .filter_map(|e| match e {
            Element::Tok(k) => Some(*k),
            Element::Node(_) => None,
        })
        .collect();
    assert!(kinds.starts_with(&[WHITESPACE, FLAG, WHITESPACE, ACCOUNT]));
}

#[test]
fn hash_flagged_posting_wraps_hash_inside_node() {
    use SyntaxKind::*;
    // `# Account ...` is a valid Beancount posting flag (legacy
    // `parse_flag` accepts `Token::Hash`; `identify_directive`
    // accepts HASH as a transaction trigger). Pin that
    // `starts_posting_sub_line` recognizes it so the line is
    // wrapped in POSTING rather than falling through as flat
    // tokens.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20# Assets:Cash  -5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let kinds: Vec<SyntaxKind> = elements_of(&ps[0])
        .iter()
        .filter_map(|e| match e {
            Element::Tok(k) => Some(*k),
            Element::Node(_) => None,
        })
        .collect();
    assert!(kinds.starts_with(&[WHITESPACE, HASH, WHITESPACE, ACCOUNT]));
}

#[test]
fn hash_flagged_posting_attached_meta_entry_lives_inside_posting() {
    use SyntaxKind::*;
    // Combines HASH flag with posting-attached META_ENTRY (the
    // shape the bare hash_flagged_posting_wraps_hash_inside_node
    // test alone couldn't catch a regression on). If a future
    // change drops HASH from `starts_posting_sub_line`, this test
    // fails because the line would no longer open a POSTING and
    // the deeper-indented META_ENTRY would orphan to TRANSACTION.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20# Assets:Cash  -5.00 USD\n\
                  \x20\x20\x20\x20note: \"hash-flagged\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let posting_meta_count = ps[0].children().filter(|n| n.kind() == META_ENTRY).count();
    assert_eq!(posting_meta_count, 1);

    let txs: Vec<SyntaxNode> = tree
        .children()
        .filter(|c| c.kind() == TRANSACTION)
        .collect();
    let tx_meta = txs[0].children().filter(|n| n.kind() == META_ENTRY).count();
    assert_eq!(tx_meta, 0);
}

#[test]
fn deeper_indented_trailing_comment_at_eof_stays_inside_posting() {
    use SyntaxKind::*;
    // Doc-comment-attribution rule extended to the EOF case: a
    // deeper-indented `;` comment that is the LAST sub-line of the
    // file (no final NEWLINE) still attaches to the open POSTING.
    // Per rule 5 of `cst::trivia` (recursive application: an
    // unterminated POSTING ends at its last content token without a
    // NEWLINE child of its own).
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash 1 USD\n\
                  \x20\x20\x20\x20; deep trailing";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let posting_comment_count = ps[0]
        .children_with_tokens()
        .filter(|e| e.kind() == COMMENT)
        .count();
    assert_eq!(
        posting_comment_count, 1,
        "EOF-trailing deep `;` comment is a child of POSTING",
    );

    // No COMMENT orphaned to TRANSACTION level.
    let txs: Vec<SyntaxNode> = tree
        .children()
        .filter(|c| c.kind() == TRANSACTION)
        .collect();
    let tx_comment = txs[0]
        .children_with_tokens()
        .filter(|e| e.kind() == COMMENT)
        .count();
    assert_eq!(tx_comment, 0);
}

#[test]
fn deeper_indented_emacs_directive_attaches_to_open_posting() {
    use SyntaxKind::*;
    // `is_comment_token` includes EMACS_DIRECTIVE (`#+`). The
    // indented-comment branch in `emit_transaction_body` routes it
    // through the same indent-attribution rule as COMMENT: deeper-
    // indented than the open POSTING = stays INSIDE POSTING.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash 1 USD\n\
                  \x20\x20\x20\x20#+STARTUP: overview\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let emacs_inside_posting = ps[0]
        .children_with_tokens()
        .filter(|e| e.kind() == EMACS_DIRECTIVE)
        .count();
    assert_eq!(
        emacs_inside_posting, 1,
        "EMACS_DIRECTIVE recognized as comment-class trivia, attaches by indent",
    );
}

#[test]
fn deeper_indented_shebang_attaches_to_open_posting() {
    use SyntaxKind::*;
    // Companion to the EMACS_DIRECTIVE test: pin that SHEBANG
    // (`#!`) is also recognized as comment-class trivia via
    // `is_comment_token` and follows the same indent-attribution
    // rule. Catches a regression that drops SHEBANG from the
    // helper while leaving EMACS_DIRECTIVE in place.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash 1 USD\n\
                  \x20\x20\x20\x20#!/usr/bin/env something\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let shebang_inside_posting = ps[0]
        .children_with_tokens()
        .filter(|e| e.kind() == SHEBANG)
        .count();
    assert_eq!(
        shebang_inside_posting, 1,
        "SHEBANG recognized as comment-class trivia, attaches by indent",
    );
}

#[test]
fn deeper_indented_percent_comment_attaches_to_open_posting() {
    use SyntaxKind::*;
    // PERCENT_COMMENT (`%`) is included in `is_comment_token` but
    // every other comment-attribution test uses `;`. Pin the `%`
    // path so a regression that demotes PERCENT_COMMENT (e.g., via
    // a typo or split refactor) fails here.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash 1 USD\n\
                  \x20\x20\x20\x20% percent-style doc\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let pct_inside_posting = ps[0]
        .children_with_tokens()
        .filter(|e| e.kind() == PERCENT_COMMENT)
        .count();
    assert_eq!(
        pct_inside_posting, 1,
        "PERCENT_COMMENT recognized as comment-class trivia, attaches by indent",
    );
}

#[test]
fn directive_body_absorbs_indented_emacs_directive_when_block_has_meta() {
    use SyntaxKind::*;
    // The `is_comment_token` widening also affects
    // `upcoming_indented_block_has_meta` and
    // `is_indented_directive_continuation` for NON-transaction
    // directives. Pin that an indented `#+STARTUP` line inside an
    // OPEN_DIRECTIVE that ALSO contains a meta line is absorbed as
    // a continuation (rather than orphaning to SOURCE_FILE).
    // Mirrors the existing `indented_comment_before_first_metadata`
    // / `indented_comment_between_metadata_lines` tests, which use
    // `;` only; this pins the SHEBANG/EMACS_DIRECTIVE branch.
    let source = "2024-01-01 open Assets:Cash\n\
                  \x20\x20#+STARTUP: overview\n\
                  \x20\x20key: \"v\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), OPEN_DIRECTIVE);

    // The EMACS_DIRECTIVE token lives inside the OPEN_DIRECTIVE,
    // not orphaned anywhere else in the tree. Use `descendants`
    // symmetrically on both sides so a future refactor that wraps
    // SOURCE_FILE trivia in any nested node doesn't make the
    // orphan check vacuously pass.
    let emacs_total = tree
        .descendants_with_tokens()
        .filter(|e| e.kind() == EMACS_DIRECTIVE)
        .count();
    let emacs_in_directive = ds[0]
        .descendants_with_tokens()
        .filter(|e| e.kind() == EMACS_DIRECTIVE)
        .count();
    assert_eq!(emacs_total, 1, "exactly one EMACS_DIRECTIVE in the tree");
    assert_eq!(
        emacs_in_directive, 1,
        "EMACS_DIRECTIVE absorbed by OPEN_DIRECTIVE"
    );

    // The block_has_meta look-ahead is what kept the EMACS line
    // inside the directive: the subsequent `key: "v"` becomes a
    // META_ENTRY child of OPEN_DIRECTIVE. Assert that META_ENTRY
    // actually appears so a regression that breaks the META_KEY
    // arm (closing the directive AFTER the EMACS line but BEFORE
    // the meta) fails here, not silently.
    let meta_entries_in_directive = ds[0]
        .descendants()
        .filter(|n| n.kind() == META_ENTRY)
        .count();
    assert_eq!(meta_entries_in_directive, 1, "META_ENTRY also absorbed");
}

#[test]
fn directive_body_does_not_absorb_indented_emacs_directive_when_no_meta() {
    use SyntaxKind::*;
    // Complementary case: when an OPEN_DIRECTIVE has NO meta block,
    // an indented EMACS_DIRECTIVE / SHEBANG / `;`-comment that
    // follows the header is NOT a continuation (per the
    // block_has_meta gate). Pins that the widening did not
    // accidentally make these tokens unconditional continuations.
    let source = "2024-01-01 open Assets:Cash\n\
                  \x20\x20#+STARTUP: trailing only\n\
                  2024-01-02 open Assets:Bank\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(
        ds.len(),
        2,
        "two OPEN_DIRECTIVES, separated by EMACS_DIRECTIVE rule-2 trivia"
    );
    assert_eq!(ds[0].kind(), OPEN_DIRECTIVE);
    assert_eq!(ds[1].kind(), OPEN_DIRECTIVE);

    // The EMACS_DIRECTIVE is rule-2 inter-directive trivia: it
    // attaches as LEADING trivia of the SECOND directive (per
    // `cst::trivia`), NOT as a continuation of the first.
    // Symmetric `descendants` walks on both sides and a total-
    // count sanity check guard against future structural changes
    // that wrap trivia in a nested node.
    let emacs_total = tree
        .descendants_with_tokens()
        .filter(|e| e.kind() == EMACS_DIRECTIVE)
        .count();
    let emacs_in_first = ds[0]
        .descendants_with_tokens()
        .filter(|e| e.kind() == EMACS_DIRECTIVE)
        .count();
    let emacs_in_second = ds[1]
        .descendants_with_tokens()
        .filter(|e| e.kind() == EMACS_DIRECTIVE)
        .count();
    assert_eq!(emacs_total, 1, "exactly one EMACS_DIRECTIVE in the tree");
    assert_eq!(
        emacs_in_first, 0,
        "EMACS_DIRECTIVE is NOT absorbed by header-only directive"
    );
    assert_eq!(
        emacs_in_second, 1,
        "EMACS_DIRECTIVE leads the next directive as rule-2 trivia"
    );
}

#[test]
fn catch_all_indented_unknown_content_closes_posting_and_emits_flat() {
    use SyntaxKind::*;
    // Catch-all `else` branch of emit_transaction_body: an indented
    // sub-line that is neither posting, meta, nor comment closes
    // any open POSTING and emits flat at TRANSACTION level.
    // Examples: a stray bare STRING on its own indented line. Pin
    // the behavior so PR 2.2c (AMOUNT continuations etc.) doesn't
    // silently shift attribution without an explicit test update.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash 1 USD\n\
                  \x20\x20\"stray string on own line\"\n\
                  \x20\x20Expenses:Food 1 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(
        ps.len(),
        2,
        "stray indented STRING closes POSTING; next POSTING opens fresh"
    );

    let txs: Vec<SyntaxNode> = tree
        .children()
        .filter(|c| c.kind() == TRANSACTION)
        .collect();
    // The stray STRING token is a flat child of TRANSACTION (not
    // inside either POSTING). TRANSACTION's direct STRING tokens
    // include the header narration "x" PLUS the stray, for a total
    // of 2.
    let tx_strings: usize = txs[0]
        .children_with_tokens()
        .filter(|e| e.kind() == STRING)
        .count();
    assert_eq!(tx_strings, 2);
    for p in &ps {
        let inside_string = p
            .children_with_tokens()
            .filter(|e| e.kind() == STRING)
            .count();
        assert_eq!(inside_string, 0);
    }
}

#[test]
fn same_indent_comment_between_posting_and_deeper_meta_orphans_meta() {
    use SyntaxKind::*;
    // The same-indent `;` comment between a posting and a deeper-
    // indented META_KEY closes the POSTING (per the
    // indent-attribution rule: comment indent is not strictly
    // greater than posting indent). The subsequent deeper-indented
    // META_KEY then has no open POSTING and lands at TRANSACTION
    // level. Matches the legacy AST parser's
    // `parse_posting_metadata` loop, which terminates posting-
    // attached metadata at any indented sub-line that is not a
    // DeepIndent META_KEY (a same-indent COMMENT being one such
    // terminator). Python beancount parity is NOT verified here —
    // a future compat audit may find Python attaches the deeper
    // META to the still-open posting, in which case this test is
    // the touch-point. Pinned so a future refactor can't silently
    // flip the attribution without a test update.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash -5 USD\n\
                  \x20\x20; explicit break at posting indent\n\
                  \x20\x20\x20\x20key: \"orphaned\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let posting_meta_count = ps[0].children().filter(|n| n.kind() == META_ENTRY).count();
    assert_eq!(
        posting_meta_count, 0,
        "same-indent comment ends posting-attached meta block; deeper meta orphans to TRANSACTION",
    );

    let txs: Vec<SyntaxNode> = tree
        .children()
        .filter(|c| c.kind() == TRANSACTION)
        .collect();
    let tx_meta = txs[0].children().filter(|n| n.kind() == META_ENTRY).count();
    assert_eq!(tx_meta, 1);
}

#[test]
fn single_char_currency_flagged_posting_wraps_currency_as_flag() {
    use SyntaxKind::*;
    // `P Account ...` — `P` tokenizes as CURRENCY (lexer priority
    // 3) but functions as a posting flag, mirroring the transaction
    // header's same Currency-vs-Flag tie-break. POSTING still wraps
    // the line.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20P Assets:Cash  -5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let kinds: Vec<SyntaxKind> = elements_of(&ps[0])
        .iter()
        .filter_map(|e| match e {
            Element::Tok(k) => Some(*k),
            Element::Node(_) => None,
        })
        .collect();
    assert!(kinds.starts_with(&[WHITESPACE, CURRENCY, WHITESPACE, ACCOUNT]));
}

// ---------- Phase 2.2c: AMOUNT / COST_SPEC / PRICE_ANNOTATION ----------

/// Walk all `AMOUNT` descendants of a node, in source order.
fn amounts(node: &SyntaxNode) -> Vec<SyntaxNode> {
    node.descendants()
        .filter(|n| n.kind() == SyntaxKind::AMOUNT)
        .collect()
}

/// Walk all `COST_SPEC` descendants of a node, in source order.
fn cost_specs(node: &SyntaxNode) -> Vec<SyntaxNode> {
    node.descendants()
        .filter(|n| n.kind() == SyntaxKind::COST_SPEC)
        .collect()
}

/// Walk all `PRICE_ANNOTATION` descendants of a node, in source order.
fn price_annotations(node: &SyntaxNode) -> Vec<SyntaxNode> {
    node.descendants()
        .filter(|n| n.kind() == SyntaxKind::PRICE_ANNOTATION)
        .collect()
}

#[test]
fn amount_wraps_positive_number_and_currency() {
    use SyntaxKind::*;
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  100.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let amts = amounts(&tree);
    assert_eq!(amts.len(), 1);
    assert_eq!(
        elements_of(&amts[0]),
        tok_seq(&[NUMBER, WHITESPACE, CURRENCY]),
    );
}

#[test]
fn amount_wraps_negative_number_and_currency_with_sign_token() {
    use SyntaxKind::*;
    // Lexer emits MINUS + NUMBER for negative amounts (enables
    // arithmetic expressions). The sign token lives INSIDE the
    // AMOUNT wrapper.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  -100.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let amts = amounts(&tree);
    assert_eq!(amts.len(), 1);
    assert_eq!(
        elements_of(&amts[0]),
        tok_seq(&[MINUS, NUMBER, WHITESPACE, CURRENCY]),
    );
}

#[test]
fn amount_wraps_explicit_plus_sign_and_currency() {
    use SyntaxKind::*;
    // `+100 USD` — the lexer emits PLUS + NUMBER; both live
    // inside AMOUNT.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  +100.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let amts = amounts(&tree);
    assert_eq!(amts.len(), 1);
    assert_eq!(
        elements_of(&amts[0]),
        tok_seq(&[PLUS, NUMBER, WHITESPACE, CURRENCY]),
    );
}

#[test]
fn amount_wraps_number_only_no_currency() {
    use SyntaxKind::*;
    // Incomplete amount: NUMBER without a trailing currency.
    // AMOUNT wraps the NUMBER alone.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  100.00\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let amts = amounts(&tree);
    assert_eq!(amts.len(), 1);
    assert_eq!(elements_of(&amts[0]), tok_seq(&[NUMBER]));
}

#[test]
fn amount_wraps_currency_only_no_number() {
    use SyntaxKind::*;
    // Incomplete amount: bare CURRENCY (currency-only amount).
    // AMOUNT wraps the CURRENCY alone.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let amts = amounts(&tree);
    assert_eq!(amts.len(), 1);
    assert_eq!(elements_of(&amts[0]), tok_seq(&[CURRENCY]));
}

#[test]
fn auto_posting_with_no_amount_has_no_amount_node() {
    // Account-only "auto" posting — the booker fills in the
    // amount from the others. No AMOUNT wrapper because there's
    // nothing to wrap.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let amts = amounts(&tree);
    assert_eq!(amts.len(), 0, "auto posting has no AMOUNT child");
    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
}

#[test]
fn cost_spec_wraps_simple_per_unit_cost() {
    use SyntaxKind::*;
    // Per-unit cost spec: `{NUMBER WS CURRENCY}`. COST_SPEC's
    // direct children include the brace tokens and the inner
    // amount tokens flat (per-2.2c design — contents are
    // unstructured until phase 3).
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  10 HOOL {500.00 USD}\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let cs = cost_specs(&tree);
    assert_eq!(cs.len(), 1);
    assert_eq!(
        elements_of(&cs[0]),
        tok_seq(&[L_BRACE, NUMBER, WHITESPACE, CURRENCY, R_BRACE]),
    );
}

#[test]
fn cost_spec_wraps_total_double_brace() {
    use SyntaxKind::*;
    // `{{ ... }}` total-cost form.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  10 HOOL {{5000.00 USD}}\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let cs = cost_specs(&tree);
    assert_eq!(cs.len(), 1);
    assert_eq!(
        elements_of(&cs[0]),
        tok_seq(&[L_DOUBLE_BRACE, NUMBER, WHITESPACE, CURRENCY, R_DOUBLE_BRACE]),
    );
}

#[test]
fn cost_spec_wraps_per_unit_plus_total_brace_hash() {
    use SyntaxKind::*;
    // `{# ... }` per-unit + total form (HASH separator inside).
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  10 HOOL {# 5000.00 USD}\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let cs = cost_specs(&tree);
    assert_eq!(cs.len(), 1);
    // L_BRACE_HASH opener, content tokens, R_BRACE close.
    let kinds: Vec<SyntaxKind> = elements_of(&cs[0])
        .iter()
        .filter_map(|e| match e {
            Element::Tok(k) => Some(*k),
            Element::Node(_) => None,
        })
        .collect();
    assert!(kinds.contains(&L_BRACE_HASH));
    assert!(kinds.contains(&R_BRACE));
}

#[test]
fn cost_spec_unclosed_at_eof_still_wraps_per_rule_5() {
    use SyntaxKind::*;
    // Per rule 5, an unclosed brace at EOF still gets wrapped;
    // the COST_SPEC simply has no matching close-brace child.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  10 HOOL {500.00 USD";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let cs = cost_specs(&tree);
    assert_eq!(cs.len(), 1);
    let kinds: Vec<SyntaxKind> = elements_of(&cs[0])
        .iter()
        .filter_map(|e| match e {
            Element::Tok(k) => Some(*k),
            Element::Node(_) => None,
        })
        .collect();
    assert!(kinds.contains(&L_BRACE));
    assert!(!kinds.contains(&R_BRACE), "no close brace consumed");
    assert!(kinds.contains(&CURRENCY));
}

#[test]
fn price_annotation_wraps_per_unit_with_nested_amount() {
    use SyntaxKind::*;
    // `@ NUMBER WS CURRENCY` — per-unit price. PRICE_ANNOTATION
    // contains AT + WHITESPACE + AMOUNT.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  10 HOOL @ 500.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let prices = price_annotations(&tree);
    assert_eq!(prices.len(), 1);
    assert_eq!(
        elements_of(&prices[0]),
        vec![
            Element::Tok(AT),
            Element::Tok(WHITESPACE),
            Element::Node(AMOUNT),
        ],
    );
    // The nested AMOUNT has its own NUMBER/CURRENCY.
    let inner_amount = prices[0].children().find(|n| n.kind() == AMOUNT).unwrap();
    assert_eq!(
        elements_of(&inner_amount),
        tok_seq(&[NUMBER, WHITESPACE, CURRENCY]),
    );
}

#[test]
fn price_annotation_wraps_total_at_at() {
    use SyntaxKind::*;
    // `@@ NUMBER WS CURRENCY` — total price. The opener distinguishes
    // per-unit (AT) from total (AT_AT).
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  10 HOOL @@ 5000.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let prices = price_annotations(&tree);
    assert_eq!(prices.len(), 1);
    let first_child_kind = elements_of(&prices[0]).first().copied();
    assert_eq!(first_child_kind, Some(Element::Tok(AT_AT)));
    let inner_amount = prices[0].children().find(|n| n.kind() == AMOUNT).unwrap();
    assert_eq!(
        elements_of(&inner_amount),
        tok_seq(&[NUMBER, WHITESPACE, CURRENCY]),
    );
}

#[test]
fn posting_with_amount_cost_spec_and_price_annotation_all_three() {
    use SyntaxKind::*;
    // Full posting form: units AMOUNT, COST_SPEC, PRICE_ANNOTATION
    // in canonical order. Each gets its own wrapper inside POSTING.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  10 HOOL {500.00 USD} @ 510.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let posting_kids = elements_of(&ps[0]);
    // Locate the three sub-nodes.
    let amount_count = posting_kids
        .iter()
        .filter(|e| matches!(e, Element::Node(AMOUNT)))
        .count();
    let cost_count = posting_kids
        .iter()
        .filter(|e| matches!(e, Element::Node(COST_SPEC)))
        .count();
    let price_count = posting_kids
        .iter()
        .filter(|e| matches!(e, Element::Node(PRICE_ANNOTATION)))
        .count();
    assert_eq!(amount_count, 1, "one units AMOUNT");
    assert_eq!(cost_count, 1, "one COST_SPEC");
    assert_eq!(price_count, 1, "one PRICE_ANNOTATION");

    // Source-order: AMOUNT before COST_SPEC before PRICE_ANNOTATION.
    let amount_idx = posting_kids
        .iter()
        .position(|e| matches!(e, Element::Node(AMOUNT)))
        .unwrap();
    let cost_idx = posting_kids
        .iter()
        .position(|e| matches!(e, Element::Node(COST_SPEC)))
        .unwrap();
    let price_idx = posting_kids
        .iter()
        .position(|e| matches!(e, Element::Node(PRICE_ANNOTATION)))
        .unwrap();
    assert!(amount_idx < cost_idx);
    assert!(cost_idx < price_idx);
}

#[test]
fn posting_amount_and_trailing_comment_keeps_comment_outside_amount() {
    use SyntaxKind::*;
    // A trailing same-line comment after the amount stays as a
    // flat POSTING child, NOT inside AMOUNT (the amount wrapper
    // closes at the last currency / number).
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  100 USD ; trailing\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let amts = amounts(&tree);
    assert_eq!(amts.len(), 1);
    // The COMMENT token lives at POSTING level, not inside AMOUNT.
    let amount_comments = amts[0]
        .descendants_with_tokens()
        .filter(|e| e.kind() == COMMENT)
        .count();
    assert_eq!(amount_comments, 0, "comment is not absorbed into AMOUNT");
    let ps = postings(&tree);
    let posting_comments = ps[0]
        .children_with_tokens()
        .filter(|e| e.kind() == COMMENT)
        .count();
    assert_eq!(posting_comments, 1, "comment is a POSTING flat child");
}

#[test]
fn posting_attached_meta_entry_after_amount_still_attaches() {
    use SyntaxKind::*;
    // Combines AMOUNT wrapping with the indent-aware meta
    // attribution from PR 2.2b: a deeper-indented META_KEY after
    // a posting with an AMOUNT still attaches to the POSTING.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  10 HOOL {500.00 USD}\n\
                  \x20\x20\x20\x20note: \"posting-attached\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let amount_count = ps[0].children().filter(|n| n.kind() == AMOUNT).count();
    let cost_count = ps[0].children().filter(|n| n.kind() == COST_SPEC).count();
    let meta_count = ps[0].children().filter(|n| n.kind() == META_ENTRY).count();
    assert_eq!(amount_count, 1);
    assert_eq!(cost_count, 1);
    assert_eq!(meta_count, 1);
}

#[test]
fn hash_flagged_posting_with_amount_wraps_both() {
    use SyntaxKind::*;
    // HASH flag + AMOUNT together — pins that the flag-flagged
    // arm of starts_posting_sub_line still allows AMOUNT wrapping
    // inside the same POSTING.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20# Assets:Cash  -5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let amount_count = ps[0].children().filter(|n| n.kind() == AMOUNT).count();
    assert_eq!(amount_count, 1);
    // The HASH and ACCOUNT are flat siblings, then AMOUNT.
    let first_four: Vec<Element> = elements_of(&ps[0]).into_iter().take(4).collect();
    assert_eq!(
        first_four,
        vec![
            Element::Tok(WHITESPACE),
            Element::Tok(HASH),
            Element::Tok(WHITESPACE),
            Element::Tok(ACCOUNT),
        ],
    );
}

#[test]
fn amount_with_only_negative_number_no_currency() {
    use SyntaxKind::*;
    // `MINUS NUMBER` without a CURRENCY (incomplete amount).
    // AMOUNT wraps MINUS NUMBER only.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  -100\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let amts = amounts(&tree);
    assert_eq!(amts.len(), 1);
    assert_eq!(elements_of(&amts[0]), tok_seq(&[MINUS, NUMBER]));
}

#[test]
fn price_annotation_without_amount_still_wraps_opener_only() {
    use SyntaxKind::*;
    // Degenerate `@` with no following amount (malformed).
    // PRICE_ANNOTATION wraps the AT opener and stops; round-trip
    // is preserved.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  10 HOOL @\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let prices = price_annotations(&tree);
    assert_eq!(prices.len(), 1);
    assert_eq!(elements_of(&prices[0]), tok_seq(&[AT]));
}

#[test]
fn cost_spec_with_inner_label_and_date_stays_flat_internally() {
    use SyntaxKind::*;
    // `{NUMBER CURRENCY, "label", DATE}` — multi-component cost.
    // COST_SPEC's internal structure is flat for phase 2.2c;
    // phase 3 typed-AST will surface accessors.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  10 HOOL {500.00 USD, \"lot1\", 2024-01-15}\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let cs = cost_specs(&tree);
    assert_eq!(cs.len(), 1);
    let kinds: Vec<SyntaxKind> = elements_of(&cs[0])
        .iter()
        .filter_map(|e| match e {
            Element::Tok(k) => Some(*k),
            Element::Node(_) => None,
        })
        .collect();
    assert!(kinds.contains(&NUMBER));
    assert!(kinds.contains(&CURRENCY));
    assert!(kinds.contains(&STRING));
    assert!(kinds.contains(&DATE));
    assert!(kinds.contains(&L_BRACE));
    assert!(kinds.contains(&R_BRACE));
}

#[test]
fn amount_wraps_number_and_currency_with_no_whitespace_between() {
    use SyntaxKind::*;
    // The lexer's NUMBER and CURRENCY regexes are exclusive
    // (NUMBER stops at a non-digit, CURRENCY starts on an
    // uppercase letter), so `1USD` lexes as adjacent NUMBER +
    // CURRENCY with NO WHITESPACE between. Real corpus shape
    // (e.g., beancount-import fixtures). AMOUNT must still wrap
    // the CURRENCY despite the missing separator — regression for
    // the round-1 review finding where emit_amount required a WS
    // token between NUMBER and CURRENCY.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash 1USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let amts = amounts(&tree);
    assert_eq!(amts.len(), 1);
    assert_eq!(
        elements_of(&amts[0]),
        tok_seq(&[NUMBER, CURRENCY]),
        "AMOUNT wraps both NUMBER and adjacent CURRENCY (no WS between)",
    );
}

#[test]
fn price_annotation_with_negative_amount_wraps_sign_inside_nested_amount() {
    use SyntaxKind::*;
    // `@ -5 USD` — negative price. The nested AMOUNT contains
    // MINUS NUMBER WS CURRENCY. Pins the sign-detection path
    // inside emit_price_annotation.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  10 HOOL @ -5.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let prices = price_annotations(&tree);
    assert_eq!(prices.len(), 1);
    let inner_amount = prices[0].children().find(|n| n.kind() == AMOUNT).unwrap();
    assert_eq!(
        elements_of(&inner_amount),
        tok_seq(&[MINUS, NUMBER, WHITESPACE, CURRENCY]),
    );
}

#[test]
fn cost_spec_empty_braces_wraps_open_close_pair_only() {
    use SyntaxKind::*;
    // `{}` — empty cost spec (Beancount accepts this as a
    // "no-cost" marker). COST_SPEC contains exactly the L_BRACE +
    // R_BRACE pair.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  10 HOOL {}\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let cs = cost_specs(&tree);
    assert_eq!(cs.len(), 1);
    assert_eq!(elements_of(&cs[0]), tok_seq(&[L_BRACE, R_BRACE]));
}

#[test]
fn cost_spec_with_merge_star_keeps_star_inside_node() {
    use SyntaxKind::*;
    // `{*}` — merge marker. Per the legacy parser, the STAR
    // inside braces signals lot merging. emit_cost_spec keeps
    // STAR as a flat content token between the braces.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  10 HOOL {*}\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let cs = cost_specs(&tree);
    assert_eq!(cs.len(), 1);
    assert_eq!(elements_of(&cs[0]), tok_seq(&[L_BRACE, STAR, R_BRACE]));
}

#[test]
fn price_annotation_at_eof_without_newline_still_wraps_opener_only() {
    use SyntaxKind::*;
    // Per rule 5, an unterminated PRICE_ANNOTATION at EOF (no
    // newline, no amount) still wraps — the PRICE_ANNOTATION
    // contains just the AT opener.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash 10 HOOL @";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let prices = price_annotations(&tree);
    assert_eq!(prices.len(), 1);
    assert_eq!(elements_of(&prices[0]), tok_seq(&[AT]));
}

#[test]
fn total_price_annotation_at_at_eof_without_newline_still_wraps_opener_only() {
    use SyntaxKind::*;
    // Companion to the single-`@` EOF test: pin that `@@` (total
    // price opener) at EOF also wraps. Both code paths emit
    // through the same opener branch in emit_price_annotation,
    // but the AT_AT-specific path was unpinned.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash 10 HOOL @@";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let prices = price_annotations(&tree);
    assert_eq!(prices.len(), 1);
    assert_eq!(elements_of(&prices[0]), tok_seq(&[AT_AT]));
}

#[test]
fn balance_and_price_directive_header_amounts_stay_flat_not_wrapped() {
    use SyntaxKind::*;
    // Phase 2.2c scopes AMOUNT wrapping to POSTING only. BALANCE
    // and PRICE directive headers emit their inline NUMBER +
    // CURRENCY tokens flat via `emit_through_terminator`, NOT
    // wrapped in an AMOUNT node. Phase 3 typed-AST
    // `Balance::amount()` / `Price::amount()` will need a token-
    // walking strategy distinct from `Posting::amount()`. Pinned
    // here so a future refactor that unifies the code path (e.g.,
    // calling emit_amount from the directive header) is a visible,
    // intentional break rather than a silent design shift.
    //
    // Each sub-case also asserts the directive's specific kind, so
    // a regression that drops keyword recognition (and falls
    // through to flat passthrough under SOURCE_FILE) doesn't
    // trivially satisfy the `amts.len() == 0` assertion.
    let source = "2024-06-30 balance Assets:Cash 100.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);
    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), BALANCE_DIRECTIVE);
    assert_eq!(
        amounts(&tree).len(),
        0,
        "BALANCE header NUMBER + CURRENCY are flat children of BALANCE_DIRECTIVE",
    );

    let price_source = "2024-01-01 price USD 1.10 EUR\n";
    let price_tree = parse_structured(price_source);
    assert_round_trip(price_source, &price_tree);
    let price_ds = directives(&price_tree);
    assert_eq!(price_ds.len(), 1);
    assert_eq!(price_ds[0].kind(), PRICE_DIRECTIVE);
    assert_eq!(
        amounts(&price_tree).len(),
        0,
        "PRICE header NUMBER + CURRENCY are flat children of PRICE_DIRECTIVE",
    );
}

#[test]
fn amount_wraps_arithmetic_no_spaces() {
    use SyntaxKind::*;
    // Phase 2.4 closes the 2.2c.1 divergence: `10+5 USD` is a
    // SINGLE AMOUNT containing the full expression run, matching
    // Python beancount's `parse_expr` (verified: `bean-check`
    // accepts the form). All tokens are flat children of AMOUNT;
    // phase 3 typed-AST will surface evaluated value via inspecting
    // the children.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  10+5 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let amts: Vec<SyntaxNode> = ps[0].children().filter(|n| n.kind() == AMOUNT).collect();
    assert_eq!(amts.len(), 1);
    assert_eq!(
        elements_of(&amts[0]),
        tok_seq(&[NUMBER, PLUS, NUMBER, WHITESPACE, CURRENCY]),
    );
}

#[test]
fn amount_wraps_arithmetic_with_spaces_around_op() {
    use SyntaxKind::*;
    // `100 + 5 USD` (spaces around operator) — AMOUNT consumes the
    // whole `NUMBER WS PLUS WS NUMBER` run plus the trailing
    // `WS CURRENCY`.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  100 + 5 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let amts: Vec<SyntaxNode> = ps[0].children().filter(|n| n.kind() == AMOUNT).collect();
    assert_eq!(amts.len(), 1);
    assert_eq!(
        elements_of(&amts[0]),
        tok_seq(&[
            NUMBER, WHITESPACE, PLUS, WHITESPACE, NUMBER, WHITESPACE, CURRENCY
        ]),
    );
}

#[test]
fn amount_wraps_signed_arithmetic_negative_outer() {
    use SyntaxKind::*;
    // `-10+5 USD` — leading MINUS, then NUMBER PLUS NUMBER, then
    // CURRENCY. All inside a single AMOUNT.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  -10+5 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let amts: Vec<SyntaxNode> = ps[0].children().filter(|n| n.kind() == AMOUNT).collect();
    assert_eq!(amts.len(), 1);
    assert_eq!(
        elements_of(&amts[0]),
        tok_seq(&[MINUS, NUMBER, PLUS, NUMBER, WHITESPACE, CURRENCY]),
    );
}

#[test]
fn amount_wraps_parenthesized_subexpression() {
    use SyntaxKind::*;
    // `-(10+5) USD` — MINUS L_PAREN NUMBER PLUS NUMBER R_PAREN
    // WS CURRENCY, all inside one AMOUNT. Phase 2.4 handles paren
    // groups via balanced-depth scanning.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  -(10+5) USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let amts: Vec<SyntaxNode> = ps[0].children().filter(|n| n.kind() == AMOUNT).collect();
    assert_eq!(amts.len(), 1);
    assert_eq!(
        elements_of(&amts[0]),
        tok_seq(&[
            MINUS, L_PAREN, NUMBER, PLUS, NUMBER, R_PAREN, WHITESPACE, CURRENCY
        ]),
    );
}

#[test]
fn amount_wraps_multiplication_and_division() {
    use SyntaxKind::*;
    // STAR / SLASH operators work the same as PLUS / MINUS.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  10*2/4 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let amts: Vec<SyntaxNode> = ps[0].children().filter(|n| n.kind() == AMOUNT).collect();
    assert_eq!(amts.len(), 1);
    assert_eq!(
        elements_of(&amts[0]),
        tok_seq(&[NUMBER, STAR, NUMBER, SLASH, NUMBER, WHITESPACE, CURRENCY]),
    );
}

#[test]
fn amount_wraps_nested_parens_via_depth_tracking() {
    use SyntaxKind::*;
    // `((1+2))` — nested parens. emit_amount_operand tracks depth
    // so the inner R_PAREN doesn't prematurely close the outer.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  ((1+2)) USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let amts: Vec<SyntaxNode> = ps[0].children().filter(|n| n.kind() == AMOUNT).collect();
    assert_eq!(amts.len(), 1);
    assert_eq!(
        elements_of(&amts[0]),
        tok_seq(&[
            L_PAREN, L_PAREN, NUMBER, PLUS, NUMBER, R_PAREN, R_PAREN, WHITESPACE, CURRENCY
        ]),
    );
}

#[test]
fn amount_wraps_real_corpus_arithmetic_shape() {
    use SyntaxKind::*;
    // The canonical real-corpus shape `NUMBER WS STAR WS NUMBER
    // WS CURRENCY` (`700.00 * 0.1 BRL`) — appears in 6+ files in
    // `tests/compatibility/files/apyb-financeiro/`. Pins the
    // exact multi-space-around-STAR pattern that drives the
    // manifest churn from this PR; the other arithmetic tests
    // cover synthetic shapes.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Bancos:BB  700.00 * 0.1 BRL\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let amts: Vec<SyntaxNode> = ps[0].children().filter(|n| n.kind() == AMOUNT).collect();
    assert_eq!(amts.len(), 1);
    assert_eq!(
        elements_of(&amts[0]),
        tok_seq(&[
            NUMBER, WHITESPACE, STAR, WHITESPACE, NUMBER, WHITESPACE, CURRENCY
        ]),
    );
}

#[test]
fn price_annotation_inner_amount_wraps_arithmetic() {
    use SyntaxKind::*;
    // `@ 5+1 USD` — the per-unit price is itself an arithmetic
    // expression. emit_price_annotation delegates to emit_amount,
    // so the inner AMOUNT should wrap the whole expression as one
    // node. Pinned because no corpus file currently exercises
    // arithmetic in PRICE_ANNOTATION; without a test, a future
    // refactor that special-cases the inner-amount path would
    // silently regress without manifest signal.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  10 HOOL @ 5+1 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    let prices: Vec<SyntaxNode> = ps[0]
        .children()
        .filter(|n| n.kind() == PRICE_ANNOTATION)
        .collect();
    assert_eq!(prices.len(), 1);
    let inner_amount = prices[0].children().find(|n| n.kind() == AMOUNT).unwrap();
    assert_eq!(
        elements_of(&inner_amount),
        tok_seq(&[NUMBER, PLUS, NUMBER, WHITESPACE, CURRENCY]),
    );
}

#[test]
fn amount_with_unclosed_paren_at_newline_stops_per_rule_5() {
    use SyntaxKind::*;
    // Rule 5 (unterminated final content) extends to paren
    // expressions inside AMOUNT: when an unclosed `(` hits NEWLINE,
    // emit_amount_operand stops emitting and the AMOUNT closes
    // with depth>0 (no R_PAREN child). The NEWLINE goes back to
    // the surrounding scope (POSTING line terminator). Pins the
    // exact tree shape so a future refactor that changes the stop
    // condition is a visible, intentional break.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  (10+5 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 1);
    let amts: Vec<SyntaxNode> = ps[0].children().filter(|n| n.kind() == AMOUNT).collect();
    assert_eq!(amts.len(), 1);
    // AMOUNT contains the open paren and its consumed-before-
    // NEWLINE content; NO R_PAREN child.
    let kinds: Vec<SyntaxKind> = elements_of(&amts[0])
        .iter()
        .filter_map(|e| match e {
            Element::Tok(k) => Some(*k),
            Element::Node(_) => None,
        })
        .collect();
    assert!(kinds.contains(&L_PAREN));
    assert!(!kinds.contains(&R_PAREN));
    // POSTING's NEWLINE terminator is OUTSIDE the AMOUNT (sibling).
    let posting_kids = elements_of(&ps[0]);
    let newline_after_amount = posting_kids
        .iter()
        .position(|e| matches!(e, Element::Tok(NEWLINE)));
    let amount_idx = posting_kids
        .iter()
        .position(|e| matches!(e, Element::Node(AMOUNT)))
        .unwrap();
    assert!(
        newline_after_amount.is_some_and(|n| n > amount_idx),
        "NEWLINE terminator follows the AMOUNT, not consumed inside it",
    );
}

#[test]
fn mixed_shape_sibling_postings_each_wrap_their_own_amount_or_not() {
    use SyntaxKind::*;
    // Three postings in one transaction with different shapes:
    // auto (no amount), basic (NUMBER + CURRENCY), full (with
    // COST_SPEC and PRICE_ANNOTATION). Pins that emit_posting_line
    // re-initializes its state for each posting line and doesn't
    // leak an open AMOUNT / COST_SPEC scope across siblings.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash\n\
                  \x20\x20Assets:Bank  -5.00 USD\n\
                  \x20\x20Income:Misc  10 HOOL {500.00 USD} @ 510.00 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ps = postings(&tree);
    assert_eq!(ps.len(), 3);

    // First: auto posting, no AMOUNT.
    let p0_amounts = ps[0].children().filter(|n| n.kind() == AMOUNT).count();
    let p0_costs = ps[0].children().filter(|n| n.kind() == COST_SPEC).count();
    let p0_prices = ps[0]
        .children()
        .filter(|n| n.kind() == PRICE_ANNOTATION)
        .count();
    assert_eq!(p0_amounts, 0);
    assert_eq!(p0_costs, 0);
    assert_eq!(p0_prices, 0);

    // Second: basic posting, one AMOUNT, no COST_SPEC / PRICE.
    let p1_amounts = ps[1].children().filter(|n| n.kind() == AMOUNT).count();
    let p1_costs = ps[1].children().filter(|n| n.kind() == COST_SPEC).count();
    let p1_prices = ps[1]
        .children()
        .filter(|n| n.kind() == PRICE_ANNOTATION)
        .count();
    assert_eq!(p1_amounts, 1);
    assert_eq!(p1_costs, 0);
    assert_eq!(p1_prices, 0);

    // Third: full posting, one of each.
    let p2_amounts = ps[2].children().filter(|n| n.kind() == AMOUNT).count();
    let p2_costs = ps[2].children().filter(|n| n.kind() == COST_SPEC).count();
    let p2_prices = ps[2]
        .children()
        .filter(|n| n.kind() == PRICE_ANNOTATION)
        .count();
    assert_eq!(p2_amounts, 1);
    assert_eq!(p2_costs, 1);
    assert_eq!(p2_prices, 1);
}

#[test]
fn commodity_with_metadata_wraps_full_multi_line_directive() {
    use SyntaxKind::*;
    // Per cst::trivia, a directive that carries indented metadata
    // sub-lines spans MULTIPLE LINES — the directive's last content
    // token is the last content token of its LAST sub-line, not
    // the header. The COMMODITY_DIRECTIVE node must therefore span
    // the header AND the metadata line.
    let source = "2024-01-01 commodity HOOL\n  name: \"Hooli Common shares.\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), COMMODITY_DIRECTIVE);
    // PR 2.2a: the metadata sub-line is now wrapped in META_ENTRY.
    // The directive owns the header tokens followed by the
    // META_ENTRY node (which contains the indented metadata's
    // tokens internally).
    assert_eq!(
        elements_of(&ds[0]),
        vec![
            Element::Tok(DATE),
            Element::Tok(WHITESPACE),
            Element::Tok(COMMODITY_KW),
            Element::Tok(WHITESPACE),
            Element::Tok(CURRENCY),
            Element::Tok(NEWLINE),
            Element::Node(META_ENTRY),
        ],
    );

    // Drill into the META_ENTRY: it owns the indent + key +
    // value tokens + terminator NEWLINE.
    let me = ds[0]
        .children()
        .find(|n| n.kind() == META_ENTRY)
        .expect("directive contains a META_ENTRY child");
    assert_eq!(
        elements_of(&me),
        tok_seq(&[WHITESPACE, META_KEY, WHITESPACE, STRING, NEWLINE]),
    );

    // SOURCE_FILE owns ONLY the directive — no orphaned metadata.
    assert_eq!(elements_of(&tree), vec![Element::Node(COMMODITY_DIRECTIVE)]);
}

#[test]
fn open_with_multiple_metadata_lines_wraps_all_inside_directive() {
    use SyntaxKind::*;
    let source = "2024-01-01 open Assets:Cash USD\n\
                  \x20\x20description: \"main checking\"\n\
                  \x20\x20priority: \"high\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), OPEN_DIRECTIVE);
    // OPEN_DIRECTIVE node should contain header + BOTH metadata
    // lines (no orphaned content under SOURCE_FILE).
    assert_eq!(elements_of(&tree), vec![Element::Node(OPEN_DIRECTIVE)]);
}

#[test]
fn directive_with_metadata_then_next_directive() {
    use SyntaxKind::*;
    // After a metadata-carrying directive, the next directive
    // starts cleanly — the metadata-loop must stop when the indent
    // pattern ends.
    let source = "2024-01-01 open Assets:Cash USD\n\
                  \x20\x20description: \"main\"\n\
                  2024-01-02 close Assets:Cash\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 2);
    assert_eq!(ds[0].kind(), OPEN_DIRECTIVE);
    assert_eq!(ds[1].kind(), CLOSE_DIRECTIVE);
}

#[test]
fn indented_comment_after_no_metadata_directive_leads_next_directive() {
    use SyntaxKind::*;
    // An indented comment AFTER a directive that has no metadata
    // is inter-directive trivia per rule 2 — it leads the NEXT
    // directive, NOT trailing into the previous one. The widening
    // of is_indented_directive_continuation must be gated on a
    // prior META_KEY in the body; otherwise this comment is
    // wrongly absorbed into the preceding directive.
    let source = "2024-01-01 open Assets:Cash\n\
                  \x20\x20; documentation for the next directive\n\
                  2024-01-02 close Assets:Cash\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 2);
    assert_eq!(ds[0].kind(), OPEN_DIRECTIVE);
    assert_eq!(ds[1].kind(), CLOSE_DIRECTIVE);

    // d1 OWNS its header NEWLINE only — no trailing trivia.
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[DATE, WHITESPACE, OPEN_KW, WHITESPACE, ACCOUNT, NEWLINE]),
        "rule 2: indented comment after header-only directive must NOT be absorbed; \
         it's inter-directive trivia leading the next directive",
    );

    // d2 leads with the indented comment + its NEWLINE.
    let d2_first = elements_of(&ds[1])
        .iter()
        .take_while(|e| !matches!(e, Element::Tok(DATE)))
        .copied()
        .collect::<Vec<_>>();
    assert_eq!(
        d2_first,
        tok_seq(&[WHITESPACE, COMMENT, NEWLINE]),
        "rule 2: leading trivia of d2 must include the inter-directive comment",
    );
}

#[test]
fn indented_comment_at_eof_after_no_metadata_directive_is_file_trailing() {
    use SyntaxKind::*;
    // An indented comment at EOF following a header-only directive
    // is file-trailing trivia per rule 4 — it attaches to
    // SOURCE_FILE, NOT inside the directive. v3's overbroad
    // widening incorrectly absorbed this; the META_KEY gate
    // restores rule 4 conformance.
    let source = "2024-01-01 open Assets:Cash\n\
                  \x20\x20; trailing indented comment\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[DATE, WHITESPACE, OPEN_KW, WHITESPACE, ACCOUNT, NEWLINE]),
        "directive owns ONLY its header + terminator NEWLINE",
    );

    // SOURCE_FILE owns the trailing WS + COMMENT + NEWLINE.
    assert_eq!(
        elements_of(&tree),
        vec![
            Element::Node(OPEN_DIRECTIVE),
            Element::Tok(WHITESPACE),
            Element::Tok(COMMENT),
            Element::Tok(NEWLINE),
        ],
        "rule 4: indented trailing comment is file-trailing under SOURCE_FILE",
    );
}

#[test]
fn indented_comment_before_first_metadata_stays_inside_directive() {
    use SyntaxKind::*;
    // The "documentation-comment-for-the-following-field" idiom
    // — an indented `;` line BEFORE the first META_KEY. v4's per-
    // line `body_has_meta` couldn't see the META_KEY that came
    // after the comment, so v4 silently closed the directive at
    // the comment and orphaned the metadata. v5's prospective
    // upcoming_indented_block_has_meta scan catches it.
    let source = "2024-01-01 open Assets:Cash\n\
                  \x20\x20; documentation for the next field\n\
                  \x20\x20description: \"main checking\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), OPEN_DIRECTIVE);
    // The OPEN_DIRECTIVE owns the entire input — header, the
    // documentation comment, AND the metadata line. SOURCE_FILE
    // has no orphaned children.
    assert_eq!(elements_of(&tree), vec![Element::Node(OPEN_DIRECTIVE)]);
    // Specifically: NO bare META_KEY appears as a direct child of
    // SOURCE_FILE (would mean the v4 orphaning regression).
    let sf_token_kinds: Vec<SyntaxKind> = elements_of(&tree)
        .iter()
        .filter_map(|e| match e {
            Element::Tok(k) => Some(*k),
            Element::Node(_) => None,
        })
        .collect();
    assert!(
        !sf_token_kinds.contains(&META_KEY),
        "META_KEY orphaned to SOURCE_FILE: {sf_token_kinds:?}",
    );
}

#[test]
fn indented_comment_between_metadata_lines_stays_inside_directive() {
    use SyntaxKind::*;
    // Beancount idiom: documentation comments between metadata
    // entries. They MUST stay inside the directive — otherwise the
    // metadata that follows is orphaned to SOURCE_FILE, losing
    // structural ownership and producing a tree where bare
    // META_KEY tokens sit directly under SOURCE_FILE.
    let source = "2024-01-01 open Assets:Cash\n\
                  \x20\x20k1: \"v1\"\n\
                  \x20\x20; doc comment for k2\n\
                  \x20\x20k2: \"v2\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), OPEN_DIRECTIVE);
    // The entire multi-line body — header + k1 + indented comment
    // + k2 — must be inside the OPEN_DIRECTIVE. SOURCE_FILE owns
    // ONLY the directive node.
    assert_eq!(elements_of(&tree), vec![Element::Node(OPEN_DIRECTIVE)]);
    // Specifically: no META_KEY appears as a direct child of
    // SOURCE_FILE (would mean orphaning).
    let sf_children: Vec<SyntaxKind> = elements_of(&tree)
        .iter()
        .filter_map(|e| match e {
            Element::Tok(k) => Some(*k),
            Element::Node(_) => None,
        })
        .collect();
    assert!(
        !sf_children.contains(&META_KEY),
        "META_KEY orphaned to SOURCE_FILE: {sf_children:?}",
    );
}

#[test]
fn blank_line_between_metadata_lines_terminates_directive() {
    use SyntaxKind::*;
    // A blank line breaks the indented-metadata run; the second
    // metadata line is NOT part of the same directive. Conservative
    // interpretation: stop at the first non-indented-meta line.
    let source = "2024-01-01 open Assets:Cash USD\n\
                  \x20\x20description: \"main\"\n\
                  \n\
                  2024-01-02 close Assets:Cash\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 2);
    assert_eq!(ds[0].kind(), OPEN_DIRECTIVE);
    assert_eq!(ds[1].kind(), CLOSE_DIRECTIVE);
    // The blank-line NEWLINE leads d2 per rule 2.
    let d2_first = elements_of(&ds[1]).first().copied();
    assert_eq!(d2_first, Some(Element::Tok(NEWLINE)));
}

#[test]
fn malformed_date_then_keyword_on_next_line_is_not_a_directive() {
    // Beancount directive headers are single-line: `DATE keyword
    // ...` on ONE line. If a DATE is followed by a NEWLINE (then
    // a keyword on the next line), the identifier MUST NOT
    // recognize it as a directive — otherwise emit_through_terminator
    // would stop at the first NEWLINE and produce a node
    // containing only `[DATE, NEWLINE]`, orphaning the keyword.
    let source = "2024-01-01\nopen Assets:Cash\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);
    // Neither line is a recognized directive — both pass through
    // flat.
    let ds = directives(&tree);
    assert!(
        ds.is_empty(),
        "DATE alone on a line is malformed; identifier must not pretend it starts an OPEN_DIRECTIVE just because the next non-trivia token (skipping the NEWLINE) happens to be OPEN_KW",
    );
}

#[test]
fn recognized_and_passthrough_can_coexist() {
    use SyntaxKind::*;
    // All four directive shapes recognized: OPTION (PR 2.3),
    // OPEN, TRANSACTION (PR 2.1b), CLOSE. Pure-passthrough lines
    // (error-recovery shapes) are now exceptional.
    let source = "option \"title\" \"My Ledger\"\n\
                  2024-01-01 open Assets:Cash\n\
                  2024-01-15 * \"Coffee\"\n\
                  2024-01-16 close Assets:Cash\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 4);
    assert_eq!(ds[0].kind(), OPTION_DIRECTIVE);
    assert_eq!(ds[1].kind(), OPEN_DIRECTIVE);
    assert_eq!(ds[2].kind(), TRANSACTION);
    assert_eq!(ds[3].kind(), CLOSE_DIRECTIVE);
}

// ---------- Phase 2.3: edge directives (OPTION / INCLUDE / PLUGIN / CUSTOM) ----------

#[test]
fn option_directive() {
    use SyntaxKind::*;
    let source = "option \"title\" \"My Ledger\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), OPTION_DIRECTIVE);
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[OPTION_KW, WHITESPACE, STRING, WHITESPACE, STRING, NEWLINE]),
    );
}

#[test]
fn include_directive() {
    use SyntaxKind::*;
    let source = "include \"shared/2024.beancount\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), INCLUDE_DIRECTIVE);
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[INCLUDE_KW, WHITESPACE, STRING, NEWLINE]),
    );
}

#[test]
fn plugin_directive_without_config() {
    use SyntaxKind::*;
    // Plugin without config string: just `plugin "module"`.
    let source = "plugin \"beancount.plugins.implicit_prices\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), PLUGIN_DIRECTIVE);
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[PLUGIN_KW, WHITESPACE, STRING, NEWLINE]),
    );
}

#[test]
fn plugin_directive_with_config_string() {
    use SyntaxKind::*;
    // Plugin with optional config string: `plugin "module" "config"`.
    let source = "plugin \"my.plugin\" \"{\\\"key\\\": 42}\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), PLUGIN_DIRECTIVE);
    assert_eq!(
        elements_of(&ds[0]),
        tok_seq(&[PLUGIN_KW, WHITESPACE, STRING, WHITESPACE, STRING, NEWLINE]),
    );
}

#[test]
fn custom_directive_with_string_values() {
    use SyntaxKind::*;
    // CUSTOM with a type name string + arbitrary string values.
    let source = "2024-01-01 custom \"budget\" \"Food\" \"500 USD\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), CUSTOM_DIRECTIVE);
    // Header tokens: DATE WS CUSTOM_KW WS STRING WS STRING WS STRING NEWLINE.
    let kinds: Vec<SyntaxKind> = elements_of(&ds[0])
        .iter()
        .filter_map(|e| match e {
            Element::Tok(k) => Some(*k),
            Element::Node(_) => None,
        })
        .collect();
    assert!(kinds.contains(&DATE));
    assert!(kinds.contains(&CUSTOM_KW));
    assert_eq!(kinds.iter().filter(|&&k| k == STRING).count(), 3);
}

#[test]
fn custom_directive_with_mixed_value_types() {
    use SyntaxKind::*;
    // CUSTOM accepts a heterogeneous trailing value list: STRING,
    // ACCOUNT, NUMBER + CURRENCY (amount), DATE, BOOL_TRUE /
    // BOOL_FALSE. All stay flat inside CUSTOM_DIRECTIVE (no AMOUNT
    // wrapper at the directive-header level per phase 2.2c scope).
    let source = "2024-01-01 custom \"limits\" \"cap\" Assets:Cash 500 USD 2024-12-31 TRUE\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), CUSTOM_DIRECTIVE);
    // No AMOUNT wrapper inside CUSTOM_DIRECTIVE (directive headers
    // emit flat — same as BALANCE / PRICE per
    // `balance_and_price_directive_header_amounts_stay_flat_not_wrapped`).
    let amount_count = ds[0].descendants().filter(|n| n.kind() == AMOUNT).count();
    assert_eq!(amount_count, 0);
}

#[test]
fn option_directive_with_metadata_wraps_multi_line() {
    use SyntaxKind::*;
    // Per the Directive-Terminator Rule (and PR 2.1a's body
    // shape), an OPTION_DIRECTIVE with trailing indented META_KEY
    // sub-lines spans multiple lines. The META_ENTRY wrapping
    // from PR 2.2a applies.
    let source = "option \"title\" \"My Ledger\"\n\
                  \x20\x20doc: \"primary file\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), OPTION_DIRECTIVE);
    let metas = ds[0]
        .descendants()
        .filter(|n| n.kind() == META_ENTRY)
        .count();
    assert_eq!(metas, 1);
}

#[test]
fn plugin_directive_terminates_at_next_top_level() {
    use SyntaxKind::*;
    // Adjacent top-level directives don't merge.
    let source = "plugin \"a\"\n\
                  include \"b.bean\"\n\
                  option \"c\" \"d\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 3);
    assert_eq!(ds[0].kind(), PLUGIN_DIRECTIVE);
    assert_eq!(ds[1].kind(), INCLUDE_DIRECTIVE);
    assert_eq!(ds[2].kind(), OPTION_DIRECTIVE);
}

#[test]
fn custom_directive_unterminated_at_eof_still_wraps_per_rule_5() {
    use SyntaxKind::*;
    // Rule 5: an unterminated CUSTOM directive at EOF (no final
    // newline) still gets wrapped — the directive simply has no
    // NEWLINE child.
    let source = "2024-01-01 custom \"type\" \"value\"";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), CUSTOM_DIRECTIVE);
    let has_trailing_newline = elements_of(&ds[0])
        .iter()
        .any(|e| matches!(e, Element::Tok(NEWLINE)));
    assert!(!has_trailing_newline);
}

#[test]
fn include_directive_with_metadata_wraps_multi_line() {
    use SyntaxKind::*;
    // The body / metadata code path is shared across all edge
    // directives; pinning INCLUDE-with-meta complements the
    // OPTION-with-meta test and guards against a future refactor
    // that special-cases dated vs keyword directives.
    let source = "include \"shared/2024.beancount\"\n\
                  \x20\x20note: \"shared accounts\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), INCLUDE_DIRECTIVE);
    let mes: Vec<SyntaxNode> = ds[0]
        .descendants()
        .filter(|n| n.kind() == META_ENTRY)
        .collect();
    assert_eq!(mes.len(), 1);
    // Pin full META_ENTRY shape so a regression that produces a
    // structurally-wrong META_ENTRY but the same count still fails.
    assert_eq!(
        elements_of(&mes[0]),
        tok_seq(&[WHITESPACE, META_KEY, WHITESPACE, STRING, NEWLINE]),
    );
}

#[test]
fn plugin_directive_with_metadata_wraps_multi_line() {
    use SyntaxKind::*;
    let source = "plugin \"my.plugin\" \"cfg\"\n\
                  \x20\x20tolerance: \"0.01\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), PLUGIN_DIRECTIVE);
    let mes: Vec<SyntaxNode> = ds[0]
        .descendants()
        .filter(|n| n.kind() == META_ENTRY)
        .collect();
    assert_eq!(mes.len(), 1);
    assert_eq!(
        elements_of(&mes[0]),
        tok_seq(&[WHITESPACE, META_KEY, WHITESPACE, STRING, NEWLINE]),
    );
}

#[test]
fn custom_directive_with_metadata_wraps_multi_line() {
    use SyntaxKind::*;
    let source = "2024-01-01 custom \"budget\" \"food\"\n\
                  \x20\x20source: \"manual\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), CUSTOM_DIRECTIVE);
    let mes: Vec<SyntaxNode> = ds[0]
        .descendants()
        .filter(|n| n.kind() == META_ENTRY)
        .collect();
    assert_eq!(mes.len(), 1);
    assert_eq!(
        elements_of(&mes[0]),
        tok_seq(&[WHITESPACE, META_KEY, WHITESPACE, STRING, NEWLINE]),
    );
}

/// For trailing-inline-comment tests: assert that a directive
/// contains exactly one COMMENT child AND that COMMENT appears
/// BEFORE the directive's NEWLINE terminator. Catches a
/// regression that reorders trailing tokens (e.g., closes the
/// directive before consuming the same-line comment, putting the
/// COMMENT logically after the terminator).
fn assert_directive_has_trailing_comment_before_newline(directive: &SyntaxNode) {
    use SyntaxKind::*;
    let kids = elements_of(directive);
    let comment_idx = kids
        .iter()
        .position(|e| matches!(e, Element::Tok(COMMENT)))
        .expect("directive must contain a COMMENT child");
    let newline_idx = kids
        .iter()
        .position(|e| matches!(e, Element::Tok(NEWLINE)))
        .expect("directive must contain its NEWLINE terminator");
    assert!(
        comment_idx < newline_idx,
        "trailing same-line COMMENT must precede the NEWLINE inside the directive",
    );
    let comment_count = kids
        .iter()
        .filter(|e| matches!(e, Element::Tok(COMMENT)))
        .count();
    assert_eq!(comment_count, 1);
}

#[test]
fn option_directive_with_trailing_inline_comment_attaches_inside() {
    use SyntaxKind::*;
    // Rule 1 of `cst::trivia`: a same-line trailing `;` comment
    // attaches INSIDE the directive. The body code path
    // (`emit_through_terminator`) handles this uniformly for all
    // directive shapes; pinning the four new kinds protects
    // against a regression that splits the path.
    let source = "option \"title\" \"My Ledger\" ; an explanation\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), OPTION_DIRECTIVE);
    assert_directive_has_trailing_comment_before_newline(&ds[0]);
}

#[test]
fn include_directive_with_trailing_inline_comment_attaches_inside() {
    use SyntaxKind::*;
    let source = "include \"shared.beancount\" ; main shared file\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), INCLUDE_DIRECTIVE);
    assert_directive_has_trailing_comment_before_newline(&ds[0]);
}

#[test]
fn plugin_directive_with_trailing_inline_comment_attaches_inside() {
    use SyntaxKind::*;
    let source = "plugin \"my.plugin\" ; description\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), PLUGIN_DIRECTIVE);
    assert_directive_has_trailing_comment_before_newline(&ds[0]);
}

#[test]
fn custom_directive_with_trailing_inline_comment_attaches_inside() {
    use SyntaxKind::*;
    let source = "2024-01-01 custom \"budget\" \"food\" ; monthly cap\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 1);
    assert_eq!(ds[0].kind(), CUSTOM_DIRECTIVE);
    assert_directive_has_trailing_comment_before_newline(&ds[0]);
}

#[test]
fn all_four_edge_directives_mixed_with_dated_directives() {
    use SyntaxKind::*;
    // Smoke test: all 4 new edge directives plus an OPEN and a
    // TRANSACTION in one source. Pins that CUSTOM (the only dated
    // edge directive — dispatched via the DATE-peek arm of
    // identify_directive) coexists cleanly with both keyword-head
    // edge directives and the legacy dated/standalone ones.
    let source = "option \"title\" \"X\"\n\
                  include \"shared.bean\"\n\
                  plugin \"my.plugin\"\n\
                  2024-01-01 open Assets:Cash\n\
                  2024-01-15 * \"tx\"\n\
                  \x20\x20Assets:Cash 1 USD\n\
                  2024-01-20 custom \"note\" \"end of test\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 6);
    assert_eq!(ds[0].kind(), OPTION_DIRECTIVE);
    assert_eq!(ds[1].kind(), INCLUDE_DIRECTIVE);
    assert_eq!(ds[2].kind(), PLUGIN_DIRECTIVE);
    assert_eq!(ds[3].kind(), OPEN_DIRECTIVE);
    assert_eq!(ds[4].kind(), TRANSACTION);
    assert_eq!(ds[5].kind(), CUSTOM_DIRECTIVE);
}

// ---------- Phase 2.4: ERROR_NODE wrapping ----------

/// Walk all `ERROR_NODE` descendants in source order.
fn error_nodes(node: &SyntaxNode) -> Vec<SyntaxNode> {
    node.descendants()
        .filter(|n| n.kind() == SyntaxKind::ERROR_NODE)
        .collect()
}

#[test]
fn unknown_keyword_line_wraps_in_error_node() {
    use SyntaxKind::*;
    // `bogus ...` is not a Beancount directive shape. PR 2.4 wraps
    // the whole line in an ERROR_NODE so downstream consumers can
    // identify malformed regions instead of having to scan flat
    // SOURCE_FILE children for stray content.
    let source = "bogus \"x\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let errs = error_nodes(&tree);
    assert_eq!(errs.len(), 1);
    // All tokens of the line live INSIDE the ERROR_NODE.
    let kinds: Vec<SyntaxKind> = elements_of(&errs[0])
        .iter()
        .filter_map(|e| match e {
            Element::Tok(k) => Some(*k),
            Element::Node(_) => None,
        })
        .collect();
    assert!(kinds.contains(&STRING));
    assert!(kinds.contains(&NEWLINE));
}

#[test]
fn unrecognized_dated_keyword_wraps_in_error_node() {
    // `2024-01-01 unknown ...` — DATE is recognized but the
    // following keyword isn't one of the dated-directive shapes
    // (open/close/balance/... or custom). identify_directive
    // returns None; the line wraps as ERROR_NODE.
    let source = "2024-01-01 zzz \"data\"\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let errs = error_nodes(&tree);
    assert_eq!(errs.len(), 1);
    let ds = directives(&tree);
    assert_eq!(ds.len(), 0, "no real directive recognized");
}

#[test]
fn error_node_coexists_with_recognized_directives() {
    use SyntaxKind::*;
    // ERROR_NODEs sit alongside recognized directives at
    // SOURCE_FILE level. Trivia attachment follows the same rule
    // as recognized directives.
    let source = "option \"title\" \"X\"\n\
                  bogus line\n\
                  2024-01-01 open Assets:Cash\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let errs = error_nodes(&tree);
    assert_eq!(errs.len(), 1);
    let ds = directives(&tree);
    assert_eq!(ds.len(), 2);
    assert_eq!(ds[0].kind(), OPTION_DIRECTIVE);
    assert_eq!(ds[1].kind(), OPEN_DIRECTIVE);
}

#[test]
fn error_node_unterminated_at_eof_still_wraps_per_rule_5() {
    use SyntaxKind::*;
    // Rule 5: unterminated final line at EOF still wraps; the
    // ERROR_NODE simply has no NEWLINE child.
    let source = "bogus content without newline";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let errs = error_nodes(&tree);
    assert_eq!(errs.len(), 1);
    let has_newline = elements_of(&errs[0])
        .iter()
        .any(|e| matches!(e, Element::Tok(NEWLINE)));
    assert!(!has_newline);
}

#[test]
fn multiple_consecutive_error_lines_each_get_their_own_error_node() {
    // Two adjacent unrecognized lines produce TWO ERROR_NODE
    // siblings (one per line), mirroring how adjacent recognized
    // directives stay as separate sibling nodes.
    let source = "bogus one\n\
                  zzz two\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let errs = error_nodes(&tree);
    assert_eq!(errs.len(), 2);
}

#[test]
fn error_node_leading_trivia_attaches_inside_per_rule_2() {
    use SyntaxKind::*;
    // Per rule 2, leading trivia (the blank-line NEWLINE between
    // two top-level items) attaches as LEADING content INSIDE the
    // FOLLOWING node — same rule for ERROR_NODE as for recognized
    // directives.
    let source = "2024-01-01 open Assets:Cash\n\
                  \n\
                  bogus content\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let errs = error_nodes(&tree);
    assert_eq!(errs.len(), 1);
    // ERROR_NODE's first child is the blank-line NEWLINE that
    // serves as its leading trivia.
    let first = elements_of(&errs[0]).first().copied();
    assert_eq!(first, Some(Element::Tok(NEWLINE)));
}

#[test]
fn error_node_adjacent_to_multi_line_transaction_doesnt_bleed() {
    use SyntaxKind::*;
    // Multi-line TRANSACTION coexistence: the transaction body
    // (header + posting lines) must terminate cleanly when the
    // next top-level line is unrecognized, so the unrecognized
    // line wraps as its own ERROR_NODE without being absorbed
    // into the transaction. emit_transaction_body's stop
    // condition is non-indented top-level content; a regression
    // there could silently merge an ERROR_NODE line into the
    // preceding transaction.
    let source = "2024-01-15 * \"x\"\n\
                  \x20\x20Assets:Cash  -5 USD\n\
                  \x20\x20Expenses:Food  5 USD\n\
                  bogus content here\n\
                  2024-01-16 * \"y\"\n\
                  \x20\x20Assets:Cash  -3 USD\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    let ds = directives(&tree);
    assert_eq!(ds.len(), 2);
    assert_eq!(ds[0].kind(), TRANSACTION);
    assert_eq!(ds[1].kind(), TRANSACTION);

    let errs = error_nodes(&tree);
    assert_eq!(
        errs.len(),
        1,
        "exactly one ERROR_NODE between the two transactions"
    );

    // The ERROR_NODE is a direct sibling of TRANSACTION under
    // SOURCE_FILE, NOT nested inside either transaction.
    let tx_inner_errors = ds[0]
        .descendants()
        .filter(|n| n.kind() == ERROR_NODE)
        .count()
        + ds[1]
            .descendants()
            .filter(|n| n.kind() == ERROR_NODE)
            .count();
    assert_eq!(tx_inner_errors, 0);

    // Both transactions retain their full posting count.
    let p0_count = ds[0].descendants().filter(|n| n.kind() == POSTING).count();
    let p1_count = ds[1].descendants().filter(|n| n.kind() == POSTING).count();
    assert_eq!(p0_count, 2);
    assert_eq!(p1_count, 1);
}

// ---------- Edge cases ----------

#[test]
fn empty_source() {
    let tree = parse_structured("");
    assert_round_trip("", &tree);
    assert_eq!(tree.kind(), SyntaxKind::SOURCE_FILE);
    assert!(directives(&tree).is_empty());
}

#[test]
fn only_trivia_no_directives() {
    use SyntaxKind::*;
    let source = ";; only a comment\n\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    assert!(directives(&tree).is_empty());
    // All under SOURCE_FILE.
    assert_eq!(
        elements_of(&tree),
        vec![
            Element::Tok(COMMENT),
            Element::Tok(NEWLINE),
            Element::Tok(NEWLINE)
        ],
    );
}

#[test]
fn bom_under_source_file_directive_follows() {
    use SyntaxKind::*;
    let source = "\u{FEFF}2024-01-01 open Assets:Cash\n";
    let tree = parse_structured(source);
    assert_round_trip(source, &tree);

    // BOM is file-leading; first directive comes after.
    assert_eq!(
        elements_of(&tree),
        vec![Element::Tok(BOM), Element::Node(OPEN_DIRECTIVE)],
    );
}