doppio 1.0.0

A typed compiler pipeline for plain-text Ledger accounting -- parse, resolve, and elaborate .ledger files with a library API built for programmatic use.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
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
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
//! Elaboration stage: evaluate expressions, balance transactions, and
//! produce the final serialisable [`Journal`].
//!
//! This stage converts a [`resolution::HIR`] into an [`elaborator::Journal`]
//! by performing the following work:
//!
//! - **Expression evaluation** -- [`ast::ValueExpr`] trees are evaluated to
//!   concrete `(Decimal, commodity)` pairs by the [`evaluator`] submodule.
//!   Commodity aliases from the active [`resolution::Context`] are applied.
//!
//! - **Transaction balancing** -- if a transaction has exactly one posting with
//!   no explicit amount (a "null posting"), its amount is inferred as the
//!   negation of all other postings' sum. If all postings have amounts their
//!   sum must be zero; otherwise [`ElaborationError::TransactionDoesNotBalance`]
//!   is returned.
//!
//! - **Balance assertions / assignments** -- `= expected` checks are verified
//!   against the running account balance. `= target` assignments set the
//!   posting amount to `target − current_balance`.
//!
//! - **Lot pricing** -- `@ unit` and `@@ total` cost annotations are converted
//!   into a cash amount in the lot's commodity for the purpose of balancing.
//!
//! - **Account registration** -- every account mentioned in a posting is added
//!   to [`Journal::accounts`], merging any properties declared in `account`
//!   directives.

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

use rust_decimal::Decimal;

use crate::{
    ast::{self, AmountDetails, ValueExpr},
    resolution,
};

/// Per-account running balance, used during elaboration to evaluate balance
/// assertions and the `account()` expression function.
#[derive(Default, Clone, Debug)]
struct AccountBalances {
    /// The balance for each commodity held in this account.
    commodity: BTreeMap<String, Decimal>,
}

/// Mutable state threaded through the elaboration of all transactions.
///
/// Account balances are updated as each transaction is processed so that
/// balance assertions and the `account()` function see the balance *before*
/// the current posting is applied (which matches ledger-cli semantics).
#[derive(Default, Clone, Debug)]
struct RunningState {
    account_balances: BTreeMap<String, AccountBalances>,
}

/// A commodity name (e.g. `"USD"`, `"BTC"`, `"$"`).
pub type Commodity = String;

/// A multi-commodity amount: a map from commodity symbol to a `Decimal` value.
#[derive(Default, Debug)]
pub struct Amount(pub BTreeMap<Commodity, Decimal>);

/// Cleared/pending state of a resolved transaction or posting.
#[derive(Debug)]
pub enum TransactionState {
    /// No state marker.
    Uncleared,
    /// `!` -- pending confirmation.
    Pending,
    /// `*` -- confirmed / reconciled.
    Cleared,
}

impl From<ast::TransactionState> for TransactionState {
    fn from(f: ast::TransactionState) -> TransactionState {
        match f {
            ast::TransactionState::Uncleared => TransactionState::Uncleared,
            ast::TransactionState::Pending => TransactionState::Pending,
            ast::TransactionState::Cleared => TransactionState::Cleared,
        }
    }
}

/// Errors that can occur during the elaboration stage.
#[derive(Debug)]
pub enum ElaborationError {
    /// A posting amount evaluated to a bare number with no commodity, and no
    /// default commodity was set in the active context.
    AmountWithNoCommodity,
    /// A value expression evaluated to a non-amount type (e.g. a string or
    /// object) where an amount was expected.
    NonAmountWhereAmountExpected(ValueExpr),
    /// An error from the expression evaluator.
    EvaluationError(EvaluationError),
    /// A `= expected` balance assertion on a posting failed: the account's
    /// balance after this posting does not equal the asserted value.
    PostingBalanceAssertionFailed,
    /// A standalone balance assertion directive failed: the account's balance
    /// at the assertion's position in the file does not match the expected
    /// amount.
    BalanceAssertionFailed {
        /// The account whose balance was asserted.
        account: String,
        /// The date of the assertion directive.
        date: chrono::NaiveDate,
        /// The amount the assertion expected.
        expected_amount: Decimal,
        /// The commodity of the expected amount.
        expected_commodity: String,
        /// The actual balance of the account in that commodity.
        actual_amount: Decimal,
    },
    /// A transaction has more than one null posting (only one is allowed, since
    /// multiple unknowns cannot be uniquely determined).
    TooManyNullPostings,
    /// All postings have explicit amounts but they do not sum to zero.
    TransactionDoesNotBalance(Amount),
    /// An `assert` expression on an account directive evaluated to `false`
    /// for a posting to that account.
    AccountAssertionFailed {
        /// The account whose assertion fired.
        account: String,
        /// Zero-based index of the posting within the transaction.
        posting_index: usize,
        /// A rendered form of the failing expression (for diagnostics).
        ///
        /// Produced via the AST's `Display` impl, so formatting may be
        /// normalized (e.g. whitespace, `$500` rendered as `500 $`) and may
        /// not byte-match the original source text.
        expression: String,
    },
    /// A `tag` directive `assert` expression evaluated to `false` for a
    /// `; TagName: value` metadata pair on a transaction or posting.
    TagAssertionFailed {
        /// The tag name whose assertion fired (e.g. `"Statement"`).
        tag_name: String,
        /// The metadata value that failed the assertion (e.g. `"foo/bar"`).
        tag_value: String,
        /// A rendered form of the failing expression (for diagnostics).
        expression: String,
    },
}

/// Error produced when evaluating a value expression (e.g., an amount or
/// balance assertion expression) fails.
///
/// This error is always wrapped in [`ElaborationError::EvaluationError`]; it
/// is unlikely to be matched directly by callers.
#[derive(Debug)]
pub enum EvaluationError {
    /// `*` or `/` used as a unary prefix operator, which is not meaningful.
    UnaryMultiplyOrDivide,
    /// A unary operator was applied to a non-amount value (e.g. a string).
    UnaryOnNonAmount(ValueExpr),
    /// A binary operator was applied to incompatible types or mismatched
    /// commodities (e.g. `USD + EUR`).
    BinaryOperationTypeError((ValueExpr, ValueExpr, crate::ast::Op)),
    /// Field access on an object referenced a field that does not exist.
    NoSuchField(String),
    /// Field access was attempted on a non-object value.
    FieldAccessTypeError(ValueExpr),
    /// A function call with unrecognised name or argument count.
    UnknownFunctionArgs((String, Vec<ValueExpr>)),
    /// A `Typed` annotation specified a commodity that is incompatible with
    /// the inner expression's commodity.
    TypedCommodityToIncompatibleAmount((String, ValueExpr)),
    /// A function received an argument of the wrong type.
    InvalidFunctionArgs((String, ValueExpr)),
    /// A regex literal could not be compiled.
    ///
    /// Carries the offending pattern string and the error message from the
    /// `regex` crate. Using `String` rather than `regex::Error` keeps this
    /// error type free of a public dependency on the `regex` crate.
    InvalidRegexPattern(String, String),
    /// A define with a boolean body was called from a value expression context.
    ///
    /// Boolean defines (e.g. `define pos(x) = x > 0`) may only be used where a
    /// `bool_expr` is expected (e.g. inside an `assert` directive), not as part
    /// of an arithmetic expression.
    BoolDefineInValueContext(String),
    /// A parameterized define was called with the wrong number of arguments.
    DefineArgCountMismatch {
        /// The define name.
        name: String,
        /// Number of parameters the define declares.
        expected: usize,
        /// Number of arguments provided at the call site.
        got: usize,
    },
    /// Expression evaluation exceeded the recursion limit. The most common
    /// cause is mutually-recursive defines, e.g. `define a = b; define b = a`.
    RecursionLimitExceeded,
}

impl Display for EvaluationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EvaluationError::UnaryMultiplyOrDivide => {
                write!(f, "* and / cannot be used as unary prefix operators")
            }
            EvaluationError::UnaryOnNonAmount(val) => {
                write!(f, "unary operator applied to non-amount value: {val:?}")
            }
            EvaluationError::BinaryOperationTypeError((lhs, rhs, op)) => {
                write!(f, "binary operation type mismatch: {lhs:?} {op:?} {rhs:?}")
            }
            EvaluationError::NoSuchField(field) => {
                write!(f, "no such field: {field}")
            }
            EvaluationError::FieldAccessTypeError(val) => {
                write!(f, "field access on non-object value: {val:?}")
            }
            EvaluationError::UnknownFunctionArgs((name, args)) => {
                write!(
                    f,
                    "unknown function or wrong argument count: {name}({args:?})"
                )
            }
            EvaluationError::TypedCommodityToIncompatibleAmount((commodity, val)) => {
                write!(
                    f,
                    "commodity annotation '{commodity}' is incompatible with value: {val:?}"
                )
            }
            EvaluationError::InvalidFunctionArgs((name, arg)) => {
                write!(f, "invalid argument to function {name}: {arg:?}")
            }
            EvaluationError::InvalidRegexPattern(pattern, err) => {
                write!(f, "invalid regex pattern /{pattern}/: {err}")
            }
            EvaluationError::BoolDefineInValueContext(name) => {
                write!(
                    f,
                    "define '{name}' has a boolean body and cannot be used in a value expression"
                )
            }
            EvaluationError::DefineArgCountMismatch {
                name,
                expected,
                got,
            } => {
                write!(
                    f,
                    "define '{name}' expects {expected} argument(s), got {got}"
                )
            }
            EvaluationError::RecursionLimitExceeded => {
                write!(
                    f,
                    "expression evaluation exceeded recursion limit (likely a cyclic `define`)"
                )
            }
        }
    }
}

impl From<EvaluationError> for ElaborationError {
    fn from(e: EvaluationError) -> ElaborationError {
        ElaborationError::EvaluationError(e)
    }
}

impl std::error::Error for ElaborationError {}

impl Display for ElaborationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ElaborationError::AmountWithNoCommodity => {
                write!(f, "amount has no commodity and no default commodity is set")
            }
            ElaborationError::NonAmountWhereAmountExpected(expr) => {
                write!(f, "expected an amount but got: {expr:?}")
            }
            ElaborationError::EvaluationError(e) => {
                write!(f, "evaluation error: {e}")
            }
            ElaborationError::PostingBalanceAssertionFailed => {
                write!(f, "posting balance assertion failed")
            }
            ElaborationError::BalanceAssertionFailed {
                account,
                date,
                expected_amount,
                expected_commodity,
                actual_amount,
            } => {
                write!(
                    f,
                    "balance assertion failed for account {account} on {date}: \
                     expected {expected_amount} {expected_commodity}, \
                     actual {actual_amount} {expected_commodity}"
                )
            }
            ElaborationError::AccountAssertionFailed {
                account,
                posting_index,
                expression,
            } => {
                write!(
                    f,
                    "account assertion failed for posting {posting_index} to {account}: \
                     assert {expression}"
                )
            }
            ElaborationError::TooManyNullPostings => {
                write!(f, "transaction has more than one null posting")
            }
            ElaborationError::TransactionDoesNotBalance(_) => {
                write!(f, "transaction does not balance")
            }
            ElaborationError::TagAssertionFailed {
                tag_name,
                tag_value,
                expression,
            } => {
                write!(
                    f,
                    "tag assertion failed for {tag_name}: \"{tag_value}\": assert {expression}"
                )
            }
        }
    }
}

impl TryFrom<resolution::HIR> for crate::elaboration::Journal {
    type Error = ElaborationError;

    fn try_from(value: resolution::HIR) -> Result<Self, Self::Error> {
        let mut state = RunningState::default();

        let mut transactions = vec![];

        // Pre-populate the accounts map from directives so that accounts
        // declared with notes but never posted to still appear in the output.
        // Metadata is denormalised after the entry loop -- see end of fn.
        let mut accounts = BTreeMap::new();
        for (name, properties) in &value.global_context.account_properties {
            accounts.insert(
                name.clone(),
                crate::elaboration::AccountProperties {
                    note: properties.note.clone(),
                    metadata: properties
                        .metadata
                        .iter()
                        .map(|(k, v)| (k.clone(), v.clone()))
                        .collect(),
                },
            );
        }

        for entry in value.entries {
            let entry_context = &value.contexts[entry.context_id];
            match entry.data {
                resolution::Entry::Assertion(assertion) => {
                    // Evaluate the expected amount expression.
                    let (expected_amount, expected_commodity) =
                        evaluator::eval_and_normalize_amount(
                            assertion.amount,
                            entry_context,
                            &state,
                        )?;

                    // Look up the account's current balance for this commodity.
                    let actual_amount = state
                        .account_balances
                        .get(&assertion.account)
                        .and_then(|ab| ab.commodity.get(&expected_commodity))
                        .copied()
                        .unwrap_or(Decimal::ZERO);

                    // NOTE: strict (`==`) is currently treated identically to
                    // weak (`=`). Both check that the account balance for the
                    // specified commodity matches exactly. A future enhancement
                    // could make strict assertions also verify that the account
                    // holds no *other* commodities.
                    let _ = assertion.strict;

                    if actual_amount != expected_amount {
                        return Err(ElaborationError::BalanceAssertionFailed {
                            account: assertion.account,
                            date: assertion.date,
                            expected_amount,
                            expected_commodity,
                            actual_amount,
                        });
                    }
                }
                resolution::Entry::Transaction(mut transaction) => {
                    // `transaction_state` accumulates the running sum of all
                    // explicit posting amounts (per commodity) for balancing.
                    let mut transaction_state = Amount(BTreeMap::default());

                    // Prefer an explicit "payee:" metadata key; fall back to
                    // the transaction description as the default payee.
                    let payee = transaction
                        .metadata
                        .remove("payee")
                        .unwrap_or_else(|| transaction.description.clone());

                    // Two-pass approach: first evaluate all postings that have
                    // explicit amounts, accumulating the running sum. Null
                    // postings are collected for the second pass, where the
                    // single allowed null posting is filled in as the negation
                    // of the total.
                    let mut null_postings = vec![];
                    let mut resolved_postings = vec![];

                    for mut posting in transaction.postings {
                        let posting_kind = posting.kind;
                        if let Some(amount) = posting.amount {
                            let account_name = entry_context
                                .account_aliases
                                .get(&posting.account)
                                .cloned()
                                .unwrap_or(posting.account);
                            let account_balance = state.account_balances.get(&account_name);
                            // `lot_cash` -- the (total, commodity) pair to use for
                            // transaction balancing, along with the elaborated
                            // lot annotation for the proto output.
                            let (value, commodity, lot_cash, proto_lot) = match amount {
                                AmountDetails::Amount {
                                    value,
                                    lot_annotation,
                                    lot_pricing,
                                    balance_assertion,
                                } => {
                                    let (value, commodity) = evaluator::eval_and_normalize_amount(
                                        value,
                                        entry_context,
                                        &state,
                                    )?;

                                    // Evaluate the optional lot annotation (cost/date/note).
                                    // Preserved on the proto Posting regardless of which
                                    // path drives the cash balance.
                                    //
                                    // `cost_for_balance`: the evaluated (per_unit_cost,
                                    // cost_commodity) pair, kept separate so the
                                    // cash-balance fallback path can use it without
                                    // re-parsing the proto Amount.
                                    let (proto_lot, cost_for_balance) =
                                        if let Some(ann) = lot_annotation {
                                            let epoch = chrono::NaiveDate::from_ymd_opt(1970, 1, 1)
                                                .expect("epoch is valid");
                                            let proto_date =
                                                ann.date.map(|d| (d - epoch).num_days() as i32);
                                            let (proto_cost, cost_pair) =
                                                if let Some(cost_expr) = ann.cost {
                                                    let (cv, cc) =
                                                        evaluator::eval_and_normalize_amount(
                                                            cost_expr,
                                                            entry_context,
                                                            &state,
                                                        )?;
                                                    let proto_amount = crate::elaboration::Amount {
                                                        by_commodity: BTreeMap::from([(
                                                            cc.clone(),
                                                            crate::decimal_to_proto(cv),
                                                        )]),
                                                    };
                                                    (Some(proto_amount), Some((cv, cc)))
                                                } else {
                                                    (None, None)
                                                };
                                            let lot = crate::elaboration::Lot {
                                                cost: proto_cost,
                                                date: proto_date,
                                                note: ann.note,
                                            };
                                            (Some(lot), cost_pair)
                                        } else {
                                            (None, None)
                                        };

                                    // Cash-contribution priority:
                                    // 1. lot_pricing (@/@@) present  -> price drives cash (unchanged)
                                    // 2. lot_annotation.cost present -> quantity * cost_per_unit
                                    // 3. otherwise                   -> value contributes in its own
                                    //                                  commodity (today's fallback)
                                    let lot_cash = match lot_pricing {
                                        Some(ast::LotPricing::Total(expr)) => {
                                            let (mut v, c) = evaluator::eval_and_normalize_amount(
                                                expr,
                                                entry_context,
                                                &state,
                                            )?;
                                            // For a negative lot (selling), negate the cash total
                                            // so that it offsets correctly in transaction_state.
                                            if value.is_sign_negative() {
                                                v = -v;
                                            }
                                            Some((v, c))
                                        }
                                        Some(ast::LotPricing::Unit(expr)) => {
                                            // "@ unit_price" -- total cash = units * price
                                            let (v, c) = evaluator::eval_and_normalize_amount(
                                                expr,
                                                entry_context,
                                                &state,
                                            )?;
                                            Some((v * value, c))
                                        }
                                        None => {
                                            // No @/@@. If cost annotation is present, it drives
                                            // the cash balance: total = quantity * cost_per_unit.
                                            cost_for_balance.map(|(cv, cc)| (value * cv, cc))
                                        }
                                    };

                                    if let Some(balance_assertion) = balance_assertion {
                                        let (baval, bacommodity) =
                                            evaluator::eval_and_normalize_amount(
                                                balance_assertion,
                                                entry_context,
                                                &state,
                                            )?;
                                        // Assertion: current_balance + this_posting == expected.
                                        // The assertion is checked BEFORE the posting updates the
                                        // running state, so `account_balance` reflects the balance
                                        // *before* this posting -- consistent with ledger-cli.
                                        if !(bacommodity == commodity
                                            && account_balance
                                                .and_then(|ab| ab.commodity.get(&commodity))
                                                .unwrap_or(&Decimal::ZERO)
                                                + value
                                                == baval)
                                        {
                                            Err(ElaborationError::PostingBalanceAssertionFailed)?;
                                        }
                                    }
                                    (value, commodity, lot_cash, proto_lot)
                                }
                                AmountDetails::BalanceAssignment(assignment) => {
                                    // "= target_balance" -- compute the delta needed to reach the
                                    // target from the current running balance.
                                    //
                                    // If the assignment expression is bare (no commodity), try to
                                    // infer the commodity from, in order of preference:
                                    //   1. The account's existing running balance (single
                                    //      non-zero commodity) -- most common case.
                                    //   2. Other postings already processed in the current
                                    //      transaction (single commodity) -- covers e.g. bank
                                    //      imports that write `Income:Salary  =0` after a
                                    //      $-bearing `Assets:Checking` posting.
                                    // Running balances are never pruned, so we filter zero
                                    // entries to avoid stale `$=0` entries making a
                                    // single-commodity account look multi-commodity.
                                    let from_account = account_balance.and_then(|ab| {
                                        let mut non_zero = ab
                                            .commodity
                                            .iter()
                                            .filter(|(_, v)| !v.is_zero())
                                            .map(|(k, _)| k.as_str());
                                        let first = non_zero.next()?;
                                        non_zero.next().is_none().then_some(first)
                                    });
                                    let from_transaction = || {
                                        let mut keys = transaction_state.0.keys();
                                        let first = keys.next()?;
                                        keys.next().is_none().then_some(first.as_str())
                                    };
                                    let inferred_commodity = from_account.or_else(from_transaction);
                                    let (newsum, commodity) =
                                        evaluator::eval_and_normalize_amount_with_fallback(
                                            assignment,
                                            entry_context,
                                            &state,
                                            inferred_commodity,
                                        )?;
                                    let value = newsum
                                        - account_balance
                                            .and_then(|ab| ab.commodity.get(&commodity))
                                            .unwrap_or(&Decimal::ZERO);
                                    (value, commodity, None, None)
                                }
                            };
                            let payee = posting.metadata.remove("payee").unwrap_or(payee.clone());

                            // Virtual-unbalanced postings are excluded from the transaction's
                            // balance check. Real and virtual-balanced postings both contribute.
                            // For lot-priced postings, add the *cash* total (in the lot's
                            // commodity) to transaction_state rather than the commodity units.
                            if posting_kind != ast::PostingKind::VirtualUnbalanced {
                                if let Some((lot_total, lot_commodity)) = lot_cash {
                                    let dec = transaction_state.0.entry(lot_commodity).or_default();
                                    *dec += lot_total;
                                } else {
                                    let dec =
                                        transaction_state.0.entry(commodity.clone()).or_default();
                                    *dec += value;
                                }
                            }

                            let by_commodity =
                                BTreeMap::from([(commodity, crate::decimal_to_proto(value))]);
                            resolved_postings.push(crate::elaboration::Posting {
                                account: account_name,
                                payee,
                                amount: Some(crate::elaboration::Amount { by_commodity }),
                                state: crate::state_to_proto(&posting.state.into()),
                                tags: posting.tags,
                                metadata: posting.metadata,
                                kind: crate::posting_kind_to_proto(posting_kind),
                                lot: proto_lot,
                            });
                        } else {
                            // Defer processing and save for next step.
                            // (Null postings are always REAL -- you cannot write a null virtual
                            // posting, so the kind is left as the default Real from the parser.)
                            null_postings.push(posting);
                        }
                    }

                    if null_postings.len() > 1 {
                        return Err(ElaborationError::TooManyNullPostings);
                    }

                    if let Some(mut posting) = null_postings.pop() {
                        let account_name = entry_context
                            .account_aliases
                            .get(&posting.account)
                            .cloned()
                            .unwrap_or(posting.account);
                        let payee = posting.metadata.remove("payee").unwrap_or(payee.clone());

                        // The null posting's amount is the negation of the sum of all
                        // other real/balanced postings (virtual-unbalanced postings are
                        // excluded from transaction_state, so they don't affect inference).
                        // Null postings are always REAL; the kind field is left unspecified
                        // (defaults to 0 = UNSPECIFIED which is treated as REAL by consumers).
                        let by_commodity = transaction_state
                            .0
                            .iter()
                            .map(|(c, v)| (c.clone(), crate::decimal_to_proto(-v)))
                            .collect();

                        resolved_postings.push(crate::elaboration::Posting {
                            account: account_name,
                            payee,
                            amount: Some(crate::elaboration::Amount { by_commodity }),
                            state: crate::state_to_proto(&posting.state.into()),
                            tags: posting.tags,
                            metadata: posting.metadata,
                            kind: crate::posting_kind_to_proto(ast::PostingKind::Real),
                            lot: None,
                        });
                    } else {
                        // Check that transaction state is all zeros to balance the transaction.
                        // Virtual-unbalanced postings have already been excluded from
                        // transaction_state, so a transaction consisting solely of
                        // virtual-unbalanced postings will have an empty (zero) state and
                        // will not trigger this error -- which is the correct ledger-cli behaviour.
                        if transaction_state.0.values().any(|value| !value.is_zero()) {
                            return Err(ElaborationError::TransactionDoesNotBalance(
                                transaction_state,
                            ));
                        }
                    }

                    // Evaluate account-level assert/check directives for each posting.
                    //
                    // `tag()` lookups inherit transaction-level metadata: a
                    // posting with no `; Entity: ...` of its own still sees the
                    // transaction's `Entity` tag (matching OG ledger-cli
                    // semantics). Posting-level metadata wins on key collision.
                    for (posting_index, posting) in resolved_postings.iter().enumerate() {
                        if let Some(props) = value
                            .global_context
                            .account_properties
                            .get(&posting.account)
                        {
                            let merged_metadata =
                                merge_metadata(&transaction.metadata, &posting.metadata);
                            // Assertions and checks operate per-commodity. For
                            // multi-commodity postings each commodity is checked
                            // independently; in practice postings carry a single
                            // commodity.
                            for (commodity, amount_val) in posting.amounts() {
                                for assert_expr in &props.asserts {
                                    let passed = evaluator::eval_bool_expr(
                                        assert_expr,
                                        amount_val,
                                        commodity,
                                        &merged_metadata,
                                        entry_context,
                                        &state,
                                    )
                                    .map_err(ElaborationError::EvaluationError)?;
                                    if !passed {
                                        return Err(ElaborationError::AccountAssertionFailed {
                                            account: posting.account.clone(),
                                            posting_index,
                                            expression: assert_expr.to_string(),
                                        });
                                    }
                                }
                                for check_expr in &props.checks {
                                    let passed = evaluator::eval_bool_expr(
                                        check_expr,
                                        amount_val,
                                        commodity,
                                        &merged_metadata,
                                        entry_context,
                                        &state,
                                    )
                                    .map_err(ElaborationError::EvaluationError)?;
                                    if !passed {
                                        eprintln!(
                                            "warning: check failed for posting {posting_index} \
                                             to {account}: check {expr}",
                                            account = posting.account,
                                            expr = check_expr,
                                        );
                                    }
                                }
                            }
                        }
                    }

                    // Evaluate tag-level assert/check directives.
                    //
                    // Only metadata-style tags (`; TagName: value`) are validated.
                    // Bare colon-tags (e.g. `; :payroll:`) carry no value and are
                    // skipped. Validation applies to both transaction-level metadata
                    // and posting-level metadata for parity with account assertions.

                    // Validate transaction-level metadata tags.
                    eval_tag_metadata(
                        &transaction.metadata,
                        &value.global_context.tag_properties,
                        entry_context,
                        &state,
                    )?;

                    // Validate posting-level metadata tags.
                    for posting in resolved_postings.iter() {
                        eval_tag_metadata(
                            &posting.metadata,
                            &value.global_context.tag_properties,
                            entry_context,
                            &state,
                        )?;
                    }

                    // Update running account balances and register new accounts.
                    // Virtual unbalanced postings DO update the running per-account
                    // balance (matching ledger-cli) so subsequent balance assertions
                    // on the same account see the virtual contribution. They are
                    // excluded only from the transaction-balance check.
                    for posting in resolved_postings.iter() {
                        if !accounts.contains_key(&posting.account) {
                            accounts.insert(posting.account.clone(), Default::default());
                        }

                        let balances = state
                            .account_balances
                            .entry(posting.account.clone())
                            .or_default();
                        for (commodity, delta) in posting.amounts() {
                            *(balances.commodity.entry(commodity.to_string()).or_default()) +=
                                delta;
                        }
                    }

                    transactions.push(crate::elaboration::Transaction {
                        date: transaction.date.to_epoch_days(),
                        secondary_date: transaction.secondary_date.map(|d| d.to_epoch_days()),
                        state: crate::state_to_proto(&transaction.state.into()),
                        code: transaction.code,
                        description: transaction.description,
                        tags: transaction.tags,
                        metadata: transaction.metadata,
                        postings: resolved_postings,
                    });
                }
            }
        }

        // Evaluate each historical price expression using the final (most
        // recent) context, which reflects all directives seen in the file.
        let final_context = value
            .contexts
            .last()
            .expect("HIR always has at least one context");
        let mut prices = vec![];
        for hp in value.prices {
            let (price, price_commodity) =
                evaluator::eval_and_normalize_amount(hp.price, final_context, &state)?;
            prices.push(crate::elaboration::HistoricalPrice {
                date: hp.date.to_epoch_days(),
                time: hp.time,
                commodity: hp.commodity,
                price: Some(crate::decimal_to_proto(price)),
                price_commodity,
            });
        }

        let commodities = value
            .global_context
            .commodity_properties
            .into_iter()
            .map(|(name, p)| {
                (
                    name,
                    crate::elaboration::CommodityProperties {
                        format: p.format,
                        no_market: p.no_market,
                        note: p.note,
                    },
                )
            })
            .collect();

        // Denormalise account metadata by inheritance. For every account
        // in the journal (declared OR only referenced by postings), walk
        // its colon-separated ancestor chain root->leaf, merging in any
        // metadata declared on each ancestor's own `account` directive.
        // Closer ancestors override more distant ones; the account's own
        // declared metadata wins last. Consumers thus see a fully
        // resolved metadata map per account and never need to do the
        // inheritance walk themselves.
        let declared_metadata: BTreeMap<&str, &BTreeMap<String, String>> = value
            .global_context
            .account_properties
            .iter()
            .map(|(name, props)| (name.as_str(), &props.metadata))
            .collect();
        let account_names: Vec<String> = accounts.keys().cloned().collect();
        for name in account_names {
            let mut inherited: BTreeMap<String, String> = BTreeMap::new();
            for prefix in ancestor_prefixes(&name) {
                if let Some(parent_meta) = declared_metadata.get(prefix.as_str()) {
                    for (k, v) in *parent_meta {
                        inherited.insert(k.clone(), v.clone());
                    }
                }
            }
            // `inherited` now holds the merged ancestor metadata in
            // root-->-leaf order (closer wins). For declared accounts
            // their own metadata was the last entry written, so we are
            // already correct. For undeclared accounts (referenced only
            // by postings) `inherited` is purely from ancestors. Either
            // way, overwrite the field.
            if let Some(props) = accounts.get_mut(&name) {
                props.metadata = inherited;
            }
        }

        Ok(crate::elaboration::Journal {
            transactions,
            accounts,
            commodities,
            prices,
        })
    }
}

/// Yield the colon-separated ancestor prefixes of `name`, root first,
/// `name` itself last. So `"Income:Salary:Base"` yields
/// `["Income", "Income:Salary", "Income:Salary:Base"]`.
fn ancestor_prefixes(name: &str) -> Vec<String> {
    let mut prefixes = Vec::new();
    for (i, _) in name.match_indices(':') {
        prefixes.push(name[..i].to_string());
    }
    prefixes.push(name.to_string());
    prefixes
}

/// Evaluate tag-level assert/check directives for a set of metadata key-value pairs.
///
/// For each `(tag_name, tag_value)` pair in `metadata`, looks up `tag_name` in
/// Merge transaction-level metadata with posting-level metadata, with the
/// posting's own keys taking precedence. Used when evaluating per-posting
/// `tag()` lookups so that `; Entity: foo` declared at the transaction level
/// is visible to assertions on every posting in that transaction (matching
/// OG ledger-cli semantics).
fn merge_metadata(
    transaction: &BTreeMap<String, String>,
    posting: &BTreeMap<String, String>,
) -> BTreeMap<String, String> {
    let mut merged = transaction.clone();
    for (k, v) in posting {
        merged.insert(k.clone(), v.clone());
    }
    merged
}

/// `tag_properties`. If validation rules are found, runs each assert and check
/// with `value` bound to `tag_value` in the expression context.
///
/// - Failed asserts return `Err(ElaborationError::TagAssertionFailed)`.
/// - Failed checks print a warning to stderr but return `Ok(())`.
fn eval_tag_metadata(
    metadata: &BTreeMap<String, String>,
    tag_properties: &BTreeMap<String, resolution::TagProperties>,
    eval_context: &resolution::Context,
    state: &RunningState,
) -> Result<(), ElaborationError> {
    for (tag_name, tag_value) in metadata {
        if let Some(props) = tag_properties.get(tag_name) {
            for assert_expr in &props.asserts {
                let passed =
                    evaluator::eval_bool_expr_for_tag(assert_expr, tag_value, eval_context, state)
                        .map_err(ElaborationError::EvaluationError)?;
                if !passed {
                    return Err(ElaborationError::TagAssertionFailed {
                        tag_name: tag_name.clone(),
                        tag_value: tag_value.clone(),
                        expression: assert_expr.to_string(),
                    });
                }
            }
            for check_expr in &props.checks {
                let passed =
                    evaluator::eval_bool_expr_for_tag(check_expr, tag_value, eval_context, state)
                        .map_err(ElaborationError::EvaluationError)?;
                if !passed {
                    eprintln!(
                        "warning: tag check failed for {tag_name}: \"{tag_value}\": \
                         check {check_expr}",
                    );
                }
            }
        }
    }
    Ok(())
}

/// Expression evaluator: reduces [`ast::ValueExpr`] trees to concrete values.
mod evaluator {
    use std::collections::BTreeMap;

    use regex::Regex;
    use rust_decimal::Decimal;

    use crate::{
        ast::{self, BoolExpr, CmpOp, ValueExpr},
        resolution,
    };

    use super::{ElaborationError, EvaluationError, RunningState};

    /// Evaluate a value expression and extract the `(Decimal, commodity)` pair.
    ///
    /// After evaluation, commodity aliases from `eval_context` are applied so
    /// that e.g. `"Bitcoin"` becomes `"BTC"`. If the result still has no
    /// commodity, the context's `default_commodity` is used. Returns an error
    /// if the result is not an amount or no commodity can be determined.
    pub fn eval_and_normalize_amount(
        val: ast::ValueExpr,
        eval_context: &resolution::Context,
        running_state: &RunningState,
    ) -> Result<(Decimal, String), ElaborationError> {
        eval_and_normalize_amount_with_fallback(val, eval_context, running_state, None)
    }

    /// Like [`eval_and_normalize_amount`], but accepts an optional `fallback_commodity`
    /// that is used when the expression is bare (no commodity) and the context has no
    /// default commodity set. This is used by balance assignments to infer the commodity
    /// from the account's existing running balance.
    pub fn eval_and_normalize_amount_with_fallback(
        val: ast::ValueExpr,
        eval_context: &resolution::Context,
        running_state: &RunningState,
        fallback_commodity: Option<&str>,
    ) -> Result<(Decimal, String), ElaborationError> {
        // Amount expressions don't involve posting metadata (tags); pass an
        // empty map so the `tag()` built-in is a no-op when called from amount
        // contexts (which would be a programmer error, but we don't panic).
        let empty_meta = BTreeMap::default();
        match eval(val, eval_context, running_state, &empty_meta, EVAL_BUDGET)? {
            ast::ValueExpr::Amount { value, commodity } => {
                let commodity = if let Some(commodity) = commodity {
                    // Apply commodity alias (e.g. "Bitcoin" -> "BTC")
                    eval_context
                        .commodity_aliases
                        .get(&commodity)
                        .unwrap_or(&commodity)
                        .clone()
                } else {
                    // No commodity in the expression -- try context default, then
                    // the caller-supplied fallback (e.g. inferred from account balance).
                    eval_context
                        .default_commodity
                        .as_deref()
                        .or(fallback_commodity)
                        .ok_or(ElaborationError::AmountWithNoCommodity)?
                        .to_owned()
                };
                Ok((value, commodity))
            }
            val => Err(ElaborationError::NonAmountWhereAmountExpected(val)),
        }
    }

    /// Evaluate a [`BoolExpr`] in the context of a posting.
    ///
    /// `posting_amount` and `posting_commodity` are bound as `amount` and
    /// `commodity` in the expression context, which is how account assertions
    /// refer to the current posting's values.
    ///
    /// `posting_metadata` provides the key-value tag pairs from the posting's
    /// notes (e.g. `; Entity: Foo` -> `{"Entity": "Foo"}`). This is used by
    /// the `tag("name")` built-in to look up metadata values.
    ///
    /// Returns `true` if the assertion passes, `false` if it fails, or an
    /// error if expression evaluation itself fails.
    pub fn eval_bool_expr(
        expr: &BoolExpr,
        posting_amount: Decimal,
        posting_commodity: &str,
        posting_metadata: &BTreeMap<String, String>,
        eval_context: &resolution::Context,
        state: &RunningState,
    ) -> Result<bool, EvaluationError> {
        // Build a temporary context with `amount` and `commodity` injected as
        // zero-parameter defines so the evaluator can resolve them.
        let mut ctx = eval_context.clone();
        ctx.defines.insert(
            "amount".into(),
            resolution::Define {
                params: vec![],
                body: ast::DefineBody::Value(ast::ValueExpr::Amount {
                    value: posting_amount,
                    commodity: Some(posting_commodity.to_string()),
                }),
            },
        );
        ctx.defines.insert(
            "commodity".into(),
            resolution::Define {
                params: vec![],
                body: ast::DefineBody::Value(ast::ValueExpr::Str(posting_commodity.to_string())),
            },
        );

        // Check whether the LHS is a call to a bool-body define. If it is and
        // there is no comparison operator, we expand the define body as a full
        // bool expression rather than treating the call result as a numeric value.
        if expr.cmp.is_none()
            && let ast::ValueExpr::Function { name, args } = &expr.lhs
            && let Some(define) = ctx.defines.get(name.as_str())
            && let ast::DefineBody::Bool(body) = define.body.clone()
        {
            if define.params.len() != args.len() {
                return Err(EvaluationError::DefineArgCountMismatch {
                    name: name.clone(),
                    expected: define.params.len(),
                    got: args.len(),
                });
            }
            // Bind arguments into a new context and evaluate the bool body.
            let mut call_ctx = ctx.clone();
            for (param, arg_expr) in define.params.iter().zip(args.iter()) {
                let arg_val = eval(arg_expr.clone(), &ctx, state, posting_metadata, EVAL_BUDGET)?;
                call_ctx.defines.insert(
                    param.clone(),
                    resolution::Define {
                        params: vec![],
                        body: ast::DefineBody::Value(arg_val),
                    },
                );
            }
            // Evaluate the define's bool body, then apply any chain.
            let segment_result = eval_bool_expr_with_context(
                &body,
                posting_amount,
                posting_commodity,
                posting_metadata,
                &call_ctx,
                state,
            )?;
            return match &expr.chain {
                None => Ok(segment_result),
                Some((ast::BoolOp::And, cont)) => {
                    if !segment_result {
                        Ok(false)
                    } else {
                        eval_bool_expr(
                            cont,
                            posting_amount,
                            posting_commodity,
                            posting_metadata,
                            eval_context,
                            state,
                        )
                    }
                }
                Some((ast::BoolOp::Or, cont)) => {
                    if segment_result {
                        Ok(true)
                    } else {
                        eval_bool_expr(
                            cont,
                            posting_amount,
                            posting_commodity,
                            posting_metadata,
                            eval_context,
                            state,
                        )
                    }
                }
            };
        }

        // Evaluate LHS.
        let lhs_val = eval(expr.lhs.clone(), &ctx, state, posting_metadata, EVAL_BUDGET)?;

        // Compute this segment's boolean value. With no comparison operator,
        // the expression is truthy iff the LHS evaluates to a non-zero amount
        // (unusual but consistent). Either way, an `expr.chain` continuation
        // must still be evaluated below.
        let result = match &expr.cmp {
            None => match lhs_val {
                ast::ValueExpr::Amount { value, .. } => !value.is_zero(),
                _ => false,
            },
            Some((cmp_op, rhs_expr)) => {
                // For regex comparisons the RHS is already a Regex literal in
                // the AST -- pass it through to eval_cmp without re-evaluating.
                let rhs_val = match rhs_expr {
                    ast::ValueExpr::Regex(_) => rhs_expr.clone(),
                    other => eval(other.clone(), &ctx, state, posting_metadata, EVAL_BUDGET)?,
                };
                eval_cmp(cmp_op, &lhs_val, &rhs_val)?
            }
        };

        // If there is a boolean chain, short-circuit accordingly.
        match &expr.chain {
            None => Ok(result),
            Some((ast::BoolOp::And, cont)) => {
                if !result {
                    Ok(false)
                } else {
                    eval_bool_expr(
                        cont,
                        posting_amount,
                        posting_commodity,
                        posting_metadata,
                        eval_context,
                        state,
                    )
                }
            }
            Some((ast::BoolOp::Or, cont)) => {
                if result {
                    Ok(true)
                } else {
                    eval_bool_expr(
                        cont,
                        posting_amount,
                        posting_commodity,
                        posting_metadata,
                        eval_context,
                        state,
                    )
                }
            }
        }
    }

    /// Evaluate a [`BoolExpr`] using a pre-built context that already has
    /// parameter bindings in place.
    ///
    /// This is the inner workhorse used when expanding a bool-body define call:
    /// the caller has already bound the define's parameters as zero-param value
    /// defines in `eval_context`, so we evaluate the body without re-injecting
    /// `amount`/`commodity` (they are already in the context or in `eval_context`).
    // posting_amount and posting_commodity are forwarded through recursive calls
    // to eval_bool_expr (for chains); they are not used directly in the body.
    #[allow(clippy::only_used_in_recursion)]
    fn eval_bool_expr_with_context(
        expr: &BoolExpr,
        posting_amount: Decimal,
        posting_commodity: &str,
        posting_metadata: &BTreeMap<String, String>,
        eval_context: &resolution::Context,
        state: &RunningState,
    ) -> Result<bool, EvaluationError> {
        // Check for a bool-body define call in the LHS (recursive define calls).
        if expr.cmp.is_none()
            && let ast::ValueExpr::Function { name, args } = &expr.lhs
            && let Some(define) = eval_context.defines.get(name.as_str())
            && let ast::DefineBody::Bool(body) = define.body.clone()
        {
            if define.params.len() != args.len() {
                return Err(EvaluationError::DefineArgCountMismatch {
                    name: name.clone(),
                    expected: define.params.len(),
                    got: args.len(),
                });
            }
            let mut call_ctx = eval_context.clone();
            for (param, arg_expr) in define.params.iter().zip(args.iter()) {
                let arg_val = eval(
                    arg_expr.clone(),
                    eval_context,
                    state,
                    posting_metadata,
                    EVAL_BUDGET,
                )?;
                call_ctx.defines.insert(
                    param.clone(),
                    resolution::Define {
                        params: vec![],
                        body: ast::DefineBody::Value(arg_val),
                    },
                );
            }
            let segment_result = eval_bool_expr_with_context(
                &body,
                posting_amount,
                posting_commodity,
                posting_metadata,
                &call_ctx,
                state,
            )?;
            return match &expr.chain {
                None => Ok(segment_result),
                Some((ast::BoolOp::And, cont)) => {
                    if !segment_result {
                        Ok(false)
                    } else {
                        eval_bool_expr_with_context(
                            cont,
                            posting_amount,
                            posting_commodity,
                            posting_metadata,
                            eval_context,
                            state,
                        )
                    }
                }
                Some((ast::BoolOp::Or, cont)) => {
                    if segment_result {
                        Ok(true)
                    } else {
                        eval_bool_expr_with_context(
                            cont,
                            posting_amount,
                            posting_commodity,
                            posting_metadata,
                            eval_context,
                            state,
                        )
                    }
                }
            };
        }

        let lhs_val = eval(
            expr.lhs.clone(),
            eval_context,
            state,
            posting_metadata,
            EVAL_BUDGET,
        )?;
        let result = match &expr.cmp {
            None => match lhs_val {
                ast::ValueExpr::Amount { value, .. } => !value.is_zero(),
                _ => false,
            },
            Some((cmp_op, rhs_expr)) => {
                let rhs_val = match rhs_expr {
                    ast::ValueExpr::Regex(_) => rhs_expr.clone(),
                    other => eval(
                        other.clone(),
                        eval_context,
                        state,
                        posting_metadata,
                        EVAL_BUDGET,
                    )?,
                };
                eval_cmp(cmp_op, &lhs_val, &rhs_val)?
            }
        };

        match &expr.chain {
            None => Ok(result),
            Some((ast::BoolOp::And, cont)) => {
                if !result {
                    Ok(false)
                } else {
                    eval_bool_expr_with_context(
                        cont,
                        posting_amount,
                        posting_commodity,
                        posting_metadata,
                        eval_context,
                        state,
                    )
                }
            }
            Some((ast::BoolOp::Or, cont)) => {
                if result {
                    Ok(true)
                } else {
                    eval_bool_expr_with_context(
                        cont,
                        posting_amount,
                        posting_commodity,
                        posting_metadata,
                        eval_context,
                        state,
                    )
                }
            }
        }
    }

    /// Evaluate a [`BoolExpr`] in the context of a tag metadata value.
    ///
    /// `tag_value` is bound as `value` (a `Str`) in the expression context.
    /// This is the mechanism used by `tag` directive `assert`/`check` bodies
    /// to refer to the metadata value, e.g. `value =~ /^foo/`.
    ///
    /// Tag assertions have no associated posting amount or commodity, so those
    /// bindings are not injected. The `tag()` built-in is available but looks
    /// up from an empty metadata map (tag assertions are about the tag value
    /// itself, not about other metadata on the same entry).
    pub fn eval_bool_expr_for_tag(
        expr: &BoolExpr,
        tag_value: &str,
        eval_context: &resolution::Context,
        state: &RunningState,
    ) -> Result<bool, EvaluationError> {
        let empty_meta = BTreeMap::default();

        // Inject `value` as a Str binding so the expression can reference it.
        let mut ctx = eval_context.clone();
        ctx.defines.insert(
            "value".into(),
            resolution::Define {
                params: vec![],
                body: ast::DefineBody::Value(ast::ValueExpr::Str(tag_value.to_string())),
            },
        );

        let lhs_val = eval(expr.lhs.clone(), &ctx, state, &empty_meta, EVAL_BUDGET)?;

        let result = match &expr.cmp {
            None => match lhs_val {
                ast::ValueExpr::Amount { value, .. } => !value.is_zero(),
                _ => false,
            },
            Some((cmp_op, rhs_expr)) => {
                let rhs_val = match rhs_expr {
                    ast::ValueExpr::Regex(_) => rhs_expr.clone(),
                    other => eval(other.clone(), &ctx, state, &empty_meta, EVAL_BUDGET)?,
                };
                eval_cmp(cmp_op, &lhs_val, &rhs_val)?
            }
        };

        match &expr.chain {
            None => Ok(result),
            Some((ast::BoolOp::And, cont)) => {
                if !result {
                    Ok(false)
                } else {
                    eval_bool_expr_for_tag(cont, tag_value, eval_context, state)
                }
            }
            Some((ast::BoolOp::Or, cont)) => {
                if result {
                    Ok(true)
                } else {
                    eval_bool_expr_for_tag(cont, tag_value, eval_context, state)
                }
            }
        }
    }

    /// Compare two evaluated [`ast::ValueExpr`] values with a [`CmpOp`].
    ///
    /// Supported comparisons:
    /// - `Str == Str` / `Str != Str` -- commodity identity checks
    /// - `Str =~ Regex` / `Str !~ Regex` -- regex match against a string
    /// - `Amount cmp Amount` -- numeric comparisons (same or compatible commodities)
    ///
    /// Regex matching is case-sensitive by default (Rust `regex` crate semantics).
    /// Returns an error for type mismatches or an invalid regex pattern.
    fn eval_cmp(
        op: &CmpOp,
        lhs: &ast::ValueExpr,
        rhs: &ast::ValueExpr,
    ) -> Result<bool, EvaluationError> {
        match (lhs, rhs) {
            // Regex match: LHS must be a string, RHS must be a Regex literal.
            // Patterns are validated at parse time, so compilation here cannot
            // fail in well-formed input.
            (ast::ValueExpr::Str(text), ast::ValueExpr::Regex(pattern)) => {
                let re = Regex::new(pattern).map_err(|e| {
                    EvaluationError::InvalidRegexPattern(pattern.clone(), e.to_string())
                })?;
                // The only CmpOps valid with a Regex RHS are RegexMatch and
                // RegexNotMatch -- any other combination is a parser-level bug.
                Ok(match op {
                    CmpOp::RegexMatch => re.is_match(text),
                    CmpOp::RegexNotMatch => !re.is_match(text),
                    _ => unreachable!(
                        "parser should only produce RegexMatch/RegexNotMatch with a Regex RHS"
                    ),
                })
            }
            // String equality: used for `commodity == "$"`.
            (ast::ValueExpr::Str(a), ast::ValueExpr::Str(b)) => Ok(match op {
                CmpOp::Eq => a == b,
                CmpOp::Ne => a != b,
                _ => {
                    return Err(EvaluationError::BinaryOperationTypeError((
                        lhs.clone(),
                        rhs.clone(),
                        ast::Op::Add, // placeholder op; no ordering on strings
                    )));
                }
            }),
            // Numeric comparisons: used for `amount > 0`, etc.
            (
                ast::ValueExpr::Amount {
                    value: v1,
                    commodity: c1,
                },
                ast::ValueExpr::Amount {
                    value: v2,
                    commodity: c2,
                },
            ) if c1 == c2 || c1.is_none() || c2.is_none() => Ok(match op {
                CmpOp::Eq => v1 == v2,
                CmpOp::Ne => v1 != v2,
                CmpOp::Lt => v1 < v2,
                CmpOp::Le => v1 <= v2,
                CmpOp::Gt => v1 > v2,
                CmpOp::Ge => v1 >= v2,
                // Regex operators on amounts are a type error.
                CmpOp::RegexMatch | CmpOp::RegexNotMatch => {
                    return Err(EvaluationError::BinaryOperationTypeError((
                        lhs.clone(),
                        rhs.clone(),
                        ast::Op::Add,
                    )));
                }
            }),
            _ => Err(EvaluationError::BinaryOperationTypeError((
                lhs.clone(),
                rhs.clone(),
                ast::Op::Add,
            ))),
        }
    }

    /// Recursively evaluate a [`ast::ValueExpr`] to a simpler form.
    ///
    /// The evaluator reduces arithmetic, applies unary operators, resolves
    /// function calls, and handles type annotations. It does not resolve
    /// commodity aliases -- that is done by `eval_and_normalize_amount`.
    ///
    /// `posting_metadata` carries the key-value tag pairs from the posting's
    /// notes. It is forwarded into recursive calls and is read by the `tag()`
    /// built-in function.
    /// Initial recursion budget passed to [`eval`] by every external caller.
    /// Each recursive `eval` call decrements `budget`; `eval` errors with
    /// [`EvaluationError::RecursionLimitExceeded`] when it reaches 0. Protects
    /// against cyclic `define`s (e.g. `define a = b; define b = a`), which
    /// would otherwise recurse until the OS aborts the process with a stack
    /// overflow.
    ///
    /// 64 is well above any sane real-world expression depth and well below
    /// debug-build stack limits (debug frames are large).
    pub const EVAL_BUDGET: usize = 64;

    fn eval(
        val: ast::ValueExpr,
        eval_context: &resolution::Context,
        state: &RunningState,
        posting_metadata: &BTreeMap<String, String>,
        budget: usize,
    ) -> Result<ast::ValueExpr, EvaluationError> {
        let Some(budget) = budget.checked_sub(1) else {
            return Err(EvaluationError::RecursionLimitExceeded);
        };
        match val {
            // Base cases: already-reduced values pass through unchanged.
            a @ ast::ValueExpr::Amount { .. } => Ok(a),
            s @ ast::ValueExpr::Str(_) => Ok(s),
            r @ ast::ValueExpr::Regex(_) => Ok(r),
            o @ ast::ValueExpr::Object(_) => Ok(o),

            ast::ValueExpr::Unary { op, expr } => {
                match eval(*expr, eval_context, state, posting_metadata, budget)? {
                    ast::ValueExpr::Amount { value, commodity } => match op {
                        ast::Op::Sub => Ok(ast::ValueExpr::Amount {
                            value: -value,
                            commodity,
                        }),
                        ast::Op::Add => Ok(ast::ValueExpr::Amount { value, commodity }),
                        // Unary * and / are not defined for amounts.
                        _ => Err(EvaluationError::UnaryMultiplyOrDivide),
                    },
                    val => Err(EvaluationError::UnaryOnNonAmount(val)),
                }
            }

            ast::ValueExpr::Binary { lhs, rhs, op } => {
                match (
                    eval(*lhs, eval_context, state, posting_metadata, budget)?,
                    eval(*rhs, eval_context, state, posting_metadata, budget)?,
                ) {
                    // One side has a commodity, the other is dimensionless --
                    // the commodity propagates to the result. Both match arms
                    // handle the two orderings (commodity first or second).
                    (
                        ast::ValueExpr::Amount {
                            value: v1,
                            commodity: c,
                        },
                        ast::ValueExpr::Amount {
                            value: v2,
                            commodity: None,
                        },
                    )
                    | (
                        ast::ValueExpr::Amount {
                            value: v1,
                            commodity: None,
                        },
                        ast::ValueExpr::Amount {
                            value: v2,
                            commodity: c,
                        },
                    ) => Ok(match op {
                        ast::Op::Add => ast::ValueExpr::Amount {
                            value: v1 + v2,
                            commodity: c,
                        },
                        ast::Op::Sub => ast::ValueExpr::Amount {
                            value: v1 - v2,
                            commodity: c,
                        },
                        ast::Op::Mul => ast::ValueExpr::Amount {
                            value: v1 * v2,
                            commodity: c,
                        },
                        ast::Op::Div => ast::ValueExpr::Amount {
                            value: v1 / v2,
                            commodity: c,
                        },
                    }),

                    // Both sides have the same commodity -- straightforward arithmetic.
                    (
                        ast::ValueExpr::Amount {
                            value: v1,
                            commodity: c,
                        },
                        ast::ValueExpr::Amount {
                            value: v2,
                            commodity: c2,
                        },
                    ) if c == c2 => Ok(match op {
                        ast::Op::Add => ast::ValueExpr::Amount {
                            value: v1 + v2,
                            commodity: c,
                        },
                        ast::Op::Sub => ast::ValueExpr::Amount {
                            value: v1 - v2,
                            commodity: c,
                        },
                        ast::Op::Mul => ast::ValueExpr::Amount {
                            value: v1 * v2,
                            commodity: c,
                        },
                        ast::Op::Div => ast::ValueExpr::Amount {
                            value: v1 / v2,
                            commodity: c,
                        },
                    }),

                    // Special case: "$-123" parses as Commodity("$") sub Amount(123, None).
                    // The grammar sees the minus sign as a binary subtraction between the
                    // currency symbol and the following number because of how prefix_op and
                    // the amount rule interact. We handle it by treating Sub as negation.
                    (
                        ast::ValueExpr::Commodity(commodity),
                        ast::ValueExpr::Amount {
                            value,
                            commodity: None,
                        },
                    )
                    | (
                        ast::ValueExpr::Amount {
                            value,
                            commodity: None,
                        },
                        ast::ValueExpr::Commodity(commodity),
                    ) => match op {
                        ast::Op::Sub => Ok(ast::ValueExpr::Amount {
                            value: -value,
                            commodity: Some(commodity),
                        }),
                        ast::Op::Add => Ok(ast::ValueExpr::Amount {
                            value,
                            commodity: Some(commodity),
                        }),
                        _ => Err(EvaluationError::UnaryMultiplyOrDivide),
                    },

                    (a, b) => Err(EvaluationError::BinaryOperationTypeError((a, b, op))),
                }
            }

            ast::ValueExpr::Function { name, args } => {
                // Check user-defined parameterized macros before built-ins.
                if let Some(define) = eval_context.defines.get(name.as_str()) {
                    if define.params.len() != args.len() {
                        return Err(EvaluationError::DefineArgCountMismatch {
                            name: name.clone(),
                            expected: define.params.len(),
                            got: args.len(),
                        });
                    }
                    return match &define.body {
                        ast::DefineBody::Bool(_) => {
                            Err(EvaluationError::BoolDefineInValueContext(name.clone()))
                        }
                        ast::DefineBody::Value(body_expr) => {
                            // Evaluate arguments in the caller's context, then
                            // bind them by name in a temporary child context.
                            let mut ctx = eval_context.clone();
                            for (param, arg_expr) in define.params.iter().zip(args.iter()) {
                                let arg_val = eval(
                                    arg_expr.clone(),
                                    eval_context,
                                    state,
                                    posting_metadata,
                                    budget,
                                )?;
                                ctx.defines.insert(
                                    param.clone(),
                                    resolution::Define {
                                        params: vec![],
                                        body: ast::DefineBody::Value(arg_val),
                                    },
                                );
                            }
                            eval(body_expr.clone(), &ctx, state, posting_metadata, budget)
                        }
                    };
                }

                match (name.as_str(), args.as_slice()) {
                    // scrub(x) -- identity function used by some ledger-cli extensions
                    // to mark amounts as "scrubbed" (processed). Treated as a no-op.
                    ("scrub", [arg]) => {
                        eval(arg.clone(), eval_context, state, posting_metadata, budget)
                    }

                    // account("Name") -- returns an object with a "total" field
                    // containing the current running balance of the named account.
                    // Only the primary commodity ($) is currently surfaced.
                    ("account", [account]) => {
                        if let ValueExpr::Str(account) = eval(
                            account.clone(),
                            eval_context,
                            state,
                            posting_metadata,
                            budget,
                        )? {
                            let account = eval_context
                                .account_aliases
                                .get(&account)
                                .unwrap_or(&account);
                            let balance = state
                                .account_balances
                                .get(account)
                                .and_then(|ab| ab.commodity.get("$"))
                                .cloned()
                                .unwrap_or_default();
                            Ok(ast::ValueExpr::Object(BTreeMap::from([(
                                "total".into(),
                                ast::ValueExpr::Amount {
                                    value: balance,
                                    commodity: Some("$".into()),
                                },
                            )])))
                        } else {
                            Err(EvaluationError::InvalidFunctionArgs((
                                name,
                                account.clone(),
                            )))
                        }
                    }

                    // tag("name") -- looks up a metadata key on the current posting.
                    //
                    // The posting's notes are parsed into key-value pairs by the
                    // resolution stage (e.g. `; Entity: Foo` -> `{"Entity": "Foo"}`).
                    // If the key is present its value is returned as a Str; if absent
                    // an empty string is returned so that `tag("X") =~ /pattern/`
                    // works naturally (empty string never matches a non-empty pattern).
                    ("tag", [key_expr]) => {
                        if let ValueExpr::Str(key) = eval(
                            key_expr.clone(),
                            eval_context,
                            state,
                            posting_metadata,
                            budget,
                        )? {
                            let value = posting_metadata.get(&key).cloned().unwrap_or_default();
                            Ok(ast::ValueExpr::Str(value))
                        } else {
                            Err(EvaluationError::InvalidFunctionArgs((
                                name,
                                key_expr.clone(),
                            )))
                        }
                    }

                    _ => Err(EvaluationError::UnknownFunctionArgs((name, args))),
                }
            }

            // A bare commodity symbol or identifier. If the name matches a
            // `define` alias in the active context, substitute and re-evaluate
            // the stored expression. Otherwise return the Commodity as-is;
            // the Binary handler above resolves it when paired with a number.
            ast::ValueExpr::Commodity(ref name) => {
                if let Some(define) = eval_context.defines.get(name.as_str()) {
                    // Zero-parameter defines act as simple aliases: expand the body.
                    // Parameterized defines require a call site (handled in the
                    // Function arm above); a bare reference is not valid.
                    if define.params.is_empty() {
                        match &define.body {
                            ast::DefineBody::Value(expr) => {
                                eval(expr.clone(), eval_context, state, posting_metadata, budget)
                            }
                            // A boolean-body define referenced as a plain identifier is
                            // not meaningful in a value-expression context; treat it as
                            // an unresolved commodity (same as if it were undefined).
                            ast::DefineBody::Bool(_) => Ok(val),
                        }
                    } else {
                        Ok(val)
                    }
                } else {
                    Ok(val)
                }
            }

            ast::ValueExpr::Typed {
                expr,
                commodity: new_commodity,
            } => match eval(*expr, eval_context, state, posting_metadata, budget)? {
                // Accept if the inner expression has no commodity or the same commodity.
                ast::ValueExpr::Amount { value, commodity }
                    if commodity.is_none() || commodity.as_ref() == Some(&new_commodity) =>
                {
                    Ok(ast::ValueExpr::Amount {
                        value,
                        commodity: Some(new_commodity),
                    })
                }
                a => Err(EvaluationError::TypedCommodityToIncompatibleAmount((
                    new_commodity,
                    a,
                ))),
            },

            ast::ValueExpr::Access { expr, field } => {
                match eval(*expr, eval_context, state, posting_metadata, budget)? {
                    ast::ValueExpr::Object(map) => map
                        .get(&field)
                        .cloned()
                        .ok_or(EvaluationError::NoSuchField(field)),
                    val => Err(EvaluationError::FieldAccessTypeError(val)),
                }
            }

            // A parenthesised boolean expression in a value-expression position,
            // e.g. `(amt > 0 or tag("TaxImplication") !~ /^\s*$/)`.
            //
            // Evaluate the inner [`ast::BoolExpr`] and convert the result to a
            // dimensionless `Amount` of `1` (true) or `0` (false) so it can
            // participate in arithmetic or be used as the LHS of a comparison.
            //
            // `posting_amount`/`posting_commodity` are extracted from the
            // defines that `eval_bool_expr` injects before calling `eval`;
            // if absent (Group used outside a posting context) we default to 0/"".
            ast::ValueExpr::Group(bool_expr) => {
                let (posting_amount, posting_commodity) =
                    extract_posting_context_from_defines(eval_context);
                let result = eval_bool_expr_with_context(
                    &bool_expr,
                    posting_amount,
                    &posting_commodity,
                    posting_metadata,
                    eval_context,
                    state,
                )?;
                Ok(ast::ValueExpr::Amount {
                    value: if result { Decimal::ONE } else { Decimal::ZERO },
                    commodity: None,
                })
            }
        }
    }

    /// Extract posting amount and commodity from the defines that
    /// [`eval_bool_expr`] injects into the eval context before calling [`eval`].
    ///
    /// Returns `(Decimal::ZERO, "")` when the bindings are absent, which
    /// happens when a `Group` expression appears outside a posting context.
    fn extract_posting_context_from_defines(ctx: &resolution::Context) -> (Decimal, String) {
        let amount = ctx
            .defines
            .get("amount")
            .and_then(|d| {
                if let ast::DefineBody::Value(ast::ValueExpr::Amount { value, .. }) = &d.body {
                    Some(*value)
                } else {
                    None
                }
            })
            .unwrap_or(Decimal::ZERO);
        let commodity = ctx
            .defines
            .get("commodity")
            .and_then(|d| {
                if let ast::DefineBody::Value(ast::ValueExpr::Str(s)) = &d.body {
                    Some(s.clone())
                } else {
                    None
                }
            })
            .unwrap_or_default();
        (amount, commodity)
    }
}

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

    #[test]
    fn test_amount_default_is_empty() {
        let amount = Amount::default();
        assert!(amount.0.is_empty());
    }

    #[test]
    fn test_amount_multi_commodity() {
        let amount = Amount(BTreeMap::from([
            ("USD".to_string(), dec!(42.5)),
            ("$".to_string(), dec!(-1.5)),
        ]));
        assert_eq!(amount.0.len(), 2);
        assert_eq!(amount.0["USD"], dec!(42.5));
        assert_eq!(amount.0["$"], dec!(-1.5));
    }

    #[test]
    fn test_prices_wired_through_to_journal() {
        use crate::{ast, resolution};

        // Build an AST journal with a single P directive.
        let price_ast = ast::HistoricalPrice {
            date: ast::Date {
                year: Some(2024),
                month: 6,
                date: 15,
            },
            time: Some("14:30:00".into()),
            commodity: "AAPL".into(),
            price: ast::ValueExpr::amount(rust_decimal::Decimal::from(182), "$".into()),
        };
        let journal_ast = ast::Journal {
            entries: vec![ast::Entry::HistoricalPrice(price_ast)],
        };

        // Resolution stage.
        let hir = resolution::HIR::try_from(journal_ast).expect("resolution should succeed");
        assert_eq!(hir.prices.len(), 1, "HIR should contain one price");

        // Elaboration stage.
        let journal =
            crate::elaboration::Journal::try_from(hir).expect("elaboration should succeed");

        assert_eq!(journal.prices.len(), 1, "Journal should contain one price");
        let price = &journal.prices[0];

        // date: 2024-06-15 -> days since epoch
        let expected_days = chrono::NaiveDate::from_ymd_opt(2024, 6, 15)
            .unwrap()
            .to_epoch_days();
        assert_eq!(price.date, expected_days);
        assert_eq!(price.time.as_deref(), Some("14:30:00"));
        assert_eq!(price.commodity, "AAPL");
        assert_eq!(
            price.price.as_ref().unwrap().to_decimal(),
            rust_decimal::Decimal::from(182)
        );
        assert_eq!(price.price_commodity, "$");
    }

    /// Parse a ledger journal string through the full pipeline and return the
    /// elaborated `Journal`. Panics on any parse/resolution/elaboration error.
    fn elaborate(input: &str) -> crate::elaboration::Journal {
        use crate::{grammars::ledger::parse_ledger, resolution::HIR};
        let ast = parse_ledger(input).expect("parse failed");
        let hir = HIR::try_from(ast).expect("resolution failed");
        crate::elaboration::Journal::try_from(hir).expect("elaboration failed")
    }

    #[test]
    fn test_define_simple_amount_alias() {
        // `monthly_rent` is defined as $1500.00 and used in a posting amount.
        let input = "\
define monthly_rent = $1500.00

2024-01-01 Rent Payment
    Expenses:Rent  monthly_rent
    Assets:Checking
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 1);
        let tx = &journal.transactions[0];
        // The Expenses:Rent posting should have $1500.00
        let rent_posting = tx
            .postings
            .iter()
            .find(|p| p.account == "Expenses:Rent")
            .unwrap();
        assert_eq!(
            rent_posting.amount_in("$"),
            Some(dec!(1500.00)),
            "define alias should expand to $1500.00"
        );
        // Assets:Checking should be the balancing null posting: -$1500.00
        let checking_posting = tx
            .postings
            .iter()
            .find(|p| p.account == "Assets:Checking")
            .unwrap();
        assert_eq!(
            checking_posting.amount_in("$"),
            Some(dec!(-1500.00)),
            "balancing posting should be -$1500.00"
        );
    }

    #[test]
    fn test_define_used_in_arithmetic_expression() {
        // Aliases can appear inside arithmetic: `2 * base_amount`.
        let input = "\
define base_amount = 100 USD

2024-02-01 Double Amount
    Expenses:Food  2 * base_amount
    Assets:Cash
";
        // The expression `2 * base_amount` becomes `2 * 100 USD` = `200 USD`.
        // Note: `base_amount` parses as Commodity("base_amount"); after define
        // substitution it becomes Amount{100, Some("USD")}.
        // `2` parses as Amount{2, None}. Mul of (None, USD) -> 200 USD.
        let journal = elaborate(input);
        let tx = &journal.transactions[0];
        let food = tx
            .postings
            .iter()
            .find(|p| p.account == "Expenses:Food")
            .unwrap();
        assert_eq!(
            food.amount_in("USD"),
            Some(dec!(200)),
            "2 * define alias should expand to 200 USD"
        );
    }

    #[test]
    fn test_define_does_not_affect_earlier_transactions() {
        // A define directive must not retroactively affect transactions that
        // appeared before it in the source file.
        //
        // We test this by parsing a transaction where `myval` is NOT yet
        // defined -- it should be treated as a bare commodity rather than an
        // alias, causing an evaluation error (non-amount commodity alone does
        // not balance). The transaction after the define succeeds.
        //
        // Actually: a bare Commodity alone won't resolve to an amount, so the
        // first transaction would fail to elaborate. Instead, use an explicit
        // amount for the first transaction and verify the define is only in
        // context 1 via the HIR, not context 0.
        use crate::{grammars::ledger::parse_ledger, resolution::HIR};

        let input = "\
2024-01-01 Before Define
    Expenses:A  $10.00
    Assets:Cash

define myval = $99.00

2024-01-02 After Define
    Expenses:B  myval
    Assets:Cash
";
        let ast = parse_ledger(input).expect("parse failed");
        let hir = HIR::try_from(ast).expect("resolution failed");

        // There should be 2 contexts (0 = initial, 1 = after define).
        assert_eq!(hir.contexts.len(), 2);
        // First transaction references context 0 -- no defines.
        assert_eq!(hir.entries[0].context_id, 0);
        assert!(hir.contexts[0].defines.is_empty());
        // Second transaction references context 1 -- has the define.
        assert_eq!(hir.entries[1].context_id, 1);
        assert!(hir.contexts[1].defines.contains_key("myval"));

        // Elaboration should succeed end-to-end.
        let journal = crate::elaboration::Journal::try_from(hir).expect("elaboration failed");
        let after_tx = &journal.transactions[1];
        let b_posting = after_tx
            .postings
            .iter()
            .find(|p| p.account == "Expenses:B")
            .unwrap();
        assert_eq!(b_posting.amount_in("$"), Some(dec!(99.00)));
    }

    // -----------------------------------------------------------------------
    // Tests for `--cleared` flag: TransactionState threading and filtering
    // -----------------------------------------------------------------------

    /// Verify that transaction state (`*` cleared, no marker uncleared) is
    /// preserved all the way through parse -> resolution -> elaboration.
    #[test]
    fn test_transaction_state_preserved_through_pipeline() {
        let input = "\
2024-01-01 * Cleared Transaction
    Expenses:Food  $10.00
    Assets:Checking

2024-01-02 Uncleared Transaction
    Expenses:Food  $5.00
    Assets:Checking

2024-01-03 ! Pending Transaction
    Expenses:Food  $3.00
    Assets:Checking
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 3);
        assert!(
            journal.transactions[0].state == crate::elaboration::TransactionState::Cleared as i32,
            "first transaction should be Cleared"
        );
        assert!(
            journal.transactions[1].state == crate::elaboration::TransactionState::Uncleared as i32,
            "second transaction should be Uncleared"
        );
        assert!(
            journal.transactions[2].state == crate::elaboration::TransactionState::Pending as i32,
            "third transaction should be Pending"
        );
    }

    /// Simulate the `balance --cleared` filter: only transactions with state
    /// `Cleared` should contribute to balances.
    ///
    /// Mixed input: one cleared ($10), one uncleared ($5), one pending ($3).
    /// The filtered balance for `Expenses:Food` should be $10 only.
    #[test]
    fn test_cleared_filter_mixed_transactions() {
        let input = "\
2024-01-01 * Cleared Transaction
    Expenses:Food  $10.00
    Assets:Checking

2024-01-02 Uncleared Transaction
    Expenses:Food  $5.00
    Assets:Checking

2024-01-03 ! Pending Transaction
    Expenses:Food  $3.00
    Assets:Checking
";
        let journal = elaborate(input);

        // Reproduce the `--cleared` filter from main.rs.
        let cleared_total: rust_decimal::Decimal = journal
            .transactions
            .iter()
            .filter(|txn| txn.state == crate::elaboration::TransactionState::Cleared as i32)
            .flat_map(|txn| txn.postings.iter())
            .filter(|p| p.account == "Expenses:Food")
            .filter_map(|p| p.amount_in("$"))
            .sum();

        assert_eq!(
            cleared_total,
            dec!(10.00),
            "--cleared should include only the $10.00 cleared transaction"
        );
    }

    /// When no transactions are cleared, filtering by `--cleared` yields an
    /// empty result (no contributions to any account balance).
    #[test]
    fn test_cleared_filter_no_cleared_transactions() {
        let input = "\
2024-01-01 Uncleared One
    Expenses:Food  $10.00
    Assets:Checking

2024-01-02 ! Pending One
    Expenses:Food  $5.00
    Assets:Checking
";
        let journal = elaborate(input);

        let count = journal
            .transactions
            .iter()
            .filter(|txn| txn.state == crate::elaboration::TransactionState::Cleared as i32)
            .count();

        assert_eq!(count, 0, "no cleared transactions should be found");
    }

    /// Without `--cleared`, all transactions (cleared and uncleared) are
    /// included in the balance. Verifies the default behaviour is unchanged.
    #[test]
    fn test_no_cleared_filter_includes_all_transactions() {
        let input = "\
2024-01-01 * Cleared Transaction
    Expenses:Food  $10.00
    Assets:Checking

2024-01-02 Uncleared Transaction
    Expenses:Food  $5.00
    Assets:Checking
";
        let journal = elaborate(input);

        // No filter -- sum all transactions.
        let total: rust_decimal::Decimal = journal
            .transactions
            .iter()
            .flat_map(|txn| txn.postings.iter())
            .filter(|p| p.account == "Expenses:Food")
            .filter_map(|p| p.amount_in("$"))
            .sum();

        assert_eq!(
            total,
            dec!(15.00),
            "without --cleared both transactions should contribute to the balance"
        );
    }

    // -----------------------------------------------------------------------
    // Tests for standalone balance assertion enforcement (issue #37)
    // -----------------------------------------------------------------------

    /// Try to elaborate a ledger input string, returning the elaboration
    /// result (including errors) rather than panicking.
    fn try_elaborate(input: &str) -> Result<crate::elaboration::Journal, ElaborationError> {
        use crate::{grammars::ledger::parse_ledger, resolution::HIR};
        let ast = parse_ledger(input).expect("parse failed");
        let hir = HIR::try_from(ast).expect("resolution failed");
        crate::elaboration::Journal::try_from(hir)
    }

    #[test]
    fn test_balance_assertion_succeeds_when_balance_matches() {
        let input = "\
2024-01-01 Opening
    Assets:Checking  $1000.00
    Equity:Opening

2024-01-01 = Assets:Checking  $1000.00
";
        // Should elaborate without error.
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    #[test]
    fn test_balance_assertion_fails_when_balance_mismatches() {
        let input = "\
2024-01-01 Opening
    Assets:Checking  $1000.00
    Equity:Opening

2024-01-01 = Assets:Checking  $500.00
";
        let result = try_elaborate(input);
        assert!(result.is_err(), "assertion should fail");
        let err = result.unwrap_err();
        match err {
            ElaborationError::BalanceAssertionFailed {
                ref account,
                expected_amount,
                actual_amount,
                ..
            } => {
                assert_eq!(account, "Assets:Checking");
                assert_eq!(expected_amount, dec!(500.00));
                assert_eq!(actual_amount, dec!(1000.00));
            }
            other => panic!("expected BalanceAssertionFailed, got: {other:?}"),
        }
        // Verify Display produces a useful message.
        let msg = err.to_string();
        assert!(
            msg.contains("Assets:Checking"),
            "error should name the account: {msg}"
        );
        assert!(
            msg.contains("500"),
            "error should show expected amount: {msg}"
        );
        assert!(
            msg.contains("1000"),
            "error should show actual amount: {msg}"
        );
    }

    #[test]
    fn test_balance_assertion_zero_balance_at_start() {
        // Asserting zero for an account that has never been posted to should succeed.
        let input = "\
2024-01-01 = Assets:Checking  $0.00
";
        let journal = elaborate(input);
        assert!(journal.transactions.is_empty());
    }

    #[test]
    fn test_balance_assertion_nonzero_at_start_fails() {
        // Asserting a nonzero amount for an account with no postings should fail.
        let input = "\
2024-01-01 = Assets:Checking  $100.00
";
        let result = try_elaborate(input);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ElaborationError::BalanceAssertionFailed { .. }
        ));
    }

    #[test]
    fn test_balance_assertion_after_multiple_transactions() {
        let input = "\
2024-01-01 First deposit
    Assets:Checking  $500.00
    Income:Salary

2024-01-15 Second deposit
    Assets:Checking  $300.00
    Income:Salary

2024-01-31 = Assets:Checking  $800.00
";
        // $500 + $300 = $800 -- assertion should pass.
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 2);
    }

    #[test]
    fn test_balance_assertion_with_expression() {
        let input = "\
2024-01-01 Opening
    Assets:Checking  $1000.00
    Equity:Opening

2024-01-01 = Assets:Checking  $500.00 + $500.00
";
        // $500 + $500 = $1000 -- assertion should pass.
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    #[test]
    fn test_balance_assertion_weak_ignores_other_commodities() {
        // Account holds both $ and EUR. A weak assertion on $ only should pass
        // as long as the $ balance matches -- EUR is ignored.
        let input = "\
2024-01-01 USD deposit
    Assets:Multi  $1000.00
    Equity:Opening

2024-01-02 EUR deposit
    Assets:Multi  500.00 EUR
    Equity:Opening

2024-01-02 = Assets:Multi  $1000.00
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 2);
    }

    #[test]
    fn test_balance_assertion_between_transactions() {
        // Assertion between two transactions: checks balance at that point.
        let input = "\
2024-01-01 First
    Assets:Checking  $100.00
    Equity:Opening

2024-01-01 = Assets:Checking  $100.00

2024-01-02 Second
    Assets:Checking  $50.00
    Income:Salary

2024-01-02 = Assets:Checking  $150.00
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 2);
    }

    #[test]
    fn test_balance_assertion_strict_treated_as_weak() {
        // Strict (`==`) currently behaves the same as weak (`=`).
        let input = "\
2024-01-01 Opening
    Assets:Checking  $1000.00
    Equity:Opening

2024-01-01 == Assets:Checking  $1000.00
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    // -- Account-level assert/check tests ------------------------------------─

    /// Helper: attempt elaboration and expect success.
    fn elaborate_ok(input: &str) -> crate::elaboration::Journal {
        elaborate(input)
    }

    /// Helper: attempt elaboration and expect an `AccountAssertionFailed` error.
    fn elaborate_assert_fails(input: &str) -> (String, usize, String) {
        use crate::{grammars::ledger::parse_ledger, resolution::HIR};
        let ast = parse_ledger(input).expect("parse failed");
        let hir = HIR::try_from(ast).expect("resolution failed");
        match crate::elaboration::Journal::try_from(hir).expect_err("expected assertion failure") {
            ElaborationError::AccountAssertionFailed {
                account,
                posting_index,
                expression,
            } => (account, posting_index, expression),
            e => panic!("expected AccountAssertionFailed, got {e:?}"),
        }
    }

    #[test]
    fn test_account_assert_commodity_passes() {
        // Posting to Assets:Checking with "$" commodity -- assertion must pass.
        let input = "\
account Assets:Checking
    assert commodity == \"$\"

2024-01-01 Deposit
    Assets:Checking  $500.00
    Income:Salary
";
        let journal = elaborate_ok(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    #[test]
    fn test_account_assert_commodity_fails() {
        // Posting with wrong commodity triggers the assertion.
        let input = "\
account Assets:Checking
    assert commodity == \"$\"

2024-01-01 Foreign deposit
    Assets:Checking  500 EUR
    Income:Salary
";
        let (account, posting_index, expression) = elaborate_assert_fails(input);
        assert_eq!(account, "Assets:Checking");
        assert_eq!(posting_index, 0);
        assert!(
            expression.contains("commodity"),
            "expression should mention 'commodity', got: {expression}"
        );
    }

    #[test]
    fn test_account_assert_amount_positive_passes() {
        // Income account asserts amount < 0 (income postings are negative).
        let input = "\
account Income:Salary
    assert amount < 0

2024-01-01 Paycheck
    Income:Salary  $-3000.00
    Assets:Checking
";
        let journal = elaborate_ok(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    #[test]
    fn test_account_assert_amount_fails() {
        // A positive posting to an income account should trip the assertion.
        let input = "\
account Income:Salary
    assert amount < 0

2024-01-01 Bad entry
    Income:Salary  $100.00
    Assets:Checking
";
        let (account, _, expression) = elaborate_assert_fails(input);
        assert_eq!(account, "Income:Salary");
        assert!(
            expression.contains("amount"),
            "expression should mention 'amount'"
        );
    }

    #[test]
    fn test_account_assert_dimensionless_lhs_compares_with_amount() {
        // `0 < amount` (LHS bare, RHS commodity-bearing) must work the same as
        // `amount > 0`. The commodity-compatibility check on numeric comparisons
        // must be symmetric -- without that, this would error with
        // BinaryOperationTypeError instead of evaluating cleanly.
        let input = "\
account Assets:Savings
    assert 0 < amount

2024-01-01 Deposit
    Assets:Savings  $100.00
    Assets:Checking
";
        // 0 < $100 is true -- assertion passes, elaboration succeeds.
        let journal = elaborate_ok(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    #[test]
    fn test_account_assert_dimensionless_lhs_fails_when_false() {
        // Same shape as above but the comparison evaluates false -- the
        // assertion should fail (not error with a type mismatch).
        let input = "\
account Assets:Savings
    assert 0 < amount

2024-01-01 Withdrawal
    Assets:Savings  $-50.00
    Assets:Checking
";
        let (account, _, _) = elaborate_assert_fails(input);
        assert_eq!(account, "Assets:Savings");
    }

    #[test]
    fn test_account_assert_no_whitespace_around_cmp_op() {
        // `amount>0` with no spaces around the comparison operator must parse
        // and evaluate correctly. Punctuation operators don't need whitespace
        // (matching arithmetic operators in `value_expr`).
        let input = "\
account Assets:Savings
    assert amount>0

2024-01-01 Deposit
    Assets:Savings  $100.00
    Assets:Checking
";
        let journal = elaborate_ok(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    #[test]
    fn test_multiple_asserts_all_must_pass() {
        // Two assert lines -- both must hold. First passes, second fails.
        let input = "\
account Assets:Savings
    assert commodity == \"$\"
    assert amount > 0

2024-01-01 Withdrawal
    Assets:Savings  $-100.00
    Assets:Checking
";
        // commodity == "$" passes, but amount > 0 fails for -100.
        let (account, _, _) = elaborate_assert_fails(input);
        assert_eq!(account, "Assets:Savings");
    }

    #[test]
    fn test_account_check_failure_does_not_halt() {
        // `check` produces a warning but elaboration succeeds.
        let input = "\
account Expenses:Food
    check amount > 0

2024-01-01 Refund
    Expenses:Food  $-10.00
    Assets:Checking
";
        // Should NOT error -- check is non-fatal.
        let journal = elaborate_ok(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    #[test]
    fn test_account_check_passing_no_warning() {
        // check passes silently.
        let input = "\
account Expenses:Food
    check amount > 0

2024-01-01 Dinner
    Expenses:Food  $25.00
    Assets:Checking
";
        let journal = elaborate_ok(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    #[test]
    fn test_assert_only_applies_to_declared_account() {
        // Assertion on Assets:Checking does not affect Expenses:Food postings.
        let input = "\
account Assets:Checking
    assert commodity == \"$\"

2024-01-01 Euro lunch
    Expenses:Food  50 EUR
    Assets:Checking  -50 EUR
";
        // The Expenses:Food posting has no assertion -- no error there.
        // The Assets:Checking posting uses EUR, which fails the assertion.
        let (account, _, _) = elaborate_assert_fails(input);
        assert_eq!(account, "Assets:Checking");
    }

    #[test]
    fn test_bool_expr_and_chain_fails_when_rhs_false() {
        // Regression test for issue #78: `and`/`or` in a bool_expr chain were
        // being silently consumed as a commodity by value_expr's postfix, causing
        // the chain to be dropped and the assertion to pass incorrectly.
        //
        // With $50, `amount > 0 and amount < 0` evaluates as `true AND false = false`,
        // so the assertion must fail.
        let input = "\
account Assets:Savings
    assert amount > 0 and amount < 0

2024-01-01 Deposit
    Assets:Savings  $50.00
    Assets:Checking
";
        let (account, _, _) = elaborate_assert_fails(input);
        assert_eq!(account, "Assets:Savings");
    }

    #[test]
    fn test_bool_expr_or_chain_passes_when_either_true() {
        // `amount > 0 or amount < 0` -- true for any nonzero amount.
        // $50 > 0 is true, so the OR chain should pass.
        let input = "\
account Assets:Savings
    assert amount > 0 or amount < 0

2024-01-01 Deposit
    Assets:Savings  $50.00
    Assets:Checking
";
        let journal = elaborate_ok(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    // -----------------------------------------------------------------------
    // Tests for balance assignment commodity inference (issue #71)
    // -----------------------------------------------------------------------

    /// A bare `=0` balance assignment should succeed when the account already
    /// has a running balance in exactly one commodity -- the commodity is inferred
    /// from that prior balance, so no explicit commodity or default is needed.
    #[test]
    fn test_balance_assignment_infers_commodity_from_account_balance() {
        // Account A receives $100 in the first transaction, then in the second
        // transaction `=0` brings it back to zero. The posting amount for
        // Account A in the second transaction should be -$100.
        let input = "\
2026-04-01 Setup
    Account A  $100
    Account B

2026-04-02 Zero out
    Account A  =0
    Account B
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 2);

        let tx = &journal.transactions[1];
        let posting_a = tx
            .postings
            .iter()
            .find(|p| p.account == "Account A")
            .expect("Account A posting not found");

        // The assignment `=0` means: new balance is $0, prior balance is $100,
        // so delta = $0 - $100 = -$100.
        assert_eq!(
            posting_a.amount_in("$"),
            Some(dec!(-100)),
            "balance assignment =0 after $100 should yield -$100 delta"
        );
    }

    /// A balance assignment with an explicit commodity (e.g. `=$0`) should
    /// work exactly as before -- the inferred-commodity path is not taken when
    /// the expression already carries a commodity.
    #[test]
    fn test_balance_assignment_explicit_commodity_still_works() {
        let input = "\
2026-04-01 Setup
    Account A  $100
    Account B

2026-04-02 Zero out
    Account A  =$0
    Account B
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 2);

        let tx = &journal.transactions[1];
        let posting_a = tx
            .postings
            .iter()
            .find(|p| p.account == "Account A")
            .expect("Account A posting not found");

        assert_eq!(
            posting_a.amount_in("$"),
            Some(dec!(-100)),
            "explicit =$0 should also yield -$100 delta"
        );
    }

    /// A bare `=0` with a `default commodity` directive set should still work
    /// through the existing default-commodity path (no regression).
    #[test]
    fn test_balance_assignment_with_default_commodity() {
        let input = "\
commodity $
    default

2026-04-01 Setup
    Account A  $100
    Account B

2026-04-02 Zero out
    Account A  =0
    Account B
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 2);

        let tx = &journal.transactions[1];
        let posting_a = tx
            .postings
            .iter()
            .find(|p| p.account == "Account A")
            .expect("Account A posting not found");

        assert_eq!(
            posting_a.amount_in("$"),
            Some(dec!(-100)),
            "default-commodity path should yield -$100 delta"
        );
    }

    /// Running balances are not pruned when a commodity reaches zero. A stale
    /// zero-balance entry from an earlier `=$0` should not make a
    /// single-non-zero-commodity account look ambiguous.
    #[test]
    fn test_balance_assignment_ignores_stale_zero_commodities() {
        let input = "\
2026-04-01 Setup USD
    Account A  $100
    Account B

2026-04-02 Zero out USD
    Account A  =$0
    Account B

2026-04-03 Add EUR
    Account A  EUR 50
    Account B

2026-04-04 Zero out (bare)
    Account A  =0
    Account B
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 4);

        // Account A's running balance map at this point is { $: 0, EUR: 50 }.
        // The bare `=0` should infer EUR (the only non-zero commodity), not
        // fail with multi-commodity ambiguity.
        let tx = &journal.transactions[3];
        let posting_a = tx
            .postings
            .iter()
            .find(|p| p.account == "Account A")
            .expect("Account A posting not found");
        assert_eq!(
            posting_a.amount_in("EUR"),
            Some(dec!(-50)),
            "bare =0 should infer the only non-zero commodity (EUR)"
        );
    }

    /// A bare `=0` on an account with no prior balance should still succeed
    /// when the same transaction has another posting establishing the
    /// commodity context. This is the bank-import use case.
    #[test]
    fn test_balance_assignment_infers_commodity_from_same_transaction() {
        // The third posting absorbs the unbalanced amount so the transaction
        // balances; Account B's `=0` itself yields a $0 delta (target $0,
        // prior $0). The key behavior is that Account B is elaborated
        // successfully (no `AmountWithNoCommodity` error) and lands in the
        // expected commodity.
        let input = "\
2026-04-01 Test
    Account A  $100
    Account B  =0
    Account C  $-100
";
        let journal = elaborate(input);
        let tx = &journal.transactions[0];
        let posting_b = tx
            .postings
            .iter()
            .find(|p| p.account == "Account B")
            .expect("Account B posting not found");
        assert!(
            posting_b.amount_in("$").is_some(),
            "bare =0 should infer $ from same-transaction context: {:?}",
            posting_b.amount
        );
        assert_eq!(
            posting_b.amount_in("$"),
            Some(dec!(0)),
            "Account B target is 0 with no prior balance, so delta is 0"
        );
    }

    /// When an account has no prior balance, no transaction context, and no
    /// default commodity, a bare `=0` balance assignment must still error.
    #[test]
    fn test_balance_assignment_no_context_errors() {
        let input = "\
2026-04-01 Test
    Account A  =0
";
        let result = try_elaborate(input);
        assert!(
            result.is_err(),
            "bare =0 with no commodity context anywhere should error"
        );
    }

    // -----------------------------------------------------------------------
    // Tests for regex match operators (`=~` / `!~`) -- issue #79
    // -----------------------------------------------------------------------

    /// `assert "abc" =~ /^a/` passes: the string starts with 'a'.
    #[test]
    fn test_regex_match_string_literal_passes() {
        let input = "\
account Expenses:Food
    assert \"abc\" =~ /^a/

2024-01-01 Test
    Expenses:Food  $10.00
    Assets:Checking
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    /// `assert "abc" =~ /^z/` fails: the string does not start with 'z'.
    #[test]
    fn test_regex_match_string_literal_fails() {
        let input = "\
account Expenses:Food
    assert \"abc\" =~ /^z/

2024-01-01 Test
    Expenses:Food  $10.00
    Assets:Checking
";
        let result = try_elaborate(input);
        assert!(
            result.is_err(),
            "regex match should fail when string doesn't match pattern"
        );
    }

    /// `assert "abc" !~ /^z/` passes: the string does not start with 'z'.
    #[test]
    fn test_regex_not_match_passes_when_no_match() {
        let input = "\
account Expenses:Food
    assert \"abc\" !~ /^z/

2024-01-01 Test
    Expenses:Food  $10.00
    Assets:Checking
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    /// `assert "abc" !~ /^a/` fails: the string matches, so `!~` is false.
    #[test]
    fn test_regex_not_match_fails_when_match() {
        let input = "\
account Expenses:Food
    assert \"abc\" !~ /^a/

2024-01-01 Test
    Expenses:Food  $10.00
    Assets:Checking
";
        let result = try_elaborate(input);
        assert!(
            result.is_err(),
            "!~ should fail when string matches pattern"
        );
    }

    /// Regex with a non-trivial pattern including anchors and character classes.
    #[test]
    fn test_regex_match_non_empty_string_pattern() {
        // Pattern `[^\/].+` requires at least two chars and the first isn't a slash.
        let input = "\
account Expenses:Travel
    assert commodity =~ /[a-z]/

2024-01-01 Test
    Expenses:Travel  100 usd
    Assets:Checking
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    // -----------------------------------------------------------------------
    // Tests for `tag("name")` function -- issue #80
    // -----------------------------------------------------------------------

    /// Transaction-level metadata is inherited by postings: an assert that
    /// looks up `tag("Entity")` on a posting that has no Entity of its own
    /// should see the transaction-level Entity tag (matches OG ledger-cli).
    #[test]
    fn test_tag_fn_inherits_transaction_metadata() {
        let input = "\
account Expenses:Food
    assert tag(\"Entity\") =~ /^Foo/

2024-01-01 Lunch
    ; Entity: Foo Inc
    Expenses:Food  $10.00
    Assets:Checking
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    /// Posting-level metadata wins over transaction-level on key collision.
    #[test]
    fn test_tag_fn_posting_overrides_transaction() {
        let input = "\
account Expenses:Food
    assert tag(\"Entity\") =~ /^Bar/

2024-01-01 Lunch
    ; Entity: Foo Inc
    Expenses:Food  $10.00
    ; Entity: Bar LLC
    Assets:Checking
";
        // Expenses:Food's Entity is Bar LLC (posting wins) -> matches /^Bar/.
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    /// `assert tag("X") =~ /^foo/` passes when posting has `; X: foobar`.
    #[test]
    fn test_tag_fn_matches_metadata_value() {
        let input = "\
account Expenses:Food
    assert tag(\"Entity\") =~ /^foo/

2024-01-01 Test
    Expenses:Food  $10.00
    ; Entity: foobar
    Assets:Checking
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    /// `assert tag("X") !~ /^foo/` passes when posting has no X tag (empty
    /// string does not match `/^foo/`).
    #[test]
    fn test_tag_fn_absent_key_returns_empty_string() {
        let input = "\
account Expenses:Food
    assert tag(\"Entity\") !~ /^foo/

2024-01-01 Test
    Expenses:Food  $10.00
    Assets:Checking
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    /// `assert tag("X") =~ /^foo/` fails when posting has no X tag (empty
    /// string does not match a non-empty pattern).
    #[test]
    fn test_tag_fn_absent_key_fails_match() {
        let input = "\
account Expenses:Food
    assert tag(\"Entity\") =~ /^foo/

2024-01-01 Test
    Expenses:Food  $10.00
    Assets:Checking
";
        let result = try_elaborate(input);
        assert!(
            result.is_err(),
            "tag() on absent key returns empty string, which should not match /^foo/"
        );
    }

    /// Chained check: `tag("A") !~ /^\s*$/ and tag("B") !~ /^\s*$/`.
    /// Both tags present and non-blank -> passes.
    #[test]
    fn test_tag_fn_chained_and_both_present() {
        let input = "\
account Income:Salary
    assert tag(\"Entity\") !~ /^\\s*$/ and tag(\"IncomeType\") !~ /^\\s*$/

2024-01-01 Paycheck
    Income:Salary  $-5000.00
    ; Entity: AcmeCorp
    ; IncomeType: Salary
    Assets:Checking  $5000.00
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    /// Chained check: one tag present, one absent -> fails.
    #[test]
    fn test_tag_fn_chained_and_one_missing() {
        let input = "\
account Income:Salary
    assert tag(\"Entity\") !~ /^\\s*$/ and tag(\"IncomeType\") !~ /^\\s*$/

2024-01-01 Paycheck
    Income:Salary  $-5000.00
    ; Entity: AcmeCorp
    Assets:Checking  $5000.00
";
        let result = try_elaborate(input);
        assert!(
            result.is_err(),
            "chained tag() check should fail when one tag is absent"
        );
    }

    // -----------------------------------------------------------------------
    // Tests for `tag()` with bare (`:foo:`) tags
    // -----------------------------------------------------------------------

    /// `tag()` only inspects key-value metadata (`; Key: value`), not bare
    /// colon-delimited tags (`; :foo:`).  A posting with `:foo:` and an
    /// assertion `tag("foo") =~ /foo/` fails because `tag("foo")` returns ""
    /// (the bare tag name is not in the metadata map).
    ///
    /// This is intentional: bare tags carry no associated value, so `tag()`
    /// returning "" is the correct "not found" signal.  Use bare tags for
    /// filtering via external tooling rather than in `assert`/`check` expressions.
    #[test]
    fn test_tag_fn_does_not_see_bare_colon_tags() {
        let input = "\
account Expenses:Food
    assert tag(\"foo\") =~ /foo/

2024-01-01 Test
    Expenses:Food  $10.00
    ; :foo:
    Assets:Checking
";
        let result = try_elaborate(input);
        assert!(
            result.is_err(),
            "tag() must return \"\" for bare colon-style tags; /foo/ should not match"
        );
    }

    // -----------------------------------------------------------------------
    // Tests for invalid regex error -- issue #79
    // -----------------------------------------------------------------------

    /// An invalid regex pattern in an `assert` expression should fail at
    /// parse time, not silently accepted to fail later during elaboration.
    #[test]
    fn test_invalid_regex_fails_at_parse_time() {
        use crate::grammars::ledger::parse_ledger;
        let input = "\
account Expenses:Food
    assert commodity =~ /[unclosed/
";
        let result = parse_ledger(input);
        let err = result.expect_err("invalid regex should fail parsing");
        let msg = err.to_string();
        assert!(
            msg.contains("[unclosed") && msg.contains("invalid regex"),
            "error message should include the invalid pattern and identify it as a regex; got: {msg}"
        );
    }

    // -----------------------------------------------------------------------
    // Tests for tag directive validation -- issue #82
    // -----------------------------------------------------------------------

    /// `tag X\n    assert value =~ /^foo/` with `; X: foobar` passes.
    #[test]
    fn test_tag_assert_passes_when_value_matches() {
        let input = "\
tag Statement
    assert value =~ /^foo/

2024-01-01 Test
    ; Statement: foobar
    Expenses:Food  $10.00
    Assets:Checking
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    /// `tag X\n    assert value =~ /^foo/` with `; X: barfoo` fails with
    /// `TagAssertionFailed`.
    #[test]
    fn test_tag_assert_fails_when_value_does_not_match() {
        let input = "\
tag Statement
    assert value =~ /^foo/

2024-01-01 Test
    ; Statement: barfoo
    Expenses:Food  $10.00
    Assets:Checking
";
        let result = try_elaborate(input);
        assert!(
            matches!(result, Err(ElaborationError::TagAssertionFailed { .. })),
            "expected TagAssertionFailed, got: {result:?}"
        );
        if let Err(ElaborationError::TagAssertionFailed {
            tag_name,
            tag_value,
            ..
        }) = result
        {
            assert_eq!(tag_name, "Statement");
            assert_eq!(tag_value, "barfoo");
        }
    }

    /// `tag X\n    check value =~ /^foo/` with `; X: barfoo` warns but
    /// elaboration succeeds.
    #[test]
    fn test_tag_check_warns_does_not_halt() {
        let input = "\
tag Statement
    check value =~ /^foo/

2024-01-01 Test
    ; Statement: barfoo
    Expenses:Food  $10.00
    Assets:Checking
";
        // Should succeed (check does not halt elaboration).
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    /// Multiple asserts under one tag: all must pass.
    #[test]
    fn test_tag_multiple_asserts_all_must_pass() {
        let input = "\
tag IncomeType
    assert value =~ /^(Donations|RBI|UBTI)$/

2024-01-01 Income
    ; IncomeType: RBI
    Income:Donations  $100.00
    Assets:Checking
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    /// An invalid value fails all asserts.
    #[test]
    fn test_tag_assert_invalid_value_fails() {
        let input = "\
tag IncomeType
    assert value =~ /^(Donations|RBI|UBTI)$/

2024-01-01 Income
    ; IncomeType: Salary
    Income:Salary  $100.00
    Assets:Checking
";
        let result = try_elaborate(input);
        assert!(
            matches!(result, Err(ElaborationError::TagAssertionFailed { .. })),
            "expected TagAssertionFailed for unrecognised IncomeType"
        );
    }

    /// A tag declared but not referenced in any transaction produces no errors.
    #[test]
    fn test_tag_declared_but_unused_no_error() {
        let input = "\
tag Receipt
    assert value =~ /foo/

2024-01-01 Test
    Expenses:Food  $10.00
    Assets:Checking
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    /// Posting-level metadata is also validated (not just transaction-level).
    #[test]
    fn test_tag_assert_on_posting_level_metadata() {
        let input = "\
tag Statement
    assert value =~ /^foo/

2024-01-01 Test
    Expenses:Food  $10.00
    ; Statement: barfoo
    Assets:Checking
";
        let result = try_elaborate(input);
        assert!(
            matches!(result, Err(ElaborationError::TagAssertionFailed { .. })),
            "posting-level tag metadata should also be validated"
        );
    }

    /// Posting-level metadata with a passing value succeeds.
    #[test]
    fn test_tag_assert_on_posting_level_metadata_passes() {
        let input = "\
tag Statement
    assert value =~ /^foo/

2024-01-01 Test
    Expenses:Food  $10.00
    ; Statement: foobar
    Assets:Checking
";
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    /// Bare colon-tags (e.g. `; :payroll:`) have no value and are NOT validated
    /// by `tag` directive rules -- they are skipped entirely.
    #[test]
    fn test_tag_directive_does_not_validate_bare_colon_tags() {
        let input = "\
tag payroll
    assert value =~ /^.+$/

2024-01-01 Payroll
    ; :payroll:
    Income:Salary  $5000.00
    Assets:Checking
";
        // Bare colon-tags don't have a value, so they never reach the tag
        // directive validator. Elaboration should succeed.
        let journal = elaborate(input);
        assert_eq!(journal.transactions.len(), 1);
    }

    // -----------------------------------------------------------------------
    // Tests for parameterized defines (issue #81)
    // -----------------------------------------------------------------------

    /// `define isPositive(x) = x > 0` in an account assert -- passing case.
    #[test]
    fn test_parameterized_define_bool_passing() {
        let input = "\
define isPositive(x) = x > 0

account Expenses:Food
    assert isPositive(amount)

2024-01-01 Lunch
    Expenses:Food  $10.00
    Assets:Cash
";
        elaborate(input);
    }

    /// `define isNegative(x) = x < 0` in an account assert -- positive amount
    /// should trigger the assertion.
    #[test]
    fn test_parameterized_define_bool_failing() {
        let input = "\
define isNegative(x) = x < 0

account Expenses:Food
    assert isNegative(amount)

2024-01-01 Lunch
    Expenses:Food  $10.00
    Assets:Cash
";
        let ast = crate::grammars::ledger::parse_ledger(input).expect("parse failed");
        let hir = crate::resolution::HIR::try_from(ast).expect("resolution failed");
        let result = crate::elaboration::Journal::try_from(hir);
        assert!(
            matches!(result, Err(ElaborationError::AccountAssertionFailed { .. })),
            "positive amount should fail isNegative assertion; got: {result:?}"
        );
    }

    /// Bool define using `tag()` and `!~` regex match.
    #[test]
    fn test_parameterized_define_with_tag_and_regex_passing() {
        let input = "\
define hasReceipt(x) = tag(\"Receipt\") !~ /^\\s*$/ and x > 0

account Expenses:Food
    assert hasReceipt(amount)

2024-01-01 Lunch
    Expenses:Food  $10.00
    ; Receipt: scan123.pdf
    Assets:Cash
";
        elaborate(input);
    }

    /// Two-argument define: `between(lo, hi) = amount > lo and amount < hi`
    /// where `amount` is in scope from the posting context.
    #[test]
    fn test_parameterized_define_two_args_passing() {
        let input = "\
define between(lo, hi) = amount > lo and amount < hi

account Expenses:Food
    assert between(0, 100)

2024-01-01 Lunch
    Expenses:Food  $50.00
    Assets:Cash
";
        elaborate(input);
    }

    /// Same `between` define -- amount outside range fails.
    #[test]
    fn test_parameterized_define_two_args_failing() {
        let input = "\
define between(lo, hi) = amount > lo and amount < hi

account Expenses:Food
    assert between(0, 10)

2024-01-01 BigPurchase
    Expenses:Food  $50.00
    Assets:Cash
";
        let ast = crate::grammars::ledger::parse_ledger(input).expect("parse failed");
        let hir = crate::resolution::HIR::try_from(ast).expect("resolution failed");
        let result = crate::elaboration::Journal::try_from(hir);
        assert!(
            matches!(result, Err(ElaborationError::AccountAssertionFailed { .. })),
            "$50 should fail between(0, 10); got: {result:?}"
        );
    }

    /// Param named `amount` shadows the implicit posting binding.
    #[test]
    fn test_parameterized_define_param_shadows_amount() {
        let input = "\
define isPositiveAmt(amount) = amount > 0

account Expenses:Food
    assert isPositiveAmt(amount)

2024-01-01 Lunch
    Expenses:Food  $10.00
    Assets:Cash
";
        elaborate(input);
    }

    /// A zero-parameter value-body define continues to work as before.
    #[test]
    fn test_zero_param_define_value_body_still_works() {
        let input = "\
define monthly = $1500.00

2024-01-01 Rent
    Expenses:Rent  monthly
    Assets:Cash
";
        let journal = elaborate(input);
        let rent = journal.transactions[0]
            .postings
            .iter()
            .find(|p| p.account == "Expenses:Rent")
            .unwrap();
        assert_eq!(rent.amount_in("$"), Some(dec!(1500.00)));
    }

    /// Mutually-recursive defines must produce a `RecursionLimitExceeded`
    /// error rather than crash the process with a stack overflow.
    #[test]
    fn test_mutually_recursive_defines_caught() {
        let input = "\
define a = b
define b = a

2024-01-01 Test
    Expenses:Food  a
    Assets:Cash
";
        let result = try_elaborate(input);
        assert!(
            matches!(
                result,
                Err(ElaborationError::EvaluationError(
                    EvaluationError::RecursionLimitExceeded
                ))
            ),
            "cyclic defines should produce RecursionLimitExceeded; got: {result:?}"
        );
    }

    /// Self-referential define caught the same way.
    #[test]
    fn test_self_referential_define_caught() {
        let input = "\
define x = x

2024-01-01 Test
    Expenses:Food  x
    Assets:Cash
";
        let result = try_elaborate(input);
        assert!(
            matches!(
                result,
                Err(ElaborationError::EvaluationError(
                    EvaluationError::RecursionLimitExceeded
                ))
            ),
            "self-referential define should produce RecursionLimitExceeded; got: {result:?}"
        );
    }

    /// A parameterized value-body define can be used in a posting amount.
    #[test]
    fn test_parameterized_define_value_body_in_posting() {
        let input = "\
define double(x) = x * 2

2024-01-01 Purchase
    Expenses:Food  double(50 USD)
    Assets:Cash
";
        let journal = elaborate(input);
        let food = journal.transactions[0]
            .postings
            .iter()
            .find(|p| p.account == "Expenses:Food")
            .unwrap();
        assert_eq!(food.amount_in("USD"), Some(dec!(100)));
    }

    // -- Issue #89: parenthesised bool expressions in value/bool positions --

    #[test]
    fn test_paren_bool_simple_assert_passes() {
        // `(amount > 0)` in an account assert should pass for a positive posting.
        let input = "\
account Assets:Savings
    assert (amount > 0)

2024-01-01 Deposit
    Assets:Savings  $100.00
    Assets:Cash
";
        elaborate(input); // must not panic
    }

    #[test]
    fn test_paren_bool_or_chain_passes_when_first_true() {
        // `(amount > 0 or amount < -10)` -- first arm true, should pass.
        let input = "\
account Assets:Savings
    assert (amount > 0 or amount < -10)

2024-01-01 Deposit
    Assets:Savings  $100.00
    Assets:Cash
";
        elaborate(input);
    }

    #[test]
    fn test_paren_bool_or_chain_passes_when_second_true() {
        // `(amount > 0 or amount < -10)` -- second arm true.
        let input = "\
account Assets:Savings
    assert (amount > 0 or amount < -10)

2024-01-01 Withdrawal
    Assets:Cash  $100.00
    Assets:Savings  $-100.00
";
        // $-100 satisfies `amount < -10` (the second branch).
        // NOTE: amount here would be -100 which is < -10 -> passes.
        elaborate(input);
    }

    #[test]
    fn test_define_paren_bool_used_in_assert() {
        // A parameterized define whose body is a parenthesised bool_expr,
        // then used in an account assert.
        let input = "\
define inRange(x) = (x > 0 and x < 1000)

account Assets:Savings
    assert inRange(amount)

2024-01-01 Deposit
    Assets:Savings  $100.00
    Assets:Cash
";
        elaborate(input);
    }

    #[test]
    fn test_issue_89_define_with_complex_paren_bool() {
        // The exact pattern from issue #89 (simplified to avoid needing real
        // metadata -- just verify it elaborates without error when the outer
        // `or` short-circuits on the amount comparison).
        let input = "\
define assetChecker(amt) = (amt > -100.00 or (tag(\"TaxImplication\") !~ /^\\s*$/ and tag(\"Entity\") !~ /^\\s*$/))

account Assets:Savings
    assert assetChecker(amount)

2024-01-01 Deposit
    Assets:Savings  $500.00
    Assets:Cash
";
        // amount=500 > -100 -> outer `or` short-circuits to true.
        elaborate(input);
    }

    // --------------------------------------------------------------------------
    // Virtual posting unit tests (#140)
    // --------------------------------------------------------------------------

    /// A transaction with a real posting, a virtual-unbalanced posting, and
    /// a null posting: the unbalanced posting must not affect the null-posting
    /// inference (i.e. the null posting absorbs only the real posting's amount).
    #[test]
    fn virtual_unbalanced_does_not_affect_null_posting_inference() {
        let input = "\
2024-01-15 Test
    Assets:Checking           $100
    (Equity:Reservations)     $-25
    Equity:Opening
";
        let j = elaborate(input);
        let t = &j.transactions[0];
        assert_eq!(t.postings.len(), 3);

        // Null posting should be inferred as -$100 (negation of real $100),
        // not -$75 (which would incorrectly include the virtual unbalanced).
        let null_p = t
            .postings
            .iter()
            .find(|p| p.account == "Equity:Opening")
            .expect("null posting present");
        assert_eq!(null_p.amount_in("$"), Some(dec!(-100)));

        let virt = t
            .postings
            .iter()
            .find(|p| p.account == "Equity:Reservations")
            .expect("virtual posting present");
        assert_eq!(virt.amount_in("$"), Some(dec!(-25)));

        use crate::elaboration::PostingKind;
        assert_eq!(virt.kind, PostingKind::VirtualUnbalanced as i32);
        assert_eq!(null_p.kind, PostingKind::Real as i32);
    }

    /// A transaction with a real posting, a virtual-balanced posting, and a
    /// null posting: the balanced posting participates in the null-posting
    /// inference (the null absorbs the sum of real + balanced).
    #[test]
    fn virtual_balanced_participates_in_null_posting_inference() {
        let input = "\
2024-01-15 Test
    Assets:Checking           $100
    [Equity:Reservations]     $25
    Equity:Opening
";
        let j = elaborate(input);
        let t = &j.transactions[0];
        assert_eq!(t.postings.len(), 3);

        // Null posting absorbs -(100 + 25) = -$125 because the balanced
        // virtual posting contributes to the transaction state.
        let null_p = t
            .postings
            .iter()
            .find(|p| p.account == "Equity:Opening")
            .expect("null posting present");
        assert_eq!(null_p.amount_in("$"), Some(dec!(-125)));

        let virt = t
            .postings
            .iter()
            .find(|p| p.account == "Equity:Reservations")
            .expect("virtual posting present");
        assert_eq!(virt.amount_in("$"), Some(dec!(25)));

        use crate::elaboration::PostingKind;
        assert_eq!(virt.kind, PostingKind::VirtualBalanced as i32);
    }

    /// A transaction consisting solely of virtual-unbalanced postings should
    /// elaborate without a balance error: there are no real postings to balance.
    #[test]
    fn transaction_with_only_virtual_unbalanced_postings_does_not_error() {
        let input = "\
2024-01-15 Memo-only entry
    (Budget:Food)    $50
    (Budget:Travel)  $-50
";
        let j = elaborate(input);
        let t = &j.transactions[0];
        assert_eq!(t.postings.len(), 2);

        use crate::elaboration::PostingKind;
        for p in &t.postings {
            assert_eq!(p.kind, PostingKind::VirtualUnbalanced as i32);
        }
    }

    /// A virtual-unbalanced posting must update the running per-account balance
    /// so that a subsequent standalone balance assertion on the same account
    /// reflects the virtual amount -- matching ledger-cli behaviour.
    #[test]
    fn virtual_unbalanced_posting_updates_account_balance_for_assertions() {
        // The virtual posting credits $-25 to Equity:Reservations.
        // A subsequent balance assertion checks that the account balance is $-25,
        // which should succeed because virtual-unbalanced postings contribute to
        // account_balances even though they're excluded from the transaction check.
        let input = "\
2024-01-15 Setup
    Assets:Checking           $100
    (Equity:Reservations)     $-25
    Equity:Opening

2024-01-15 = Equity:Reservations  $-25
";
        // Should elaborate without error -- the balance assertion sees the virtual
        // posting's contribution.
        let j = elaborate(input);
        assert_eq!(j.transactions.len(), 1);

        let virt = j.transactions[0]
            .postings
            .iter()
            .find(|p| p.account == "Equity:Reservations")
            .expect("virtual posting present");
        assert_eq!(virt.amount_in("$"), Some(dec!(-25)));
    }

    // ----------------------------------------------------------------------
    // Lot annotation elaborator tests
    // ----------------------------------------------------------------------

    #[test]
    fn test_lot_cost_only_drives_cash_balance() {
        // 10 AAPL {$150} (no @ price) -> cash side -$1500.
        let input = "\
2024-03-01 Buy AAPL
    Assets:Brokerage   10 AAPL {$150}
    Assets:Cash
";
        let journal = elaborate(input);
        let t = &journal.transactions[0];
        assert_eq!(t.postings[0].amount_in("AAPL"), Some(dec!(10)));
        // No @/@@, cost annotation drives the cash balance: 10 * $150 = $1500.
        assert_eq!(
            t.postings[1].amount_in("$"),
            Some(dec!(-1500)),
            "cash side should be -$1500 when lot cost drives balance"
        );
        // Lot cost preserved on the proto posting.
        assert_eq!(t.postings[0].lot_cost_in("$"), Some(dec!(150)));
    }

    #[test]
    fn test_lot_cost_and_price_price_wins_cash_cost_preserved() {
        // 10 AAPL {$150} @ $155 -> cash -$1550 (price drives balance),
        // but lot.cost = $150 is still stored.
        let input = "\
2024-03-01 Buy AAPL
    Assets:Brokerage   10 AAPL {$150} @ $155
    Assets:Cash
";
        let journal = elaborate(input);
        let t = &journal.transactions[0];
        assert_eq!(t.postings[0].amount_in("AAPL"), Some(dec!(10)));
        // Price wins over lot cost for cash balance: 10 * $155 = $1550.
        assert_eq!(
            t.postings[1].amount_in("$"),
            Some(dec!(-1550)),
            "cash side should be -$1550 when @ price is present"
        );
        // Lot cost annotation is preserved even though it didn't drive balance.
        assert_eq!(
            t.postings[0].lot_cost_in("$"),
            Some(dec!(150)),
            "lot cost should be $150, not the price $155"
        );
    }

    #[test]
    fn test_lot_no_cost_no_price_value_in_own_commodity() {
        // 10 AAPL (no annotation, no price) -> the null posting balances in
        // AAPL (today's fallback: the commodity contributes itself).
        let input = "\
2024-03-01 Transfer
    Assets:Brokerage   10 AAPL
    Assets:OtherBrokerage
";
        let journal = elaborate(input);
        let t = &journal.transactions[0];
        assert_eq!(t.postings[0].amount_in("AAPL"), Some(dec!(10)));
        // Null posting inferred as -10 AAPL.
        assert_eq!(
            t.postings[1].amount_in("AAPL"),
            Some(dec!(-10)),
            "null posting should balance as -10 AAPL when no price is given"
        );
        assert!(!t.postings[0].has_lot(), "no lot annotation should be set");
    }
}