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
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
//! 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,
};
/// Identity of a single lot held in an account.
///
/// Mirrors the inventory key all three reference tools track: a position's
/// cost basis, acquisition date, and free-form note. Two `{cost}`
/// annotations with the same numeric value but different commodities are
/// distinct lots; same date with different costs are distinct lots; etc.
///
/// `None` for any field means the corresponding annotation was absent on
/// the posting. A posting with no lot annotation at all keys into the
/// inventory under `Option::None` (the "default bucket") and aggregates
/// with other plain-commodity postings just like the pre-#237 model.
#[derive(Default, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct LotKey {
/// Per-unit cost basis evaluated to a concrete decimal. None when
/// the posting carried other lot fields (e.g. `[date]` only) but
/// no `{cost}` annotation.
pub(crate) cost: Option<Decimal>,
/// Cost commodity (e.g. `"USD"` for a `{1500 USD}` annotation).
pub(crate) cost_commodity: Option<String>,
/// Acquisition date (`[YYYY-MM-DD]` annotation).
pub(crate) date: Option<chrono::NaiveDate>,
/// Free-form note (Beancount calls this "label").
pub(crate) note: Option<String>,
}
/// Per-account running inventory, keyed at lot granularity.
///
/// All three reference tools (ledger-cli, hledger, Beancount) track
/// account state as a per-lot inventory rather than a per-commodity
/// aggregate. Two purchases of the same commodity at different costs
/// remain distinct positions; a sale that names a specific lot
/// decrements that lot only. The wire format already preserves the
/// per-posting `Lot` annotation; this struct is the elaborator-side
/// counterpart so phantom-lot reductions are detectable, lot
/// augmentation is preserved, and downstream consumers of the running
/// state can query per-lot positions directly. See #237.
///
/// Postings without a lot annotation key into `(commodity, None)` and
/// aggregate as before — the "default bucket" preserves backward
/// compatibility for journals that don't use `{cost}` / `[date]` /
/// `((note))`.
#[derive(Default, Clone, Debug)]
struct AccountInventory {
/// Per-(commodity, lot) running units. Keyed by commodity *then*
/// lot so callers iterating commodity totals can range-scan
/// efficiently when needed.
positions: BTreeMap<(String, Option<LotKey>), Decimal>,
}
impl AccountInventory {
/// Sum the running balance across all lots in `commodity`.
/// This is the commodity-aggregate view that pre-#237 callers
/// relied on for balance assertions, subtree aggregation, and
/// `==*` synthesis -- nothing about the user-visible
/// per-(account, commodity) total changes.
fn commodity_balance(&self, commodity: &str) -> Decimal {
self.positions
.iter()
.filter(|((c, _), _)| c == commodity)
.map(|(_, v)| *v)
.sum()
}
/// Iterate over every (commodity, lot) position, yielding non-zero
/// entries. Used by the post-elaboration metadata + report passes.
fn iter_positions(&self) -> impl Iterator<Item = (&(String, Option<LotKey>), &Decimal)> {
self.positions.iter().filter(|(_, v)| !v.is_zero())
}
/// Iterate over the distinct commodities held (regardless of lot).
fn commodities(&self) -> impl Iterator<Item = &String> {
self.positions.keys().map(|(c, _)| c)
}
/// Adjust the position keyed by (commodity, lot) by `delta`. Creates
/// the entry with the default `Decimal::ZERO` if it doesn't exist.
fn add(&mut self, commodity: String, lot: Option<LotKey>, delta: Decimal) {
*self.positions.entry((commodity, lot)).or_default() += delta;
}
}
/// 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_inventories: BTreeMap<String, AccountInventory>,
/// Beancount `pad` markers awaiting their next `balance` assertion,
/// keyed by the pad's target account. A new pad on the same target
/// account overwrites any earlier one (Beancount's
/// "most-recent-pad-wins" rule for back-to-back pads on a single
/// account). A pad that never sees a follow-up balance assertion is
/// silently discarded at end-of-journal.
pending_pads: BTreeMap<String, PendingPad>,
}
/// A pad directive observed but not yet consumed by a balance assertion.
#[derive(Clone, Debug, Default)]
struct PendingPad {
/// The pad's own date -- used as the synthesized transaction's date.
date: chrono::NaiveDate,
/// The counter-account that will absorb the padding amount.
source_account: String,
/// Commodities for which this pad has already fired a synthesised
/// transaction. Beancount fires the pad once per commodity at the
/// first balance assertion that references it; subsequent
/// assertions in the same commodity check the running balance
/// against the asserted amount without re-padding. Different
/// commodities can each consume the pad once.
padded_commodities: std::collections::BTreeSet<String>,
}
/// 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.
///
/// Marked `#[non_exhaustive]`: external matchers must include a `_`
/// arm. New variants surface as we extend doppio's elaboration
/// semantics (#237, #238, #242 added several; future booking modes
/// and validators are expected to add more), so locking-out
/// exhaustive matches up-front keeps additive variant work from
/// forcing a major SemVer bump on every release.
#[derive(Debug)]
#[non_exhaustive]
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,
},
/// A `{{total}}` lot annotation was attached to a posting whose
/// unit count is zero, so per-unit basis cannot be derived from
/// the total.
TotalCostWithZeroUnits,
/// In Strict lot validation mode, a posting reduces an account's
/// position in `commodity` while naming a lot key for which no
/// matching prior augmentation exists. Beancount's strict booking
/// method rejects these as ambiguous: there is no augmentation to
/// trace the reduction back to. See
/// [`crate::resolution::LotValidationMode::Strict`].
PhantomLotReduction {
/// The account whose position the posting is trying to reduce.
account: String,
/// The commodity being reduced.
commodity: String,
/// The named lot key that was not found in the inventory.
lot: String,
},
/// A posting carries a MISSING-cost lot spec (`{}` or partial like
/// `{2024-01-15}`) under [`crate::resolution::BookingMethod::Strict`],
/// but the partial spec matches more than one lot in the account's
/// inventory. Beancount's STRICT booking rejects these as
/// ambiguous; FIFO/LIFO/HIFO/AVERAGE would resolve them. See #238.
AmbiguousLotMatch {
/// The account.
account: String,
/// The commodity being reduced.
commodity: String,
/// Number of inventory lots that matched the partial spec.
match_count: usize,
},
/// A booking pass tried to consume more units than the account's
/// inventory holds in the named commodity (or matching lot subset
/// when a partial spec was given). The reduction is over-sized
/// for what the inventory can supply.
OverReductionInBooking {
/// The account being reduced.
account: String,
/// The commodity being reduced.
commodity: String,
/// Units the posting tried to consume (positive).
requested: Decimal,
/// Units actually available across all matching lots.
available: Decimal,
},
/// A posting with a MISSING-cost lot spec (`{}`) carries POSITIVE
/// units (i.e. augmentation) under a non-NONE booking method.
/// Augmenting with `{}` requires the cost to come from somewhere
/// (an `@price` annotation, typically); supporting that is
/// out of scope for the initial #238 cut.
AugmentingPostingWithMissingCost {
/// The account.
account: String,
/// The commodity.
commodity: 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.
///
/// `#[non_exhaustive]` for the same reason as
/// [`ElaborationError`]: future expression / function additions are
/// expected to surface new variants here, and we don't want each
/// addition to count as a major SemVer break.
#[derive(Debug)]
#[non_exhaustive]
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}"
)
}
ElaborationError::TotalCostWithZeroUnits => {
write!(
f,
"`{{{{total}}}}` lot cost cannot be applied to a posting with zero units"
)
}
ElaborationError::PhantomLotReduction {
account,
commodity,
lot,
} => {
write!(
f,
"phantom-lot reduction: account `{account}` has no prior augmentation \
of `{commodity}` matching lot `{lot}`"
)
}
ElaborationError::AmbiguousLotMatch {
account,
commodity,
match_count,
} => {
write!(
f,
"ambiguous booking: account `{account}` has {match_count} \
matching lots of `{commodity}`; STRICT booking requires \
exactly one (use FIFO/LIFO/HIFO/AVERAGE on `open` to disambiguate)"
)
}
ElaborationError::OverReductionInBooking {
account,
commodity,
requested,
available,
} => {
write!(
f,
"over-reduction during booking: account `{account}` has \
{available} {commodity} available across matching lots, \
but the posting tried to reduce {requested}"
)
}
ElaborationError::AugmentingPostingWithMissingCost { account, commodity } => {
write!(
f,
"MISSING-cost lot annotation (`{{}}`) on an augmenting posting \
of `{commodity}` to `{account}`: doppio's booking implementation \
handles reductions only; spell out `{{cost}}` explicitly for augmentations"
)
}
}
}
}
/// Run the elaboration pass on a resolved [`resolution::HIR`], applying
/// the semantic ruleset in `config`.
///
/// This is the single entry point to the elaborator. The
/// [`resolution::ElaborationConfig`] passed here is the *only* place the
/// elaborator picks up its semantic choices (tolerance rule, balance
/// mode, assertion scope, ...) -- the parser/frontend stages do not
/// inject any. Callers typically pass `&frontend.elaboration_defaults()` for the
/// matching tool's behaviour, or any other `ElaborationConfig` to
/// experiment with cross-syntax-semantics combinations. Per-commodity
/// overrides set by source directives (Beancount's
/// `option "inferred_tolerance_default"`) layer on top of the config at
/// elaboration time via [`resolution::GlobalContext::tolerance_overrides`].
pub fn elaborate(
value: resolution::HIR,
config: &resolution::ElaborationConfig,
) -> Result<crate::elaboration::Journal, ElaborationError> {
{
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(),
},
);
}
let tolerance_mode = config.tolerance_mode;
let tolerance_overrides = value.global_context.tolerance_overrides.clone();
// Per-commodity inferred scales populated by the resolution stage (#281).
// Used by the `@`-price cost computation to round `qty * price` products
// to the journal's intended precision before the balance check.
let commodity_properties = value.global_context.commodity_properties;
let balance_mode = config.balance_mode.clone();
let assertion_scope = config.assertion_scope;
let lot_validation_mode = config.lot_validation_mode;
// Auto-rule queries are pre-compiled to regexes during resolution;
// here we just need to extract the rules so we can iterate
// `value.entries` (consuming it) without conflicting with a borrow
// on `value.auto_rules`.
let auto_rules = value.auto_rules;
for entry in value.entries {
let entry_context = &value.contexts[entry.context_id];
match entry.data {
resolution::Entry::Pad(p) => {
// Beancount `pad`: remember the (target, source) pair so
// upcoming balance assertions on `target` can each fire
// it once per commodity. A second pad on the same target
// overwrites the first (most-recent-pad-wins) -- the new
// pad's `padded_commodities` set starts empty, re-arming
// it for every commodity.
state.pending_pads.insert(
p.target_account,
PendingPad {
date: p.date,
source_account: p.source_account,
padded_commodities: std::collections::BTreeSet::new(),
},
);
}
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.
// Beancount's `balance` directive aggregates the entire account
// subtree (parent + every descendant); ledger-cli/hledger's
// posting-level `=`/`==` and the doppio-extended top-level form
// check the named account in isolation. The frontend selects via
// [`crate::resolution::AssertionScope`]. A pending pad on the
// same account uses the same lookup so the synthesized
// pad amount is the residual against the right scope.
let mut actual_amount = match assertion_scope {
crate::resolution::AssertionScope::Direct => state
.account_inventories
.get(&assertion.account)
.map(|inv| inv.commodity_balance(&expected_commodity))
.unwrap_or(Decimal::ZERO),
crate::resolution::AssertionScope::Subtree => subtree_commodity_balance(
&state.account_inventories,
&assertion.account,
)
.get(&expected_commodity)
.copied()
.unwrap_or(Decimal::ZERO),
};
// If a pad on this account is pending and has not yet
// fired for the asserted commodity, synthesize a
// balancing transaction (back-dated to the pad's date)
// that brings `actual_amount` up to `expected_amount`,
// and apply it to the running state so the assertion
// below passes by construction. The synthesized
// transaction is also pushed into the output journal so
// downstream consumers see the inserted postings.
//
// Per bean-check 3.2.0: each pad fires exactly once
// *per commodity*. Different commodities can each
// consume the pad once; subsequent assertions in an
// already-padded commodity check the running balance
// against the asserted amount without re-padding (and
// therefore fail honestly when a later real posting
// moves the balance away from the originally-padded
// total). The `padded_commodities` set on each
// `PendingPad` tracks which commodities have fired.
// See #220.
let pad_should_fire = state
.pending_pads
.get(&assertion.account)
.map(|pad| !pad.padded_commodities.contains(&expected_commodity))
.unwrap_or(false);
if pad_should_fire
&& let Some(pad) = state.pending_pads.get(&assertion.account).cloned()
{
let diff = expected_amount - actual_amount;
if !diff.is_zero() {
// Ensure both accounts exist in the accounts map
// (so callers iterating accounts see them).
for acct in [&assertion.account, &pad.source_account] {
if !accounts.contains_key(acct.as_str()) {
accounts.insert(acct.clone(), Default::default());
}
}
// Update running balances: target += diff, source -= diff.
// Pad-synthesised postings have no lot annotation; key
// into the default (lot=None) bucket on each side.
state
.account_inventories
.entry(assertion.account.clone())
.or_default()
.add(expected_commodity.clone(), None, diff);
state
.account_inventories
.entry(pad.source_account.clone())
.or_default()
.add(expected_commodity.clone(), None, -diff);
// Build the synthesized transaction.
let pad_marker_meta: BTreeMap<String, String> =
[("pad".to_string(), pad.source_account.clone())]
.into_iter()
.collect();
let target_amount = crate::elaboration::Amount {
by_commodity: BTreeMap::from([(
expected_commodity.clone(),
crate::decimal_to_proto(diff),
)]),
};
let source_amount = crate::elaboration::Amount {
by_commodity: BTreeMap::from([(
expected_commodity.clone(),
crate::decimal_to_proto(-diff),
)]),
};
let synthesized_postings = vec![
crate::elaboration::Posting {
account: assertion.account.clone(),
payee: String::from("(pad)"),
amount: Some(target_amount),
state: crate::state_to_proto(&TransactionState::Cleared),
tags: vec![],
metadata: BTreeMap::new(),
kind: crate::posting_kind_to_proto(ast::PostingKind::Real),
lot: None,
},
crate::elaboration::Posting {
account: pad.source_account.clone(),
payee: String::from("(pad)"),
amount: Some(source_amount),
state: crate::state_to_proto(&TransactionState::Cleared),
tags: vec![],
metadata: BTreeMap::new(),
kind: crate::posting_kind_to_proto(ast::PostingKind::Real),
lot: None,
},
];
transactions.push(crate::elaboration::Transaction {
date: pad.date.to_epoch_days(),
secondary_date: None,
state: crate::state_to_proto(&TransactionState::Cleared),
code: None,
description: String::from(
"(padding inserted for balance assertion)",
),
tags: vec![],
metadata: pad_marker_meta,
postings: synthesized_postings,
});
// The assertion now holds by construction.
actual_amount = expected_amount;
}
// Mark this commodity as padded -- whether or not
// a transaction was synthesised. The zero-diff
// case (`if !diff.is_zero()` above skipped
// synthesis) still consumes the pad: bean-check
// treats the assertion as the pad's "fire" event
// even when the running balance already matches.
if let Some(pad_mut) = state.pending_pads.get_mut(&assertion.account) {
pad_mut
.padded_commodities
.insert(expected_commodity.clone());
}
}
// 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.
// In `BalanceMode::AtPriceWithSynthesis`, this is at @price;
// in `CostBasis`, it is at cost.
let mut transaction_state = Amount(BTreeMap::default());
// Parallel running sum at COST basis. Diverges from
// `transaction_state` only in `AtPriceWithSynthesis` mode for
// postings that have BOTH `{cost}` and `@price` (where the
// two summands are different). After the balance check, any
// non-zero value here is the realized capital gain in that
// commodity, and we synthesize a posting on the configured
// gains account so the elaborated transaction is also
// cost-basis-balanced. See #210.
let mut cost_basis_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![];
// Per-transaction lots already consumed by inline
// booking, so a second MISSING-cost reduction in
// the same transaction doesn't re-draw against the
// same inventory units. Keyed by
// `(account, commodity, lot_key)`.
let mut booked_consumed: BTreeMap<(String, String, LotKey), Decimal> =
BTreeMap::new();
// Accumulates per-(item_commodity, lot_key) net units from explicit
// lot-bearing postings eligible for null-posting per-lot synthesis (#276).
//
// ledger-cli and Beancount have **genuinely different** auto-balance
// semantics for transactions with `{cost}`-only explicit legs:
//
// ledger-cli: `Assets:Foo 10 AAPL {$150} / Assets:Cash`
// → Cash gets `-10 AAPL {$150}` (per-lot inverse;
// Cash carries an AAPL "short position" at the lot's cost).
//
// Beancount: same input → Cash gets `-1500 USD` (cash residue;
// Cash carries USD, not AAPL).
//
// These are mathematically equivalent at the value level but produce
// different `(account, commodity, amount)` tuples in the elaborated
// Journal — which downstream consumers see directly. Beancount further
// enforces its model via `LotValidationMode::Strict`, which raises
// `PhantomLotReduction` if a negative lot lands on an account without
// prior holdings. The gate routes each frontend to its reference tool's
// behavior; it is a structural encoding of the divergence, not a
// defensive workaround.
//
// Eligibility criteria per posting (all must hold):
// - Real or virtual-balanced (affects transaction balance).
// - `{cost}` annotation present (lot_key.cost.is_some()).
// - NO `@ price` annotation. With `@ price` ledger uses the
// cash-residue path (e.g. for sales, where the auto-balance leg
// is the proceeds).
// - Positive net units (items flowing INTO an account). Negative
// units are sales/reductions; ledger uses cash-residue there.
// - `LotValidationMode::Permissive` (ledger-cli / hledger). Beancount
// uses `Strict` and the cash-residue path.
//
// Value: `(net_item_units, proto_lot)` — the proto_lot is cloned
// onto the synthesized inverse posting.
let mut lot_bearing_state: BTreeMap<
(String, LotKey),
(Decimal, crate::elaboration::Lot),
> = BTreeMap::new();
// Capture the account-properties map by reference
// before the per-posting loop: inside the
// `AmountDetails::Amount` arm, the local `value`
// (a `Decimal`) shadows the outer `value: HIR`,
// so `value.global_context` is unreachable there.
let account_properties = &value.global_context.account_properties;
// Implicit-cost inference (#251, #285): when enabled, detect
// transactions whose real-posting net balance reduces to exactly
// 2 non-zero commodities and synthesise a `@` per-unit-cost
// annotation on the postings in the positive-net commodity
// BEFORE the per-posting loop so that the regular lot-pricing
// path handles it transparently. Only ledger-cli and hledger
// enable this (`infer_implicit_total_cost = true`).
if config.infer_implicit_total_cost {
infer_implicit_total_cost(
&mut transaction.postings,
entry_context,
&state,
)?;
}
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_inventories.get(&account_name);
// `lot_cash` -- the (total, commodity) pair to use for
// transaction balancing, along with the elaborated
// lot annotation for the proto output.
// `no_price_annotation`: true when no `@`/`@@` price annotation
// accompanied this posting's amount. Used by the per-lot synthesis
// pass to decide whether to emit a per-lot inverse on the null
// account (#276): ledger-cli emits per-lot item postings when
// `{cost}` is present WITHOUT a `@ price`; when `@ price` is also
// present the cost-basis cash path applies instead.
#[allow(clippy::type_complexity)]
let (
value,
commodity,
lot_cash,
proto_lot,
cost_basis_cash,
no_price_annotation,
): (
Decimal,
String,
Option<(Decimal, String)>,
Option<crate::elaboration::Lot>,
Option<(Decimal, String)>,
bool,
) = 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");
// Auto-fill the lot date from the
// transaction date for AUGMENTING
// postings (positive units, explicit
// cost): matches bean-check, which
// writes the transaction date as
// the lot's acquisition date when
// `{}` carries no `[date]`.
// Reducing postings (negative
// units) and MISSING-cost specs are
// left as the user wrote them: the
// booking pass walks inventory and
// re-emits explicit-cost postings
// with the matched lot's date.
// Required for FIFO / LIFO to
// distinguish lots whose only other
// annotation is cost.
let is_augmenting =
!value.is_sign_negative() && !value.is_zero();
let lot_date =
ann.date.or(if is_augmenting && ann.cost.is_some() {
Some(transaction.date)
} else {
Option::None
});
let proto_date =
lot_date.map(|d| (d - epoch).num_days() as i32);
let cost_is_total = ann.cost_is_total;
let (proto_cost, cost_pair) =
if let Some(cost_expr) = ann.cost {
let (mut cv, cc) =
evaluator::eval_and_normalize_amount(
cost_expr,
entry_context,
&state,
)?;
// `{{total}}` form: convert total -> per-unit
// by dividing by the posting's absolute unit
// count. The proto stores the canonical
// per-unit form; the source-syntax
// distinction is intentionally erased here.
if cost_is_total {
if value.is_zero() {
return Err(
ElaborationError::TotalCostWithZeroUnits,
);
}
cv /= value.abs();
}
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)
};
// The cost-basis cash equivalent (always
// computed; used for `cost_basis_state`
// and, in `CostBasis` mode, for the
// primary `lot_cash` too).
let cost_basis_cash = cost_for_balance
.as_ref()
.map(|(cv, cc)| (value * *cv, cc.clone()));
// Cash-contribution priority depends on
// `balance_mode` (#210):
//
// - `CostBasis` (ledger-cli, Beancount):
// `{cost}` drives cash; `@price` is
// informational only. The user is
// responsible for writing an explicit
// gain/loss posting that absorbs any
// cost-vs-price residual.
//
// - `AtPriceWithSynthesis` (hledger):
// `@price` drives cash when present;
// `{cost}` falls back when absent. The
// cost-vs-price residual is captured
// in `cost_basis_state` and a gains
// posting is synthesized after the
// transaction-balance check.
// Helper: evaluate the @price expression
// into a (units * price, commodity) cash
// contribution.
let at_price_cash = |lp: ast::LotPricing,
state: &RunningState|
-> Result<
Option<(Decimal, String)>,
ElaborationError,
> {
Ok(match lp {
ast::LotPricing::Total(expr) => {
let (mut v, c) =
evaluator::eval_and_normalize_amount(
expr,
entry_context,
state,
)?;
if value.is_sign_negative() {
v = -v;
}
Some((v, c))
}
ast::LotPricing::Unit(expr) => {
// Intent-driven canonical cost (#281):
// round `qty * price` to the price
// commodity's inferred decimal precision
// before accumulating into the transaction
// balance. This matches ledger-cli's
// per-posting price-rounding compensation
// (xact.cc:872-904) without a tolerance
// window — the balance check still requires
// exact zero, but "cost" is redefined as
// the intent-rounded value.
//
// `inferred_scale` was populated during the
// resolution walk as the max scale seen for
// the commodity across all direct posting
// amounts. For `$`, prior `$474.31` amounts
// establish scale 2. High-precision prices
// like `$53.659999...28 digits` are then
// rounded to 2dp (cents), removing
// IEEE-double noise and producing a
// zero-sum balance.
//
// Exception: when the `@`-price was
// expressed in a different commodity and
// reached the canonical form via a
// `C`-directive chain conversion (#288),
// skip rounding. Chain-converted values
// are exact (e.g. `21050 COPPER / 10000
// = 2.105 GOLD` with no precision loss),
// so rounding would introduce error
// (`2.10`) rather than remove it.
// ledger-cli matches this: it accumulates
// amounts in their native commodity and
// only converts to the chain root at
// display/reporting time.
let (v, c, precision) = evaluator::eval_and_normalize_amount_with_precision(
expr,
entry_context,
state,
None,
)?;
let exact_cost = v * value;
// Intent-rounding is only meaningful for
// values that may carry IEEE-double noise
// from a high-precision input literal.
// A `Precision::Exact` price (currently:
// produced by a `C`-directive chain
// conversion) is mathematically exact;
// rounding it to the result commodity's
// inferred display scale would discard
// genuine precision (e.g. truncating
// `21050 COPPER → 2.105 GOLD` to
// `2.10 GOLD`), which ledger-cli does NOT
// do — it accumulates in the native
// commodity and only converts at display
// time.
let canonical_cost = match precision {
evaluator::Precision::Exact => exact_cost,
evaluator::Precision::PossiblyNoisy => {
commodity_properties
.get(&c)
.map(|p| {
exact_cost
.round_dp(p.inferred_scale)
})
.unwrap_or(exact_cost)
}
};
Some((canonical_cost, c))
}
})
};
// Capture whether a `@`/`@@` price annotation was
// present BEFORE consuming `lot_pricing` in the
// `lot_cash` computation below. This is used by the
// per-lot synthesis pass to distinguish pure inventory
// moves (`{cost}` only → per-lot inverse) from buy/sell
// transactions (`{cost} @ price` → cash path).
let had_lot_pricing = lot_pricing.is_some();
let lot_cash = match &balance_mode {
resolution::BalanceMode::CostBasis => {
// `{cost}` drives balance when
// present. When absent (e.g.
// ledger's `10 AAPL @ $150` BUY
// syntax with no separate `{cost}`),
// fall back to `@price` because
// there's no cost-basis to use.
// `@price` ignored only when
// `{cost}` is present.
match &cost_basis_cash {
Some(_) => cost_basis_cash.clone(),
None => match lot_pricing {
Some(lp) => at_price_cash(lp, &state)?,
None => None,
},
}
}
resolution::BalanceMode::AtPriceWithSynthesis {
..
} => match lot_pricing {
Some(lp) => at_price_cash(lp, &state)?,
None => cost_basis_cash.clone(),
},
};
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
.map(|ab| ab.commodity_balance(&commodity))
.unwrap_or(Decimal::ZERO)
+ value
== baval)
{
Err(ElaborationError::PostingBalanceAssertionFailed)?;
}
}
(
value,
commodity,
lot_cash,
proto_lot,
cost_basis_cash,
!had_lot_pricing,
)
}
AmountDetails::BalanceAssignmentAllCommodities(target) => {
// hledger `==* target` (or `=* target`) form -- typically
// `==* 0` in a fiscal-year retained-earnings transaction.
// Synthesize a multi-commodity posting that brings every
// commodity currently held by the account to `target`.
//
// The target expression is expected to be a bare number
// with no commodity (e.g. `0`); we evaluate it once and
// apply the same target value to each commodity.
// Evaluate `target` to a single numeric value. The
// `==* X` form has no commodity attached -- the
// target applies to whatever commodities the
// account already holds.
let target_value = evaluator::eval_amount_value(
target,
entry_context,
&state,
)?;
// Aggregate the named account *and its subtree*. hledger's
// `==*` operates on the entire subtree, not just the named
// account: e.g. `Income ==* 0` zeroes the whole `Income:*`
// subtree by synthesizing a corrective posting on `Income`
// itself.
let deltas: Vec<(String, Decimal)> = subtree_commodity_balance(
&state.account_inventories,
&account_name,
)
.into_iter()
.map(|(c, v)| (c, target_value - v))
.collect();
if !accounts.contains_key(&account_name) {
accounts.insert(account_name.clone(), Default::default());
}
// Update transaction_state and account_inventories.
let bal_entry = state
.account_inventories
.entry(account_name.clone())
.or_default();
let mut by_commodity: BTreeMap<
String,
crate::elaboration::Decimal,
> = BTreeMap::new();
if posting_kind != ast::PostingKind::VirtualUnbalanced {
for (c, delta) in &deltas {
*transaction_state.0.entry(c.clone()).or_default() +=
delta;
// Mirror into cost_basis_state so
// the post-balance synthesis pass
// (#210) doesn't see a phantom
// residual on `==*` postings.
*cost_basis_state.0.entry(c.clone()).or_default() +=
delta;
}
}
for (c, delta) in &deltas {
// The `==*` synthesis arm aggregates across all lots
// and writes the corrective delta into the default
// (lot=None) bucket on the named account. Lot-bearing
// positions in the same commodity are unchanged; only
// the aggregated commodity total reaches the asserted
// amount.
bal_entry.add(c.clone(), None, *delta);
by_commodity
.insert(c.clone(), crate::decimal_to_proto(*delta));
}
let payee =
posting.metadata.remove("payee").unwrap_or(payee.clone());
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: None,
});
// Skip the standard single-commodity push path; we already
// pushed the synthesized multi-commodity posting above.
continue;
}
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
.commodities()
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
.filter(|c| !ab.commodity_balance(c).is_zero())
.map(|c| c.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
.map(|ab| ab.commodity_balance(&commodity))
.unwrap_or(Decimal::ZERO);
// BalanceAssignment never carries a lot or price annotation.
(value, commodity, None, None, None, true)
}
};
// Inline booking (#242): when the lot
// annotation carried a MISSING cost (`{}`
// or partial like `{2024-01-15}`) and the
// account has a non-NONE booking method,
// walk the running inventory NOW (before
// contributing to transaction_state) and
// synthesise per-matched-lot postings.
// Each booked sub-posting carries its
// explicit cost basis on the proto Lot,
// and the cost-basis cash (NOT @price)
// flows into transaction_state -- so the
// null posting fills against the post-
// booking residual and gain inference is
// correct.
//
// Booking also fires for *partial-spec*
// reductions like `-30 AAPL {185.40 USD}`
// (cost specified, date / label missing):
// bean-check's strict booking matches such
// a partial spec against the concrete
// dated inventory lot and rewrites the
// reduction's lot key to the matched lot's
// full key. doppio mirrors this so per-lot
// running state (#237) tracks the
// reduction against the same bucket as the
// augmentation (#227 parity comparator).
// Cost-MISSING reductions trigger
// unconditionally; partial-spec reductions
// only when the inventory has positions in
// the same `(account, commodity)` to draw
// against -- otherwise the
// "create-labeled-short-position" path
// (matching bean-check's no-prior
// behaviour) takes over.
let needs_booking = proto_lot.as_ref().is_some_and(|l| {
if l.cost.is_none() {
return true;
}
if !value.is_sign_negative() {
return false;
}
state
.account_inventories
.get(&account_name)
.is_some_and(|inv| {
inv.positions
.iter()
.any(|((c, _), v)| c == &commodity && !v.is_zero())
})
});
if needs_booking {
let booking_method = value_global_account_property(
&account_name,
account_properties,
config.default_booking_method,
);
if !matches!(booking_method, resolution::BookingMethod::None) {
let payee_for_booking =
posting.metadata.remove("payee").unwrap_or(payee.clone());
let booked = book_missing_cost_inline(
&account_name,
&payee_for_booking,
posting_kind,
&posting.state.into(),
&posting.tags,
&posting.metadata,
&commodity,
value,
proto_lot.as_ref().expect("checked"),
booking_method,
state.account_inventories.get(&account_name),
&mut booked_consumed,
)?;
if !accounts.contains_key(&account_name) {
accounts.insert(account_name.clone(), Default::default());
}
if posting_kind != ast::PostingKind::VirtualUnbalanced {
for (_, cash) in &booked {
let (cb_total, cb_commodity) = cash;
*transaction_state
.0
.entry(cb_commodity.clone())
.or_default() += *cb_total;
*cost_basis_state
.0
.entry(cb_commodity.clone())
.or_default() += *cb_total;
}
}
for (booked_posting, _) in booked {
resolved_postings.push(booked_posting);
}
continue;
}
}
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.clone())
.or_default();
*dec += *lot_total;
} else {
let dec =
transaction_state.0.entry(commodity.clone()).or_default();
*dec += value;
}
// `cost_basis_state` mirrors `transaction_state`
// except lot-priced postings contribute their
// COST-basis cash equivalent (when present),
// not their @price-based one. Diverges only in
// `AtPriceWithSynthesis` mode for postings with
// both `{cost}` and `@price`.
if let Some((cb_total, cb_commodity)) = &cost_basis_cash {
let dec =
cost_basis_state.0.entry(cb_commodity.clone()).or_default();
*dec += *cb_total;
} else if let Some((lot_total, lot_commodity)) = &lot_cash {
// No cost annotation; the lot_cash IS the
// cost-basis contribution (or the only
// contribution available).
let dec = cost_basis_state
.0
.entry(lot_commodity.clone())
.or_default();
*dec += *lot_total;
} else {
let dec =
cost_basis_state.0.entry(commodity.clone()).or_default();
*dec += value;
}
}
// Track explicit lot-bearing postings for per-lot null-posting
// synthesis (#276). The synthesis path mirrors ledger-cli's
// semantics: when an auto-balance leg sits opposite a `{cost}`-
// annotated explicit leg, ledger emits a per-lot inverse on the
// auto-balance leg (so e.g. a Cash account opposite `10 AAPL {$150}`
// ends up holding `-10 AAPL {$150}`, not `-$1500`). Beancount has
// a different model (cash residue, not per-lot inverse) — see the
// `lot_bearing_state` declaration above for the full structural
// explanation; this gate routes each frontend to its reference
// tool's behavior.
//
// A posting qualifies when ALL of:
//
// 1. Real or virtual-balanced (affects transaction balance).
// 2. `{cost}` annotation is present (lot_key.cost.is_some()).
// 3. NO `@ price` annotation. With `@ price` (typically a sale)
// ledger-cli switches to the cash-residue path; the auto-
// balance leg is the proceeds in the price commodity.
// 4. Positive net units (items flowing INTO accounts). Negative
// units are sales/reductions; cash-residue is correct there.
// 5. `Permissive` lot-validation mode (ledger-cli / hledger).
// Beancount's `Strict` mode applies the cash-residue rule
// and would reject the per-lot inverse via
// `PhantomLotReduction` for auto-balance accounts that
// don't already hold the item commodity. Real Beancount
// fixtures (bean-example, bean-starter, bean-basic) hit
// this path with cash auto-balance legs, so the gate is
// load-bearing — verified by CI failures on those fixtures
// when the gate is removed.
if posting_kind != ast::PostingKind::VirtualUnbalanced
&& no_price_annotation
&& lot_validation_mode == resolution::LotValidationMode::Permissive
&& let Some(proto_lot_ref) = &proto_lot
&& let Some(lot_key) = lot_key_from_proto(Some(proto_lot_ref))
&& lot_key.cost.is_some()
&& value.is_sign_positive()
{
let entry = lot_bearing_state
.entry((commodity.clone(), lot_key))
.or_insert((Decimal::ZERO, proto_lot_ref.clone()));
entry.0 += 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());
// Offset `cost_basis_state` by the full transaction balance so
// any residual in `cost_basis_state` after this point represents
// realized capital gain (only non-zero in `AtPriceWithSynthesis`
// mode for transactions with `{cost} @price` postings; see #210).
// This must happen once over the full `transaction_state`, before
// the per-lot and cash-residue postings below.
for (c, v) in &transaction_state.0 {
*cost_basis_state.0.entry(c.clone()).or_default() -= *v;
}
// Convert the posting state once — reused across all synthesized
// postings (per-lot and cash-residue).
let proto_state = crate::state_to_proto(&posting.state.into());
// Per-lot synthesis (#276): for each distinct (commodity, lot_key)
// accumulated from positive-unit `{cost}`-bearing explicit postings,
// emit one inverse item posting on the auto-balanced account. This
// preserves per-lot identity at the null account, matching ledger-cli's
// inventory semantics for inter-account transfers and first-time grants.
//
// Only positive-unit lots participate: negative-unit (sale/reduction)
// postings are excluded from `lot_bearing_state` because their cost-
// basis cash already flows through `transaction_state` correctly —
// ledger-cli empirically produces a cost-basis cash posting (not a
// per-lot item posting) on the null account for sale transactions.
//
// For each qualifying lot:
// - synthesize an inverse item posting (amount = -net_units of commodity)
// with the lot annotation copied verbatim.
// - deduct the lot's cash contribution (net_units * cost) from
// `cash_residue` so the subsequent cash posting carries only the
// non-lot residual (zero for pure inventory transactions).
let mut cash_residue = transaction_state.0.clone();
let mut any_lot_posted = false;
for ((item_commodity, lot_key), (net_units, proto_lot)) in
&lot_bearing_state
{
// Deduct this lot's cost contribution from the cash residue.
// `lot_key.cost` is the per-unit cost, so total = net_units * cost.
if let (Some(cost), Some(cost_commodity)) =
(&lot_key.cost, &lot_key.cost_commodity)
{
let lot_cash_total = net_units * cost;
*cash_residue.entry(cost_commodity.clone()).or_default() -=
lot_cash_total;
}
// Synthesize the inverse item posting with the lot annotation.
let by_commodity = BTreeMap::from([(
item_commodity.clone(),
crate::decimal_to_proto(-net_units),
)]);
resolved_postings.push(crate::elaboration::Posting {
account: account_name.clone(),
payee: payee.clone(),
amount: Some(crate::elaboration::Amount { by_commodity }),
state: proto_state,
tags: posting.tags.clone(),
metadata: posting.metadata.clone(),
kind: crate::posting_kind_to_proto(ast::PostingKind::Real),
lot: Some(proto_lot.clone()),
});
any_lot_posted = true;
}
// Emit a plain cash posting for whatever remains after deducting the
// per-lot cost contributions. For pure cash transactions and for buy
// transactions (no positive-unit lot postings), this is the only
// posting emitted. Preserve the wire-format invariant: always emit
// exactly one posting when no lot postings were emitted.
// 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: BTreeMap<String, _> = cash_residue
.iter()
.filter(|(_, v)| !v.is_zero())
.map(|(c, v)| (c.clone(), crate::decimal_to_proto(-v)))
.collect();
if !by_commodity.is_empty() || !any_lot_posted {
resolved_postings.push(crate::elaboration::Posting {
account: account_name,
payee,
amount: Some(crate::elaboration::Amount { by_commodity }),
state: proto_state,
tags: posting.tags,
metadata: posting.metadata,
kind: crate::posting_kind_to_proto(ast::PostingKind::Real),
lot: None,
});
}
} else {
// No null posting. The transaction must balance to
// zero per commodity, modulo the active tolerance
// policy. Sub-tolerance residuals are absorbed into a
// single multi-commodity synthesized posting whose
// account is `""` (doppio's "rounding residual"
// sentinel; see #198).
//
// Virtual-unbalanced postings have already been
// excluded from `transaction_state`, so a transaction
// consisting solely of virtual-unbalanced postings
// has an empty (zero) state and bypasses this check.
let residuals: Vec<(String, Decimal)> = transaction_state
.0
.iter()
.filter(|(_, v)| !v.is_zero())
.map(|(c, v)| (c.clone(), *v))
.collect();
let mut absorbed: BTreeMap<String, Decimal> = BTreeMap::new();
for (commodity, residual) in &residuals {
// Per-commodity override (e.g. from Beancount's
// `option "inferred_tolerance_default"
// "USD:0.005"`) wins over the rule-based
// fraction-of-smallest-precision default.
let tolerance =
if let Some(absolute) = tolerance_overrides.get(commodity) {
*absolute
} else {
let resolution::ToleranceMode::FractionOfSmallestPrecision(
fraction,
) = tolerance_mode;
if fraction.is_zero() {
Decimal::ZERO
} else {
// tolerance = fraction * 10^(-min_scale).
//
// When `fraction == 1` (ledger/hledger mode),
// `min_scale` is derived from `inferred_scale`
// on `CommodityProperties` when present and
// non-zero. `inferred_scale` encodes the
// journal's declared precision intent (from
// D/format directives and direct posting scales
// across all transactions, #281/#286). This
// matches ledger-cli's commodity display-
// precision `is_zero()` check (xact.cc:872-904):
// a residue smaller than `10^(-inferred_scale)`
// is sub-precision noise. For `$` with
// inferred_scale=2, tolerance = $0.01.
//
// For all other fractions (e.g. Beancount's
// fraction=0.5), the original per-posting
// min_scale rule is used: tolerance = fraction *
// 10^(-least_precise_posting_scale). This
// preserves Beancount's inferred-tolerance
// semantics unchanged.
//
// The inferred_scale path also falls back to
// per-posting min_scale when the commodity has
// no CommodityProperties entry (no direct
// postings and no D/format directive).
let min_scale: u32 = if fraction == Decimal::ONE {
// ledger/hledger: prefer journal-wide
// inferred_scale for the commodity.
commodity_properties
.get(commodity)
.map(|props| props.inferred_scale)
.filter(|&s| s > 0)
.unwrap_or_else(|| {
resolved_postings
.iter()
.filter_map(|p| {
p.amount
.as_ref()?
.by_commodity
.get(commodity)
})
.map(|d| d.scale)
.min()
.unwrap_or(0)
})
} else {
// Beancount and others: least-precise
// posting's decimal scale.
resolved_postings
.iter()
.filter_map(|p| {
p.amount.as_ref()?.by_commodity.get(commodity)
})
.map(|d| d.scale)
.min()
.unwrap_or(0)
};
let one_unit = Decimal::new(1, min_scale);
fraction * one_unit
}
};
if residual.abs() > tolerance {
return Err(ElaborationError::TransactionDoesNotBalance(
transaction_state,
));
}
absorbed.insert(commodity.clone(), -*residual);
}
// Synthesize one multi-commodity posting that
// absorbs every (sub-tolerance) residual. The
// empty-string account is intentionally not added
// to `accounts` or `account_inventories`: it's a
// wire-format artefact, not a user-facing account.
if !absorbed.is_empty() {
let by_commodity: BTreeMap<String, crate::elaboration::Decimal> =
absorbed
.iter()
.map(|(c, v)| (c.clone(), crate::decimal_to_proto(*v)))
.collect();
resolved_postings.push(crate::elaboration::Posting {
account: String::new(),
payee: payee.clone(),
amount: Some(crate::elaboration::Amount { by_commodity }),
state: crate::state_to_proto(&TransactionState::Cleared),
tags: vec![],
metadata: BTreeMap::new(),
kind: crate::posting_kind_to_proto(ast::PostingKind::Real),
lot: None,
});
}
}
// After the @price-driven balance check has passed, in
// `AtPriceWithSynthesis` mode, any non-zero entry in
// `cost_basis_state` is a realized capital gain in that
// commodity. Synthesize a posting on the configured
// gains account whose amount = -residual, so the
// elaborated transaction is also cost-basis-balanced.
// Result: `.dop` files are uniformly cost-basis-balanced
// regardless of source frontend (#210).
if let resolution::BalanceMode::AtPriceWithSynthesis { gains_account } =
&balance_mode
{
let gains: BTreeMap<String, Decimal> = cost_basis_state
.0
.iter()
.filter(|(_, v)| !v.is_zero())
.map(|(c, v)| (c.clone(), -*v))
.collect();
if !gains.is_empty() {
if !accounts.contains_key(gains_account.as_str()) {
accounts.insert(gains_account.clone(), Default::default());
}
let gains_balances = state
.account_inventories
.entry(gains_account.clone())
.or_default();
let mut by_commodity: BTreeMap<String, crate::elaboration::Decimal> =
BTreeMap::new();
for (c, v) in &gains {
// Synthesised gains land on the gains-account's
// default (lot=None) bucket; no specific lot to
// attribute the synthetic posting to.
gains_balances.add(c.clone(), None, *v);
by_commodity.insert(c.clone(), crate::decimal_to_proto(*v));
}
resolved_postings.push(crate::elaboration::Posting {
account: gains_account.clone(),
payee: payee.clone(),
amount: Some(crate::elaboration::Amount { by_commodity }),
state: crate::state_to_proto(&TransactionState::Cleared),
tags: vec![],
metadata: BTreeMap::new(),
kind: crate::posting_kind_to_proto(ast::PostingKind::Real),
lot: None,
});
}
}
// 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,
)?;
}
// Strict lot-validation: project this transaction's
// lot-bearing postings onto the running inventory and
// reject any reducing posting whose lot key picks
// *one of several* lots in the same (account,
// commodity) where none of them match. This mirrors
// Beancount's STRICT booking method, which is
// ambiguity-rejection rather than positive-position
// requirement: when an account holds zero of a
// commodity, a -5 AAPL {200 USD} posting creates a
// labeled short position (Beancount accepts it);
// when the same account already holds AAPL under a
// different lot key, the named lot must match.
//
// Augmentation followed by reduction within the
// same transaction is folded into the projected
// delta first, so a tx that creates and then
// reduces the same lot has zero net contribution
// and is accepted. See #237.
if lot_validation_mode == resolution::LotValidationMode::Strict {
let mut projected: BTreeMap<(String, String, LotKey), Decimal> =
BTreeMap::new();
for posting in resolved_postings.iter() {
let Some(lot_key) = lot_key_from_proto(posting.lot.as_ref()) else {
continue;
};
for (commodity, delta) in posting.amounts() {
*projected
.entry((
posting.account.clone(),
commodity.to_string(),
lot_key.clone(),
))
.or_default() += delta;
}
}
for ((account, commodity, lot), delta) in &projected {
if !delta.is_sign_negative() {
continue;
}
// Per-account opt-out: an EXPLICIT
// `BookingMethod::None` on the `open`
// directive means "this account allows
// mixed inventories; don't validate".
// Doesn't apply to accounts that merely
// *fall back* to the frontend default --
// those still participate in
// `LotValidationMode::Strict` checking.
let booking_method = value
.global_context
.account_properties
.get(account)
.and_then(|p| p.booking_method);
if matches!(booking_method, Some(resolution::BookingMethod::None)) {
continue;
}
// The reducer's LotKey acts as a *partial
// spec*: None fields match any value in the
// inventory. A reducer like `{$150}` (cost
// specified, date inherited as None) matches
// any inventory lot at $150 regardless of
// its (auto-filled) acquisition date. See
// #238 for the rationale.
let any_match = state
.account_inventories
.get(account)
.map(|inv| {
inv.positions.iter().any(|((c, k), v)| {
c == commodity
&& !v.is_zero()
&& k.as_ref().is_some_and(|inv_lot| {
lot_matches_pattern(lot, inv_lot)
})
})
})
.unwrap_or(false);
if any_match {
continue;
}
let any_prior_same_commodity = state
.account_inventories
.get(account)
.map(|inv| {
inv.positions
.iter()
.any(|((c, _), v)| c == commodity && !v.is_zero())
})
.unwrap_or(false);
if any_prior_same_commodity {
return Err(ElaborationError::PhantomLotReduction {
account: account.clone(),
commodity: commodity.clone(),
lot: format_lot_key(lot),
});
}
}
}
// Apply automated posting rules.
//
// For each real posting in the already-resolved transaction,
// check every active `=` rule. When the rule's query matches
// the posting's account name, instantiate the rule's body
// postings as virtual-unbalanced entries and append them to
// `resolved_postings`. Virtual-unbalanced postings are
// excluded from the transaction balance check (already
// complete above), so appending them here is safe.
//
// Multiplier semantics: a body posting whose amount is a
// commodity-less bare number is scaled by the matched
// posting's amount in its commodity. A body posting with an
// explicit commodity is taken literally.
//
// `resolved_postings` is grown in-place; we only match
// against the postings that existed BEFORE rule application
// (snapshot the length first).
let base_posting_count = resolved_postings.len();
for rule in &auto_rules {
// Walk postings that existed before any rule application
// (indices 0..base_posting_count). Collect the account
// name and amounts eagerly so we don't hold a borrow on
// `resolved_postings` while pushing to it below.
let matches: Vec<(String, Vec<(String, Decimal)>)> = (0
..base_posting_count)
.filter_map(|pi| {
let p = &resolved_postings[pi];
if !rule.query.is_match(&p.account) {
return None;
}
let amounts: Vec<(String, Decimal)> =
p.amounts().map(|(c, v)| (c.to_string(), v)).collect();
Some((p.account.clone(), amounts))
})
.collect();
for (_matched_account, matched_amounts) in matches {
for rule_posting in rule.postings.iter() {
let synth_account = entry_context
.account_aliases
.get(&rule_posting.account)
.cloned()
.unwrap_or_else(|| rule_posting.account.clone());
// Determine the synthesised amount (or None for
// a null body posting).
let synth_amount: Option<crate::elaboration::Amount> =
match &rule_posting.amount {
None => {
// No amount written: synthesise with
// no amount (mirrors ledger-cli's
// "elide amount" semantic).
None
}
Some(amount_details) => {
// Extract the value expression from
// the body posting's AmountDetails.
// Rule body postings are always
// plain amounts (no balance
// assignment syntax).
let body_value_expr = match amount_details.clone() {
AmountDetails::Amount { value, .. } => value,
// Other variants are not valid
// in rule bodies; skip synthesis.
_ => continue,
};
// Determine whether the body amount is a
// bare number (multiplier) or carries an
// explicit commodity (literal) by inspecting
// the *parsed* expression before evaluation.
//
// A body posting is a multiplier when the
// expression is a commodity-less Amount or a
// Unary { op: Neg, expr: commodity-less Amount }.
// All other forms (explicit commodity, arithmetic
// combining commodity-bearing sub-exprs, etc.)
// are treated as literals.
let is_bare_number =
is_bare_number_expr(&body_value_expr);
if is_bare_number {
// Multiplier: evaluate the scalar and scale
// each matched posting amount by it.
let scalar = evaluator::eval_amount_value(
body_value_expr,
entry_context,
&state,
)?;
let by_commodity: BTreeMap<_, _> = matched_amounts
.iter()
.map(|(c, v)| {
(
c.clone(),
crate::decimal_to_proto(scalar * v),
)
})
.collect();
if by_commodity.is_empty() {
None
} else {
Some(crate::elaboration::Amount {
by_commodity,
})
}
} else {
// Literal: evaluate and use the body amount directly.
let (body_val, body_commodity) =
evaluator::eval_and_normalize_amount(
body_value_expr,
entry_context,
&state,
)?;
let by_commodity = BTreeMap::from([(
body_commodity,
crate::decimal_to_proto(body_val),
)]);
Some(crate::elaboration::Amount { by_commodity })
}
}
};
if !accounts.contains_key(&synth_account) {
accounts.insert(synth_account.clone(), Default::default());
}
// Synthesised postings are always virtual-unbalanced,
// regardless of the kind written in the rule body.
// (ledger-cli enforces this convention for `=` rule
// body postings -- see issue #249.)
resolved_postings.push(crate::elaboration::Posting {
account: synth_account,
payee: payee.clone(),
amount: synth_amount,
state: crate::state_to_proto(&TransactionState::Uncleared),
tags: vec![],
metadata: BTreeMap::new(),
kind: crate::posting_kind_to_proto(
ast::PostingKind::VirtualUnbalanced,
),
lot: None,
});
}
}
}
// 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_inventories
.entry(posting.account.clone())
.or_default();
// Pull the lot key off the elaborated posting (if
// any) so reductions and balance assertions later
// see the right per-lot inventory. Postings with
// no lot annotation key into the default
// (lot=None) bucket and aggregate as before.
let lot_key = lot_key_from_proto(posting.lot.as_ref());
for (commodity, delta) in posting.amounts() {
balances.add(commodity.to_string(), lot_key.clone(), 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)?;
// Canonicalise the primary commodity through the alias map. The
// price expression on the RHS already routes through
// `eval_and_normalize_amount`, which applies the alias map to
// `price_commodity`; the primary commodity is a separate `String`
// copied straight from the AST and would otherwise leave an alias
// in the elaborated journal (#338).
let commodity = final_context
.commodity_conversions
.get(&hp.commodity)
.map(|(c, _)| c.clone())
.unwrap_or(hp.commodity);
prices.push(crate::elaboration::HistoricalPrice {
date: hp.date.to_epoch_days(),
time: hp.time,
commodity,
price: Some(crate::decimal_to_proto(price)),
price_commodity,
});
}
let commodities = 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,
})
}
}
/// Returns `true` if `expr` is a bare number (no commodity annotation).
///
/// Used during automated-rule (`=`) body posting evaluation to decide
/// whether the amount acts as a **multiplier** (scale the matched posting's
/// amount) or a **literal** (use the value as-is with its own commodity).
///
/// The check is syntactic: we inspect the parsed `ValueExpr` tree without
/// evaluating it. A bare number is:
/// - `ValueExpr::Amount { commodity: None, .. }` — the canonical form for
/// `0.12` or `100` parsed without a commodity symbol.
/// - `ValueExpr::Unary { op: Op::Sub | Op::Add, expr }` where `expr` is
/// itself a bare-number expression — handles `-0.10` in rule bodies.
///
/// Everything else (explicit commodity, arithmetic, function call, etc.)
/// is a literal and will be evaluated and used directly.
fn is_bare_number_expr(expr: &ast::ValueExpr) -> bool {
match expr {
ast::ValueExpr::Amount { commodity, .. } => commodity.is_none(),
ast::ValueExpr::Unary { expr, .. } => is_bare_number_expr(expr),
_ => false,
}
}
/// 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
}
/// Visit `account` itself (if present in `map`) and every descendant
/// whose name has `account + ":"` as a prefix, in lexicographic order.
///
/// Account names are colon-separated paths. With keys held in a flat
/// `BTreeMap<String, _>`, the subtree is exactly the half-open range
/// `[account + ":", account + ";")`: `:` is `0x3A` and `;` is `0x3B`,
/// and no byte sequence sorts strictly between them, so every key in
/// that range begins with `account + ":"`. The named account itself
/// is fetched separately because it sorts immediately before the
/// range.
fn for_each_descendant<T>(map: &BTreeMap<String, T>, account: &str, mut f: impl FnMut(&str, &T)) {
let prefix = format!("{account}:");
let upper = format!("{account};");
if let Some((k, v)) = map.get_key_value(account) {
f(k.as_str(), v);
}
for (k, v) in map.range::<String, _>(prefix..upper) {
f(k.as_str(), v);
}
}
/// Extract a [`LotKey`] from an elaborated [`crate::elaboration::Lot`]
/// (the proto wire-format representation). Returns `None` if the
/// posting carried no lot annotation; otherwise returns a key whose
/// fields mirror the wire format: per-unit cost as `(amount, commodity)`,
/// acquisition date (decoded from epoch days), and free-form note.
///
/// `Lot.cost` is a multi-commodity `Amount`; in practice every
/// elaborated lot has at most one commodity in the cost map (the cost
/// commodity), so we read the first entry. If the cost map is empty
/// (a lot with `[date]` only, for example), `cost` and `cost_commodity`
/// are `None`.
/// Does `inventory` satisfy the constraints in `pattern`? Each field
/// of `pattern` that is `Some(_)` must equal the corresponding
/// inventory field; `None` fields in `pattern` match any value. Used
/// by both the phantom-lot validator and the booking pass when a
/// reducer's lot annotation only partially specifies the lot key.
fn lot_matches_pattern(pattern: &LotKey, inventory: &LotKey) -> bool {
if let Some(c) = &pattern.cost
&& Some(c) != inventory.cost.as_ref()
{
return false;
}
if let Some(c) = &pattern.cost_commodity
&& Some(c) != inventory.cost_commodity.as_ref()
{
return false;
}
if let Some(d) = &pattern.date
&& Some(d) != inventory.date.as_ref()
{
return false;
}
if let Some(n) = &pattern.note
&& Some(n) != inventory.note.as_ref()
{
return false;
}
true
}
/// Resolve the booking method for `account`, with fallback to the
/// frontend's `default_booking_method`. Used by the per-posting loop
/// to decide whether a MISSING-cost reduction should be booked
/// inline.
fn value_global_account_property(
account: &str,
account_properties: &BTreeMap<String, resolution::AccountProperties>,
default: resolution::BookingMethod,
) -> resolution::BookingMethod {
account_properties
.get(account)
.and_then(|p| p.booking_method)
.unwrap_or(default)
}
/// Inline booking helper invoked from the per-posting loop when a
/// MISSING-cost lot annotation triggers it (#238 + #242).
///
/// The caller has already evaluated the posting's units and built the
/// partial proto Lot (with `cost = None`). This helper:
///
/// 1. Walks the running inventory in the order dictated by `method`.
/// 2. Filters lots by any partial spec on `partial_lot` (date hint,
/// note hint).
/// 3. For each matched lot, synthesises a booked
/// [`crate::elaboration::Posting`] carrying the matched lot's
/// explicit cost and the take-units of `commodity`.
/// 4. Updates `in_tx_consumed` so a later MISSING-cost posting in
/// the same transaction can't double-consume from the same lot.
/// 5. Returns each booked posting paired with its cost-basis cash
/// contribution `(decimal, cost_commodity)`. The caller folds
/// this into `transaction_state` and `cost_basis_state`.
///
/// Errors:
/// - [`ElaborationError::AugmentingPostingWithMissingCost`] for
/// positive `units` (booking is reduction-only in the first cut).
/// - [`ElaborationError::AmbiguousLotMatch`] when STRICT booking has
/// more than one eligible lot.
/// - [`ElaborationError::OverReductionInBooking`] when the posting
/// asks for more units than the matching lots hold.
///
/// AVERAGE booking falls through to FIFO behaviour (the AVERAGE-
/// specific lot collapse is documented as follow-up to #238).
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
fn book_missing_cost_inline(
account: &str,
payee: &str,
posting_kind: ast::PostingKind,
posting_state: &TransactionState,
posting_tags: &[String],
posting_metadata: &BTreeMap<String, String>,
commodity: &str,
units: Decimal,
partial_lot: &crate::elaboration::Lot,
method: resolution::BookingMethod,
inventory: Option<&AccountInventory>,
in_tx_consumed: &mut BTreeMap<(String, String, LotKey), Decimal>,
) -> Result<Vec<(crate::elaboration::Posting, (Decimal, String))>, ElaborationError> {
if !units.is_sign_negative() {
return Err(ElaborationError::AugmentingPostingWithMissingCost {
account: account.to_string(),
commodity: commodity.to_string(),
});
}
// Partial cost-spec hints: every Some field on the partial spec
// is a constraint; eligible inventory lots must match it. The
// remaining None fields are wildcards. `{1700 USD}` filters by
// cost only; `{2024-01-15}` filters by date only;
// `{1700 USD, 2024-01-15}` requires both. Lots that pass all
// constraints become candidates for the booking method's
// ordering rule.
let cost_hint = partial_lot.cost.as_ref().and_then(|amount| {
amount
.by_commodity
.iter()
.next()
.map(|(c, v)| (v.to_decimal(), c.clone()))
});
let date_hint = partial_lot.date.and_then(|epoch_days| {
chrono::NaiveDate::from_ymd_opt(1970, 1, 1)
.and_then(|epoch| epoch.checked_add_signed(chrono::Duration::days(epoch_days as i64)))
});
let note_hint = partial_lot.note.clone();
let mut eligible_lots: Vec<(LotKey, Decimal)> = inventory
.map(|inv| {
inv.positions
.iter()
.filter_map(|((c, lot_key_opt), bal)| {
if c != commodity {
return None;
}
let lot_key = lot_key_opt.clone()?;
if !bal.is_sign_positive() || bal.is_zero() {
return None;
}
if let Some((cv, cc)) = cost_hint.as_ref()
&& (lot_key.cost.as_ref() != Some(cv)
|| lot_key.cost_commodity.as_ref() != Some(cc))
{
return None;
}
if let Some(d) = date_hint
&& lot_key.date != Some(d)
{
return None;
}
if let Some(n) = note_hint.as_deref()
&& lot_key.note.as_deref() != Some(n)
{
return None;
}
let already = in_tx_consumed
.get(&(account.to_string(), commodity.to_string(), lot_key.clone()))
.copied()
.unwrap_or_default();
let remaining = *bal - already;
if remaining.is_zero() || !remaining.is_sign_positive() {
return None;
}
Some((lot_key, remaining))
})
.collect()
})
.unwrap_or_default();
match method {
resolution::BookingMethod::Fifo
| resolution::BookingMethod::Strict
| resolution::BookingMethod::StrictWithSize
| resolution::BookingMethod::Average => {
eligible_lots.sort_by_key(|(k, _)| k.date);
}
resolution::BookingMethod::Lifo => {
eligible_lots.sort_by_key(|b| std::cmp::Reverse(b.0.date));
}
resolution::BookingMethod::Hifo => {
eligible_lots.sort_by_key(|b| std::cmp::Reverse(b.0.cost));
}
resolution::BookingMethod::None => unreachable!("caller filters NONE"),
}
if matches!(method, resolution::BookingMethod::Strict) && eligible_lots.len() > 1 {
return Err(ElaborationError::AmbiguousLotMatch {
account: account.to_string(),
commodity: commodity.to_string(),
match_count: eligible_lots.len(),
});
}
let mut to_consume = -units; // positive
let total_available: Decimal = eligible_lots.iter().map(|(_, b)| *b).sum();
if to_consume > total_available {
return Err(ElaborationError::OverReductionInBooking {
account: account.to_string(),
commodity: commodity.to_string(),
requested: to_consume,
available: total_available,
});
}
let mut out = Vec::new();
for (lot_key, balance) in eligible_lots {
if to_consume.is_zero() {
break;
}
let take = to_consume.min(balance);
let take_units = -take; // back to negative
let cost = lot_key.cost.expect(
"eligible_lots filters retained only lots with explicit cost; \
None-cost positions are skipped",
);
let cost_commodity = lot_key
.cost_commodity
.clone()
.expect("eligible lots have cost_commodity when cost is Some");
let cost_basis_cash = (take_units * cost, cost_commodity.clone());
let proto_amount = crate::elaboration::Amount {
by_commodity: BTreeMap::from([(
commodity.to_string(),
crate::decimal_to_proto(take_units),
)]),
};
let proto_cost = crate::elaboration::Amount {
by_commodity: BTreeMap::from([(cost_commodity.clone(), crate::decimal_to_proto(cost))]),
};
let proto_date = lot_key.date.and_then(|d| {
chrono::NaiveDate::from_ymd_opt(1970, 1, 1).map(|epoch| (d - epoch).num_days() as i32)
});
let booked = crate::elaboration::Posting {
account: account.to_string(),
payee: payee.to_string(),
amount: Some(proto_amount),
state: crate::state_to_proto(posting_state),
tags: posting_tags.to_vec(),
metadata: posting_metadata.clone(),
kind: crate::posting_kind_to_proto(posting_kind),
lot: Some(crate::elaboration::Lot {
cost: Some(proto_cost),
date: proto_date,
note: lot_key.note.clone(),
}),
};
*in_tx_consumed
.entry((account.to_string(), commodity.to_string(), lot_key.clone()))
.or_default() += take;
out.push((booked, cost_basis_cash));
to_consume -= take;
}
Ok(out)
}
/// Detect whether `postings` reduce to a two-commodity net balance and, if so,
/// synthesise a `@`-style per-unit cost annotation on the postings in the
/// commodity with a positive net balance.
///
/// This generalises the original 2-leg implicit-cost-basis inference (#251) to
/// N-leg transactions. The trigger is not the literal posting count but the
/// count of **distinct non-zero commodities in the real-posting net balance**.
/// When that count is exactly 2 and no posting carries an existing `@`/`@@`
/// price or `{cost}` lot annotation, the inference fires.
///
/// ## Algorithm (mirrors ledger-cli `xact.cc` phase 3)
///
/// Let `net_pos` be the net with a positive balance, `net_neg` the one with a
/// negative balance, and their commodities `comm_pos` / `comm_neg`.
///
/// ```text
/// per_unit_price = |net_neg| / net_pos (in comm_neg units per comm_pos unit)
/// ```
///
/// Every posting in `comm_pos` receives a synthesised
/// [`ast::LotPricing::Unit`] (i.e. `@ per_unit_price comm_neg`). The
/// elaborator's `@`-price path then computes each posting's cash contribution
/// as `per_unit_price × posting_amount`, so the per-posting costs sum to
/// exactly `net_neg` and the transaction balances cleanly.
///
/// ## Sign convention
///
/// *Buy case* (`GGGGG net > 0`, `$ net < 0`):
/// `@ $20.52 per GGGGG` on the GGGGG posting. `lot_cash = 20.52 × 866.231 =
/// 17783.72 $`. Together with the `$-17783.72` posting the $ balance is zero.
///
/// *Sell case* (`AAPL net < 0`, `$ net > 0`):
/// `@ (70/1911.96) AAPL per $` on each $ posting. The elaborator multiplies
/// by each $ posting's amount and the AAPL contributions cancel the `-70 AAPL`
/// posting. All four-leg cancelling-pair transactions (#285) reduce to this
/// shape.
///
/// If the shape does not match (fewer or more than 2 non-zero commodities,
/// any posting has a virtual kind or an existing price/cost annotation, any
/// posting carries a non-`Amount` variant), the function returns without
/// modifying `postings`.
///
/// Only called when `ElaborationConfig::infer_implicit_total_cost` is `true`.
fn infer_implicit_total_cost(
postings: &mut [resolution::Posting],
eval_context: &resolution::Context,
state: &RunningState,
) -> Result<(), ElaborationError> {
// Phase 1: scan all real postings for eligibility and evaluate amounts.
// We build a parallel vec of (posting_index, value, commodity) for every
// real posting with a simple `Amount` variant. Any posting with an existing
// `@ price`, `@@ total`, or `{cost}` annotation disqualifies the whole
// transaction (return early). Non-real and null-amount postings are skipped.
let mut evaluated: Vec<(usize, Decimal, String)> = Vec::new();
for (idx, posting) in postings.iter().enumerate() {
if posting.kind != ast::PostingKind::Real {
continue;
}
let amount = match &posting.amount {
None => continue,
Some(a) => a,
};
match amount {
ast::AmountDetails::Amount {
value,
lot_annotation,
lot_pricing,
..
} => {
// Any existing price or cost annotation → do not infer.
if lot_pricing.is_some() {
return Ok(());
}
if lot_annotation
.as_ref()
.is_some_and(|ann| ann.cost.is_some())
{
return Ok(());
}
let (val, comm) =
evaluator::eval_and_normalize_amount(value.clone(), eval_context, state)?;
evaluated.push((idx, val, comm));
}
// BalanceAssignment / BalanceAssignmentAllCommodities — do not infer.
_ => return Ok(()),
}
}
// Phase 2: compute the per-commodity net balance across all real postings.
let mut net: BTreeMap<String, Decimal> = BTreeMap::new();
for (_, val, comm) in &evaluated {
*net.entry(comm.clone()).or_default() += val;
}
// Restrict to non-zero entries. Exactly 2 required.
let nonzero: Vec<(String, Decimal)> = net.into_iter().filter(|(_, v)| !v.is_zero()).collect();
if nonzero.len() != 2 {
return Ok(());
}
// Phase 3: identify which commodity has a positive net and which has a
// negative net. Both must be non-zero and have opposite signs (otherwise
// the shape is degenerate — two postings both positive, or both negative).
let (comm_pos, net_pos, comm_neg, net_neg) =
if nonzero[0].1 > Decimal::ZERO && nonzero[1].1 < Decimal::ZERO {
(
nonzero[0].0.clone(),
nonzero[0].1,
nonzero[1].0.clone(),
nonzero[1].1,
)
} else if nonzero[1].1 > Decimal::ZERO && nonzero[0].1 < Decimal::ZERO {
(
nonzero[1].0.clone(),
nonzero[1].1,
nonzero[0].0.clone(),
nonzero[0].1,
)
} else {
// Both nets have the same sign — degenerate, do not infer.
return Ok(());
};
// Phase 4: compute the per-unit price and annotate.
//
// per_unit_price = |net_neg| / net_pos (comm_neg per comm_pos unit).
//
// Mirrors ledger-cli xact.cc phase 3:
// `per_unit_cost = (*y / *x).abs().unrounded()`
// where *x is the "item" total and *y is the "cash" total.
//
// We annotate the comm_pos postings (the ones with positive individual or
// net amounts — mirrors the existing 2-leg convention of annotating the
// "buyer" / positive leg). The elaborator's Unit-pricing path then
// computes `per_unit_price × posting_amount` for each posting, giving
// each one a comm_neg cash contribution whose sum equals `net_neg`.
let per_unit_price = net_neg.abs() / net_pos;
for (idx, _, comm) in &evaluated {
if comm == &comm_pos
&& let Some(ast::AmountDetails::Amount { lot_pricing, .. }) = &mut postings[*idx].amount
{
*lot_pricing = Some(ast::LotPricing::Unit(ast::ValueExpr::Amount {
value: per_unit_price,
commodity: Some(comm_neg.clone()),
}));
}
}
Ok(())
}
/// Render a [`LotKey`] for human-readable diagnostic output (error
/// messages, primarily). Mirrors the source-syntax order
/// `{cost} [date] ((note))`, omitting fields that are `None`. Empty
/// keys (all fields `None`) render as `{}` so the surrounding error
/// message still carries punctuation.
fn format_lot_key(lot: &LotKey) -> String {
let mut parts = Vec::new();
if let (Some(cost), Some(commodity)) = (&lot.cost, &lot.cost_commodity) {
parts.push(format!("{{{} {}}}", cost, commodity));
}
if let Some(date) = lot.date {
parts.push(format!("[{}]", date));
}
if let Some(note) = &lot.note {
parts.push(format!("(({}))", note));
}
if parts.is_empty() {
"{}".to_string()
} else {
parts.join(" ")
}
}
fn lot_key_from_proto(lot: Option<&crate::elaboration::Lot>) -> Option<LotKey> {
let lot = lot?;
let mut cost = None;
let mut cost_commodity = None;
if let Some(amount) = lot.cost.as_ref()
&& let Some((commodity, value)) = amount.by_commodity.iter().next()
{
cost = Some(value.to_decimal());
cost_commodity = Some(commodity.clone());
}
let date = lot.date.and_then(|epoch_days| {
chrono::NaiveDate::from_ymd_opt(1970, 1, 1)
.and_then(|epoch| epoch.checked_add_signed(chrono::Duration::days(epoch_days as i64)))
});
Some(LotKey {
cost,
cost_commodity,
date,
note: lot.note.clone(),
})
}
/// Per-commodity sum of the running balance across `account` and
/// every descendant. Used by Beancount's subtree-aware `balance`
/// directive (#214) and by hledger's `==*` synthesis (#207). Zero
/// entries are dropped.
fn subtree_commodity_balance(
account_inventories: &BTreeMap<String, AccountInventory>,
account: &str,
) -> BTreeMap<String, Decimal> {
let mut out: BTreeMap<String, Decimal> = BTreeMap::new();
for_each_descendant(account_inventories, account, |_, inv| {
// Collapse the lot dimension: the subtree-aggregate view sums
// every lot in each commodity, matching what the pre-#237 code
// computed when running state was per-commodity only.
for ((c, _lot), v) in inv.iter_positions() {
*out.entry(c.clone()).or_default() += *v;
}
});
out
}
/// 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)
}
/// Evaluate a value expression and return only its numeric component.
///
/// Used by callers that have a meaningful target value but no
/// associated commodity -- for example `==* 0` (hledger's
/// "zero across every commodity" balance assignment), where the
/// target applies to whatever commodities the account already
/// holds. Skipping commodity normalisation avoids inventing a
/// fake commodity for the inference machinery.
///
/// Errors if the evaluated expression is not an amount.
pub fn eval_amount_value(
val: ast::ValueExpr,
eval_context: &resolution::Context,
running_state: &RunningState,
) -> Result<Decimal, ElaborationError> {
let empty_meta = BTreeMap::default();
match eval(val, eval_context, running_state, &empty_meta, EVAL_BUDGET)? {
ast::ValueExpr::Amount { value, .. } => Ok(value),
other => Err(EvaluationError::UnaryOnNonAmount(other).into()),
}
}
/// 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> {
let (value, commodity, _precision) = eval_and_normalize_amount_with_precision(
val,
eval_context,
running_state,
fallback_commodity,
)?;
Ok((value, commodity))
}
/// Whether an evaluated amount's value is mathematically exact or may
/// carry input-precision noise. Surfaced by
/// [`eval_and_normalize_amount_with_precision`] so callers (specifically
/// the elaborator's `@`-price cost computation) can decide whether to
/// round to the result commodity's intent precision.
///
/// `Exact` is set when the amount passes through a `C`-directive
/// chain conversion: the value was divided by a fixed divisor stored on
/// [`resolution::Context::commodity_conversions`], an operation that is
/// lossless by construction. Rounding such values would discard
/// genuine precision (e.g. truncating `21050 COPPER → 2.105 GOLD`
/// to `2.10 GOLD` and losing 50 COPPER per posting).
///
/// `PossiblyNoisy` is set otherwise. The value may have been multiplied
/// against an input literal that carries IEEE-double serialisation noise
/// (e.g. a tool round-tripping `$53.66` through a 64-bit float emits
/// `$53.6599999999999999998612221219`). Rounding to the result
/// commodity's inferred scale absorbs that noise without affecting
/// values that were already at intent precision.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Precision {
Exact,
PossiblyNoisy,
}
/// Like [`eval_and_normalize_amount_with_fallback`], but also returns a
/// [`Precision`] tag describing whether the result is mathematically exact
/// or may carry input-precision noise.
///
/// The tag drives the elaborator's `@`-price intent-rounding decision:
/// `Exact` values are emitted unchanged (rounding would discard precision
/// rather than absorb noise); `PossiblyNoisy` values are rounded to the
/// commodity's inferred display scale to absorb IEEE-double serialisation
/// noise from inputs like `$53.6599999999999999998612221219`.
///
/// Currently the only signal that produces `Exact` is having passed
/// through a `C`-directive chain conversion (a division by a fixed
/// divisor stored in [`resolution::Context::commodity_conversions`]),
/// which by construction is lossless. A 1:1 alias entry also produces
/// `Exact`, which is harmless — the divisor is `Decimal::ONE` so the
/// rounding step it skips would have been a no-op anyway.
pub fn eval_and_normalize_amount_with_precision(
val: ast::ValueExpr,
eval_context: &resolution::Context,
running_state: &RunningState,
fallback_commodity: Option<&str>,
) -> Result<(Decimal, String, Precision), 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 (value, commodity, precision) = if let Some(commodity) = commodity {
// Apply commodity conversion: if the commodity appears in
// commodity_conversions, divide the amount by the stored divisor
// and rebrand to the canonical commodity.
//
// For plain aliases (from `commodity X\n alias Y`) the divisor
// is Decimal::ONE (a 1:1 rename), so the amount is unchanged.
//
// For `C N1 X = N2 Y` directives, divisor = N1 * N2:
// 250c / 100 = 2.50s (for C 1s = 100c)
// 250c / 100 = 2.50c (for C 100c = 1s, posting in canonical)
if let Some((canonical, divisor)) =
eval_context.commodity_conversions.get(&commodity)
{
(value / divisor, canonical.clone(), Precision::Exact)
} else {
(value, commodity, Precision::PossiblyNoisy)
}
} else {
// No commodity in the expression -- try context default, then
// the caller-supplied fallback (e.g. inferred from account balance).
let commodity = eval_context
.default_commodity
.as_deref()
.or(fallback_commodity)
.ok_or(ElaborationError::AmountWithNoCommodity)?
.to_owned();
(value, commodity, Precision::PossiblyNoisy)
};
Ok((value, commodity, precision))
}
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_inventories
.get(account)
.map(|ab| ab.commodity_balance("$"))
.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::elaborate(hir, &crate::grammars::ledger::ledger_defaults())
.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::elaborate(hir, &crate::grammars::ledger::ledger_defaults())
.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::elaborate(hir, &crate::grammars::ledger::ledger_defaults())
.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::elaborate(hir, &crate::grammars::ledger::ledger_defaults())
}
#[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::elaborate(hir, &crate::grammars::ledger::ledger_defaults())
.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::elaborate(hir, &crate::grammars::ledger::ledger_defaults());
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::elaborate(hir, &crate::grammars::ledger::ledger_defaults());
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_inventories 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) — per-lot inverse on null account (#276 fix).
//
// Empirically verified against ledger-cli:
// `ledger balance --lots --flat` gives `-10 AAPL {USD150}` on Assets:Cash,
// NOT `-$1500`. When `{cost}` is present with no `@ price`, ledger treats the
// transaction as a pure inventory move and emits the per-lot item inverse on the
// null account. The cost annotation drives lot identity, not cash balancing.
// Cash balancing applies only when `@ price` is ALSO present (see the
// `test_lot_cost_and_price_cost_wins_cash` test).
//
// This test's expectation was updated from `Some(-1500)` to `None` for the `$`
// posting as part of the #276 fix to match ledger-cli's principled behavior.
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)));
// Per-lot synthesis: Assets:Cash receives -10 AAPL {$150} (inverse of the lot),
// not a dollar cash posting.
assert_eq!(
t.postings[1].amount_in("AAPL"),
Some(dec!(-10)),
"null posting should be -10 AAPL (per-lot inverse, no @price present)"
);
assert_eq!(
t.postings[1].amount_in("$"),
None,
"no dollar cash posting when {{cost}} has no accompanying @price"
);
assert!(
t.postings[1].has_lot(),
"null posting should carry the lot annotation"
);
// Lot cost preserved on the explicit posting.
assert_eq!(t.postings[0].lot_cost_in("$"), Some(dec!(150)));
}
#[test]
fn test_lot_cost_and_price_cost_wins_cash() {
// 10 AAPL {$150} @ $155 in ledger semantics: `{cost}` drives
// balance (cash = -$1500), `@price` is informational only and
// preserved on the proto Lot. Updated for #210 to match
// ledger-cli's actual semantics; previously this test
// documented doppio's now-fixed @price-wins bug.
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)));
// Cost drives balance: 10 * $150 = $1500.
assert_eq!(
t.postings[1].amount_in("$"),
Some(dec!(-1500)),
"cash side should be -$1500 when {{cost}} is present (cost wins over @price)"
);
// Lot cost annotation is preserved.
assert_eq!(t.postings[0].lot_cost_in("$"), Some(dec!(150)));
}
#[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");
}
// ----------------------------------------------------------------------
// Lot validation tests (#237)
// ----------------------------------------------------------------------
/// Elaborate `input` (ledger syntax) with the given lot validation
/// mode. Used by the strict-mode tests below; ledger syntax is
/// convenient because lot annotations parse identically across the
/// frontends, so the only thing under test is the elaborator's
/// strict-mode logic.
fn elaborate_with_lot_mode(
input: &str,
mode: resolution::LotValidationMode,
) -> 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");
let mut config = crate::grammars::ledger::ledger_defaults();
config.lot_validation_mode = mode;
crate::elaborate(hir, &config)
}
#[test]
fn strict_mode_rejects_phantom_lot_among_existing_lots() {
// The classic phantom-lot case Beancount also rejects: prior
// augmentations exist in the same (account, commodity) but
// under different lot keys. The reducing posting names a lot
// with no matching position, so the booking is ambiguous and
// strict mode rejects.
let input = "\
2024-03-01 Buy AAPL at $150
Assets:Brokerage 10 AAPL {$150}
Assets:Cash
2024-03-02 Try to sell at a phantom cost basis
Assets:Brokerage -5 AAPL {$200}
Assets:Cash $1000
";
let err = elaborate_with_lot_mode(input, resolution::LotValidationMode::Strict)
.expect_err("strict mode should reject phantom lot among existing lots");
match err {
ElaborationError::PhantomLotReduction {
ref account,
ref commodity,
..
} => {
assert_eq!(account, "Assets:Brokerage");
assert_eq!(commodity, "AAPL");
}
other => panic!("expected PhantomLotReduction, got {other:?}"),
}
}
#[test]
fn strict_mode_accepts_phantom_lot_with_no_prior_positions() {
// Beancount's STRICT booking is ambiguity-rejection, not
// positive-position requirement. With zero prior holdings of
// AAPL in the account, a -5 AAPL {$150} posting is allowed
// (creates a labeled short position) -- bean-check accepts
// this and so does doppio.
let input = "\
2024-03-02 Open short position
Assets:Brokerage -5 AAPL {$150}
Assets:Cash $750
";
elaborate_with_lot_mode(input, resolution::LotValidationMode::Strict)
.expect("strict mode should accept reduction with no prior positions");
}
#[test]
fn permissive_mode_accepts_phantom_lot_among_existing_lots() {
// Same journal as the rejection test above; in permissive
// mode (ledger-cli + hledger default) the phantom reduction
// is silently accepted.
let input = "\
2024-03-01 Buy AAPL at $150
Assets:Brokerage 10 AAPL {$150}
Assets:Cash
2024-03-02 Try to sell at a phantom cost basis
Assets:Brokerage -5 AAPL {$200}
Assets:Cash $1000
";
let journal = elaborate_with_lot_mode(input, resolution::LotValidationMode::Permissive)
.expect("permissive mode should accept");
assert_eq!(journal.transactions.len(), 2);
}
#[test]
fn strict_mode_accepts_augmentation_followed_by_reduction_same_transaction() {
// A transaction can both create a lot and immediately reduce
// it: the projected per-(account, commodity, lot) net delta is
// computed across all postings before checking, so prior=0
// with delta=0 (or positive) is allowed.
let input = "\
2024-03-02 Buy and immediately rebalance
Assets:Brokerage 5 AAPL {$150}
Assets:Brokerage -5 AAPL {$150}
Assets:Cash $0
";
elaborate_with_lot_mode(input, resolution::LotValidationMode::Strict)
.expect("augment+reduce in same tx should be accepted");
}
#[test]
fn strict_mode_accepts_reduction_against_prior_augmentation() {
// Augment in transaction 1, reduce in transaction 2: the
// running inventory carries the lot across, so the second
// transaction's reduction is not phantom.
let input = "\
2024-03-01 Buy AAPL
Assets:Brokerage 10 AAPL {$150}
Assets:Cash
2024-03-02 Sell AAPL
Assets:Brokerage -5 AAPL {$150}
Assets:Cash $750
";
let journal = elaborate_with_lot_mode(input, resolution::LotValidationMode::Strict)
.expect("reduction with prior augmentation should be accepted");
assert_eq!(journal.transactions.len(), 2);
}
#[test]
fn strict_mode_does_not_constrain_postings_without_lot_annotation() {
// A posting with no lot annotation keys into the (commodity,
// None) bucket. Strict booking applies only to lot-bearing
// postings: a bare reduction of a commodity not previously
// augmented is still a transaction-balance issue, not a
// phantom-lot issue. Here we balance via a bare augmentation.
let input = "\
2024-03-01 Plain transfer
Assets:Cash -$50
Expenses:Food $50
";
elaborate_with_lot_mode(input, resolution::LotValidationMode::Strict)
.expect("non-lot postings should be unaffected by strict mode");
}
// --- implicit cost-basis inference (#251) --------------------------------
/// Parse a ledger journal through the full pipeline using ledger defaults
/// and return the elaborated Journal (panics on error).
fn elaborate_ledger(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::elaborate(hir, &crate::grammars::ledger::ledger_defaults())
.expect("elaboration failed")
}
/// Parse a ledger journal through the full pipeline using ledger defaults
/// and return the Result (for negative tests).
fn try_elaborate_ledger(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::elaborate(hir, &crate::grammars::ledger::ledger_defaults())
}
#[test]
fn implicit_cost_ledger_two_leg_stock_buy() {
// The canonical example from the issue: a stock purchase with an implicit
// total cost. ledger-cli accepts this as `866.231 GGGGG @@ $17783.72`.
// doppio should elaborate it without error.
let input = "\
2002/09/30 * Buy
Assets:Stock 866.231 GGGGG
Assets:Cash $-17783.72
";
let journal = elaborate_ledger(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
// The stock posting should have 866.231 GGGGG.
let stock = tx
.postings
.iter()
.find(|p| p.account == "Assets:Stock")
.expect("stock posting present");
assert_eq!(
stock.amount_in("GGGGG"),
Some(dec!(866.231)),
"stock posting amount"
);
// The cash posting should be -$17783.72.
let cash = tx
.postings
.iter()
.find(|p| p.account == "Assets:Cash")
.expect("cash posting present");
assert_eq!(
cash.amount_in("$"),
Some(dec!(-17783.72)),
"cash posting amount"
);
}
#[test]
fn implicit_cost_ledger_two_leg_balances() {
// The transaction must balance after inference: no TransactionDoesNotBalance.
let input = "\
2024-01-15 Buy ETH
Assets:Crypto 2.5 ETH
Assets:Bank $-5000
";
// Should not error.
let journal = elaborate_ledger(input);
assert_eq!(journal.transactions.len(), 1);
// Also verify via the running balance: after this transaction,
// Assets:Bank should be -$5000 and Assets:Crypto should be 2.5 ETH.
let tx = &journal.transactions[0];
let bank = tx
.postings
.iter()
.find(|p| p.account == "Assets:Bank")
.expect("bank posting");
assert_eq!(bank.amount_in("$"), Some(dec!(-5000)));
let crypto = tx
.postings
.iter()
.find(|p| p.account == "Assets:Crypto")
.expect("crypto posting");
assert_eq!(crypto.amount_in("ETH"), Some(dec!(2.5)));
}
#[test]
fn implicit_cost_ledger_inferred_lot_matches_explicit() {
// A transaction with an explicit `@@` annotation should produce the same
// final posting amounts as one where the `@@` is inferred.
// Both should elaborate successfully and produce balanced transactions.
let explicit_input = "\
2024-03-01 Buy stock explicit
Assets:Brokerage 10 AAPL @@ $1800
Assets:Cash $-1800
";
let implicit_input = "\
2024-03-01 Buy stock implicit
Assets:Brokerage 10 AAPL
Assets:Cash $-1800
";
let explicit_journal = elaborate_ledger(explicit_input);
let implicit_journal = elaborate_ledger(implicit_input);
// Both should have one balanced transaction.
assert_eq!(explicit_journal.transactions.len(), 1);
assert_eq!(implicit_journal.transactions.len(), 1);
let explicit_tx = &explicit_journal.transactions[0];
let implicit_tx = &implicit_journal.transactions[0];
// Both should have the same commodity amounts on each posting.
let explicit_brokerage = explicit_tx
.postings
.iter()
.find(|p| p.account == "Assets:Brokerage")
.expect("explicit brokerage posting");
let implicit_brokerage = implicit_tx
.postings
.iter()
.find(|p| p.account == "Assets:Brokerage")
.expect("implicit brokerage posting");
assert_eq!(
explicit_brokerage.amount_in("AAPL"),
implicit_brokerage.amount_in("AAPL"),
"brokerage AAPL amounts should match"
);
let explicit_cash = explicit_tx
.postings
.iter()
.find(|p| p.account == "Assets:Cash")
.expect("explicit cash posting");
let implicit_cash = implicit_tx
.postings
.iter()
.find(|p| p.account == "Assets:Cash")
.expect("implicit cash posting");
assert_eq!(
explicit_cash.amount_in("$"),
implicit_cash.amount_in("$"),
"cash amounts should match"
);
}
#[test]
fn implicit_cost_hledger_two_leg() {
// hledger also infers implicit cost; test that the hledger frontend
// accepts the two-leg shape without error.
use crate::{grammars::hledger::parse_hledger, resolution::HIR};
let input = "\
2024-01-15 Buy
Assets:Crypto 2.5 ETH
Assets:Bank $-5000
";
let ast = parse_hledger(input).expect("parse");
let hir = HIR::try_from(ast).expect("resolution");
let journal = crate::elaborate(hir, &crate::grammars::hledger::hledger_defaults())
.expect("hledger elaboration should accept implicit cost");
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
// The ETH posting should have 2.5 ETH.
let crypto = tx
.postings
.iter()
.find(|p| p.account == "Assets:Crypto")
.expect("crypto posting");
assert_eq!(
crypto.amount_in("ETH"),
Some(dec!(2.5)),
"hledger implicit cost: ETH posting amount"
);
// The bank posting should be -$5000.
let bank = tx
.postings
.iter()
.find(|p| p.account == "Assets:Bank")
.expect("bank posting");
assert_eq!(
bank.amount_in("$"),
Some(dec!(-5000)),
"hledger implicit cost: bank posting amount"
);
}
#[test]
fn implicit_cost_beancount_two_leg_still_rejects() {
// Beancount requires explicit cost; the same two-leg shape must still
// produce TransactionDoesNotBalance under beancount_defaults.
use crate::{grammars::beancount::parse_beancount, resolution::HIR};
let input = "\
2024-01-15 * \"Buy\"
Assets:Crypto 2.5 ETH
Assets:Bank -5000 USD
";
let ast = parse_beancount(input).expect("beancount parse");
let hir = HIR::try_from(ast).expect("resolution");
let result = crate::elaborate(hir, &crate::grammars::beancount::beancount_defaults());
assert!(
matches!(result, Err(ElaborationError::TransactionDoesNotBalance(_))),
"Beancount must not infer implicit cost; got: {result:?}"
);
}
#[test]
fn implicit_cost_three_leg_residual_cash_succeeds() {
// A 3-leg buy (stock + commission + cash) reduces to 2 non-zero
// commodity nets (AAPL=+10, $=-1795) and should trigger inference.
// The commission posting cancels part of the cash, leaving an effective
// 2-commodity-net shape: AAPL net +10, $ net -1795. The per-unit price
// inferred is $179.5 per AAPL (=$1795/10). After elaboration the
// transaction should balance without error.
let input = "\
2024-01-15 Three legs
Assets:Brokerage 10 AAPL
Assets:Cash $-1800
Expenses:Commission $5
";
let journal = elaborate_ledger(input);
assert_eq!(
journal.transactions.len(),
1,
"three-leg with 2 net commodities should elaborate successfully"
);
let tx = &journal.transactions[0];
let brokerage = tx
.postings
.iter()
.find(|p| p.account == "Assets:Brokerage")
.expect("brokerage posting");
assert_eq!(
brokerage.amount_in("AAPL"),
Some(dec!(10)),
"AAPL posting amount"
);
}
#[test]
fn implicit_cost_explicit_at_at_no_regression() {
// An explicit `@@` annotation should continue to work; the inferred
// path must not fire when an explicit price is already present.
let input = "\
2024-01-15 Buy with explicit price
Assets:Brokerage 10 AAPL @@ $1800
Assets:Cash $-1800
";
// Should elaborate without error.
let journal = elaborate_ledger(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
let stock = tx
.postings
.iter()
.find(|p| p.account == "Assets:Brokerage")
.expect("brokerage posting");
// The amount should be 10 AAPL.
assert_eq!(
stock.amount_in("AAPL"),
Some(dec!(10)),
"explicit @@ should preserve AAPL units"
);
// Cash posting should be -$1800.
let cash = tx
.postings
.iter()
.find(|p| p.account == "Assets:Cash")
.expect("cash posting");
assert_eq!(cash.amount_in("$"), Some(dec!(-1800)));
}
#[test]
fn implicit_cost_virtual_posting_does_not_fire() {
// A virtual posting does not count as one of the two "real" postings.
// If the real postings don't form the two-leg shape, inference must
// not fire, and the transaction should balance normally (or fail).
//
// Here: one real posting with $, one virtual unbalanced posting with
// GGGGG, and a null real posting. The real postings balance in $ (via
// null inference). No implicit cost should be synthesised.
let input = "\
2024-01-15 Virtual example
Assets:Cash $-1000
(Track:Units) 10 GGGGG
Equity:Opening
";
// The virtual posting is excluded from balance. The two real postings
// (Assets:Cash and Equity:Opening null) should balance normally.
let journal = elaborate_ledger(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
// The Equity:Opening posting should have been null-inferred to $1000.
let equity = tx
.postings
.iter()
.find(|p| p.account == "Equity:Opening")
.expect("equity posting");
assert_eq!(
equity.amount_in("$"),
Some(dec!(1000)),
"null posting should be filled to $1000"
);
// The virtual posting should NOT have a lot annotation.
let virtual_posting = tx
.postings
.iter()
.find(|p| p.account == "Track:Units")
.expect("virtual posting");
assert!(
virtual_posting.lot.is_none(),
"virtual posting should not receive an inferred lot"
);
}
// -------------------------------------------------------------------------
// N-leg implicit cost-basis inference (#285)
// -------------------------------------------------------------------------
/// Minimal repro from ledger-standard.dat line 4063: a 4-leg sale with two
/// cancelling cash legs. The commodity net balance is AAPL=-70, $=+1911.96
/// (exactly 2 non-zero commodities). doppio should infer the implicit cost
/// and elaborate without error, producing the correct per-account balances.
///
/// ledger-cli accepts this as a sale of 70 AAPL for $1,911.96 (per-unit
/// price $27.31 per AAPL). The two $955.98 legs are inter-account cash
/// transfers that cancel in the net.
#[test]
fn test_implicit_cost_basis_4leg_cancelling_pair() {
let input = "\
2004/04/21 * b45923836563f437a6394be8f4fd035bf7145f8d
fc0e191163be4d1966e3c51b1635401f9e82a807 -70 AAPL
f0d45665b22d0562833aa3bf373c5b15640d833e $-955.98
49c6eb709b3d1613e4d6a1c04ee0ed9d23d665a4 $955.98
fc0e191163be4d1966e3c51b1635401f9e82a807 $1,911.96
";
let journal = elaborate_ledger(input);
assert_eq!(
journal.transactions.len(),
1,
"4-leg cancelling-pair should elaborate without error"
);
let tx = &journal.transactions[0];
// The AAPL posting on fc0e... should be -70 AAPL.
let aapl_posting = tx
.postings
.iter()
.find(|p| {
p.account == "fc0e191163be4d1966e3c51b1635401f9e82a807"
&& p.amount_in("AAPL").is_some()
})
.expect("AAPL posting on fc0e... account");
assert_eq!(
aapl_posting.amount_in("AAPL"),
Some(dec!(-70)),
"AAPL posting amount"
);
// The f0d45665... account should have -$955.98.
let f0_posting = tx
.postings
.iter()
.find(|p| p.account == "f0d45665b22d0562833aa3bf373c5b15640d833e")
.expect("f0d45665... posting");
assert_eq!(
f0_posting.amount_in("$"),
Some(dec!(-955.98)),
"f0d45665... posting amount"
);
// The 49c6eb70... account should have +$955.98.
let c6_posting = tx
.postings
.iter()
.find(|p| p.account == "49c6eb709b3d1613e4d6a1c04ee0ed9d23d665a4")
.expect("49c6eb70... posting");
assert_eq!(
c6_posting.amount_in("$"),
Some(dec!(955.98)),
"49c6eb70... posting amount"
);
}
/// Baseline: the original 2-leg shape from #251 must continue to work
/// identically after generalising the trigger. This guards against
/// regressions in the buy-side (positive GGGGG net) path.
#[test]
fn test_implicit_cost_basis_2leg_unchanged() {
let input = "\
2002/09/30 * Buy
Assets:Stock 866.231 GGGGG
Assets:Cash $-17783.72
";
let journal = elaborate_ledger(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
let stock = tx
.postings
.iter()
.find(|p| p.account == "Assets:Stock")
.expect("stock posting");
assert_eq!(
stock.amount_in("GGGGG"),
Some(dec!(866.231)),
"GGGGG posting amount unchanged"
);
let cash = tx
.postings
.iter()
.find(|p| p.account == "Assets:Cash")
.expect("cash posting");
assert_eq!(
cash.amount_in("$"),
Some(dec!(-17783.72)),
"cash posting amount unchanged"
);
}
/// A 3-leg transaction where two cash postings DO NOT cancel (e.g. buy with
/// commission). The commodity net balance is AAPL=+10, $=-1795 — still
/// exactly 2 non-zero commodities — so inference fires. The effective per-
/// unit price is $179.5 per AAPL ($1795 / 10 AAPL).
#[test]
fn test_implicit_cost_basis_3leg_residual_cash() {
let input = "\
2024-01-15 Buy with commission
Assets:Brokerage 10 AAPL
Assets:Cash $-1805
Expenses:Fee $5
";
// Net: AAPL=+10, $=-1800. Two non-zero commodities; inference fires.
let journal = elaborate_ledger(input);
assert_eq!(
journal.transactions.len(),
1,
"3-leg buy-with-fee should elaborate successfully"
);
let tx = &journal.transactions[0];
let brokerage = tx
.postings
.iter()
.find(|p| p.account == "Assets:Brokerage")
.expect("brokerage posting");
assert_eq!(
brokerage.amount_in("AAPL"),
Some(dec!(10)),
"AAPL posting amount"
);
let fee = tx
.postings
.iter()
.find(|p| p.account == "Expenses:Fee")
.expect("fee posting");
assert_eq!(fee.amount_in("$"), Some(dec!(5)), "fee posting amount");
}
/// A transaction with 3 distinct non-zero commodity nets must NOT trigger
/// inference. doppio should reject it with TransactionDoesNotBalance as
/// before.
#[test]
fn test_implicit_cost_basis_3_commodities_no_inference() {
// AAPL net = +10, $ net = -1800, EUR net = +50 → 3 non-zero commodities.
let input = "\
2024-01-15 Three commodities
Assets:Brokerage 10 AAPL
Assets:Cash $-1800
Income:Dividends 50 EUR
";
let result = try_elaborate_ledger(input);
assert!(
matches!(result, Err(ElaborationError::TransactionDoesNotBalance(_))),
"3-commodity net must not trigger implicit cost inference; got: {result:?}"
);
}
/// A transaction that WOULD match the 2-commodity-net shape but already has
/// an explicit `@` or `@@` annotation must not have its annotation
/// overwritten. The explicit annotation wins.
#[test]
fn test_implicit_cost_basis_with_explicit_annotation_no_inference() {
// 4-leg shape (same net as the minimal repro), but with an explicit
// `@` annotation already on the $ posting.
let input = "\
2004/04/21 * Explicit annotation
fc0e191163be4d1966e3c51b1635401f9e82a807 -70 AAPL
f0d45665b22d0562833aa3bf373c5b15640d833e $-955.98 @ 0.03661 AAPL
49c6eb709b3d1613e4d6a1c04ee0ed9d23d665a4 $955.98
fc0e191163be4d1966e3c51b1635401f9e82a807 $1,911.96
";
// The explicit annotation disqualifies the transaction from inference.
// (The explicit price doesn't balance either, so we just confirm inference
// did not silently overwrite it — the transaction should error, not succeed
// silently with an injected annotation.)
let result = try_elaborate_ledger(input);
// It might balance or not depending on the explicit annotation; the key
// assertion is that doppio did NOT overwrite the explicit annotation with
// an inferred one. We check that by confirming the inferred path was not
// entered (which would panic on `lot_pricing.is_some()` check above).
// Any result (Ok or Err) is acceptable here — the test guards the
// "early-return on existing annotation" path.
let _ = result; // Either outcome is valid; no inference should have fired.
}
/// Beancount frontend: `infer_implicit_total_cost = false`. Even with the
/// broadened N-leg trigger, Beancount must not infer implicit cost — the
/// same 4-leg shape should continue to be rejected.
#[test]
fn test_beancount_unaffected_by_nleg_inference() {
use crate::{grammars::beancount::parse_beancount, resolution::HIR};
// Beancount uses explicit cost on every lot-bearing posting.
// The same 2-commodity-net shape must still fail under beancount_defaults.
let input = "\
2024-01-15 * \"Buy\"
Assets:Crypto 2.5 ETH
Assets:Bank -5000 USD
";
let ast = parse_beancount(input).expect("beancount parse");
let hir = HIR::try_from(ast).expect("resolution");
let result = crate::elaborate(hir, &crate::grammars::beancount::beancount_defaults());
assert!(
matches!(result, Err(ElaborationError::TransactionDoesNotBalance(_))),
"Beancount must not infer implicit cost even with N-leg trigger; got: {result:?}"
);
}
// -------------------------------------------------------------------------
// Automated posting rule (`=`) tests (#249)
// -------------------------------------------------------------------------
/// A rule with an explicit commodity-bearing amount applies a literal amount
/// to every matched posting.
#[test]
fn auto_rule_literal_amount_synthesises_posting() {
let input = "\
= /^Income/
(Liabilities:Tithe) $12.00
2024-01-01 * Salary
Income:Salary $-100.00
Assets:Checking
";
let journal = elaborate(input);
// There is exactly one transaction in the output.
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
// The rule synthesises one virtual-unbalanced posting.
let synth: Vec<_> = tx
.postings
.iter()
.filter(|p| p.account == "Liabilities:Tithe")
.collect();
assert_eq!(synth.len(), 1, "one synthesised posting expected");
let amount = synth[0]
.amount
.as_ref()
.expect("synthesised posting has amount");
let decimal = amount.by_commodity.get("$").expect("$ commodity");
assert_eq!(
decimal.to_decimal(),
rust_decimal::Decimal::from(12),
"literal $12.00 expected"
);
}
/// A rule with a commodity-less bare decimal uses multiplier semantics:
/// the synthesised posting's amount is `matched_amount * scalar`.
#[test]
fn auto_rule_multiplier_scales_matched_posting() {
let input = "\
= /^Income/
(Liabilities:Tithe) 0.10
2024-01-01 * Salary
Income:Salary $-100.00
Assets:Checking
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
let synth: Vec<_> = tx
.postings
.iter()
.filter(|p| p.account == "Liabilities:Tithe")
.collect();
assert_eq!(synth.len(), 1, "one synthesised posting expected");
let amount = synth[0]
.amount
.as_ref()
.expect("synthesised posting has amount");
let decimal = amount.by_commodity.get("$").expect("$ commodity");
// 0.10 * $-100.00 = $-10.00
assert_eq!(
decimal.to_decimal(),
rust_decimal::Decimal::from(-10),
"10% of $-100 = $-10 expected"
);
}
/// A rule that does not match any posting produces no synthesised postings.
#[test]
fn auto_rule_no_match_produces_no_postings() {
let input = "\
= /^Expenses/
(Liabilities:Tithe) 0.10
2024-01-01 * Salary
Income:Salary $-100.00
Assets:Checking
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
let synth: Vec<_> = tx
.postings
.iter()
.filter(|p| p.account == "Liabilities:Tithe")
.collect();
assert_eq!(synth.len(), 0, "no match, no synthesised posting expected");
}
/// A rule matches across multiple transactions and synthesises postings
/// for each one independently.
#[test]
fn auto_rule_applies_to_multiple_transactions() {
let input = "\
= /^Income/
(Liabilities:Tithe) 0.10
2024-01-01 * January salary
Income:Salary $-100.00
Assets:Checking
2024-02-01 * February salary
Income:Salary $-200.00
Assets:Checking
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 2);
for tx in &journal.transactions {
let synth: Vec<_> = tx
.postings
.iter()
.filter(|p| p.account == "Liabilities:Tithe")
.collect();
assert_eq!(
synth.len(),
1,
"each transaction gets its own synthesised posting"
);
}
}
/// A rule pattern that matches two postings in the same transaction
/// synthesises two body postings (one per match).
#[test]
fn auto_rule_matches_multiple_postings_in_same_transaction() {
let input = "\
= /^Income/
(Liabilities:Tithe) 0.10
2024-01-01 * Multi-income
Income:Salary $-100.00
Income:Bonus $-50.00
Assets:Checking
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
let synth: Vec<_> = tx
.postings
.iter()
.filter(|p| p.account == "Liabilities:Tithe")
.collect();
// Income:Salary and Income:Bonus both match; two synthesised postings expected.
assert_eq!(synth.len(), 2, "two matches => two synthesised postings");
}
/// A rule body posting with no amount synthesises a posting with no amount
/// (matches ledger-cli's "elide amount" semantic).
#[test]
fn auto_rule_body_posting_no_amount_synthesises_amountless_posting() {
let input = "\
= /^Income/
(Liabilities:Tithe)
2024-01-01 * Salary
Income:Salary $-100.00
Assets:Checking
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
let synth: Vec<_> = tx
.postings
.iter()
.filter(|p| p.account == "Liabilities:Tithe")
.collect();
assert_eq!(synth.len(), 1, "one synthesised posting expected");
assert!(
synth[0].amount.is_none(),
"body posting with no amount should produce amountless synthesised posting"
);
}
/// A periodic (`~`) directive is parsed but does not produce any transactions.
#[test]
fn periodic_directive_parse_and_discard() {
let input = "\
~ monthly
Expenses:Rent $1000
Assets:Checking
2024-01-01 * Real transaction
Expenses:Food $50
Assets:Cash
";
let journal = elaborate(input);
// Only the real transaction appears; the `~` directive is discarded.
assert_eq!(journal.transactions.len(), 1);
assert_eq!(journal.transactions[0].description, "Real transaction");
}
/// Auto-rule application is confined to ledger/hledger frontends.
/// The Beancount frontend does not produce auto-rules; its elaboration
/// under ledger defaults produces no synthesised postings either.
#[test]
fn beancount_frontend_unaffected_by_auto_rules() {
use crate::{grammars::beancount::parse_beancount, resolution::HIR};
// A minimal valid Beancount journal with no `=` directives.
let input = "\
2024-01-01 open Assets:Checking USD
2024-01-01 open Income:Salary USD
2024-01-01 * \"Salary\"
Income:Salary -100 USD
Assets:Checking 100 USD
";
let ast = parse_beancount(input).expect("parse failed");
let hir = HIR::try_from(ast).expect("resolution failed");
assert!(
hir.auto_rules.is_empty(),
"Beancount frontend should produce no auto-rules"
);
let journal = crate::elaborate(hir, &crate::grammars::ledger::ledger_defaults())
.expect("elaboration failed");
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
// No synthesised postings beyond the two real ones.
assert_eq!(
tx.postings.len(),
2,
"no synthesised postings expected from Beancount journal"
);
}
/// An auto-rule with an invalid regex query fails at *resolution* time
/// (a syntactic error in the source), not during elaboration.
#[test]
fn auto_rule_invalid_regex_fails_at_resolution() {
use crate::{grammars::ledger::parse_ledger, resolution::HIR};
let input = "\
= /[unclosed/
(Liabilities:Bad) $1.00
2024-01-01 * Salary
Income:Salary $-100.00
Assets:Checking
";
let ast = parse_ledger(input).expect("parse should succeed");
let err = HIR::try_from(ast).expect_err("resolution should reject invalid regex");
match err {
resolution::ResolutionError::InvalidAutoRuleQuery(query, _) => {
assert_eq!(query, "/[unclosed/");
}
other => panic!("expected InvalidAutoRuleQuery, got {other:?}"),
}
}
/// hledger auto-rule with multiplier semantics matches ledger behaviour.
#[test]
fn hledger_auto_rule_parity_with_ledger() {
use crate::{grammars::hledger::parse_hledger, resolution::HIR};
let input = "\
= expenses:groceries
(budget:groceries) 0.10
2024-01-01 * Shopping
expenses:groceries $50
assets:cash
";
let ast = parse_hledger(input).expect("parse failed");
let hir = HIR::try_from(ast).expect("resolution failed");
let journal = crate::elaborate(hir, &crate::grammars::hledger::hledger_defaults())
.expect("elaboration failed");
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
let synth: Vec<_> = tx
.postings
.iter()
.filter(|p| p.account == "budget:groceries")
.collect();
assert_eq!(synth.len(), 1, "one synthesised posting expected");
let amount = synth[0]
.amount
.as_ref()
.expect("synthesised posting has amount");
let decimal = amount.by_commodity.get("$").expect("$ commodity");
// 0.10 * $50 = $5.00
assert_eq!(
decimal.to_decimal(),
rust_decimal::Decimal::from(5),
"10% of $50 = $5 expected"
);
}
// -------------------------------------------------------------------------
// Explicit `*N` multiplier syntax tests (#254)
// -------------------------------------------------------------------------
/// The explicit `*N` prefix form in a ledger auto-rule body is parsed
/// and lowers to the same bare-number multiplier as a plain bare decimal.
/// `*0.10` against `$-100.00` should produce `$-10.00` (10% tithe).
#[test]
fn ledger_star_n_multiplier_equals_bare_decimal() {
let input = "\
= /^Income/
(Liabilities:Tithe) *0.10
2024-01-01 * Salary
Income:Salary $-100.00
Assets:Checking
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
let synth: Vec<_> = tx
.postings
.iter()
.filter(|p| p.account == "Liabilities:Tithe")
.collect();
assert_eq!(synth.len(), 1, "one synthesised posting expected");
let amount = synth[0]
.amount
.as_ref()
.expect("synthesised posting has amount");
let decimal = amount.by_commodity.get("$").expect("$ commodity");
// *0.10 * $-100.00 = $-10.00 (same as bare 0.10)
assert_eq!(
decimal.to_decimal(),
rust_decimal::Decimal::from(-10),
"*0.10 of $-100 should yield $-10"
);
}
/// `*-1` negates the matched posting's amount — the canonical mirror-entry
/// pattern used to reflect income into a budget equity account.
#[test]
fn ledger_star_negative_one_negates_matched_amount() {
let input = "\
= /^Income/
Equity:Budget *-1
2024-01-01 * Salary
Income:Salary $-100.00
Assets:Checking
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
let synth: Vec<_> = tx
.postings
.iter()
.filter(|p| p.account == "Equity:Budget")
.collect();
assert_eq!(synth.len(), 1, "one synthesised posting expected");
let amount = synth[0]
.amount
.as_ref()
.expect("synthesised posting has amount");
let decimal = amount.by_commodity.get("$").expect("$ commodity");
// *-1 * $-100.00 = $100.00 (sign flip)
assert_eq!(
decimal.to_decimal(),
rust_decimal::Decimal::from(100),
"*-1 of $-100 should yield $100"
);
}
/// `* 0.5` with whitespace between `*` and the number is accepted.
#[test]
fn ledger_star_n_with_whitespace_is_accepted() {
let input = "\
= /^Income/
(Split:Half) * 0.5
2024-01-01 * Salary
Income:Salary $-200.00
Assets:Checking
";
let journal = elaborate(input);
let tx = &journal.transactions[0];
let synth: Vec<_> = tx
.postings
.iter()
.filter(|p| p.account == "Split:Half")
.collect();
assert_eq!(synth.len(), 1);
let amount = synth[0].amount.as_ref().expect("has amount");
let decimal = amount.by_commodity.get("$").expect("$ commodity");
// * 0.5 * $-200.00 = $-100.00
assert_eq!(
decimal.to_decimal(),
rust_decimal::Decimal::from(-100),
"* 0.5 of $-200 should yield $-100"
);
}
/// hledger frontend: `*N` explicit multiplier is accepted and produces the
/// same result as the bare decimal form.
#[test]
fn hledger_star_n_multiplier_equals_bare_decimal() {
use crate::{grammars::hledger::parse_hledger, resolution::HIR};
let input = "\
= expenses:groceries
(budget:groceries) *0.10
2024-01-01 * Shopping
expenses:groceries $50
assets:cash
";
let ast = parse_hledger(input).expect("parse failed");
let hir = HIR::try_from(ast).expect("resolution failed");
let journal = crate::elaborate(hir, &crate::grammars::hledger::hledger_defaults())
.expect("elaboration failed");
let tx = &journal.transactions[0];
let synth: Vec<_> = tx
.postings
.iter()
.filter(|p| p.account == "budget:groceries")
.collect();
assert_eq!(synth.len(), 1, "one synthesised posting expected");
let amount = synth[0].amount.as_ref().expect("has amount");
let decimal = amount.by_commodity.get("$").expect("$ commodity");
// *0.10 * $50 = $5.00
assert_eq!(
decimal.to_decimal(),
rust_decimal::Decimal::from(5),
"*0.10 of $50 should yield $5"
);
}
/// hledger frontend: `*-1` (negative multiplier) negates the matched amount.
#[test]
fn hledger_star_negative_one_negates_matched_amount() {
use crate::{grammars::hledger::parse_hledger, resolution::HIR};
let input = "\
= expenses:groceries
(budget:groceries) *-1
2024-01-01 * Shopping
expenses:groceries $50
assets:cash
";
let ast = parse_hledger(input).expect("parse failed");
let hir = HIR::try_from(ast).expect("resolution failed");
let journal = crate::elaborate(hir, &crate::grammars::hledger::hledger_defaults())
.expect("elaboration failed");
let tx = &journal.transactions[0];
let synth: Vec<_> = tx
.postings
.iter()
.filter(|p| p.account == "budget:groceries")
.collect();
assert_eq!(synth.len(), 1, "one synthesised posting expected");
let amount = synth[0].amount.as_ref().expect("has amount");
let decimal = amount.by_commodity.get("$").expect("$ commodity");
// *-1 * $50 = $-50
assert_eq!(
decimal.to_decimal(),
rust_decimal::Decimal::from(-50),
"*-1 of $50 should yield $-50"
);
}
// -----------------------------------------------------------------------
// C directive (commodity conversion) tests — #248 stage 2
// -----------------------------------------------------------------------
/// `C 1.00s = 100c`: posting 250c converts to 2.50s.
///
/// N1 = 1, N2 = 100. Divisor = N2/N1 = 100/1 = 100.
/// 250c / 100 = 2.50s. Formulas N1*N2 and N2/N1 coincide for N1=1.
#[test]
fn test_c_directive_c_to_s() {
let input = "\
C 1.00s = 100c
2024-01-01 Test
Assets:Cash 250c
Equity
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
let cash = tx
.postings
.iter()
.find(|p| p.account == "Assets:Cash")
.unwrap();
assert_eq!(
cash.amount_in("s"),
Some(dec!(2.50)),
"250c / 100 should be 2.50s"
);
}
/// `C 100c = 1.00s`: LHS commodity is c (canonical), posting 250c stays 250c.
///
/// N1 = 100, N2 = 1. Principled math: `C N1 X = N2 Y` means N1 X = N2 Y,
/// so 1 X = (N2/N1) Y. A posting in the canonical X commodity is not
/// rescaled — the self-loop sentinel carries divisor = 1. Therefore a
/// `250c` posting remains 250c in the elaborated journal.
///
/// This differs from the legacy N1*N2 formula's "normalisation" behaviour.
/// Under principled math, `C 100c = 1s` means "100 cents = 1 shilling";
/// a posting of 250 cents is simply 250 cents (no implicit scale).
#[test]
fn test_c_directive_canonical_posting() {
let input = "\
C 100c = 1.00s
2024-01-01 Test
Assets:Cash 250c
Equity
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
let cash = tx
.postings
.iter()
.find(|p| p.account == "Assets:Cash")
.unwrap();
// Under principled math the self-loop for the canonical LHS commodity has
// divisor = 1, so 250c / 1 = 250c (no rescaling).
assert_eq!(
cash.amount_in("c"),
Some(dec!(250)),
"posting in canonical commodity should not be rescaled (divisor = 1)"
);
}
/// Alias regression: plain `commodity X / alias Y` (divisor=1) should
/// still produce a 1:1 rename and NOT divide the amount.
#[test]
fn test_alias_divisor_one_regression() {
let input = "\
commodity BTC
alias Bitcoin
2024-01-01 Test
Assets:Wallet 2 Bitcoin
Equity
";
let journal = elaborate(input);
let tx = &journal.transactions[0];
let wallet = tx
.postings
.iter()
.find(|p| p.account == "Assets:Wallet")
.unwrap();
// Should be 2 BTC (divisor=1 -> no scaling).
assert_eq!(
wallet.amount_in("BTC"),
Some(dec!(2)),
"alias with divisor=1 should be a plain rename, not scaled"
);
}
/// Aliased postings must not leave a phantom raw-symbol entry in the
/// elaborated `commodities` map. The elaborator rebrands postings to the
/// canonical commodity, so an entry keyed by the alias is orphan metadata
/// with no link back to the canonical. (#336)
#[test]
fn test_alias_does_not_create_phantom_commodity_entry() {
let input = "\
commodity USD
alias $
2024-01-01 Test
Assets:Checking $100
Equity:Opening
";
let journal = elaborate(input);
// Posting itself is canonicalised — sanity check, since the bug
// sits one level deeper than this.
let checking = journal.transactions[0]
.postings
.iter()
.find(|p| p.account == "Assets:Checking")
.unwrap();
assert_eq!(checking.amount_in("USD"), Some(dec!(100)));
// The commodities map must not contain the alias key.
assert!(
!journal.commodities.contains_key("$"),
"alias `$` should not appear as a separate commodity in the \
elaborated journal; commodities keys = {:?}",
journal.commodities.keys().collect::<Vec<_>>()
);
assert!(
journal.commodities.contains_key("USD"),
"canonical commodity `USD` should be present"
);
}
/// Same bug shape as #336/#337 at the `P` directive site: the primary
/// commodity of a `P` directive must be canonicalised through the alias
/// map; otherwise the elaborated `HistoricalPrice.commodity` retains the
/// raw source token and downstream price lookups against the canonical
/// posting commodity miss the entry. (#338)
#[test]
fn test_p_directive_primary_commodity_alias_resolved() {
let input = "\
commodity USD
alias $
P 2024-06-01 $ 1.10 EUR
2024-06-02 Test
Assets:Wallet $100
Equity:Opening
";
let journal = elaborate(input);
assert_eq!(journal.prices.len(), 1);
let hp = &journal.prices[0];
assert_eq!(
hp.commodity, "USD",
"P directive primary commodity must be canonicalised through the \
alias map; got `{}`",
hp.commodity
);
assert_eq!(hp.price_commodity, "EUR");
}
/// `C` directive does not retroactively affect transactions that appeared
/// before it in the source file (context-versioning invariant).
#[test]
fn test_c_directive_not_retroactive() {
let input = "\
2024-01-01 Before
Assets:Cash 250c
Equity
C 1.00s = 100c
2024-01-02 After
Assets:Cash 250c
Equity
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 2);
// Transaction before the C directive: commodity should be unchanged 'c'.
let before = &journal.transactions[0];
let before_cash = before
.postings
.iter()
.find(|p| p.account == "Assets:Cash")
.unwrap();
assert_eq!(
before_cash.amount_in("c"),
Some(dec!(250)),
"posting before C directive should not be affected"
);
// Transaction after the C directive: 250c -> 2.50s.
let after = &journal.transactions[1];
let after_cash = after
.postings
.iter()
.find(|p| p.account == "Assets:Cash")
.unwrap();
assert_eq!(
after_cash.amount_in("s"),
Some(dec!(2.50)),
"posting after C directive should convert to canonical commodity"
);
}
/// 2-hop balance verification: `C 1G = 100s` + `C 1s = 100c`.
///
/// A mixed-commodity transaction with one posting in G and one in c must
/// balance after the full transitive chain is applied. Both postings in the
/// elaborated Journal are expressed in the chain root G.
///
/// Chain: c → s → G (total divisor = 10000).
/// 10000c / 10000 = 1G. The G posting is already at root.
#[test]
fn test_c_directive_chain_applied_for_balance_verification() {
let input = "\
C 1.00s = 100c
C 1.00G = 100s
2024-01-01 mixed
Assets:A 1G
Assets:B -10000c
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
let asset_a = tx
.postings
.iter()
.find(|p| p.account == "Assets:A")
.unwrap();
let asset_b = tx
.postings
.iter()
.find(|p| p.account == "Assets:B")
.unwrap();
// Assets:A is 1G (already at chain root).
assert_eq!(
asset_a.amount_in("G"),
Some(dec!(1)),
"Assets:A should be 1G"
);
// Assets:B: -10000c → -10000 / 10000 = -1G via the c→s→G chain.
assert_eq!(
asset_b.amount_in("G"),
Some(dec!(-1)),
"Assets:B should be -1G after 2-hop c→s→G conversion"
);
}
/// 3-hop balance verification: `C 1P = 10G` + `C 1G = 100s` + `C 1s = 100c`.
///
/// Chain: c → s → G → P (total divisor = 100000).
/// 100000c / 100000 = 1P.
#[test]
fn test_c_directive_three_hop_chain() {
let input = "\
C 1.00s = 100c
C 1.00G = 100s
C 1.00P = 10G
2024-01-01 mixed
Assets:A 1P
Assets:B -100000c
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
let asset_a = tx
.postings
.iter()
.find(|p| p.account == "Assets:A")
.unwrap();
let asset_b = tx
.postings
.iter()
.find(|p| p.account == "Assets:B")
.unwrap();
// Assets:A is 1P (already at chain root).
assert_eq!(
asset_a.amount_in("P"),
Some(dec!(1)),
"Assets:A should be 1P"
);
// Assets:B: -100000c resolves via c→s→G→P (divisor = 100000) = -1P.
assert_eq!(
asset_b.amount_in("P"),
Some(dec!(-1)),
"Assets:B should be -1P after 3-hop c→s→G→P conversion"
);
}
/// Cycle detection: `C 1X = 1Y` + `C 1Y = 1X` must produce a
/// `ResolutionError::CommodityConversionCycle`.
#[test]
fn test_c_directive_cycle_detection() {
use crate::{grammars::ledger::parse_ledger, resolution::HIR};
let input = "\
C 1.00X = 1Y
C 1.00Y = 1X
2024-01-01 t
Assets:A 1X
Equity
";
let ast = parse_ledger(input).expect("parse should succeed");
let err = HIR::try_from(ast).expect_err("cycle should be detected at resolution time");
assert!(
matches!(
err,
crate::resolution::ResolutionError::CommodityConversionCycle(_)
),
"expected CommodityConversionCycle, got: {err:?}"
);
}
/// Single-hop happy path (regression of #261's basic case).
///
/// `C 1.00s = 100c` with a posting of 250c resolves to 2.50s.
/// (Already covered by `test_c_directive_c_to_s`; this is an explicit
/// guard that the fixpoint does not break the 1-hop case.)
#[test]
fn test_c_directive_single_hop_regression() {
let input = "\
C 1.00s = 100c
2024-01-01 Test
Assets:Cash 250c
Equity
";
let journal = elaborate(input);
let tx = &journal.transactions[0];
let cash = tx
.postings
.iter()
.find(|p| p.account == "Assets:Cash")
.unwrap();
assert_eq!(
cash.amount_in("s"),
Some(dec!(2.50)),
"single-hop: 250c / 100 should be 2.50s"
);
}
/// `C` does not affect Beancount-style journals; this is a compile-time
/// property (Beancount frontend never emits `Entry::CommodityConversion`),
/// but we verify the elaborator produces sane output for a plain USD
/// beancount journal run through the ledger pipeline.
#[test]
fn test_c_directive_parse_ledger_round_trip() {
// A trivially balanced transaction with no C directive — should parse
// and elaborate without issue.
let input = "\
2024-01-01 Simple
Assets:Cash 100 USD
Equity
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
let cash = tx
.postings
.iter()
.find(|p| p.account == "Assets:Cash")
.unwrap();
assert_eq!(cash.amount_in("USD"), Some(dec!(100)));
}
// -----------------------------------------------------------------------
// N1 ≠ 1 regression tests — #274 (correct divisor formula N2/N1)
// -----------------------------------------------------------------------
/// Regression from #274 empirical example: `C 100 SLV = 1 G`.
///
/// N1 = 100, N2 = 1. Divisor = N2/N1 = 1/100 = 0.01.
/// 1G / 0.01 = 100 SLV. The old N1*N2=100 formula gave 1G/100=0.01 SLV.
///
/// A balanced transaction `Assets:A 1G / Assets:B -100 SLV` must elaborate
/// without error: both sides reduce to the SLV chain root.
#[test]
fn test_c_directive_n1_ne_1_single_hop_g_to_slv() {
let input = "\
C 100 SLV = 1 G
2024-01-01 mixed
Assets:A 1 G
Assets:B -100 SLV
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
let asset_a = tx
.postings
.iter()
.find(|p| p.account == "Assets:A")
.unwrap();
let asset_b = tx
.postings
.iter()
.find(|p| p.account == "Assets:B")
.unwrap();
// 1G / (1/100) = 100 SLV (divisor = N2/N1 = 1/100 = 0.01)
assert_eq!(
asset_a.amount_in("SLV"),
Some(dec!(100)),
"1G should convert to 100 SLV with N1=100, N2=1"
);
// -100 SLV / 1 (self-loop sentinel for SLV) = -100 SLV
assert_eq!(
asset_b.amount_in("SLV"),
Some(dec!(-100)),
"SLV posting should remain -100 SLV"
);
}
/// Full repro from issue #274: `C 1 SLV = 100c` + `C 100 SLV = 1 G`.
///
/// Both conversions target SLV (Y-shape topology, hub at SLV).
/// - c → SLV: divisor = N2/N1 = 100/1 = 100; 1c → 1/100 SLV
/// - G → SLV: divisor = N2/N1 = 1/100 = 0.01; 1G → 1/0.01 = 100 SLV
///
/// Transaction `1G / -10000c` balances: 100 SLV + (-10000/100) SLV = 0.
#[test]
fn test_c_directive_n1_ne_1_issue_274_repro() {
let input = "\
C 1 SLV = 100c
C 100 SLV = 1 G
2024-01-01 mixed
Assets:A 1 G
Assets:B -10000c
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
let asset_a = tx
.postings
.iter()
.find(|p| p.account == "Assets:A")
.unwrap();
let asset_b = tx
.postings
.iter()
.find(|p| p.account == "Assets:B")
.unwrap();
// 1G / 0.01 = 100 SLV
assert_eq!(
asset_a.amount_in("SLV"),
Some(dec!(100)),
"1G should convert to 100 SLV"
);
// -10000c / 100 = -100 SLV
assert_eq!(
asset_b.amount_in("SLV"),
Some(dec!(-100)),
"-10000c should convert to -100 SLV"
);
}
/// N1 ≠ 1 with fractional ratio: `C 5 X = 500 Y`.
///
/// N1 = 5, N2 = 500. Principled math: 5X = 500Y, so 1X = 100Y.
/// Divisor = N2/N1 = 500/5 = 100.
///
/// A transaction `Assets:A 5X / Assets:B -500Y` balances:
/// 5X (canonical, self-loop divisor=1 → stays 5X)
/// -500Y / 100 = -5X
/// sum = 5 + (-5) = 0 ✓
#[test]
fn test_c_directive_n1_ne_1_fractional_ratio() {
let input = "\
C 5 X = 500 Y
2024-01-01 Test
Assets:A 5 X
Assets:B -500 Y
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
let asset_a = tx
.postings
.iter()
.find(|p| p.account == "Assets:A")
.unwrap();
let asset_b = tx
.postings
.iter()
.find(|p| p.account == "Assets:B")
.unwrap();
// 5X: self-loop divisor=1, so 5X / 1 = 5X (no rescaling).
assert_eq!(
asset_a.amount_in("X"),
Some(dec!(5)),
"5X should remain 5X (canonical, self-loop divisor=1)"
);
// -500Y / 100 = -5X (divisor = N2/N1 = 100).
assert_eq!(
asset_b.amount_in("X"),
Some(dec!(-5)),
"-500Y should convert to -5X via divisor = N2/N1 = 100"
);
}
/// Two-hop chain with N1 ≠ 1 in one hop: `C 1 X = 5 Y` + `C 2 Z = 1 X`.
///
/// Principled math:
/// C 1 X = 5 Y → 1X = 5Y → divisor Y→X = N2/N1 = 5/1 = 5
/// C 2 Z = 1 X → 2Z = 1X → divisor X→Z = N2/N1 = 1/2 = 0.5
/// Combined Y→Z = 5 * 0.5 = 2.5
///
/// Verify: 1X = 5Y and 2Z = 1X = 5Y, so 1Z = 2.5Y.
/// Transaction `2Z / -5Y`: 2Z stays 2Z, -5Y / 2.5 = -2Z. Balances ✓.
#[test]
fn test_c_directive_two_hop_n1_ne_1() {
let input = "\
C 1 X = 5 Y
C 2 Z = 1 X
2024-01-01 Test
Assets:A 2 Z
Assets:B -5 Y
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
let asset_a = tx
.postings
.iter()
.find(|p| p.account == "Assets:A")
.unwrap();
let asset_b = tx
.postings
.iter()
.find(|p| p.account == "Assets:B")
.unwrap();
// Z is root. Self-loop divisor = 1, so 2Z stays 2Z.
assert_eq!(
asset_a.amount_in("Z"),
Some(dec!(2)),
"2Z should remain 2Z (self-loop divisor=1)"
);
// -5Y via Y→Z composed divisor = 2.5: -5 / 2.5 = -2Z.
assert_eq!(
asset_b.amount_in("Z"),
Some(dec!(-2)),
"-5Y should convert to -2Z via 2-hop chain (divisor=2.5)"
);
}
/// Zero LHS amount `C 0 X = 100 Y` must produce
/// `ResolutionError::InvalidCommodityConversion` — division by zero.
#[test]
fn test_c_directive_zero_lhs_errors() {
use crate::{grammars::ledger::parse_ledger, resolution::HIR};
let input = "\
C 0 X = 100 Y
2024-01-01 t
Assets:A 1 Y
Equity
";
let ast = parse_ledger(input).expect("parse should succeed");
let err =
HIR::try_from(ast).expect_err("zero LHS amount should produce a resolution error");
assert!(
matches!(
err,
crate::resolution::ResolutionError::InvalidCommodityConversion(_, _)
),
"expected InvalidCommodityConversion, got: {err:?}"
);
}
// -----------------------------------------------------------------------
// Auto-balance per-lot synthesis tests (#276)
// -----------------------------------------------------------------------
/// Minimal repro from issue #276: an inventory transfer where explicit
/// legs carry `{cost}` lot annotations and the auto-balanced leg should
/// receive per-lot inverse postings, not a single cash aggregate.
///
/// After elaboration:
/// - `Assets:Tajer:Items` nets to 0 Widget (buys cancel the per-lot
/// transfer reversal) with NO spurious GOLD residual.
/// - `Assets:Wyshona:Items` accumulates 2 Widget.
/// - `Assets:Tajer` absorbs -22 GOLD (cash paid for the buys).
#[test]
fn test_auto_balance_lot_bearing_transfer() {
let input = "\
2024/01/01 Buy 2 widgets at Tajer
Assets:Tajer:Items \"Widget\" 1 @ 10 GOLD
Assets:Tajer:Items \"Widget\" 1 @ 12 GOLD
Assets:Tajer
2024/01/02 Transfer to Wyshona
Assets:Wyshona:Items \"Widget\" 1 {10 GOLD}
Assets:Wyshona:Items \"Widget\" 1 {12 GOLD}
Assets:Tajer:Items
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 2, "two transactions expected");
// Transaction 1: buys — cash path unchanged.
let t1 = &journal.transactions[0];
let tajer_cash = t1
.postings
.iter()
.find(|p| p.account == "Assets:Tajer")
.expect("Assets:Tajer must be present in tx1");
assert_eq!(
tajer_cash.amount_in("GOLD"),
Some(dec!(-22)),
"Assets:Tajer should absorb -22 GOLD from the two @-price buys"
);
// Transaction 2: transfer.
let t2 = &journal.transactions[1];
// Wyshona:Items receives 2 Widget total.
let wyshona_total: rust_decimal::Decimal = t2
.postings
.iter()
.filter(|p| p.account == "Assets:Wyshona:Items")
.filter_map(|p| p.amount_in("Widget"))
.sum();
assert_eq!(
wyshona_total,
dec!(2),
"Assets:Wyshona:Items should receive 2 Widget"
);
// Tajer:Items auto-balanced leg: per-lot inverse postings, no GOLD.
let tajer_items: Vec<_> = t2
.postings
.iter()
.filter(|p| p.account == "Assets:Tajer:Items")
.collect();
assert!(
!tajer_items.is_empty(),
"Assets:Tajer:Items must have at least one posting in the transfer tx"
);
let gold_residual: rust_decimal::Decimal =
tajer_items.iter().filter_map(|p| p.amount_in("GOLD")).sum();
assert_eq!(
gold_residual,
dec!(0),
"Assets:Tajer:Items must have no GOLD residual after per-lot synthesis"
);
let widget_net: rust_decimal::Decimal = tajer_items
.iter()
.filter_map(|p| p.amount_in("Widget"))
.sum();
assert_eq!(
widget_net,
dec!(-2),
"Assets:Tajer:Items should net -2 Widget from the per-lot inverse postings"
);
assert!(
tajer_items.iter().all(|p| p.has_lot()),
"all auto-balanced Tajer:Items postings should carry a lot annotation"
);
}
/// Two explicit postings at the same lot key should produce ONE grouped
/// inverse posting on the auto-balanced account, not one per explicit leg.
#[test]
fn test_auto_balance_distinct_lot_keys_grouped() {
let input = "\
2024/01/01 Buy widgets
Assets:Source \"Widget\" 3 @ 10 GOLD
Assets:Vault
2024/01/02 Transfer grouped
Assets:Dest \"Widget\" 1 {10 GOLD}
Assets:Dest \"Widget\" 2 {10 GOLD}
Assets:Source
";
// tx2: two explicit postings at the same lot key {10 GOLD}.
// lot_bearing_state groups them: ("Widget", {10 GOLD}) -> 3.
// Auto-balanced: one posting of -3 Widget {10 GOLD} on Assets:Source.
let journal = elaborate(input);
let t2 = &journal.transactions[1];
let source_postings: Vec<_> = t2
.postings
.iter()
.filter(|p| p.account == "Assets:Source")
.collect();
assert_eq!(
source_postings.len(),
1,
"grouped lot key should produce exactly one inverse posting, not one per leg"
);
assert_eq!(
source_postings[0].amount_in("Widget"),
Some(dec!(-3)),
"grouped inverse should sum to -3 Widget"
);
assert!(
source_postings[0].has_lot(),
"the grouped inverse posting must carry the lot annotation"
);
assert_eq!(
source_postings[0].lot_cost_in("GOLD"),
Some(dec!(10)),
"lot cost should be 10 GOLD"
);
}
/// Plain cash transaction — auto-balance behavior must be unchanged:
/// one posting on the null account with the cash negation, no lot.
#[test]
fn test_auto_balance_cash_only_regression() {
let input = "\
2024-01-01 Coffee
Expenses:Coffee $4.50
Assets:Checking
";
let journal = elaborate(input);
let t = &journal.transactions[0];
let checking = t
.postings
.iter()
.find(|p| p.account == "Assets:Checking")
.expect("Assets:Checking must be present");
assert_eq!(
checking.amount_in("$"),
Some(dec!(-4.50)),
"cash-only null posting should balance as -$4.50"
);
assert!(
!checking.has_lot(),
"cash-only null posting must not carry a lot annotation"
);
let checking_count = t
.postings
.iter()
.filter(|p| p.account == "Assets:Checking")
.count();
assert_eq!(
checking_count, 1,
"cash-only auto-balance should produce exactly one posting"
);
}
/// First-time inventory grant: the null account (`Equity:Open`) has never
/// held Widget, but the principled rule still emits a per-lot inverse on
/// it. This is the case the old `null_holds_commodity` heuristic got wrong.
///
/// Empirically verified against ledger-cli:
/// ```text
/// Assets:Items|Widget 1 {GOLD10}
/// Equity:Open|Widget -1 {GOLD10}
/// ```
/// `Equity:Open` receives `-1 Widget {GOLD 10}`, not `-10 GOLD`.
#[test]
fn test_auto_balance_first_time_inventory_grant() {
let input = "\
2024/01/01 Initial grant
Assets:Items \"Widget\" 1 {10 GOLD}
Equity:Open
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let t = &journal.transactions[0];
// Equity:Open should receive exactly one posting.
let equity_postings: Vec<_> = t
.postings
.iter()
.filter(|p| p.account == "Equity:Open")
.collect();
assert_eq!(
equity_postings.len(),
1,
"Equity:Open should have exactly one synthesized posting"
);
let ep = equity_postings[0];
// It must be a Widget posting (per-lot inverse), not a GOLD cash posting.
assert_eq!(
ep.amount_in("Widget"),
Some(dec!(-1)),
"Equity:Open should receive -1 Widget (per-lot inverse)"
);
assert_eq!(
ep.amount_in("GOLD"),
None,
"Equity:Open must not receive a GOLD cash posting"
);
// The posting must carry the lot annotation.
assert!(
ep.has_lot(),
"the synthesized posting must carry a lot annotation"
);
assert_eq!(
ep.lot_cost_in("GOLD"),
Some(dec!(10)),
"lot cost on Equity:Open posting should be 10 GOLD"
);
}
/// Sale with cash auto-balance: `Assets:Items Widget -1 {10 GOLD} @ 15 GOLD`
/// followed by a null `Assets:Cash` posting.
///
/// Empirically verified against ledger-cli (`ledger -f sale.dat balance --lots --flat`):
/// ```text
/// Assets:Cash GOLD 10
/// Equity:Open Widget -1 {GOLD 10}
/// ```
///
/// Key observation: ledger-cli auto-balances `Assets:Cash` with the COST BASIS
/// (10 GOLD), not the sale price (15 GOLD). The `@ 15 GOLD` annotation is used
/// for market valuation only; the cost-basis mode drives the balance.
///
/// The principled rule (positive-unit `{cost}` lots only) correctly produces
/// this behavior: the sale posting has negative units (-1 Widget), so it is
/// NOT included in `lot_bearing_state`. The cash-residue path emits `+10 GOLD`
/// on Assets:Cash, matching ledger-cli exactly.
///
/// Note: doppio does not synthesize a realized-gain posting for the 5-GOLD
/// spread. That is a separate concern tracked in #210/#238. If those issues
/// are resolved, this test's expectations for Assets:Cash may need updating.
#[test]
fn test_auto_balance_sale_with_cash_auto_balance() {
let input = "\
2024/01/01 Buy first
Assets:Items \"Widget\" 1 {10 GOLD}
Equity:Open
2024/01/02 Sell with cash auto-balance
Assets:Items \"Widget\" -1 {10 GOLD} @ 15 GOLD
Assets:Cash
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 2);
let t2 = &journal.transactions[1];
// Assets:Cash should receive exactly one posting: +10 GOLD (cost basis).
let cash_postings: Vec<_> = t2
.postings
.iter()
.filter(|p| p.account == "Assets:Cash")
.collect();
assert_eq!(
cash_postings.len(),
1,
"Assets:Cash should have exactly one posting (cash-residue path)"
);
let cp = cash_postings[0];
// Cost-basis cash: +10 GOLD (not +15 GOLD from the @-price).
assert_eq!(
cp.amount_in("GOLD"),
Some(dec!(10)),
"Assets:Cash should receive +10 GOLD (cost-basis auto-balance, matching ledger-cli)"
);
// No per-lot Widget posting on Assets:Cash.
assert_eq!(
cp.amount_in("Widget"),
None,
"Assets:Cash must not receive a Widget posting (sale posting excluded from per-lot synthesis)"
);
assert!(
!cp.has_lot(),
"Assets:Cash posting must not carry a lot annotation"
);
}
// ──────────────────────────────────────────────────────────────────────────
// Intent-driven canonical-cost balance (#281)
// Scale inference lives in resolution (HIR); elaborator reads the result.
// ──────────────────────────────────────────────────────────────────────────
/// Reproduction of `tests/parity/ledger-standard.dat` line ~1880.
///
/// This transaction has four `@`-priced postings whose prices are
/// 28-decimal-place IEEE-double serialisations. Computing costs at full
/// precision produces a `$0.004` residue that prevents exact-zero balance.
/// With intent-driven canonical-cost rounding (scale inferred in HIR,
/// applied in elaborator) the residue is explained by the per-posting price
/// precision, and the transaction elaborates cleanly.
#[test]
fn test_intent_rounded_cost_standard_dat_1880_repro() {
let input = "\
2003/06/19 * cbb4cc49824bf79827cde838e005848027ca0a38
c56a21d2 331.296869 LMVTX @ $53.6599999999999999998612221219
c56a21d2 -523.942988 EEEEE @ $33.9299999999999999998438748872
c56a21d2 55.981364 LMVTX @ $53.6599999999999999998612221219
c56a21d2 -88.534054 EEEEE @ $33.9299999999999999998438748872
c56a21d2
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
// The four explicit postings must be present.
let lmvtx: Vec<_> = tx
.postings
.iter()
.filter(|p| p.amount_in("LMVTX").is_some())
.collect();
assert_eq!(lmvtx.len(), 2, "expected two LMVTX postings");
let eeeee: Vec<_> = tx
.postings
.iter()
.filter(|p| p.amount_in("EEEEE").is_some())
.collect();
assert_eq!(eeeee.len(), 2, "expected two EEEEE postings");
// Quantities must be preserved exactly as written.
let lmvtx_qtys: Vec<rust_decimal::Decimal> =
lmvtx.iter().filter_map(|p| p.amount_in("LMVTX")).collect();
assert!(
lmvtx_qtys.contains(&dec!(331.296869)),
"first LMVTX qty must be 331.296869"
);
assert!(
lmvtx_qtys.contains(&dec!(55.981364)),
"second LMVTX qty must be 55.981364"
);
}
/// The ledger-cli motivating example (xact.cc:875-878).
///
/// Two postings of `0.50 bread @ $3.99` (canonical cost $2.00 each at
/// scale 2) produce a total `$` contribution of `$4.00` regardless of the
/// exact Decimal multiply result. A matching `$-4.00` on the cash account
/// balances exactly.
#[test]
fn test_intent_rounded_cost_ledger_motivating_example() {
let input = "\
2024-01-01 Bread purchase
Expenses:Food 0.50 bread @ $3.99
Expenses:Food 0.50 bread @ $3.99
Assets:Cash $-4.00
";
// Each 0.50 * $3.99 = $1.995, rounded to scale 2 (price commodity's
// inferred scale from `$-4.00`) = $2.00; total = $4.00 cancels $-4.00.
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
}
/// Exact-precision prices are unaffected by intent-driven rounding.
///
/// `1.00 cup @ $3.99`: cost = $3.9900 (rounded to scale 2, which is the
/// inferred scale of `$` from `$-3.99`). Already exact; no residue.
#[test]
fn test_intent_rounded_cost_exact_precision_unaffected() {
let input = "\
2024-01-01 Coffee
Expenses:Coffee 1.00 cup @ $3.99
Assets:Cash $-3.99
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
assert!(
tx.postings.iter().any(|p| p.amount_in("cup").is_some()),
"cup posting must be present"
);
}
/// Adversarial: a genuinely unbalanced transaction is still rejected.
///
/// Intent-driven rounding only compensates for precision residue introduced
/// by `@`-price multiplication. A transaction with an explicit commodity
/// imbalance larger than the tolerance derived from `inferred_scale` must
/// still produce `ElaborationError::TransactionDoesNotBalance`.
///
/// `1.00 G + -1.05 G`: residue = 0.05 G. `inferred_scale[G]` = 2 (from the
/// scale-2 direct postings). Tolerance = `1.0 * 10^(-2)` = 0.01 G.
/// `0.05 > 0.01` → reject. (Updated from the original `1G + -1.001G` boundary
/// case as part of #286: the ledger frontend now uses fraction=1 derived from
/// inferred_scale, so boundary-exact residues are absorbed by design.)
#[test]
fn test_intent_rounded_cost_high_precision_imbalance_rejected() {
let input = "\
2024-01-01 Unbalanced
Assets:A 1.00 G
Assets:B -1.05 G
";
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");
let result = crate::elaborate(hir, &crate::grammars::ledger::ledger_defaults());
assert!(
matches!(
result,
Err(crate::elaborator::ElaborationError::TransactionDoesNotBalance(_))
),
"genuinely unbalanced transaction (0.05 G residue > 0.01 G tolerance) must still be rejected"
);
}
/// Regression test for hledger-ascii.journal parity fixture.
///
/// In hledger grammar, a suffix-commodity amount like `-0.71 B` parses as
/// `Typed { Unary { Sub, Amount { 0.71, None } }, "B" }`. The resolution
/// stage's scale collector must recognise this form so that `B` appears in
/// `commodity_properties` with `inferred_scale = 2`; otherwise canonical-
/// cost rounding is skipped and a non-zero balance residue remains.
#[test]
fn test_intent_rounded_cost_hledger_typed_node_regression() {
let input = "\
2000-01-01 transaction 1
1 1 A @ 0.71 B
1:2 -0.71 B
";
use crate::{grammars::hledger::parse_hledger, resolution::HIR};
let ast = parse_hledger(input).expect("hledger parse failed");
let hir = HIR::try_from(ast).expect("resolution failed");
let result = crate::elaborate(hir, &crate::grammars::hledger::hledger_defaults());
assert!(
result.is_ok(),
"hledger suffix-commodity posting should balance: {:?}",
result.err()
);
let journal = result.unwrap();
assert_eq!(journal.transactions.len(), 1);
}
// ──────────────────────────────────────────────────────────────────────────
// #288 regression: @-price scale fallback when no direct posting exists
// ──────────────────────────────────────────────────────────────────────────
/// Minimal repro of the wow.dat shape that regressed in #288.
///
/// GOLD has no direct postings — the `D 1.00 GOLD` directive is a default
/// directive, not a posting. The `@ 1.25 GOLD` annotation must establish
/// `inferred_scale[GOLD] = 2`, so `1 @ 1.25 GOLD` is elaborated as
/// `-1.25 GOLD` on the auto-balance leg (not integer-rounded to `-1 GOLD`).
#[test]
fn test_at_price_intent_rounding_when_no_direct_posting_at_higher_scale() {
let input = "\
D 1.00 GOLD
2024/01/01 Buy
Assets:Items \"Widget\" 1 @ 1.25 GOLD
Assets:Cash
";
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
// The auto-balanced Assets:Cash posting must be -1.25 GOLD, not -1 GOLD.
let cash = tx
.postings
.iter()
.find(|p| p.account == "Assets:Cash")
.expect("Assets:Cash posting must be present");
let gold_amount = cash
.amount_in("GOLD")
.expect("Assets:Cash must hold GOLD (the price commodity)");
assert_eq!(
gold_amount,
dec!(-1.25),
"Assets:Cash must be -1.25 GOLD (not integer-rounded to -1 GOLD)"
);
}
// ──────────────────────────────────────────────────────────────────────────
// #286: inferred_scale-derived tolerance absorbs sub-precision residues
// ──────────────────────────────────────────────────────────────────────────
/// Minimal repro of standard.dat:4244 (#286).
///
/// A multi-commodity rebalance with 28-decimal IEEE-double `@`-prices and
/// an explicit `$0.01` dust-compensation leg. After #281's intent-rounding
/// to `inferred_scale=2` for `$`, the six priced legs produce a `$-0.01`
/// residue; the explicit `$0.01` leg compensates for half, leaving `$-0.01`.
///
/// ledger-cli accepts this via its `is_zero()` check at display precision 2.
/// doppio must accept it too: tolerance = `1.0 * 10^(-2)` = `$0.01`, and
/// `|-0.01| > 0.01` is false (strict `>`), so the residue is absorbed.
#[test]
fn test_tolerance_absorbs_subprecision_residue() {
let input = "\
2004/05/10 * cbb4cc49824bf79827cde838e005848027ca0a38
A 2,242.324241 BBBBB @ $22.7300000000000000000173472348
A 2,558.818182 DDDDD @ $8.9099999999999999998612221219
A 604.908255 FFFFF @ $41.3099999999999999999479582957
A -2,084.582278 AAAAA @ $24.4499999999999999972244424384
A -387.278233 LMVTX @ $58.8699999999999999998959165914
A -936.961582 GGGGG @ $26.6700000000000000000693889390
A $0.01
";
// This is the standard.dat:4244 minimal repro. ledger-cli accepts it;
// doppio must also accept it with the inferred_scale-derived tolerance.
let result = {
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::elaborate(hir, &crate::grammars::ledger::ledger_defaults())
};
assert!(
result.is_ok(),
"standard.dat:4244 repro must elaborate cleanly (sub-precision dust leg); got: {result:?}"
);
let journal = result.unwrap();
assert_eq!(journal.transactions.len(), 1);
}
/// Adversarial: a genuinely unbalanced transaction (residue >= `$0.01`)
/// must still be rejected even with the tolerance relaxation from #286.
///
/// `1 G` + `-1.01 G` (no `@`-prices, no intent-rounding) leaves a residue
/// of `0.01 G`. `inferred_scale[G]` = 2 (from the `0.01` posting), so
/// tolerance = `1.0 * 10^(-2)` = `0.01 G`. The strict `>` check means
/// `|0.01| > 0.01` is false — but `0.02 G` would be `> 0.01` and reject.
/// Use a larger imbalance (`0.05 G`) to ensure the check fires.
#[test]
fn test_tolerance_rejects_real_imbalance() {
// 1 G - 1.05 G = -0.05 G residue; tolerance = 0.01 G; 0.05 > 0.01 → reject.
let input = "\
2024-01-01 Unbalanced
Assets:A 1.00 G
Assets:B -1.05 G
";
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");
let result = crate::elaborate(hir, &crate::grammars::ledger::ledger_defaults());
assert!(
matches!(
result,
Err(crate::elaborator::ElaborationError::TransactionDoesNotBalance(_))
),
"real imbalance (0.05 G) must still be rejected; got: {result:?}"
);
}
/// A perfectly balanced 2-decimal `$` transaction must elaborate with no
/// residue absorbed — the tolerance path must not fire for clean journals.
#[test]
fn test_tolerance_doppio_native_clean_precision_unchanged() {
let input = "\
2024-01-01 Transfer
Assets:Checking $10.00
Assets:Savings $-10.00
";
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");
let journal = crate::elaborate(hir, &crate::grammars::ledger::ledger_defaults())
.expect("clean transaction must elaborate without error");
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
// No synthesized rounding posting (empty-string account sentinel).
assert!(
!tx.postings.iter().any(|p| p.account.is_empty()),
"no rounding residual should be synthesized for a cleanly-balanced transaction"
);
}
/// Beancount frontend uses its own tolerance mode (`fraction=0.5`) and must
/// be unaffected by the ledger-frontend default change (`fraction=1`).
///
/// A Beancount two-commodity transaction with an explicit imbalance of
/// `0.006 USD` (above the 0.005 Beancount threshold for scale-2 USD) must
/// still be rejected — the beancount defaults are unchanged.
#[test]
fn test_beancount_tolerance_unchanged() {
// 100.00 USD + (-100.006 USD) = -0.006 USD residue.
// Beancount tolerance for scale-2 USD = 0.5 * 0.01 = 0.005.
// 0.006 > 0.005 → reject.
let input = "\
2024-01-01 * \"Unbalanced\"
Assets:A 100.000 USD
Assets:B -100.006 USD
";
use crate::{grammars::beancount::parse_beancount, resolution::HIR};
let ast = parse_beancount(input).expect("beancount parse failed");
let hir = HIR::try_from(ast).expect("resolution failed");
let result = crate::elaborate(hir, &crate::grammars::beancount::beancount_defaults());
assert!(
matches!(
result,
Err(crate::elaborator::ElaborationError::TransactionDoesNotBalance(_))
),
"Beancount tolerance (0.005 USD) must reject 0.006 USD residue; got: {result:?}"
);
}
/// When a commodity has no direct postings and no D/format directive,
/// `inferred_scale` is 0. The tolerance computation falls back to the
/// per-posting min_scale, preserving the original behaviour for such
/// commodities.
///
/// A transaction with `1 RARE + (-1.005 RARE)` (no other RARE postings
/// anywhere): `inferred_scale[RARE] = 3` (from the `0.005` posting scale),
/// so the fallback is used. Tolerance = `1.0 * 10^(-3)` = `0.001 RARE`.
/// Residue = `0.005 RARE`; `0.005 > 0.001` → reject, confirming the
/// fallback doesn't silently absorb larger residues.
#[test]
fn test_tolerance_fallback_when_no_inferred_scale() {
// There is no D directive and no other RARE posting, so inferred_scale
// for RARE is 3 (the max scale from the two direct postings: 0 and 3).
// Tolerance = 1.0 * 10^(-3) = 0.001. Residue = 0.005 > 0.001 → reject.
let input = "\
2024-01-01 Unbalanced
Assets:A 1 RARE
Assets:B -1.005 RARE
";
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");
let result = crate::elaborate(hir, &crate::grammars::ledger::ledger_defaults());
assert!(
matches!(
result,
Err(crate::elaborator::ElaborationError::TransactionDoesNotBalance(_))
),
"fallback per-posting min_scale must reject residue above tolerance; got: {result:?}"
);
}
/// Guard the original #281 anchor: standard.dat:1880 still elaborates
/// cleanly after the #288 fix.
///
/// The four-leg LMVTX/EEEEE transaction has direct `$` postings at scale
/// 2 (`$474.31` etc.) and 28-decimal `@` prices. The fix must NOT let the
/// 28-decimal prices inflate `inferred_scale[$]` — direct postings must win.
#[test]
fn test_standard_dat_1880_regression_preserved() {
let input = "\
2003/06/19 * cbb4cc49824bf79827cde838e005848027ca0a38
c56a21d2 331.296869 LMVTX @ $53.6599999999999999998612221219
c56a21d2 -523.942988 EEEEE @ $33.9299999999999999998438748872
c56a21d2 55.981364 LMVTX @ $53.6599999999999999998612221219
c56a21d2 -88.534054 EEEEE @ $33.9299999999999999998438748872
c56a21d2
";
// This must elaborate cleanly — no TransactionDoesNotBalance error.
let journal = elaborate(input);
assert_eq!(journal.transactions.len(), 1);
let tx = &journal.transactions[0];
// Quantities must be preserved exactly as written (no over-rounding).
let lmvtx_qtys: Vec<rust_decimal::Decimal> = tx
.postings
.iter()
.filter_map(|p| p.amount_in("LMVTX"))
.collect();
assert!(
lmvtx_qtys.contains(&dec!(331.296869)),
"first LMVTX qty must be 331.296869, got {lmvtx_qtys:?}"
);
assert!(
lmvtx_qtys.contains(&dec!(55.981364)),
"second LMVTX qty must be 55.981364, got {lmvtx_qtys:?}"
);
}
}